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;
   17use db::smol::future::yield_now;
   18pub use shared_screen::SharedScreen;
   19mod status_bar;
   20pub mod tasks;
   21mod theme_preview;
   22mod toast_layer;
   23mod toolbar;
   24pub mod welcome;
   25mod workspace_settings;
   26
   27pub use crate::notifications::NotificationFrame;
   28pub use dock::Panel;
   29pub use multi_workspace::{
   30    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent,
   31    NewWorkspaceInWindow, NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarHandle,
   32    ToggleWorkspaceSidebar,
   33};
   34pub use path_list::{PathList, SerializedPathList};
   35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   36
   37use anyhow::{Context as _, Result, anyhow};
   38use client::{
   39    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   40    proto::{self, ErrorCode, PanelId, PeerId},
   41};
   42use collections::{HashMap, HashSet, hash_map};
   43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   44use fs::Fs;
   45use futures::{
   46    Future, FutureExt, StreamExt,
   47    channel::{
   48        mpsc::{self, UnboundedReceiver, UnboundedSender},
   49        oneshot,
   50    },
   51    future::{Shared, try_join_all},
   52};
   53use gpui::{
   54    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   55    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   56    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   57    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   58    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   59    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   60};
   61pub use history_manager::*;
   62pub use item::{
   63    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   64    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   65};
   66use itertools::Itertools;
   67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   68pub use modal_layer::*;
   69use node_runtime::NodeRuntime;
   70use notifications::{
   71    DetachAndPromptErr, Notifications, dismiss_app_notification,
   72    simple_message_notification::MessageNotification,
   73};
   74pub use pane::*;
   75pub use pane_group::{
   76    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   77    SplitDirection,
   78};
   79use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   80pub use persistence::{
   81    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   82    model::{
   83        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   84        SessionWorkspace,
   85    },
   86    read_serialized_multi_workspaces,
   87};
   88use postage::stream::Stream;
   89use project::{
   90    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   91    WorktreeSettings,
   92    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   93    project_settings::ProjectSettings,
   94    toolchain_store::ToolchainStoreEvent,
   95    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   96};
   97use remote::{
   98    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   99    remote_client::ConnectionIdentifier,
  100};
  101use schemars::JsonSchema;
  102use serde::Deserialize;
  103use session::AppSession;
  104use settings::{
  105    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  106};
  107
  108use sqlez::{
  109    bindable::{Bind, Column, StaticColumnCount},
  110    statement::Statement,
  111};
  112use status_bar::StatusBar;
  113pub use status_bar::StatusItemView;
  114use std::{
  115    any::TypeId,
  116    borrow::Cow,
  117    cell::RefCell,
  118    cmp,
  119    collections::VecDeque,
  120    env,
  121    hash::Hash,
  122    path::{Path, PathBuf},
  123    process::ExitStatus,
  124    rc::Rc,
  125    sync::{
  126        Arc, LazyLock, Weak,
  127        atomic::{AtomicBool, AtomicUsize},
  128    },
  129    time::Duration,
  130};
  131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  133pub use toolbar::{
  134    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  135};
  136pub use ui;
  137use ui::{Window, prelude::*};
  138use util::{
  139    ResultExt, TryFutureExt,
  140    paths::{PathStyle, SanitizedPath},
  141    rel_path::RelPath,
  142    serde::default_true,
  143};
  144use uuid::Uuid;
  145pub use workspace_settings::{
  146    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  147    WorkspaceSettings,
  148};
  149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  150
  151use crate::{item::ItemBufferKind, notifications::NotificationId};
  152use crate::{
  153    persistence::{
  154        SerializedAxis,
  155        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  156    },
  157    security_modal::SecurityModal,
  158};
  159
  160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  161
  162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  163    env::var("ZED_WINDOW_SIZE")
  164        .ok()
  165        .as_deref()
  166        .and_then(parse_pixel_size_env_var)
  167});
  168
  169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  170    env::var("ZED_WINDOW_POSITION")
  171        .ok()
  172        .as_deref()
  173        .and_then(parse_pixel_position_env_var)
  174});
  175
  176pub trait TerminalProvider {
  177    fn spawn(
  178        &self,
  179        task: SpawnInTerminal,
  180        window: &mut Window,
  181        cx: &mut App,
  182    ) -> Task<Option<Result<ExitStatus>>>;
  183}
  184
  185pub trait DebuggerProvider {
  186    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  187    fn start_session(
  188        &self,
  189        definition: DebugScenario,
  190        task_context: SharedTaskContext,
  191        active_buffer: Option<Entity<Buffer>>,
  192        worktree_id: Option<WorktreeId>,
  193        window: &mut Window,
  194        cx: &mut App,
  195    );
  196
  197    fn spawn_task_or_modal(
  198        &self,
  199        workspace: &mut Workspace,
  200        action: &Spawn,
  201        window: &mut Window,
  202        cx: &mut Context<Workspace>,
  203    );
  204
  205    fn task_scheduled(&self, cx: &mut App);
  206    fn debug_scenario_scheduled(&self, cx: &mut App);
  207    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  208
  209    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  210}
  211
  212/// Opens a file or directory.
  213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  214#[action(namespace = workspace)]
  215pub struct Open {
  216    /// When true, opens in a new window. When false, adds to the current
  217    /// window as a new workspace (multi-workspace).
  218    #[serde(default = "Open::default_create_new_window")]
  219    pub create_new_window: bool,
  220}
  221
  222impl Open {
  223    pub const DEFAULT: Self = Self {
  224        create_new_window: true,
  225    };
  226
  227    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  228    /// the serde default and `Open::DEFAULT` stay in sync.
  229    fn default_create_new_window() -> bool {
  230        Self::DEFAULT.create_new_window
  231    }
  232}
  233
  234impl Default for Open {
  235    fn default() -> Self {
  236        Self::DEFAULT
  237    }
  238}
  239
  240actions!(
  241    workspace,
  242    [
  243        /// Activates the next pane in the workspace.
  244        ActivateNextPane,
  245        /// Activates the previous pane in the workspace.
  246        ActivatePreviousPane,
  247        /// Activates the last pane in the workspace.
  248        ActivateLastPane,
  249        /// Switches to the next window.
  250        ActivateNextWindow,
  251        /// Switches to the previous window.
  252        ActivatePreviousWindow,
  253        /// Adds a folder to the current project.
  254        AddFolderToProject,
  255        /// Clears all notifications.
  256        ClearAllNotifications,
  257        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  258        ClearNavigationHistory,
  259        /// Closes the active dock.
  260        CloseActiveDock,
  261        /// Closes all docks.
  262        CloseAllDocks,
  263        /// Toggles all docks.
  264        ToggleAllDocks,
  265        /// Closes the current window.
  266        CloseWindow,
  267        /// Closes the current project.
  268        CloseProject,
  269        /// Opens the feedback dialog.
  270        Feedback,
  271        /// Follows the next collaborator in the session.
  272        FollowNextCollaborator,
  273        /// Moves the focused panel to the next position.
  274        MoveFocusedPanelToNextPosition,
  275        /// Creates a new file.
  276        NewFile,
  277        /// Creates a new file in a vertical split.
  278        NewFileSplitVertical,
  279        /// Creates a new file in a horizontal split.
  280        NewFileSplitHorizontal,
  281        /// Opens a new search.
  282        NewSearch,
  283        /// Opens a new window.
  284        NewWindow,
  285        /// Opens multiple files.
  286        OpenFiles,
  287        /// Opens the current location in terminal.
  288        OpenInTerminal,
  289        /// Opens the component preview.
  290        OpenComponentPreview,
  291        /// Reloads the active item.
  292        ReloadActiveItem,
  293        /// Resets the active dock to its default size.
  294        ResetActiveDockSize,
  295        /// Resets all open docks to their default sizes.
  296        ResetOpenDocksSize,
  297        /// Reloads the application
  298        Reload,
  299        /// Saves the current file with a new name.
  300        SaveAs,
  301        /// Saves without formatting.
  302        SaveWithoutFormat,
  303        /// Shuts down all debug adapters.
  304        ShutdownDebugAdapters,
  305        /// Suppresses the current notification.
  306        SuppressNotification,
  307        /// Toggles the bottom dock.
  308        ToggleBottomDock,
  309        /// Toggles centered layout mode.
  310        ToggleCenteredLayout,
  311        /// Toggles edit prediction feature globally for all files.
  312        ToggleEditPrediction,
  313        /// Toggles the left dock.
  314        ToggleLeftDock,
  315        /// Toggles the right dock.
  316        ToggleRightDock,
  317        /// Toggles zoom on the active pane.
  318        ToggleZoom,
  319        /// Toggles read-only mode for the active item (if supported by that item).
  320        ToggleReadOnlyFile,
  321        /// Zooms in on the active pane.
  322        ZoomIn,
  323        /// Zooms out of the active pane.
  324        ZoomOut,
  325        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  326        /// If the modal is shown already, closes it without trusting any worktree.
  327        ToggleWorktreeSecurity,
  328        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  329        /// Requires restart to take effect on already opened projects.
  330        ClearTrustedWorktrees,
  331        /// Stops following a collaborator.
  332        Unfollow,
  333        /// Restores the banner.
  334        RestoreBanner,
  335        /// Toggles expansion of the selected item.
  336        ToggleExpandItem,
  337    ]
  338);
  339
  340/// Activates a specific pane by its index.
  341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  342#[action(namespace = workspace)]
  343pub struct ActivatePane(pub usize);
  344
  345/// Moves an item to a specific pane by index.
  346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348#[serde(deny_unknown_fields)]
  349pub struct MoveItemToPane {
  350    #[serde(default = "default_1")]
  351    pub destination: usize,
  352    #[serde(default = "default_true")]
  353    pub focus: bool,
  354    #[serde(default)]
  355    pub clone: bool,
  356}
  357
  358fn default_1() -> usize {
  359    1
  360}
  361
  362/// Moves an item to a pane in the specified direction.
  363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  364#[action(namespace = workspace)]
  365#[serde(deny_unknown_fields)]
  366pub struct MoveItemToPaneInDirection {
  367    #[serde(default = "default_right")]
  368    pub direction: SplitDirection,
  369    #[serde(default = "default_true")]
  370    pub focus: bool,
  371    #[serde(default)]
  372    pub clone: bool,
  373}
  374
  375/// Creates a new file in a split of the desired direction.
  376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  377#[action(namespace = workspace)]
  378#[serde(deny_unknown_fields)]
  379pub struct NewFileSplit(pub SplitDirection);
  380
  381fn default_right() -> SplitDirection {
  382    SplitDirection::Right
  383}
  384
  385/// Saves all open files in the workspace.
  386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  387#[action(namespace = workspace)]
  388#[serde(deny_unknown_fields)]
  389pub struct SaveAll {
  390    #[serde(default)]
  391    pub save_intent: Option<SaveIntent>,
  392}
  393
  394/// Saves the current file with the specified options.
  395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  396#[action(namespace = workspace)]
  397#[serde(deny_unknown_fields)]
  398pub struct Save {
  399    #[serde(default)]
  400    pub save_intent: Option<SaveIntent>,
  401}
  402
  403/// Closes all items and panes in the workspace.
  404#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  405#[action(namespace = workspace)]
  406#[serde(deny_unknown_fields)]
  407pub struct CloseAllItemsAndPanes {
  408    #[serde(default)]
  409    pub save_intent: Option<SaveIntent>,
  410}
  411
  412/// Closes all inactive tabs and panes in the workspace.
  413#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  414#[action(namespace = workspace)]
  415#[serde(deny_unknown_fields)]
  416pub struct CloseInactiveTabsAndPanes {
  417    #[serde(default)]
  418    pub save_intent: Option<SaveIntent>,
  419}
  420
  421/// Closes the active item across all panes.
  422#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  423#[action(namespace = workspace)]
  424#[serde(deny_unknown_fields)]
  425pub struct CloseItemInAllPanes {
  426    #[serde(default)]
  427    pub save_intent: Option<SaveIntent>,
  428    #[serde(default)]
  429    pub close_pinned: bool,
  430}
  431
  432/// Sends a sequence of keystrokes to the active element.
  433#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  434#[action(namespace = workspace)]
  435pub struct SendKeystrokes(pub String);
  436
  437actions!(
  438    project_symbols,
  439    [
  440        /// Toggles the project symbols search.
  441        #[action(name = "Toggle")]
  442        ToggleProjectSymbols
  443    ]
  444);
  445
  446/// Toggles the file finder interface.
  447#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  448#[action(namespace = file_finder, name = "Toggle")]
  449#[serde(deny_unknown_fields)]
  450pub struct ToggleFileFinder {
  451    #[serde(default)]
  452    pub separate_history: bool,
  453}
  454
  455/// Opens a new terminal in the center.
  456#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  457#[action(namespace = workspace)]
  458#[serde(deny_unknown_fields)]
  459pub struct NewCenterTerminal {
  460    /// If true, creates a local terminal even in remote projects.
  461    #[serde(default)]
  462    pub local: bool,
  463}
  464
  465/// Opens a new terminal.
  466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  467#[action(namespace = workspace)]
  468#[serde(deny_unknown_fields)]
  469pub struct NewTerminal {
  470    /// If true, creates a local terminal even in remote projects.
  471    #[serde(default)]
  472    pub local: bool,
  473}
  474
  475/// Increases size of a currently focused dock by a given amount of pixels.
  476#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  477#[action(namespace = workspace)]
  478#[serde(deny_unknown_fields)]
  479pub struct IncreaseActiveDockSize {
  480    /// For 0px parameter, uses UI font size value.
  481    #[serde(default)]
  482    pub px: u32,
  483}
  484
  485/// Decreases size of a currently focused dock by a given amount of pixels.
  486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  487#[action(namespace = workspace)]
  488#[serde(deny_unknown_fields)]
  489pub struct DecreaseActiveDockSize {
  490    /// For 0px parameter, uses UI font size value.
  491    #[serde(default)]
  492    pub px: u32,
  493}
  494
  495/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  497#[action(namespace = workspace)]
  498#[serde(deny_unknown_fields)]
  499pub struct IncreaseOpenDocksSize {
  500    /// For 0px parameter, uses UI font size value.
  501    #[serde(default)]
  502    pub px: u32,
  503}
  504
  505/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  507#[action(namespace = workspace)]
  508#[serde(deny_unknown_fields)]
  509pub struct DecreaseOpenDocksSize {
  510    /// For 0px parameter, uses UI font size value.
  511    #[serde(default)]
  512    pub px: u32,
  513}
  514
  515actions!(
  516    workspace,
  517    [
  518        /// Activates the pane to the left.
  519        ActivatePaneLeft,
  520        /// Activates the pane to the right.
  521        ActivatePaneRight,
  522        /// Activates the pane above.
  523        ActivatePaneUp,
  524        /// Activates the pane below.
  525        ActivatePaneDown,
  526        /// Swaps the current pane with the one to the left.
  527        SwapPaneLeft,
  528        /// Swaps the current pane with the one to the right.
  529        SwapPaneRight,
  530        /// Swaps the current pane with the one above.
  531        SwapPaneUp,
  532        /// Swaps the current pane with the one below.
  533        SwapPaneDown,
  534        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  535        SwapPaneAdjacent,
  536        /// Move the current pane to be at the far left.
  537        MovePaneLeft,
  538        /// Move the current pane to be at the far right.
  539        MovePaneRight,
  540        /// Move the current pane to be at the very top.
  541        MovePaneUp,
  542        /// Move the current pane to be at the very bottom.
  543        MovePaneDown,
  544    ]
  545);
  546
  547#[derive(PartialEq, Eq, Debug)]
  548pub enum CloseIntent {
  549    /// Quit the program entirely.
  550    Quit,
  551    /// Close a window.
  552    CloseWindow,
  553    /// Replace the workspace in an existing window.
  554    ReplaceWindow,
  555}
  556
  557#[derive(Clone)]
  558pub struct Toast {
  559    id: NotificationId,
  560    msg: Cow<'static, str>,
  561    autohide: bool,
  562    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  563}
  564
  565impl Toast {
  566    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  567        Toast {
  568            id,
  569            msg: msg.into(),
  570            on_click: None,
  571            autohide: false,
  572        }
  573    }
  574
  575    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  576    where
  577        M: Into<Cow<'static, str>>,
  578        F: Fn(&mut Window, &mut App) + 'static,
  579    {
  580        self.on_click = Some((message.into(), Arc::new(on_click)));
  581        self
  582    }
  583
  584    pub fn autohide(mut self) -> Self {
  585        self.autohide = true;
  586        self
  587    }
  588}
  589
  590impl PartialEq for Toast {
  591    fn eq(&self, other: &Self) -> bool {
  592        self.id == other.id
  593            && self.msg == other.msg
  594            && self.on_click.is_some() == other.on_click.is_some()
  595    }
  596}
  597
  598/// Opens a new terminal with the specified working directory.
  599#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  600#[action(namespace = workspace)]
  601#[serde(deny_unknown_fields)]
  602pub struct OpenTerminal {
  603    pub working_directory: PathBuf,
  604    /// If true, creates a local terminal even in remote projects.
  605    #[serde(default)]
  606    pub local: bool,
  607}
  608
  609#[derive(
  610    Clone,
  611    Copy,
  612    Debug,
  613    Default,
  614    Hash,
  615    PartialEq,
  616    Eq,
  617    PartialOrd,
  618    Ord,
  619    serde::Serialize,
  620    serde::Deserialize,
  621)]
  622pub struct WorkspaceId(i64);
  623
  624impl WorkspaceId {
  625    pub fn from_i64(value: i64) -> Self {
  626        Self(value)
  627    }
  628}
  629
  630impl StaticColumnCount for WorkspaceId {}
  631impl Bind for WorkspaceId {
  632    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  633        self.0.bind(statement, start_index)
  634    }
  635}
  636impl Column for WorkspaceId {
  637    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  638        i64::column(statement, start_index)
  639            .map(|(i, next_index)| (Self(i), next_index))
  640            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  641    }
  642}
  643impl From<WorkspaceId> for i64 {
  644    fn from(val: WorkspaceId) -> Self {
  645        val.0
  646    }
  647}
  648
  649fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  650    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  651        workspace_window
  652            .update(cx, |multi_workspace, window, cx| {
  653                let workspace = multi_workspace.workspace().clone();
  654                workspace.update(cx, |workspace, cx| {
  655                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  656                });
  657            })
  658            .ok();
  659    } else {
  660        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  661        cx.spawn(async move |cx| {
  662            let OpenResult { window, .. } = task.await?;
  663            window.update(cx, |multi_workspace, window, cx| {
  664                window.activate_window();
  665                let workspace = multi_workspace.workspace().clone();
  666                workspace.update(cx, |workspace, cx| {
  667                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  668                });
  669            })?;
  670            anyhow::Ok(())
  671        })
  672        .detach_and_log_err(cx);
  673    }
  674}
  675
  676pub fn prompt_for_open_path_and_open(
  677    workspace: &mut Workspace,
  678    app_state: Arc<AppState>,
  679    options: PathPromptOptions,
  680    create_new_window: bool,
  681    window: &mut Window,
  682    cx: &mut Context<Workspace>,
  683) {
  684    let paths = workspace.prompt_for_open_path(
  685        options,
  686        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  687        window,
  688        cx,
  689    );
  690    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  691    cx.spawn_in(window, async move |this, cx| {
  692        let Some(paths) = paths.await.log_err().flatten() else {
  693            return;
  694        };
  695        if !create_new_window {
  696            if let Some(handle) = multi_workspace_handle {
  697                if let Some(task) = handle
  698                    .update(cx, |multi_workspace, window, cx| {
  699                        multi_workspace.open_project(paths, window, cx)
  700                    })
  701                    .log_err()
  702                {
  703                    task.await.log_err();
  704                }
  705                return;
  706            }
  707        }
  708        if let Some(task) = this
  709            .update_in(cx, |this, window, cx| {
  710                this.open_workspace_for_paths(false, paths, window, cx)
  711            })
  712            .log_err()
  713        {
  714            task.await.log_err();
  715        }
  716    })
  717    .detach();
  718}
  719
  720pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  721    component::init();
  722    theme_preview::init(cx);
  723    toast_layer::init(cx);
  724    history_manager::init(app_state.fs.clone(), cx);
  725
  726    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  727        .on_action(|_: &Reload, cx| reload(cx))
  728        .on_action({
  729            let app_state = Arc::downgrade(&app_state);
  730            move |_: &Open, cx: &mut App| {
  731                if let Some(app_state) = app_state.upgrade() {
  732                    prompt_and_open_paths(
  733                        app_state,
  734                        PathPromptOptions {
  735                            files: true,
  736                            directories: true,
  737                            multiple: true,
  738                            prompt: None,
  739                        },
  740                        cx,
  741                    );
  742                }
  743            }
  744        })
  745        .on_action({
  746            let app_state = Arc::downgrade(&app_state);
  747            move |_: &OpenFiles, cx: &mut App| {
  748                let directories = cx.can_select_mixed_files_and_dirs();
  749                if let Some(app_state) = app_state.upgrade() {
  750                    prompt_and_open_paths(
  751                        app_state,
  752                        PathPromptOptions {
  753                            files: true,
  754                            directories,
  755                            multiple: true,
  756                            prompt: None,
  757                        },
  758                        cx,
  759                    );
  760                }
  761            }
  762        });
  763}
  764
  765type BuildProjectItemFn =
  766    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  767
  768type BuildProjectItemForPathFn =
  769    fn(
  770        &Entity<Project>,
  771        &ProjectPath,
  772        &mut Window,
  773        &mut App,
  774    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  775
  776#[derive(Clone, Default)]
  777struct ProjectItemRegistry {
  778    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  779    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  780}
  781
  782impl ProjectItemRegistry {
  783    fn register<T: ProjectItem>(&mut self) {
  784        self.build_project_item_fns_by_type.insert(
  785            TypeId::of::<T::Item>(),
  786            |item, project, pane, window, cx| {
  787                let item = item.downcast().unwrap();
  788                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  789                    as Box<dyn ItemHandle>
  790            },
  791        );
  792        self.build_project_item_for_path_fns
  793            .push(|project, project_path, window, cx| {
  794                let project_path = project_path.clone();
  795                let is_file = project
  796                    .read(cx)
  797                    .entry_for_path(&project_path, cx)
  798                    .is_some_and(|entry| entry.is_file());
  799                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  800                let is_local = project.read(cx).is_local();
  801                let project_item =
  802                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  803                let project = project.clone();
  804                Some(window.spawn(cx, async move |cx| {
  805                    match project_item.await.with_context(|| {
  806                        format!(
  807                            "opening project path {:?}",
  808                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  809                        )
  810                    }) {
  811                        Ok(project_item) => {
  812                            let project_item = project_item;
  813                            let project_entry_id: Option<ProjectEntryId> =
  814                                project_item.read_with(cx, project::ProjectItem::entry_id);
  815                            let build_workspace_item = Box::new(
  816                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  817                                    Box::new(cx.new(|cx| {
  818                                        T::for_project_item(
  819                                            project,
  820                                            Some(pane),
  821                                            project_item,
  822                                            window,
  823                                            cx,
  824                                        )
  825                                    })) as Box<dyn ItemHandle>
  826                                },
  827                            ) as Box<_>;
  828                            Ok((project_entry_id, build_workspace_item))
  829                        }
  830                        Err(e) => {
  831                            log::warn!("Failed to open a project item: {e:#}");
  832                            if e.error_code() == ErrorCode::Internal {
  833                                if let Some(abs_path) =
  834                                    entry_abs_path.as_deref().filter(|_| is_file)
  835                                {
  836                                    if let Some(broken_project_item_view) =
  837                                        cx.update(|window, cx| {
  838                                            T::for_broken_project_item(
  839                                                abs_path, is_local, &e, window, cx,
  840                                            )
  841                                        })?
  842                                    {
  843                                        let build_workspace_item = Box::new(
  844                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  845                                                cx.new(|_| broken_project_item_view).boxed_clone()
  846                                            },
  847                                        )
  848                                        as Box<_>;
  849                                        return Ok((None, build_workspace_item));
  850                                    }
  851                                }
  852                            }
  853                            Err(e)
  854                        }
  855                    }
  856                }))
  857            });
  858    }
  859
  860    fn open_path(
  861        &self,
  862        project: &Entity<Project>,
  863        path: &ProjectPath,
  864        window: &mut Window,
  865        cx: &mut App,
  866    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  867        let Some(open_project_item) = self
  868            .build_project_item_for_path_fns
  869            .iter()
  870            .rev()
  871            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  872        else {
  873            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  874        };
  875        open_project_item
  876    }
  877
  878    fn build_item<T: project::ProjectItem>(
  879        &self,
  880        item: Entity<T>,
  881        project: Entity<Project>,
  882        pane: Option<&Pane>,
  883        window: &mut Window,
  884        cx: &mut App,
  885    ) -> Option<Box<dyn ItemHandle>> {
  886        let build = self
  887            .build_project_item_fns_by_type
  888            .get(&TypeId::of::<T>())?;
  889        Some(build(item.into_any(), project, pane, window, cx))
  890    }
  891}
  892
  893type WorkspaceItemBuilder =
  894    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  895
  896impl Global for ProjectItemRegistry {}
  897
  898/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  899/// items will get a chance to open the file, starting from the project item that
  900/// was added last.
  901pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  902    cx.default_global::<ProjectItemRegistry>().register::<I>();
  903}
  904
  905#[derive(Default)]
  906pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  907
  908struct FollowableViewDescriptor {
  909    from_state_proto: fn(
  910        Entity<Workspace>,
  911        ViewId,
  912        &mut Option<proto::view::Variant>,
  913        &mut Window,
  914        &mut App,
  915    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  916    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  917}
  918
  919impl Global for FollowableViewRegistry {}
  920
  921impl FollowableViewRegistry {
  922    pub fn register<I: FollowableItem>(cx: &mut App) {
  923        cx.default_global::<Self>().0.insert(
  924            TypeId::of::<I>(),
  925            FollowableViewDescriptor {
  926                from_state_proto: |workspace, id, state, window, cx| {
  927                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  928                        cx.foreground_executor()
  929                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  930                    })
  931                },
  932                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  933            },
  934        );
  935    }
  936
  937    pub fn from_state_proto(
  938        workspace: Entity<Workspace>,
  939        view_id: ViewId,
  940        mut state: Option<proto::view::Variant>,
  941        window: &mut Window,
  942        cx: &mut App,
  943    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  944        cx.update_default_global(|this: &mut Self, cx| {
  945            this.0.values().find_map(|descriptor| {
  946                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  947            })
  948        })
  949    }
  950
  951    pub fn to_followable_view(
  952        view: impl Into<AnyView>,
  953        cx: &App,
  954    ) -> Option<Box<dyn FollowableItemHandle>> {
  955        let this = cx.try_global::<Self>()?;
  956        let view = view.into();
  957        let descriptor = this.0.get(&view.entity_type())?;
  958        Some((descriptor.to_followable_view)(&view))
  959    }
  960}
  961
  962#[derive(Copy, Clone)]
  963struct SerializableItemDescriptor {
  964    deserialize: fn(
  965        Entity<Project>,
  966        WeakEntity<Workspace>,
  967        WorkspaceId,
  968        ItemId,
  969        &mut Window,
  970        &mut Context<Pane>,
  971    ) -> Task<Result<Box<dyn ItemHandle>>>,
  972    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  973    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  974}
  975
  976#[derive(Default)]
  977struct SerializableItemRegistry {
  978    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  979    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  980}
  981
  982impl Global for SerializableItemRegistry {}
  983
  984impl SerializableItemRegistry {
  985    fn deserialize(
  986        item_kind: &str,
  987        project: Entity<Project>,
  988        workspace: WeakEntity<Workspace>,
  989        workspace_id: WorkspaceId,
  990        item_item: ItemId,
  991        window: &mut Window,
  992        cx: &mut Context<Pane>,
  993    ) -> Task<Result<Box<dyn ItemHandle>>> {
  994        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  995            return Task::ready(Err(anyhow!(
  996                "cannot deserialize {}, descriptor not found",
  997                item_kind
  998            )));
  999        };
 1000
 1001        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1002    }
 1003
 1004    fn cleanup(
 1005        item_kind: &str,
 1006        workspace_id: WorkspaceId,
 1007        loaded_items: Vec<ItemId>,
 1008        window: &mut Window,
 1009        cx: &mut App,
 1010    ) -> Task<Result<()>> {
 1011        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1012            return Task::ready(Err(anyhow!(
 1013                "cannot cleanup {}, descriptor not found",
 1014                item_kind
 1015            )));
 1016        };
 1017
 1018        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1019    }
 1020
 1021    fn view_to_serializable_item_handle(
 1022        view: AnyView,
 1023        cx: &App,
 1024    ) -> Option<Box<dyn SerializableItemHandle>> {
 1025        let this = cx.try_global::<Self>()?;
 1026        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1027        Some((descriptor.view_to_serializable_item)(view))
 1028    }
 1029
 1030    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1031        let this = cx.try_global::<Self>()?;
 1032        this.descriptors_by_kind.get(item_kind).copied()
 1033    }
 1034}
 1035
 1036pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1037    let serialized_item_kind = I::serialized_item_kind();
 1038
 1039    let registry = cx.default_global::<SerializableItemRegistry>();
 1040    let descriptor = SerializableItemDescriptor {
 1041        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1042            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1043            cx.foreground_executor()
 1044                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1045        },
 1046        cleanup: |workspace_id, loaded_items, window, cx| {
 1047            I::cleanup(workspace_id, loaded_items, window, cx)
 1048        },
 1049        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1050    };
 1051    registry
 1052        .descriptors_by_kind
 1053        .insert(Arc::from(serialized_item_kind), descriptor);
 1054    registry
 1055        .descriptors_by_type
 1056        .insert(TypeId::of::<I>(), descriptor);
 1057}
 1058
 1059pub struct AppState {
 1060    pub languages: Arc<LanguageRegistry>,
 1061    pub client: Arc<Client>,
 1062    pub user_store: Entity<UserStore>,
 1063    pub workspace_store: Entity<WorkspaceStore>,
 1064    pub fs: Arc<dyn fs::Fs>,
 1065    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1066    pub node_runtime: NodeRuntime,
 1067    pub session: Entity<AppSession>,
 1068}
 1069
 1070struct GlobalAppState(Weak<AppState>);
 1071
 1072impl Global for GlobalAppState {}
 1073
 1074pub struct WorkspaceStore {
 1075    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1076    client: Arc<Client>,
 1077    _subscriptions: Vec<client::Subscription>,
 1078}
 1079
 1080#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1081pub enum CollaboratorId {
 1082    PeerId(PeerId),
 1083    Agent,
 1084}
 1085
 1086impl From<PeerId> for CollaboratorId {
 1087    fn from(peer_id: PeerId) -> Self {
 1088        CollaboratorId::PeerId(peer_id)
 1089    }
 1090}
 1091
 1092impl From<&PeerId> for CollaboratorId {
 1093    fn from(peer_id: &PeerId) -> Self {
 1094        CollaboratorId::PeerId(*peer_id)
 1095    }
 1096}
 1097
 1098#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1099struct Follower {
 1100    project_id: Option<u64>,
 1101    peer_id: PeerId,
 1102}
 1103
 1104impl AppState {
 1105    #[track_caller]
 1106    pub fn global(cx: &App) -> Weak<Self> {
 1107        cx.global::<GlobalAppState>().0.clone()
 1108    }
 1109    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1110        cx.try_global::<GlobalAppState>()
 1111            .map(|state| state.0.clone())
 1112    }
 1113    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1114        cx.set_global(GlobalAppState(state));
 1115    }
 1116
 1117    #[cfg(any(test, feature = "test-support"))]
 1118    pub fn test(cx: &mut App) -> Arc<Self> {
 1119        use fs::Fs;
 1120        use node_runtime::NodeRuntime;
 1121        use session::Session;
 1122        use settings::SettingsStore;
 1123
 1124        if !cx.has_global::<SettingsStore>() {
 1125            let settings_store = SettingsStore::test(cx);
 1126            cx.set_global(settings_store);
 1127        }
 1128
 1129        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1130        <dyn Fs>::set_global(fs.clone(), cx);
 1131        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1132        let clock = Arc::new(clock::FakeSystemClock::new());
 1133        let http_client = http_client::FakeHttpClient::with_404_response();
 1134        let client = Client::new(clock, http_client, cx);
 1135        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1136        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1137        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1138
 1139        theme::init(theme::LoadThemes::JustBase, cx);
 1140        client::init(&client, cx);
 1141
 1142        Arc::new(Self {
 1143            client,
 1144            fs,
 1145            languages,
 1146            user_store,
 1147            workspace_store,
 1148            node_runtime: NodeRuntime::unavailable(),
 1149            build_window_options: |_, _| Default::default(),
 1150            session,
 1151        })
 1152    }
 1153}
 1154
 1155struct DelayedDebouncedEditAction {
 1156    task: Option<Task<()>>,
 1157    cancel_channel: Option<oneshot::Sender<()>>,
 1158}
 1159
 1160impl DelayedDebouncedEditAction {
 1161    fn new() -> DelayedDebouncedEditAction {
 1162        DelayedDebouncedEditAction {
 1163            task: None,
 1164            cancel_channel: None,
 1165        }
 1166    }
 1167
 1168    fn fire_new<F>(
 1169        &mut self,
 1170        delay: Duration,
 1171        window: &mut Window,
 1172        cx: &mut Context<Workspace>,
 1173        func: F,
 1174    ) where
 1175        F: 'static
 1176            + Send
 1177            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1178    {
 1179        if let Some(channel) = self.cancel_channel.take() {
 1180            _ = channel.send(());
 1181        }
 1182
 1183        let (sender, mut receiver) = oneshot::channel::<()>();
 1184        self.cancel_channel = Some(sender);
 1185
 1186        let previous_task = self.task.take();
 1187        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1188            let mut timer = cx.background_executor().timer(delay).fuse();
 1189            if let Some(previous_task) = previous_task {
 1190                previous_task.await;
 1191            }
 1192
 1193            futures::select_biased! {
 1194                _ = receiver => return,
 1195                    _ = timer => {}
 1196            }
 1197
 1198            if let Some(result) = workspace
 1199                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1200                .log_err()
 1201            {
 1202                result.await.log_err();
 1203            }
 1204        }));
 1205    }
 1206}
 1207
 1208pub enum Event {
 1209    PaneAdded(Entity<Pane>),
 1210    PaneRemoved,
 1211    ItemAdded {
 1212        item: Box<dyn ItemHandle>,
 1213    },
 1214    ActiveItemChanged,
 1215    ItemRemoved {
 1216        item_id: EntityId,
 1217    },
 1218    UserSavedItem {
 1219        pane: WeakEntity<Pane>,
 1220        item: Box<dyn WeakItemHandle>,
 1221        save_intent: SaveIntent,
 1222    },
 1223    ContactRequestedJoin(u64),
 1224    WorkspaceCreated(WeakEntity<Workspace>),
 1225    OpenBundledFile {
 1226        text: Cow<'static, str>,
 1227        title: &'static str,
 1228        language: &'static str,
 1229    },
 1230    ZoomChanged,
 1231    ModalOpened,
 1232    Activate,
 1233    PanelAdded(AnyView),
 1234}
 1235
 1236#[derive(Debug, Clone)]
 1237pub enum OpenVisible {
 1238    All,
 1239    None,
 1240    OnlyFiles,
 1241    OnlyDirectories,
 1242}
 1243
 1244enum WorkspaceLocation {
 1245    // Valid local paths or SSH project to serialize
 1246    Location(SerializedWorkspaceLocation, PathList),
 1247    // No valid location found hence clear session id
 1248    DetachFromSession,
 1249    // No valid location found to serialize
 1250    None,
 1251}
 1252
 1253type PromptForNewPath = Box<
 1254    dyn Fn(
 1255        &mut Workspace,
 1256        DirectoryLister,
 1257        Option<String>,
 1258        &mut Window,
 1259        &mut Context<Workspace>,
 1260    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1261>;
 1262
 1263type PromptForOpenPath = Box<
 1264    dyn Fn(
 1265        &mut Workspace,
 1266        DirectoryLister,
 1267        &mut Window,
 1268        &mut Context<Workspace>,
 1269    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1270>;
 1271
 1272#[derive(Default)]
 1273struct DispatchingKeystrokes {
 1274    dispatched: HashSet<Vec<Keystroke>>,
 1275    queue: VecDeque<Keystroke>,
 1276    task: Option<Shared<Task<()>>>,
 1277}
 1278
 1279/// Collects everything project-related for a certain window opened.
 1280/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1281///
 1282/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1283/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1284/// that can be used to register a global action to be triggered from any place in the window.
 1285pub struct Workspace {
 1286    weak_self: WeakEntity<Self>,
 1287    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1288    zoomed: Option<AnyWeakView>,
 1289    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1290    zoomed_position: Option<DockPosition>,
 1291    center: PaneGroup,
 1292    left_dock: Entity<Dock>,
 1293    bottom_dock: Entity<Dock>,
 1294    right_dock: Entity<Dock>,
 1295    panes: Vec<Entity<Pane>>,
 1296    active_worktree_override: Option<WorktreeId>,
 1297    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1298    active_pane: Entity<Pane>,
 1299    last_active_center_pane: Option<WeakEntity<Pane>>,
 1300    last_active_view_id: Option<proto::ViewId>,
 1301    status_bar: Entity<StatusBar>,
 1302    pub(crate) modal_layer: Entity<ModalLayer>,
 1303    toast_layer: Entity<ToastLayer>,
 1304    titlebar_item: Option<AnyView>,
 1305    notifications: Notifications,
 1306    suppressed_notifications: HashSet<NotificationId>,
 1307    project: Entity<Project>,
 1308    follower_states: HashMap<CollaboratorId, FollowerState>,
 1309    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1310    window_edited: bool,
 1311    last_window_title: Option<String>,
 1312    dirty_items: HashMap<EntityId, Subscription>,
 1313    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1314    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1315    database_id: Option<WorkspaceId>,
 1316    app_state: Arc<AppState>,
 1317    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1318    _subscriptions: Vec<Subscription>,
 1319    _apply_leader_updates: Task<Result<()>>,
 1320    _observe_current_user: Task<Result<()>>,
 1321    _schedule_serialize_workspace: Option<Task<()>>,
 1322    _serialize_workspace_task: Option<Task<()>>,
 1323    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1324    pane_history_timestamp: Arc<AtomicUsize>,
 1325    bounds: Bounds<Pixels>,
 1326    pub centered_layout: bool,
 1327    bounds_save_task_queued: Option<Task<()>>,
 1328    on_prompt_for_new_path: Option<PromptForNewPath>,
 1329    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1330    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1331    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1332    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1333    _items_serializer: Task<Result<()>>,
 1334    session_id: Option<String>,
 1335    scheduled_tasks: Vec<Task<()>>,
 1336    last_open_dock_positions: Vec<DockPosition>,
 1337    removing: bool,
 1338    _panels_task: Option<Task<Result<()>>>,
 1339}
 1340
 1341impl EventEmitter<Event> for Workspace {}
 1342
 1343#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1344pub struct ViewId {
 1345    pub creator: CollaboratorId,
 1346    pub id: u64,
 1347}
 1348
 1349pub struct FollowerState {
 1350    center_pane: Entity<Pane>,
 1351    dock_pane: Option<Entity<Pane>>,
 1352    active_view_id: Option<ViewId>,
 1353    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1354}
 1355
 1356struct FollowerView {
 1357    view: Box<dyn FollowableItemHandle>,
 1358    location: Option<proto::PanelId>,
 1359}
 1360
 1361impl Workspace {
 1362    pub fn new(
 1363        workspace_id: Option<WorkspaceId>,
 1364        project: Entity<Project>,
 1365        app_state: Arc<AppState>,
 1366        window: &mut Window,
 1367        cx: &mut Context<Self>,
 1368    ) -> Self {
 1369        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1370            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1371                if let TrustedWorktreesEvent::Trusted(..) = e {
 1372                    // Do not persist auto trusted worktrees
 1373                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1374                        worktrees_store.update(cx, |worktrees_store, cx| {
 1375                            worktrees_store.schedule_serialization(
 1376                                cx,
 1377                                |new_trusted_worktrees, cx| {
 1378                                    let timeout =
 1379                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1380                                    cx.background_spawn(async move {
 1381                                        timeout.await;
 1382                                        persistence::DB
 1383                                            .save_trusted_worktrees(new_trusted_worktrees)
 1384                                            .await
 1385                                            .log_err();
 1386                                    })
 1387                                },
 1388                            )
 1389                        });
 1390                    }
 1391                }
 1392            })
 1393            .detach();
 1394
 1395            cx.observe_global::<SettingsStore>(|_, cx| {
 1396                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1397                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1398                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1399                            trusted_worktrees.auto_trust_all(cx);
 1400                        })
 1401                    }
 1402                }
 1403            })
 1404            .detach();
 1405        }
 1406
 1407        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1408            match event {
 1409                project::Event::RemoteIdChanged(_) => {
 1410                    this.update_window_title(window, cx);
 1411                }
 1412
 1413                project::Event::CollaboratorLeft(peer_id) => {
 1414                    this.collaborator_left(*peer_id, window, cx);
 1415                }
 1416
 1417                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1418                    this.update_window_title(window, cx);
 1419                    if this
 1420                        .project()
 1421                        .read(cx)
 1422                        .worktree_for_id(id, cx)
 1423                        .is_some_and(|wt| wt.read(cx).is_visible())
 1424                    {
 1425                        this.serialize_workspace(window, cx);
 1426                        this.update_history(cx);
 1427                    }
 1428                }
 1429                project::Event::WorktreeUpdatedEntries(..) => {
 1430                    this.update_window_title(window, cx);
 1431                    this.serialize_workspace(window, cx);
 1432                }
 1433
 1434                project::Event::DisconnectedFromHost => {
 1435                    this.update_window_edited(window, cx);
 1436                    let leaders_to_unfollow =
 1437                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1438                    for leader_id in leaders_to_unfollow {
 1439                        this.unfollow(leader_id, window, cx);
 1440                    }
 1441                }
 1442
 1443                project::Event::DisconnectedFromRemote {
 1444                    server_not_running: _,
 1445                } => {
 1446                    this.update_window_edited(window, cx);
 1447                }
 1448
 1449                project::Event::Closed => {
 1450                    window.remove_window();
 1451                }
 1452
 1453                project::Event::DeletedEntry(_, entry_id) => {
 1454                    for pane in this.panes.iter() {
 1455                        pane.update(cx, |pane, cx| {
 1456                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1457                        });
 1458                    }
 1459                }
 1460
 1461                project::Event::Toast {
 1462                    notification_id,
 1463                    message,
 1464                    link,
 1465                } => this.show_notification(
 1466                    NotificationId::named(notification_id.clone()),
 1467                    cx,
 1468                    |cx| {
 1469                        let mut notification = MessageNotification::new(message.clone(), cx);
 1470                        if let Some(link) = link {
 1471                            notification = notification
 1472                                .more_info_message(link.label)
 1473                                .more_info_url(link.url);
 1474                        }
 1475
 1476                        cx.new(|_| notification)
 1477                    },
 1478                ),
 1479
 1480                project::Event::HideToast { notification_id } => {
 1481                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1482                }
 1483
 1484                project::Event::LanguageServerPrompt(request) => {
 1485                    struct LanguageServerPrompt;
 1486
 1487                    this.show_notification(
 1488                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1489                        cx,
 1490                        |cx| {
 1491                            cx.new(|cx| {
 1492                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1493                            })
 1494                        },
 1495                    );
 1496                }
 1497
 1498                project::Event::AgentLocationChanged => {
 1499                    this.handle_agent_location_changed(window, cx)
 1500                }
 1501
 1502                _ => {}
 1503            }
 1504            cx.notify()
 1505        })
 1506        .detach();
 1507
 1508        cx.subscribe_in(
 1509            &project.read(cx).breakpoint_store(),
 1510            window,
 1511            |workspace, _, event, window, cx| match event {
 1512                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1513                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1514                    workspace.serialize_workspace(window, cx);
 1515                }
 1516                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1517            },
 1518        )
 1519        .detach();
 1520        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1521            cx.subscribe_in(
 1522                &toolchain_store,
 1523                window,
 1524                |workspace, _, event, window, cx| match event {
 1525                    ToolchainStoreEvent::CustomToolchainsModified => {
 1526                        workspace.serialize_workspace(window, cx);
 1527                    }
 1528                    _ => {}
 1529                },
 1530            )
 1531            .detach();
 1532        }
 1533
 1534        cx.on_focus_lost(window, |this, window, cx| {
 1535            let focus_handle = this.focus_handle(cx);
 1536            window.focus(&focus_handle, cx);
 1537        })
 1538        .detach();
 1539
 1540        let weak_handle = cx.entity().downgrade();
 1541        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1542
 1543        let center_pane = cx.new(|cx| {
 1544            let mut center_pane = Pane::new(
 1545                weak_handle.clone(),
 1546                project.clone(),
 1547                pane_history_timestamp.clone(),
 1548                None,
 1549                NewFile.boxed_clone(),
 1550                true,
 1551                window,
 1552                cx,
 1553            );
 1554            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1555            center_pane.set_should_display_welcome_page(true);
 1556            center_pane
 1557        });
 1558        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1559            .detach();
 1560
 1561        window.focus(&center_pane.focus_handle(cx), cx);
 1562
 1563        cx.emit(Event::PaneAdded(center_pane.clone()));
 1564
 1565        let any_window_handle = window.window_handle();
 1566        app_state.workspace_store.update(cx, |store, _| {
 1567            store
 1568                .workspaces
 1569                .insert((any_window_handle, weak_handle.clone()));
 1570        });
 1571
 1572        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1573        let mut connection_status = app_state.client.status();
 1574        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1575            current_user.next().await;
 1576            connection_status.next().await;
 1577            let mut stream =
 1578                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1579
 1580            while stream.recv().await.is_some() {
 1581                this.update(cx, |_, cx| cx.notify())?;
 1582            }
 1583            anyhow::Ok(())
 1584        });
 1585
 1586        // All leader updates are enqueued and then processed in a single task, so
 1587        // that each asynchronous operation can be run in order.
 1588        let (leader_updates_tx, mut leader_updates_rx) =
 1589            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1590        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1591            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1592                Self::process_leader_update(&this, leader_id, update, cx)
 1593                    .await
 1594                    .log_err();
 1595            }
 1596
 1597            Ok(())
 1598        });
 1599
 1600        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1601        let modal_layer = cx.new(|_| ModalLayer::new());
 1602        let toast_layer = cx.new(|_| ToastLayer::new());
 1603        cx.subscribe(
 1604            &modal_layer,
 1605            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1606                cx.emit(Event::ModalOpened);
 1607            },
 1608        )
 1609        .detach();
 1610
 1611        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1612        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1613        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1614        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1615        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1616        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1617        let status_bar = cx.new(|cx| {
 1618            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1619            status_bar.add_left_item(left_dock_buttons, window, cx);
 1620            status_bar.add_right_item(right_dock_buttons, window, cx);
 1621            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1622            status_bar
 1623        });
 1624
 1625        let session_id = app_state.session.read(cx).id().to_owned();
 1626
 1627        let mut active_call = None;
 1628        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1629            let subscriptions =
 1630                vec![
 1631                    call.0
 1632                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1633                ];
 1634            active_call = Some((call, subscriptions));
 1635        }
 1636
 1637        let (serializable_items_tx, serializable_items_rx) =
 1638            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1639        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1640            Self::serialize_items(&this, serializable_items_rx, cx).await
 1641        });
 1642
 1643        let subscriptions = vec![
 1644            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1645            cx.observe_window_bounds(window, move |this, window, cx| {
 1646                if this.bounds_save_task_queued.is_some() {
 1647                    return;
 1648                }
 1649                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1650                    cx.background_executor()
 1651                        .timer(Duration::from_millis(100))
 1652                        .await;
 1653                    this.update_in(cx, |this, window, cx| {
 1654                        this.save_window_bounds(window, cx).detach();
 1655                        this.bounds_save_task_queued.take();
 1656                    })
 1657                    .ok();
 1658                }));
 1659                cx.notify();
 1660            }),
 1661            cx.observe_window_appearance(window, |_, window, cx| {
 1662                let window_appearance = window.appearance();
 1663
 1664                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1665
 1666                GlobalTheme::reload_theme(cx);
 1667                GlobalTheme::reload_icon_theme(cx);
 1668            }),
 1669            cx.on_release({
 1670                let weak_handle = weak_handle.clone();
 1671                move |this, cx| {
 1672                    this.app_state.workspace_store.update(cx, move |store, _| {
 1673                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1674                    })
 1675                }
 1676            }),
 1677        ];
 1678
 1679        cx.defer_in(window, move |this, window, cx| {
 1680            this.update_window_title(window, cx);
 1681            this.show_initial_notifications(cx);
 1682        });
 1683
 1684        let mut center = PaneGroup::new(center_pane.clone());
 1685        center.set_is_center(true);
 1686        center.mark_positions(cx);
 1687
 1688        Workspace {
 1689            weak_self: weak_handle.clone(),
 1690            zoomed: None,
 1691            zoomed_position: None,
 1692            previous_dock_drag_coordinates: None,
 1693            center,
 1694            panes: vec![center_pane.clone()],
 1695            panes_by_item: Default::default(),
 1696            active_pane: center_pane.clone(),
 1697            last_active_center_pane: Some(center_pane.downgrade()),
 1698            last_active_view_id: None,
 1699            status_bar,
 1700            modal_layer,
 1701            toast_layer,
 1702            titlebar_item: None,
 1703            active_worktree_override: None,
 1704            notifications: Notifications::default(),
 1705            suppressed_notifications: HashSet::default(),
 1706            left_dock,
 1707            bottom_dock,
 1708            right_dock,
 1709            _panels_task: None,
 1710            project: project.clone(),
 1711            follower_states: Default::default(),
 1712            last_leaders_by_pane: Default::default(),
 1713            dispatching_keystrokes: Default::default(),
 1714            window_edited: false,
 1715            last_window_title: None,
 1716            dirty_items: Default::default(),
 1717            active_call,
 1718            database_id: workspace_id,
 1719            app_state,
 1720            _observe_current_user,
 1721            _apply_leader_updates,
 1722            _schedule_serialize_workspace: None,
 1723            _serialize_workspace_task: None,
 1724            _schedule_serialize_ssh_paths: None,
 1725            leader_updates_tx,
 1726            _subscriptions: subscriptions,
 1727            pane_history_timestamp,
 1728            workspace_actions: Default::default(),
 1729            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1730            bounds: Default::default(),
 1731            centered_layout: false,
 1732            bounds_save_task_queued: None,
 1733            on_prompt_for_new_path: None,
 1734            on_prompt_for_open_path: None,
 1735            terminal_provider: None,
 1736            debugger_provider: None,
 1737            serializable_items_tx,
 1738            _items_serializer,
 1739            session_id: Some(session_id),
 1740
 1741            scheduled_tasks: Vec::new(),
 1742            last_open_dock_positions: Vec::new(),
 1743            removing: false,
 1744        }
 1745    }
 1746
 1747    pub fn new_local(
 1748        abs_paths: Vec<PathBuf>,
 1749        app_state: Arc<AppState>,
 1750        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1751        env: Option<HashMap<String, String>>,
 1752        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1753        activate: bool,
 1754        cx: &mut App,
 1755    ) -> Task<anyhow::Result<OpenResult>> {
 1756        let project_handle = Project::local(
 1757            app_state.client.clone(),
 1758            app_state.node_runtime.clone(),
 1759            app_state.user_store.clone(),
 1760            app_state.languages.clone(),
 1761            app_state.fs.clone(),
 1762            env,
 1763            Default::default(),
 1764            cx,
 1765        );
 1766
 1767        cx.spawn(async move |cx| {
 1768            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1769            for path in abs_paths.into_iter() {
 1770                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1771                    paths_to_open.push(canonical)
 1772                } else {
 1773                    paths_to_open.push(path)
 1774                }
 1775            }
 1776
 1777            let serialized_workspace =
 1778                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1779
 1780            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1781                paths_to_open = paths.ordered_paths().cloned().collect();
 1782                if !paths.is_lexicographically_ordered() {
 1783                    project_handle.update(cx, |project, cx| {
 1784                        project.set_worktrees_reordered(true, cx);
 1785                    });
 1786                }
 1787            }
 1788
 1789            // Get project paths for all of the abs_paths
 1790            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1791                Vec::with_capacity(paths_to_open.len());
 1792
 1793            for path in paths_to_open.into_iter() {
 1794                if let Some((_, project_entry)) = cx
 1795                    .update(|cx| {
 1796                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1797                    })
 1798                    .await
 1799                    .log_err()
 1800                {
 1801                    project_paths.push((path, Some(project_entry)));
 1802                } else {
 1803                    project_paths.push((path, None));
 1804                }
 1805            }
 1806
 1807            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1808                serialized_workspace.id
 1809            } else {
 1810                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1811            };
 1812
 1813            let toolchains = DB.toolchains(workspace_id).await?;
 1814
 1815            for (toolchain, worktree_path, path) in toolchains {
 1816                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1817                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1818                    this.find_worktree(&worktree_path, cx)
 1819                        .and_then(|(worktree, rel_path)| {
 1820                            if rel_path.is_empty() {
 1821                                Some(worktree.read(cx).id())
 1822                            } else {
 1823                                None
 1824                            }
 1825                        })
 1826                }) else {
 1827                    // We did not find a worktree with a given path, but that's whatever.
 1828                    continue;
 1829                };
 1830                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1831                    continue;
 1832                }
 1833
 1834                project_handle
 1835                    .update(cx, |this, cx| {
 1836                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1837                    })
 1838                    .await;
 1839            }
 1840            if let Some(workspace) = serialized_workspace.as_ref() {
 1841                project_handle.update(cx, |this, cx| {
 1842                    for (scope, toolchains) in &workspace.user_toolchains {
 1843                        for toolchain in toolchains {
 1844                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1845                        }
 1846                    }
 1847                });
 1848            }
 1849
 1850            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1851                if let Some(window) = requesting_window {
 1852                    let centered_layout = serialized_workspace
 1853                        .as_ref()
 1854                        .map(|w| w.centered_layout)
 1855                        .unwrap_or(false);
 1856
 1857                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1858                        let workspace = cx.new(|cx| {
 1859                            let mut workspace = Workspace::new(
 1860                                Some(workspace_id),
 1861                                project_handle.clone(),
 1862                                app_state.clone(),
 1863                                window,
 1864                                cx,
 1865                            );
 1866
 1867                            workspace.centered_layout = centered_layout;
 1868
 1869                            // Call init callback to add items before window renders
 1870                            if let Some(init) = init {
 1871                                init(&mut workspace, window, cx);
 1872                            }
 1873
 1874                            workspace
 1875                        });
 1876                        if activate {
 1877                            multi_workspace.activate(workspace.clone(), cx);
 1878                        } else {
 1879                            multi_workspace.add_workspace(workspace.clone(), cx);
 1880                        }
 1881                        workspace
 1882                    })?;
 1883                    (window, workspace)
 1884                } else {
 1885                    let window_bounds_override = window_bounds_env_override();
 1886
 1887                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1888                        (Some(WindowBounds::Windowed(bounds)), None)
 1889                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1890                        && let Some(display) = workspace.display
 1891                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1892                    {
 1893                        // Reopening an existing workspace - restore its saved bounds
 1894                        (Some(bounds.0), Some(display))
 1895                    } else if let Some((display, bounds)) =
 1896                        persistence::read_default_window_bounds()
 1897                    {
 1898                        // New or empty workspace - use the last known window bounds
 1899                        (Some(bounds), Some(display))
 1900                    } else {
 1901                        // New window - let GPUI's default_bounds() handle cascading
 1902                        (None, None)
 1903                    };
 1904
 1905                    // Use the serialized workspace to construct the new window
 1906                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1907                    options.window_bounds = window_bounds;
 1908                    let centered_layout = serialized_workspace
 1909                        .as_ref()
 1910                        .map(|w| w.centered_layout)
 1911                        .unwrap_or(false);
 1912                    let window = cx.open_window(options, {
 1913                        let app_state = app_state.clone();
 1914                        let project_handle = project_handle.clone();
 1915                        move |window, cx| {
 1916                            let workspace = cx.new(|cx| {
 1917                                let mut workspace = Workspace::new(
 1918                                    Some(workspace_id),
 1919                                    project_handle,
 1920                                    app_state,
 1921                                    window,
 1922                                    cx,
 1923                                );
 1924                                workspace.centered_layout = centered_layout;
 1925
 1926                                // Call init callback to add items before window renders
 1927                                if let Some(init) = init {
 1928                                    init(&mut workspace, window, cx);
 1929                                }
 1930
 1931                                workspace
 1932                            });
 1933                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1934                        }
 1935                    })?;
 1936                    let workspace =
 1937                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1938                            multi_workspace.workspace().clone()
 1939                        })?;
 1940                    (window, workspace)
 1941                };
 1942
 1943            notify_if_database_failed(window, cx);
 1944            // Check if this is an empty workspace (no paths to open)
 1945            // An empty workspace is one where project_paths is empty
 1946            let is_empty_workspace = project_paths.is_empty();
 1947            // Check if serialized workspace has paths before it's moved
 1948            let serialized_workspace_has_paths = serialized_workspace
 1949                .as_ref()
 1950                .map(|ws| !ws.paths.is_empty())
 1951                .unwrap_or(false);
 1952
 1953            let opened_items = window
 1954                .update(cx, |_, window, cx| {
 1955                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1956                        open_items(serialized_workspace, project_paths, window, cx)
 1957                    })
 1958                })?
 1959                .await
 1960                .unwrap_or_default();
 1961
 1962            // Restore default dock state for empty workspaces
 1963            // Only restore if:
 1964            // 1. This is an empty workspace (no paths), AND
 1965            // 2. The serialized workspace either doesn't exist or has no paths
 1966            if is_empty_workspace && !serialized_workspace_has_paths {
 1967                if let Some(default_docks) = persistence::read_default_dock_state() {
 1968                    window
 1969                        .update(cx, |_, window, cx| {
 1970                            workspace.update(cx, |workspace, cx| {
 1971                                for (dock, serialized_dock) in [
 1972                                    (&workspace.right_dock, &default_docks.right),
 1973                                    (&workspace.left_dock, &default_docks.left),
 1974                                    (&workspace.bottom_dock, &default_docks.bottom),
 1975                                ] {
 1976                                    dock.update(cx, |dock, cx| {
 1977                                        dock.serialized_dock = Some(serialized_dock.clone());
 1978                                        dock.restore_state(window, cx);
 1979                                    });
 1980                                }
 1981                                cx.notify();
 1982                            });
 1983                        })
 1984                        .log_err();
 1985                }
 1986            }
 1987
 1988            window
 1989                .update(cx, |_, _window, cx| {
 1990                    workspace.update(cx, |this: &mut Workspace, cx| {
 1991                        this.update_history(cx);
 1992                    });
 1993                })
 1994                .log_err();
 1995            Ok(OpenResult {
 1996                window,
 1997                workspace,
 1998                opened_items,
 1999            })
 2000        })
 2001    }
 2002
 2003    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2004        self.weak_self.clone()
 2005    }
 2006
 2007    pub fn left_dock(&self) -> &Entity<Dock> {
 2008        &self.left_dock
 2009    }
 2010
 2011    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2012        &self.bottom_dock
 2013    }
 2014
 2015    pub fn set_bottom_dock_layout(
 2016        &mut self,
 2017        layout: BottomDockLayout,
 2018        window: &mut Window,
 2019        cx: &mut Context<Self>,
 2020    ) {
 2021        let fs = self.project().read(cx).fs();
 2022        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2023            content.workspace.bottom_dock_layout = Some(layout);
 2024        });
 2025
 2026        cx.notify();
 2027        self.serialize_workspace(window, cx);
 2028    }
 2029
 2030    pub fn right_dock(&self) -> &Entity<Dock> {
 2031        &self.right_dock
 2032    }
 2033
 2034    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2035        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2036    }
 2037
 2038    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2039        let left_dock = self.left_dock.read(cx);
 2040        let left_visible = left_dock.is_open();
 2041        let left_active_panel = left_dock
 2042            .active_panel()
 2043            .map(|panel| panel.persistent_name().to_string());
 2044        // `zoomed_position` is kept in sync with individual panel zoom state
 2045        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2046        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2047
 2048        let right_dock = self.right_dock.read(cx);
 2049        let right_visible = right_dock.is_open();
 2050        let right_active_panel = right_dock
 2051            .active_panel()
 2052            .map(|panel| panel.persistent_name().to_string());
 2053        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2054
 2055        let bottom_dock = self.bottom_dock.read(cx);
 2056        let bottom_visible = bottom_dock.is_open();
 2057        let bottom_active_panel = bottom_dock
 2058            .active_panel()
 2059            .map(|panel| panel.persistent_name().to_string());
 2060        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2061
 2062        DockStructure {
 2063            left: DockData {
 2064                visible: left_visible,
 2065                active_panel: left_active_panel,
 2066                zoom: left_dock_zoom,
 2067            },
 2068            right: DockData {
 2069                visible: right_visible,
 2070                active_panel: right_active_panel,
 2071                zoom: right_dock_zoom,
 2072            },
 2073            bottom: DockData {
 2074                visible: bottom_visible,
 2075                active_panel: bottom_active_panel,
 2076                zoom: bottom_dock_zoom,
 2077            },
 2078        }
 2079    }
 2080
 2081    pub fn set_dock_structure(
 2082        &self,
 2083        docks: DockStructure,
 2084        window: &mut Window,
 2085        cx: &mut Context<Self>,
 2086    ) {
 2087        for (dock, data) in [
 2088            (&self.left_dock, docks.left),
 2089            (&self.bottom_dock, docks.bottom),
 2090            (&self.right_dock, docks.right),
 2091        ] {
 2092            dock.update(cx, |dock, cx| {
 2093                dock.serialized_dock = Some(data);
 2094                dock.restore_state(window, cx);
 2095            });
 2096        }
 2097    }
 2098
 2099    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2100        self.items(cx)
 2101            .filter_map(|item| {
 2102                let project_path = item.project_path(cx)?;
 2103                self.project.read(cx).absolute_path(&project_path, cx)
 2104            })
 2105            .collect()
 2106    }
 2107
 2108    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2109        match position {
 2110            DockPosition::Left => &self.left_dock,
 2111            DockPosition::Bottom => &self.bottom_dock,
 2112            DockPosition::Right => &self.right_dock,
 2113        }
 2114    }
 2115
 2116    pub fn is_edited(&self) -> bool {
 2117        self.window_edited
 2118    }
 2119
 2120    pub fn add_panel<T: Panel>(
 2121        &mut self,
 2122        panel: Entity<T>,
 2123        window: &mut Window,
 2124        cx: &mut Context<Self>,
 2125    ) {
 2126        let focus_handle = panel.panel_focus_handle(cx);
 2127        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2128            .detach();
 2129
 2130        let dock_position = panel.position(window, cx);
 2131        let dock = self.dock_at_position(dock_position);
 2132        let any_panel = panel.to_any();
 2133
 2134        dock.update(cx, |dock, cx| {
 2135            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2136        });
 2137
 2138        cx.emit(Event::PanelAdded(any_panel));
 2139    }
 2140
 2141    pub fn remove_panel<T: Panel>(
 2142        &mut self,
 2143        panel: &Entity<T>,
 2144        window: &mut Window,
 2145        cx: &mut Context<Self>,
 2146    ) {
 2147        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2148            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2149        }
 2150    }
 2151
 2152    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2153        &self.status_bar
 2154    }
 2155
 2156    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2157        self.status_bar.update(cx, |status_bar, cx| {
 2158            status_bar.set_workspace_sidebar_open(open, cx);
 2159        });
 2160    }
 2161
 2162    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2163        StatusBarSettings::get_global(cx).show
 2164    }
 2165
 2166    pub fn app_state(&self) -> &Arc<AppState> {
 2167        &self.app_state
 2168    }
 2169
 2170    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2171        self._panels_task = Some(task);
 2172    }
 2173
 2174    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2175        self._panels_task.take()
 2176    }
 2177
 2178    pub fn user_store(&self) -> &Entity<UserStore> {
 2179        &self.app_state.user_store
 2180    }
 2181
 2182    pub fn project(&self) -> &Entity<Project> {
 2183        &self.project
 2184    }
 2185
 2186    pub fn path_style(&self, cx: &App) -> PathStyle {
 2187        self.project.read(cx).path_style(cx)
 2188    }
 2189
 2190    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2191        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2192
 2193        for pane_handle in &self.panes {
 2194            let pane = pane_handle.read(cx);
 2195
 2196            for entry in pane.activation_history() {
 2197                history.insert(
 2198                    entry.entity_id,
 2199                    history
 2200                        .get(&entry.entity_id)
 2201                        .cloned()
 2202                        .unwrap_or(0)
 2203                        .max(entry.timestamp),
 2204                );
 2205            }
 2206        }
 2207
 2208        history
 2209    }
 2210
 2211    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2212        let mut recent_item: Option<Entity<T>> = None;
 2213        let mut recent_timestamp = 0;
 2214        for pane_handle in &self.panes {
 2215            let pane = pane_handle.read(cx);
 2216            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2217                pane.items().map(|item| (item.item_id(), item)).collect();
 2218            for entry in pane.activation_history() {
 2219                if entry.timestamp > recent_timestamp
 2220                    && let Some(&item) = item_map.get(&entry.entity_id)
 2221                    && let Some(typed_item) = item.act_as::<T>(cx)
 2222                {
 2223                    recent_timestamp = entry.timestamp;
 2224                    recent_item = Some(typed_item);
 2225                }
 2226            }
 2227        }
 2228        recent_item
 2229    }
 2230
 2231    pub fn recent_navigation_history_iter(
 2232        &self,
 2233        cx: &App,
 2234    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2235        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2236        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2237
 2238        for pane in &self.panes {
 2239            let pane = pane.read(cx);
 2240
 2241            pane.nav_history()
 2242                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2243                    if let Some(fs_path) = &fs_path {
 2244                        abs_paths_opened
 2245                            .entry(fs_path.clone())
 2246                            .or_default()
 2247                            .insert(project_path.clone());
 2248                    }
 2249                    let timestamp = entry.timestamp;
 2250                    match history.entry(project_path) {
 2251                        hash_map::Entry::Occupied(mut entry) => {
 2252                            let (_, old_timestamp) = entry.get();
 2253                            if &timestamp > old_timestamp {
 2254                                entry.insert((fs_path, timestamp));
 2255                            }
 2256                        }
 2257                        hash_map::Entry::Vacant(entry) => {
 2258                            entry.insert((fs_path, timestamp));
 2259                        }
 2260                    }
 2261                });
 2262
 2263            if let Some(item) = pane.active_item()
 2264                && let Some(project_path) = item.project_path(cx)
 2265            {
 2266                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2267
 2268                if let Some(fs_path) = &fs_path {
 2269                    abs_paths_opened
 2270                        .entry(fs_path.clone())
 2271                        .or_default()
 2272                        .insert(project_path.clone());
 2273                }
 2274
 2275                history.insert(project_path, (fs_path, std::usize::MAX));
 2276            }
 2277        }
 2278
 2279        history
 2280            .into_iter()
 2281            .sorted_by_key(|(_, (_, order))| *order)
 2282            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2283            .rev()
 2284            .filter(move |(history_path, abs_path)| {
 2285                let latest_project_path_opened = abs_path
 2286                    .as_ref()
 2287                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2288                    .and_then(|project_paths| {
 2289                        project_paths
 2290                            .iter()
 2291                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2292                    });
 2293
 2294                latest_project_path_opened.is_none_or(|path| path == history_path)
 2295            })
 2296    }
 2297
 2298    pub fn recent_navigation_history(
 2299        &self,
 2300        limit: Option<usize>,
 2301        cx: &App,
 2302    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2303        self.recent_navigation_history_iter(cx)
 2304            .take(limit.unwrap_or(usize::MAX))
 2305            .collect()
 2306    }
 2307
 2308    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2309        for pane in &self.panes {
 2310            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2311        }
 2312    }
 2313
 2314    fn navigate_history(
 2315        &mut self,
 2316        pane: WeakEntity<Pane>,
 2317        mode: NavigationMode,
 2318        window: &mut Window,
 2319        cx: &mut Context<Workspace>,
 2320    ) -> Task<Result<()>> {
 2321        self.navigate_history_impl(
 2322            pane,
 2323            mode,
 2324            window,
 2325            &mut |history, cx| history.pop(mode, cx),
 2326            cx,
 2327        )
 2328    }
 2329
 2330    fn navigate_tag_history(
 2331        &mut self,
 2332        pane: WeakEntity<Pane>,
 2333        mode: TagNavigationMode,
 2334        window: &mut Window,
 2335        cx: &mut Context<Workspace>,
 2336    ) -> Task<Result<()>> {
 2337        self.navigate_history_impl(
 2338            pane,
 2339            NavigationMode::Normal,
 2340            window,
 2341            &mut |history, _cx| history.pop_tag(mode),
 2342            cx,
 2343        )
 2344    }
 2345
 2346    fn navigate_history_impl(
 2347        &mut self,
 2348        pane: WeakEntity<Pane>,
 2349        mode: NavigationMode,
 2350        window: &mut Window,
 2351        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2352        cx: &mut Context<Workspace>,
 2353    ) -> Task<Result<()>> {
 2354        let to_load = if let Some(pane) = pane.upgrade() {
 2355            pane.update(cx, |pane, cx| {
 2356                window.focus(&pane.focus_handle(cx), cx);
 2357                loop {
 2358                    // Retrieve the weak item handle from the history.
 2359                    let entry = cb(pane.nav_history_mut(), cx)?;
 2360
 2361                    // If the item is still present in this pane, then activate it.
 2362                    if let Some(index) = entry
 2363                        .item
 2364                        .upgrade()
 2365                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2366                    {
 2367                        let prev_active_item_index = pane.active_item_index();
 2368                        pane.nav_history_mut().set_mode(mode);
 2369                        pane.activate_item(index, true, true, window, cx);
 2370                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2371
 2372                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2373                        if let Some(data) = entry.data {
 2374                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2375                        }
 2376
 2377                        if navigated {
 2378                            break None;
 2379                        }
 2380                    } else {
 2381                        // If the item is no longer present in this pane, then retrieve its
 2382                        // path info in order to reopen it.
 2383                        break pane
 2384                            .nav_history()
 2385                            .path_for_item(entry.item.id())
 2386                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2387                    }
 2388                }
 2389            })
 2390        } else {
 2391            None
 2392        };
 2393
 2394        if let Some((project_path, abs_path, entry)) = to_load {
 2395            // If the item was no longer present, then load it again from its previous path, first try the local path
 2396            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2397
 2398            cx.spawn_in(window, async move  |workspace, cx| {
 2399                let open_by_project_path = open_by_project_path.await;
 2400                let mut navigated = false;
 2401                match open_by_project_path
 2402                    .with_context(|| format!("Navigating to {project_path:?}"))
 2403                {
 2404                    Ok((project_entry_id, build_item)) => {
 2405                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2406                            pane.nav_history_mut().set_mode(mode);
 2407                            pane.active_item().map(|p| p.item_id())
 2408                        })?;
 2409
 2410                        pane.update_in(cx, |pane, window, cx| {
 2411                            let item = pane.open_item(
 2412                                project_entry_id,
 2413                                project_path,
 2414                                true,
 2415                                entry.is_preview,
 2416                                true,
 2417                                None,
 2418                                window, cx,
 2419                                build_item,
 2420                            );
 2421                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2422                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2423                            if let Some(data) = entry.data {
 2424                                navigated |= item.navigate(data, window, cx);
 2425                            }
 2426                        })?;
 2427                    }
 2428                    Err(open_by_project_path_e) => {
 2429                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2430                        // and its worktree is now dropped
 2431                        if let Some(abs_path) = abs_path {
 2432                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2433                                pane.nav_history_mut().set_mode(mode);
 2434                                pane.active_item().map(|p| p.item_id())
 2435                            })?;
 2436                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2437                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2438                            })?;
 2439                            match open_by_abs_path
 2440                                .await
 2441                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2442                            {
 2443                                Ok(item) => {
 2444                                    pane.update_in(cx, |pane, window, cx| {
 2445                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2446                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2447                                        if let Some(data) = entry.data {
 2448                                            navigated |= item.navigate(data, window, cx);
 2449                                        }
 2450                                    })?;
 2451                                }
 2452                                Err(open_by_abs_path_e) => {
 2453                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2454                                }
 2455                            }
 2456                        }
 2457                    }
 2458                }
 2459
 2460                if !navigated {
 2461                    workspace
 2462                        .update_in(cx, |workspace, window, cx| {
 2463                            Self::navigate_history(workspace, pane, mode, window, cx)
 2464                        })?
 2465                        .await?;
 2466                }
 2467
 2468                Ok(())
 2469            })
 2470        } else {
 2471            Task::ready(Ok(()))
 2472        }
 2473    }
 2474
 2475    pub fn go_back(
 2476        &mut self,
 2477        pane: WeakEntity<Pane>,
 2478        window: &mut Window,
 2479        cx: &mut Context<Workspace>,
 2480    ) -> Task<Result<()>> {
 2481        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2482    }
 2483
 2484    pub fn go_forward(
 2485        &mut self,
 2486        pane: WeakEntity<Pane>,
 2487        window: &mut Window,
 2488        cx: &mut Context<Workspace>,
 2489    ) -> Task<Result<()>> {
 2490        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2491    }
 2492
 2493    pub fn reopen_closed_item(
 2494        &mut self,
 2495        window: &mut Window,
 2496        cx: &mut Context<Workspace>,
 2497    ) -> Task<Result<()>> {
 2498        self.navigate_history(
 2499            self.active_pane().downgrade(),
 2500            NavigationMode::ReopeningClosedItem,
 2501            window,
 2502            cx,
 2503        )
 2504    }
 2505
 2506    pub fn client(&self) -> &Arc<Client> {
 2507        &self.app_state.client
 2508    }
 2509
 2510    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2511        self.titlebar_item = Some(item);
 2512        cx.notify();
 2513    }
 2514
 2515    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2516        self.on_prompt_for_new_path = Some(prompt)
 2517    }
 2518
 2519    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2520        self.on_prompt_for_open_path = Some(prompt)
 2521    }
 2522
 2523    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2524        self.terminal_provider = Some(Box::new(provider));
 2525    }
 2526
 2527    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2528        self.debugger_provider = Some(Arc::new(provider));
 2529    }
 2530
 2531    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2532        self.debugger_provider.clone()
 2533    }
 2534
 2535    pub fn prompt_for_open_path(
 2536        &mut self,
 2537        path_prompt_options: PathPromptOptions,
 2538        lister: DirectoryLister,
 2539        window: &mut Window,
 2540        cx: &mut Context<Self>,
 2541    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2542        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2543            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2544            let rx = prompt(self, lister, window, cx);
 2545            self.on_prompt_for_open_path = Some(prompt);
 2546            rx
 2547        } else {
 2548            let (tx, rx) = oneshot::channel();
 2549            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2550
 2551            cx.spawn_in(window, async move |workspace, cx| {
 2552                let Ok(result) = abs_path.await else {
 2553                    return Ok(());
 2554                };
 2555
 2556                match result {
 2557                    Ok(result) => {
 2558                        tx.send(result).ok();
 2559                    }
 2560                    Err(err) => {
 2561                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2562                            workspace.show_portal_error(err.to_string(), cx);
 2563                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2564                            let rx = prompt(workspace, lister, window, cx);
 2565                            workspace.on_prompt_for_open_path = Some(prompt);
 2566                            rx
 2567                        })?;
 2568                        if let Ok(path) = rx.await {
 2569                            tx.send(path).ok();
 2570                        }
 2571                    }
 2572                };
 2573                anyhow::Ok(())
 2574            })
 2575            .detach();
 2576
 2577            rx
 2578        }
 2579    }
 2580
 2581    pub fn prompt_for_new_path(
 2582        &mut self,
 2583        lister: DirectoryLister,
 2584        suggested_name: Option<String>,
 2585        window: &mut Window,
 2586        cx: &mut Context<Self>,
 2587    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2588        if self.project.read(cx).is_via_collab()
 2589            || self.project.read(cx).is_via_remote_server()
 2590            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2591        {
 2592            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2593            let rx = prompt(self, lister, suggested_name, window, cx);
 2594            self.on_prompt_for_new_path = Some(prompt);
 2595            return rx;
 2596        }
 2597
 2598        let (tx, rx) = oneshot::channel();
 2599        cx.spawn_in(window, async move |workspace, cx| {
 2600            let abs_path = workspace.update(cx, |workspace, cx| {
 2601                let relative_to = workspace
 2602                    .most_recent_active_path(cx)
 2603                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2604                    .or_else(|| {
 2605                        let project = workspace.project.read(cx);
 2606                        project.visible_worktrees(cx).find_map(|worktree| {
 2607                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2608                        })
 2609                    })
 2610                    .or_else(std::env::home_dir)
 2611                    .unwrap_or_else(|| PathBuf::from(""));
 2612                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2613            })?;
 2614            let abs_path = match abs_path.await? {
 2615                Ok(path) => path,
 2616                Err(err) => {
 2617                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2618                        workspace.show_portal_error(err.to_string(), cx);
 2619
 2620                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2621                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2622                        workspace.on_prompt_for_new_path = Some(prompt);
 2623                        rx
 2624                    })?;
 2625                    if let Ok(path) = rx.await {
 2626                        tx.send(path).ok();
 2627                    }
 2628                    return anyhow::Ok(());
 2629                }
 2630            };
 2631
 2632            tx.send(abs_path.map(|path| vec![path])).ok();
 2633            anyhow::Ok(())
 2634        })
 2635        .detach();
 2636
 2637        rx
 2638    }
 2639
 2640    pub fn titlebar_item(&self) -> Option<AnyView> {
 2641        self.titlebar_item.clone()
 2642    }
 2643
 2644    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2645    /// When set, git-related operations should use this worktree instead of deriving
 2646    /// the active worktree from the focused file.
 2647    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2648        self.active_worktree_override
 2649    }
 2650
 2651    pub fn set_active_worktree_override(
 2652        &mut self,
 2653        worktree_id: Option<WorktreeId>,
 2654        cx: &mut Context<Self>,
 2655    ) {
 2656        self.active_worktree_override = worktree_id;
 2657        cx.notify();
 2658    }
 2659
 2660    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2661        self.active_worktree_override = None;
 2662        cx.notify();
 2663    }
 2664
 2665    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2666    ///
 2667    /// If the given workspace has a local project, then it will be passed
 2668    /// to the callback. Otherwise, a new empty window will be created.
 2669    pub fn with_local_workspace<T, F>(
 2670        &mut self,
 2671        window: &mut Window,
 2672        cx: &mut Context<Self>,
 2673        callback: F,
 2674    ) -> Task<Result<T>>
 2675    where
 2676        T: 'static,
 2677        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2678    {
 2679        if self.project.read(cx).is_local() {
 2680            Task::ready(Ok(callback(self, window, cx)))
 2681        } else {
 2682            let env = self.project.read(cx).cli_environment(cx);
 2683            let task = Self::new_local(
 2684                Vec::new(),
 2685                self.app_state.clone(),
 2686                None,
 2687                env,
 2688                None,
 2689                true,
 2690                cx,
 2691            );
 2692            cx.spawn_in(window, async move |_vh, cx| {
 2693                let OpenResult {
 2694                    window: multi_workspace_window,
 2695                    ..
 2696                } = task.await?;
 2697                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2698                    let workspace = multi_workspace.workspace().clone();
 2699                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2700                })
 2701            })
 2702        }
 2703    }
 2704
 2705    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2706    ///
 2707    /// If the given workspace has a local project, then it will be passed
 2708    /// to the callback. Otherwise, a new empty window will be created.
 2709    pub fn with_local_or_wsl_workspace<T, F>(
 2710        &mut self,
 2711        window: &mut Window,
 2712        cx: &mut Context<Self>,
 2713        callback: F,
 2714    ) -> Task<Result<T>>
 2715    where
 2716        T: 'static,
 2717        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2718    {
 2719        let project = self.project.read(cx);
 2720        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2721            Task::ready(Ok(callback(self, window, cx)))
 2722        } else {
 2723            let env = self.project.read(cx).cli_environment(cx);
 2724            let task = Self::new_local(
 2725                Vec::new(),
 2726                self.app_state.clone(),
 2727                None,
 2728                env,
 2729                None,
 2730                true,
 2731                cx,
 2732            );
 2733            cx.spawn_in(window, async move |_vh, cx| {
 2734                let OpenResult {
 2735                    window: multi_workspace_window,
 2736                    ..
 2737                } = task.await?;
 2738                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2739                    let workspace = multi_workspace.workspace().clone();
 2740                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2741                })
 2742            })
 2743        }
 2744    }
 2745
 2746    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2747        self.project.read(cx).worktrees(cx)
 2748    }
 2749
 2750    pub fn visible_worktrees<'a>(
 2751        &self,
 2752        cx: &'a App,
 2753    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2754        self.project.read(cx).visible_worktrees(cx)
 2755    }
 2756
 2757    #[cfg(any(test, feature = "test-support"))]
 2758    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2759        let futures = self
 2760            .worktrees(cx)
 2761            .filter_map(|worktree| worktree.read(cx).as_local())
 2762            .map(|worktree| worktree.scan_complete())
 2763            .collect::<Vec<_>>();
 2764        async move {
 2765            for future in futures {
 2766                future.await;
 2767            }
 2768        }
 2769    }
 2770
 2771    pub fn close_global(cx: &mut App) {
 2772        cx.defer(|cx| {
 2773            cx.windows().iter().find(|window| {
 2774                window
 2775                    .update(cx, |_, window, _| {
 2776                        if window.is_window_active() {
 2777                            //This can only get called when the window's project connection has been lost
 2778                            //so we don't need to prompt the user for anything and instead just close the window
 2779                            window.remove_window();
 2780                            true
 2781                        } else {
 2782                            false
 2783                        }
 2784                    })
 2785                    .unwrap_or(false)
 2786            });
 2787        });
 2788    }
 2789
 2790    pub fn move_focused_panel_to_next_position(
 2791        &mut self,
 2792        _: &MoveFocusedPanelToNextPosition,
 2793        window: &mut Window,
 2794        cx: &mut Context<Self>,
 2795    ) {
 2796        let docks = self.all_docks();
 2797        let active_dock = docks
 2798            .into_iter()
 2799            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2800
 2801        if let Some(dock) = active_dock {
 2802            dock.update(cx, |dock, cx| {
 2803                let active_panel = dock
 2804                    .active_panel()
 2805                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2806
 2807                if let Some(panel) = active_panel {
 2808                    panel.move_to_next_position(window, cx);
 2809                }
 2810            })
 2811        }
 2812    }
 2813
 2814    pub fn prepare_to_close(
 2815        &mut self,
 2816        close_intent: CloseIntent,
 2817        window: &mut Window,
 2818        cx: &mut Context<Self>,
 2819    ) -> Task<Result<bool>> {
 2820        let active_call = self.active_global_call();
 2821
 2822        cx.spawn_in(window, async move |this, cx| {
 2823            this.update(cx, |this, _| {
 2824                if close_intent == CloseIntent::CloseWindow {
 2825                    this.removing = true;
 2826                }
 2827            })?;
 2828
 2829            let workspace_count = cx.update(|_window, cx| {
 2830                cx.windows()
 2831                    .iter()
 2832                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2833                    .count()
 2834            })?;
 2835
 2836            #[cfg(target_os = "macos")]
 2837            let save_last_workspace = false;
 2838
 2839            // On Linux and Windows, closing the last window should restore the last workspace.
 2840            #[cfg(not(target_os = "macos"))]
 2841            let save_last_workspace = {
 2842                let remaining_workspaces = cx.update(|_window, cx| {
 2843                    cx.windows()
 2844                        .iter()
 2845                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2846                        .filter_map(|multi_workspace| {
 2847                            multi_workspace
 2848                                .update(cx, |multi_workspace, _, cx| {
 2849                                    multi_workspace.workspace().read(cx).removing
 2850                                })
 2851                                .ok()
 2852                        })
 2853                        .filter(|removing| !removing)
 2854                        .count()
 2855                })?;
 2856
 2857                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2858            };
 2859
 2860            if let Some(active_call) = active_call
 2861                && workspace_count == 1
 2862                && cx
 2863                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2864                    .unwrap_or(false)
 2865            {
 2866                if close_intent == CloseIntent::CloseWindow {
 2867                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2868                    let answer = cx.update(|window, cx| {
 2869                        window.prompt(
 2870                            PromptLevel::Warning,
 2871                            "Do you want to leave the current call?",
 2872                            None,
 2873                            &["Close window and hang up", "Cancel"],
 2874                            cx,
 2875                        )
 2876                    })?;
 2877
 2878                    if answer.await.log_err() == Some(1) {
 2879                        return anyhow::Ok(false);
 2880                    } else {
 2881                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2882                            task.await.log_err();
 2883                        }
 2884                    }
 2885                }
 2886                if close_intent == CloseIntent::ReplaceWindow {
 2887                    _ = cx.update(|_window, cx| {
 2888                        let multi_workspace = cx
 2889                            .windows()
 2890                            .iter()
 2891                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2892                            .next()
 2893                            .unwrap();
 2894                        let project = multi_workspace
 2895                            .read(cx)?
 2896                            .workspace()
 2897                            .read(cx)
 2898                            .project
 2899                            .clone();
 2900                        if project.read(cx).is_shared() {
 2901                            active_call.0.unshare_project(project, cx)?;
 2902                        }
 2903                        Ok::<_, anyhow::Error>(())
 2904                    });
 2905                }
 2906            }
 2907
 2908            let save_result = this
 2909                .update_in(cx, |this, window, cx| {
 2910                    this.save_all_internal(SaveIntent::Close, window, cx)
 2911                })?
 2912                .await;
 2913
 2914            // If we're not quitting, but closing, we remove the workspace from
 2915            // the current session.
 2916            if close_intent != CloseIntent::Quit
 2917                && !save_last_workspace
 2918                && save_result.as_ref().is_ok_and(|&res| res)
 2919            {
 2920                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2921                    .await;
 2922            }
 2923
 2924            save_result
 2925        })
 2926    }
 2927
 2928    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2929        self.save_all_internal(
 2930            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2931            window,
 2932            cx,
 2933        )
 2934        .detach_and_log_err(cx);
 2935    }
 2936
 2937    fn send_keystrokes(
 2938        &mut self,
 2939        action: &SendKeystrokes,
 2940        window: &mut Window,
 2941        cx: &mut Context<Self>,
 2942    ) {
 2943        let keystrokes: Vec<Keystroke> = action
 2944            .0
 2945            .split(' ')
 2946            .flat_map(|k| Keystroke::parse(k).log_err())
 2947            .map(|k| {
 2948                cx.keyboard_mapper()
 2949                    .map_key_equivalent(k, false)
 2950                    .inner()
 2951                    .clone()
 2952            })
 2953            .collect();
 2954        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2955    }
 2956
 2957    pub fn send_keystrokes_impl(
 2958        &mut self,
 2959        keystrokes: Vec<Keystroke>,
 2960        window: &mut Window,
 2961        cx: &mut Context<Self>,
 2962    ) -> Shared<Task<()>> {
 2963        let mut state = self.dispatching_keystrokes.borrow_mut();
 2964        if !state.dispatched.insert(keystrokes.clone()) {
 2965            cx.propagate();
 2966            return state.task.clone().unwrap();
 2967        }
 2968
 2969        state.queue.extend(keystrokes);
 2970
 2971        let keystrokes = self.dispatching_keystrokes.clone();
 2972        if state.task.is_none() {
 2973            state.task = Some(
 2974                window
 2975                    .spawn(cx, async move |cx| {
 2976                        // limit to 100 keystrokes to avoid infinite recursion.
 2977                        for _ in 0..100 {
 2978                            let keystroke = {
 2979                                let mut state = keystrokes.borrow_mut();
 2980                                let Some(keystroke) = state.queue.pop_front() else {
 2981                                    state.dispatched.clear();
 2982                                    state.task.take();
 2983                                    return;
 2984                                };
 2985                                keystroke
 2986                            };
 2987                            cx.update(|window, cx| {
 2988                                let focused = window.focused(cx);
 2989                                window.dispatch_keystroke(keystroke.clone(), cx);
 2990                                if window.focused(cx) != focused {
 2991                                    // dispatch_keystroke may cause the focus to change.
 2992                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2993                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2994                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2995                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2996                                    // )
 2997                                    window.draw(cx).clear();
 2998                                }
 2999                            })
 3000                            .ok();
 3001
 3002                            // Yield between synthetic keystrokes so deferred focus and
 3003                            // other effects can settle before dispatching the next key.
 3004                            yield_now().await;
 3005                        }
 3006
 3007                        *keystrokes.borrow_mut() = Default::default();
 3008                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3009                    })
 3010                    .shared(),
 3011            );
 3012        }
 3013        state.task.clone().unwrap()
 3014    }
 3015
 3016    fn save_all_internal(
 3017        &mut self,
 3018        mut save_intent: SaveIntent,
 3019        window: &mut Window,
 3020        cx: &mut Context<Self>,
 3021    ) -> Task<Result<bool>> {
 3022        if self.project.read(cx).is_disconnected(cx) {
 3023            return Task::ready(Ok(true));
 3024        }
 3025        let dirty_items = self
 3026            .panes
 3027            .iter()
 3028            .flat_map(|pane| {
 3029                pane.read(cx).items().filter_map(|item| {
 3030                    if item.is_dirty(cx) {
 3031                        item.tab_content_text(0, cx);
 3032                        Some((pane.downgrade(), item.boxed_clone()))
 3033                    } else {
 3034                        None
 3035                    }
 3036                })
 3037            })
 3038            .collect::<Vec<_>>();
 3039
 3040        let project = self.project.clone();
 3041        cx.spawn_in(window, async move |workspace, cx| {
 3042            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3043                let (serialize_tasks, remaining_dirty_items) =
 3044                    workspace.update_in(cx, |workspace, window, cx| {
 3045                        let mut remaining_dirty_items = Vec::new();
 3046                        let mut serialize_tasks = Vec::new();
 3047                        for (pane, item) in dirty_items {
 3048                            if let Some(task) = item
 3049                                .to_serializable_item_handle(cx)
 3050                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3051                            {
 3052                                serialize_tasks.push(task);
 3053                            } else {
 3054                                remaining_dirty_items.push((pane, item));
 3055                            }
 3056                        }
 3057                        (serialize_tasks, remaining_dirty_items)
 3058                    })?;
 3059
 3060                futures::future::try_join_all(serialize_tasks).await?;
 3061
 3062                if !remaining_dirty_items.is_empty() {
 3063                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3064                }
 3065
 3066                if remaining_dirty_items.len() > 1 {
 3067                    let answer = workspace.update_in(cx, |_, window, cx| {
 3068                        let detail = Pane::file_names_for_prompt(
 3069                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3070                            cx,
 3071                        );
 3072                        window.prompt(
 3073                            PromptLevel::Warning,
 3074                            "Do you want to save all changes in the following files?",
 3075                            Some(&detail),
 3076                            &["Save all", "Discard all", "Cancel"],
 3077                            cx,
 3078                        )
 3079                    })?;
 3080                    match answer.await.log_err() {
 3081                        Some(0) => save_intent = SaveIntent::SaveAll,
 3082                        Some(1) => save_intent = SaveIntent::Skip,
 3083                        Some(2) => return Ok(false),
 3084                        _ => {}
 3085                    }
 3086                }
 3087
 3088                remaining_dirty_items
 3089            } else {
 3090                dirty_items
 3091            };
 3092
 3093            for (pane, item) in dirty_items {
 3094                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3095                    (
 3096                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3097                        item.project_entry_ids(cx),
 3098                    )
 3099                })?;
 3100                if (singleton || !project_entry_ids.is_empty())
 3101                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3102                {
 3103                    return Ok(false);
 3104                }
 3105            }
 3106            Ok(true)
 3107        })
 3108    }
 3109
 3110    pub fn open_workspace_for_paths(
 3111        &mut self,
 3112        replace_current_window: bool,
 3113        paths: Vec<PathBuf>,
 3114        window: &mut Window,
 3115        cx: &mut Context<Self>,
 3116    ) -> Task<Result<Entity<Workspace>>> {
 3117        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3118        let is_remote = self.project.read(cx).is_via_collab();
 3119        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3120        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3121
 3122        let window_to_replace = if replace_current_window {
 3123            window_handle
 3124        } else if is_remote || has_worktree || has_dirty_items {
 3125            None
 3126        } else {
 3127            window_handle
 3128        };
 3129        let app_state = self.app_state.clone();
 3130
 3131        cx.spawn(async move |_, cx| {
 3132            let OpenResult { workspace, .. } = cx
 3133                .update(|cx| {
 3134                    open_paths(
 3135                        &paths,
 3136                        app_state,
 3137                        OpenOptions {
 3138                            replace_window: window_to_replace,
 3139                            ..Default::default()
 3140                        },
 3141                        cx,
 3142                    )
 3143                })
 3144                .await?;
 3145            Ok(workspace)
 3146        })
 3147    }
 3148
 3149    #[allow(clippy::type_complexity)]
 3150    pub fn open_paths(
 3151        &mut self,
 3152        mut abs_paths: Vec<PathBuf>,
 3153        options: OpenOptions,
 3154        pane: Option<WeakEntity<Pane>>,
 3155        window: &mut Window,
 3156        cx: &mut Context<Self>,
 3157    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3158        let fs = self.app_state.fs.clone();
 3159
 3160        let caller_ordered_abs_paths = abs_paths.clone();
 3161
 3162        // Sort the paths to ensure we add worktrees for parents before their children.
 3163        abs_paths.sort_unstable();
 3164        cx.spawn_in(window, async move |this, cx| {
 3165            let mut tasks = Vec::with_capacity(abs_paths.len());
 3166
 3167            for abs_path in &abs_paths {
 3168                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3169                    OpenVisible::All => Some(true),
 3170                    OpenVisible::None => Some(false),
 3171                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3172                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3173                        Some(None) => Some(true),
 3174                        None => None,
 3175                    },
 3176                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3177                        Some(Some(metadata)) => Some(metadata.is_dir),
 3178                        Some(None) => Some(false),
 3179                        None => None,
 3180                    },
 3181                };
 3182                let project_path = match visible {
 3183                    Some(visible) => match this
 3184                        .update(cx, |this, cx| {
 3185                            Workspace::project_path_for_path(
 3186                                this.project.clone(),
 3187                                abs_path,
 3188                                visible,
 3189                                cx,
 3190                            )
 3191                        })
 3192                        .log_err()
 3193                    {
 3194                        Some(project_path) => project_path.await.log_err(),
 3195                        None => None,
 3196                    },
 3197                    None => None,
 3198                };
 3199
 3200                let this = this.clone();
 3201                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3202                let fs = fs.clone();
 3203                let pane = pane.clone();
 3204                let task = cx.spawn(async move |cx| {
 3205                    let (_worktree, project_path) = project_path?;
 3206                    if fs.is_dir(&abs_path).await {
 3207                        // Opening a directory should not race to update the active entry.
 3208                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3209                        None
 3210                    } else {
 3211                        Some(
 3212                            this.update_in(cx, |this, window, cx| {
 3213                                this.open_path(
 3214                                    project_path,
 3215                                    pane,
 3216                                    options.focus.unwrap_or(true),
 3217                                    window,
 3218                                    cx,
 3219                                )
 3220                            })
 3221                            .ok()?
 3222                            .await,
 3223                        )
 3224                    }
 3225                });
 3226                tasks.push(task);
 3227            }
 3228
 3229            let results = futures::future::join_all(tasks).await;
 3230
 3231            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3232            let mut winner: Option<(PathBuf, bool)> = None;
 3233            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3234                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3235                    if !metadata.is_dir {
 3236                        winner = Some((abs_path, false));
 3237                        break;
 3238                    }
 3239                    if winner.is_none() {
 3240                        winner = Some((abs_path, true));
 3241                    }
 3242                } else if winner.is_none() {
 3243                    winner = Some((abs_path, false));
 3244                }
 3245            }
 3246
 3247            // Compute the winner entry id on the foreground thread and emit once, after all
 3248            // paths finish opening. This avoids races between concurrently-opening paths
 3249            // (directories in particular) and makes the resulting project panel selection
 3250            // deterministic.
 3251            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3252                'emit_winner: {
 3253                    let winner_abs_path: Arc<Path> =
 3254                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3255
 3256                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3257                        OpenVisible::All => true,
 3258                        OpenVisible::None => false,
 3259                        OpenVisible::OnlyFiles => !winner_is_dir,
 3260                        OpenVisible::OnlyDirectories => winner_is_dir,
 3261                    };
 3262
 3263                    let Some(worktree_task) = this
 3264                        .update(cx, |workspace, cx| {
 3265                            workspace.project.update(cx, |project, cx| {
 3266                                project.find_or_create_worktree(
 3267                                    winner_abs_path.as_ref(),
 3268                                    visible,
 3269                                    cx,
 3270                                )
 3271                            })
 3272                        })
 3273                        .ok()
 3274                    else {
 3275                        break 'emit_winner;
 3276                    };
 3277
 3278                    let Ok((worktree, _)) = worktree_task.await else {
 3279                        break 'emit_winner;
 3280                    };
 3281
 3282                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3283                        let worktree = worktree.read(cx);
 3284                        let worktree_abs_path = worktree.abs_path();
 3285                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3286                            worktree.root_entry()
 3287                        } else {
 3288                            winner_abs_path
 3289                                .strip_prefix(worktree_abs_path.as_ref())
 3290                                .ok()
 3291                                .and_then(|relative_path| {
 3292                                    let relative_path =
 3293                                        RelPath::new(relative_path, PathStyle::local())
 3294                                            .log_err()?;
 3295                                    worktree.entry_for_path(&relative_path)
 3296                                })
 3297                        }?;
 3298                        Some(entry.id)
 3299                    }) else {
 3300                        break 'emit_winner;
 3301                    };
 3302
 3303                    this.update(cx, |workspace, cx| {
 3304                        workspace.project.update(cx, |_, cx| {
 3305                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3306                        });
 3307                    })
 3308                    .ok();
 3309                }
 3310            }
 3311
 3312            results
 3313        })
 3314    }
 3315
 3316    pub fn open_resolved_path(
 3317        &mut self,
 3318        path: ResolvedPath,
 3319        window: &mut Window,
 3320        cx: &mut Context<Self>,
 3321    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3322        match path {
 3323            ResolvedPath::ProjectPath { project_path, .. } => {
 3324                self.open_path(project_path, None, true, window, cx)
 3325            }
 3326            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3327                PathBuf::from(path),
 3328                OpenOptions {
 3329                    visible: Some(OpenVisible::None),
 3330                    ..Default::default()
 3331                },
 3332                window,
 3333                cx,
 3334            ),
 3335        }
 3336    }
 3337
 3338    pub fn absolute_path_of_worktree(
 3339        &self,
 3340        worktree_id: WorktreeId,
 3341        cx: &mut Context<Self>,
 3342    ) -> Option<PathBuf> {
 3343        self.project
 3344            .read(cx)
 3345            .worktree_for_id(worktree_id, cx)
 3346            // TODO: use `abs_path` or `root_dir`
 3347            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3348    }
 3349
 3350    fn add_folder_to_project(
 3351        &mut self,
 3352        _: &AddFolderToProject,
 3353        window: &mut Window,
 3354        cx: &mut Context<Self>,
 3355    ) {
 3356        let project = self.project.read(cx);
 3357        if project.is_via_collab() {
 3358            self.show_error(
 3359                &anyhow!("You cannot add folders to someone else's project"),
 3360                cx,
 3361            );
 3362            return;
 3363        }
 3364        let paths = self.prompt_for_open_path(
 3365            PathPromptOptions {
 3366                files: false,
 3367                directories: true,
 3368                multiple: true,
 3369                prompt: None,
 3370            },
 3371            DirectoryLister::Project(self.project.clone()),
 3372            window,
 3373            cx,
 3374        );
 3375        cx.spawn_in(window, async move |this, cx| {
 3376            if let Some(paths) = paths.await.log_err().flatten() {
 3377                let results = this
 3378                    .update_in(cx, |this, window, cx| {
 3379                        this.open_paths(
 3380                            paths,
 3381                            OpenOptions {
 3382                                visible: Some(OpenVisible::All),
 3383                                ..Default::default()
 3384                            },
 3385                            None,
 3386                            window,
 3387                            cx,
 3388                        )
 3389                    })?
 3390                    .await;
 3391                for result in results.into_iter().flatten() {
 3392                    result.log_err();
 3393                }
 3394            }
 3395            anyhow::Ok(())
 3396        })
 3397        .detach_and_log_err(cx);
 3398    }
 3399
 3400    pub fn project_path_for_path(
 3401        project: Entity<Project>,
 3402        abs_path: &Path,
 3403        visible: bool,
 3404        cx: &mut App,
 3405    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3406        let entry = project.update(cx, |project, cx| {
 3407            project.find_or_create_worktree(abs_path, visible, cx)
 3408        });
 3409        cx.spawn(async move |cx| {
 3410            let (worktree, path) = entry.await?;
 3411            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3412            Ok((worktree, ProjectPath { worktree_id, path }))
 3413        })
 3414    }
 3415
 3416    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3417        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3418    }
 3419
 3420    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3421        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3422    }
 3423
 3424    pub fn items_of_type<'a, T: Item>(
 3425        &'a self,
 3426        cx: &'a App,
 3427    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3428        self.panes
 3429            .iter()
 3430            .flat_map(|pane| pane.read(cx).items_of_type())
 3431    }
 3432
 3433    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3434        self.active_pane().read(cx).active_item()
 3435    }
 3436
 3437    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3438        let item = self.active_item(cx)?;
 3439        item.to_any_view().downcast::<I>().ok()
 3440    }
 3441
 3442    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3443        self.active_item(cx).and_then(|item| item.project_path(cx))
 3444    }
 3445
 3446    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3447        self.recent_navigation_history_iter(cx)
 3448            .filter_map(|(path, abs_path)| {
 3449                let worktree = self
 3450                    .project
 3451                    .read(cx)
 3452                    .worktree_for_id(path.worktree_id, cx)?;
 3453                if worktree.read(cx).is_visible() {
 3454                    abs_path
 3455                } else {
 3456                    None
 3457                }
 3458            })
 3459            .next()
 3460    }
 3461
 3462    pub fn save_active_item(
 3463        &mut self,
 3464        save_intent: SaveIntent,
 3465        window: &mut Window,
 3466        cx: &mut App,
 3467    ) -> Task<Result<()>> {
 3468        let project = self.project.clone();
 3469        let pane = self.active_pane();
 3470        let item = pane.read(cx).active_item();
 3471        let pane = pane.downgrade();
 3472
 3473        window.spawn(cx, async move |cx| {
 3474            if let Some(item) = item {
 3475                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3476                    .await
 3477                    .map(|_| ())
 3478            } else {
 3479                Ok(())
 3480            }
 3481        })
 3482    }
 3483
 3484    pub fn close_inactive_items_and_panes(
 3485        &mut self,
 3486        action: &CloseInactiveTabsAndPanes,
 3487        window: &mut Window,
 3488        cx: &mut Context<Self>,
 3489    ) {
 3490        if let Some(task) = self.close_all_internal(
 3491            true,
 3492            action.save_intent.unwrap_or(SaveIntent::Close),
 3493            window,
 3494            cx,
 3495        ) {
 3496            task.detach_and_log_err(cx)
 3497        }
 3498    }
 3499
 3500    pub fn close_all_items_and_panes(
 3501        &mut self,
 3502        action: &CloseAllItemsAndPanes,
 3503        window: &mut Window,
 3504        cx: &mut Context<Self>,
 3505    ) {
 3506        if let Some(task) = self.close_all_internal(
 3507            false,
 3508            action.save_intent.unwrap_or(SaveIntent::Close),
 3509            window,
 3510            cx,
 3511        ) {
 3512            task.detach_and_log_err(cx)
 3513        }
 3514    }
 3515
 3516    /// Closes the active item across all panes.
 3517    pub fn close_item_in_all_panes(
 3518        &mut self,
 3519        action: &CloseItemInAllPanes,
 3520        window: &mut Window,
 3521        cx: &mut Context<Self>,
 3522    ) {
 3523        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3524            return;
 3525        };
 3526
 3527        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3528        let close_pinned = action.close_pinned;
 3529
 3530        if let Some(project_path) = active_item.project_path(cx) {
 3531            self.close_items_with_project_path(
 3532                &project_path,
 3533                save_intent,
 3534                close_pinned,
 3535                window,
 3536                cx,
 3537            );
 3538        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3539            let item_id = active_item.item_id();
 3540            self.active_pane().update(cx, |pane, cx| {
 3541                pane.close_item_by_id(item_id, save_intent, window, cx)
 3542                    .detach_and_log_err(cx);
 3543            });
 3544        }
 3545    }
 3546
 3547    /// Closes all items with the given project path across all panes.
 3548    pub fn close_items_with_project_path(
 3549        &mut self,
 3550        project_path: &ProjectPath,
 3551        save_intent: SaveIntent,
 3552        close_pinned: bool,
 3553        window: &mut Window,
 3554        cx: &mut Context<Self>,
 3555    ) {
 3556        let panes = self.panes().to_vec();
 3557        for pane in panes {
 3558            pane.update(cx, |pane, cx| {
 3559                pane.close_items_for_project_path(
 3560                    project_path,
 3561                    save_intent,
 3562                    close_pinned,
 3563                    window,
 3564                    cx,
 3565                )
 3566                .detach_and_log_err(cx);
 3567            });
 3568        }
 3569    }
 3570
 3571    fn close_all_internal(
 3572        &mut self,
 3573        retain_active_pane: bool,
 3574        save_intent: SaveIntent,
 3575        window: &mut Window,
 3576        cx: &mut Context<Self>,
 3577    ) -> Option<Task<Result<()>>> {
 3578        let current_pane = self.active_pane();
 3579
 3580        let mut tasks = Vec::new();
 3581
 3582        if retain_active_pane {
 3583            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3584                pane.close_other_items(
 3585                    &CloseOtherItems {
 3586                        save_intent: None,
 3587                        close_pinned: false,
 3588                    },
 3589                    None,
 3590                    window,
 3591                    cx,
 3592                )
 3593            });
 3594
 3595            tasks.push(current_pane_close);
 3596        }
 3597
 3598        for pane in self.panes() {
 3599            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3600                continue;
 3601            }
 3602
 3603            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3604                pane.close_all_items(
 3605                    &CloseAllItems {
 3606                        save_intent: Some(save_intent),
 3607                        close_pinned: false,
 3608                    },
 3609                    window,
 3610                    cx,
 3611                )
 3612            });
 3613
 3614            tasks.push(close_pane_items)
 3615        }
 3616
 3617        if tasks.is_empty() {
 3618            None
 3619        } else {
 3620            Some(cx.spawn_in(window, async move |_, _| {
 3621                for task in tasks {
 3622                    task.await?
 3623                }
 3624                Ok(())
 3625            }))
 3626        }
 3627    }
 3628
 3629    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3630        self.dock_at_position(position).read(cx).is_open()
 3631    }
 3632
 3633    pub fn toggle_dock(
 3634        &mut self,
 3635        dock_side: DockPosition,
 3636        window: &mut Window,
 3637        cx: &mut Context<Self>,
 3638    ) {
 3639        let mut focus_center = false;
 3640        let mut reveal_dock = false;
 3641
 3642        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3643        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3644
 3645        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3646            telemetry::event!(
 3647                "Panel Button Clicked",
 3648                name = panel.persistent_name(),
 3649                toggle_state = !was_visible
 3650            );
 3651        }
 3652        if was_visible {
 3653            self.save_open_dock_positions(cx);
 3654        }
 3655
 3656        let dock = self.dock_at_position(dock_side);
 3657        dock.update(cx, |dock, cx| {
 3658            dock.set_open(!was_visible, window, cx);
 3659
 3660            if dock.active_panel().is_none() {
 3661                let Some(panel_ix) = dock
 3662                    .first_enabled_panel_idx(cx)
 3663                    .log_with_level(log::Level::Info)
 3664                else {
 3665                    return;
 3666                };
 3667                dock.activate_panel(panel_ix, window, cx);
 3668            }
 3669
 3670            if let Some(active_panel) = dock.active_panel() {
 3671                if was_visible {
 3672                    if active_panel
 3673                        .panel_focus_handle(cx)
 3674                        .contains_focused(window, cx)
 3675                    {
 3676                        focus_center = true;
 3677                    }
 3678                } else {
 3679                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3680                    window.focus(focus_handle, cx);
 3681                    reveal_dock = true;
 3682                }
 3683            }
 3684        });
 3685
 3686        if reveal_dock {
 3687            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3688        }
 3689
 3690        if focus_center {
 3691            self.active_pane
 3692                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3693        }
 3694
 3695        cx.notify();
 3696        self.serialize_workspace(window, cx);
 3697    }
 3698
 3699    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3700        self.all_docks().into_iter().find(|&dock| {
 3701            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3702        })
 3703    }
 3704
 3705    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3706        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3707            self.save_open_dock_positions(cx);
 3708            dock.update(cx, |dock, cx| {
 3709                dock.set_open(false, window, cx);
 3710            });
 3711            return true;
 3712        }
 3713        false
 3714    }
 3715
 3716    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3717        self.save_open_dock_positions(cx);
 3718        for dock in self.all_docks() {
 3719            dock.update(cx, |dock, cx| {
 3720                dock.set_open(false, window, cx);
 3721            });
 3722        }
 3723
 3724        cx.focus_self(window);
 3725        cx.notify();
 3726        self.serialize_workspace(window, cx);
 3727    }
 3728
 3729    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3730        self.all_docks()
 3731            .into_iter()
 3732            .filter_map(|dock| {
 3733                let dock_ref = dock.read(cx);
 3734                if dock_ref.is_open() {
 3735                    Some(dock_ref.position())
 3736                } else {
 3737                    None
 3738                }
 3739            })
 3740            .collect()
 3741    }
 3742
 3743    /// Saves the positions of currently open docks.
 3744    ///
 3745    /// Updates `last_open_dock_positions` with positions of all currently open
 3746    /// docks, to later be restored by the 'Toggle All Docks' action.
 3747    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3748        let open_dock_positions = self.get_open_dock_positions(cx);
 3749        if !open_dock_positions.is_empty() {
 3750            self.last_open_dock_positions = open_dock_positions;
 3751        }
 3752    }
 3753
 3754    /// Toggles all docks between open and closed states.
 3755    ///
 3756    /// If any docks are open, closes all and remembers their positions. If all
 3757    /// docks are closed, restores the last remembered dock configuration.
 3758    fn toggle_all_docks(
 3759        &mut self,
 3760        _: &ToggleAllDocks,
 3761        window: &mut Window,
 3762        cx: &mut Context<Self>,
 3763    ) {
 3764        let open_dock_positions = self.get_open_dock_positions(cx);
 3765
 3766        if !open_dock_positions.is_empty() {
 3767            self.close_all_docks(window, cx);
 3768        } else if !self.last_open_dock_positions.is_empty() {
 3769            self.restore_last_open_docks(window, cx);
 3770        }
 3771    }
 3772
 3773    /// Reopens docks from the most recently remembered configuration.
 3774    ///
 3775    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3776    /// and clears the stored positions.
 3777    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3778        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3779
 3780        for position in positions_to_open {
 3781            let dock = self.dock_at_position(position);
 3782            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3783        }
 3784
 3785        cx.focus_self(window);
 3786        cx.notify();
 3787        self.serialize_workspace(window, cx);
 3788    }
 3789
 3790    /// Transfer focus to the panel of the given type.
 3791    pub fn focus_panel<T: Panel>(
 3792        &mut self,
 3793        window: &mut Window,
 3794        cx: &mut Context<Self>,
 3795    ) -> Option<Entity<T>> {
 3796        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3797        panel.to_any().downcast().ok()
 3798    }
 3799
 3800    /// Focus the panel of the given type if it isn't already focused. If it is
 3801    /// already focused, then transfer focus back to the workspace center.
 3802    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3803    /// panel when transferring focus back to the center.
 3804    pub fn toggle_panel_focus<T: Panel>(
 3805        &mut self,
 3806        window: &mut Window,
 3807        cx: &mut Context<Self>,
 3808    ) -> bool {
 3809        let mut did_focus_panel = false;
 3810        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3811            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3812            did_focus_panel
 3813        });
 3814
 3815        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3816            self.close_panel::<T>(window, cx);
 3817        }
 3818
 3819        telemetry::event!(
 3820            "Panel Button Clicked",
 3821            name = T::persistent_name(),
 3822            toggle_state = did_focus_panel
 3823        );
 3824
 3825        did_focus_panel
 3826    }
 3827
 3828    pub fn activate_panel_for_proto_id(
 3829        &mut self,
 3830        panel_id: PanelId,
 3831        window: &mut Window,
 3832        cx: &mut Context<Self>,
 3833    ) -> Option<Arc<dyn PanelHandle>> {
 3834        let mut panel = None;
 3835        for dock in self.all_docks() {
 3836            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3837                panel = dock.update(cx, |dock, cx| {
 3838                    dock.activate_panel(panel_index, window, cx);
 3839                    dock.set_open(true, window, cx);
 3840                    dock.active_panel().cloned()
 3841                });
 3842                break;
 3843            }
 3844        }
 3845
 3846        if panel.is_some() {
 3847            cx.notify();
 3848            self.serialize_workspace(window, cx);
 3849        }
 3850
 3851        panel
 3852    }
 3853
 3854    /// Focus or unfocus the given panel type, depending on the given callback.
 3855    fn focus_or_unfocus_panel<T: Panel>(
 3856        &mut self,
 3857        window: &mut Window,
 3858        cx: &mut Context<Self>,
 3859        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3860    ) -> Option<Arc<dyn PanelHandle>> {
 3861        let mut result_panel = None;
 3862        let mut serialize = false;
 3863        for dock in self.all_docks() {
 3864            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3865                let mut focus_center = false;
 3866                let panel = dock.update(cx, |dock, cx| {
 3867                    dock.activate_panel(panel_index, window, cx);
 3868
 3869                    let panel = dock.active_panel().cloned();
 3870                    if let Some(panel) = panel.as_ref() {
 3871                        if should_focus(&**panel, window, cx) {
 3872                            dock.set_open(true, window, cx);
 3873                            panel.panel_focus_handle(cx).focus(window, cx);
 3874                        } else {
 3875                            focus_center = true;
 3876                        }
 3877                    }
 3878                    panel
 3879                });
 3880
 3881                if focus_center {
 3882                    self.active_pane
 3883                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3884                }
 3885
 3886                result_panel = panel;
 3887                serialize = true;
 3888                break;
 3889            }
 3890        }
 3891
 3892        if serialize {
 3893            self.serialize_workspace(window, cx);
 3894        }
 3895
 3896        cx.notify();
 3897        result_panel
 3898    }
 3899
 3900    /// Open the panel of the given type
 3901    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3902        for dock in self.all_docks() {
 3903            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3904                dock.update(cx, |dock, cx| {
 3905                    dock.activate_panel(panel_index, window, cx);
 3906                    dock.set_open(true, window, cx);
 3907                });
 3908            }
 3909        }
 3910    }
 3911
 3912    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3913        for dock in self.all_docks().iter() {
 3914            dock.update(cx, |dock, cx| {
 3915                if dock.panel::<T>().is_some() {
 3916                    dock.set_open(false, window, cx)
 3917                }
 3918            })
 3919        }
 3920    }
 3921
 3922    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3923        self.all_docks()
 3924            .iter()
 3925            .find_map(|dock| dock.read(cx).panel::<T>())
 3926    }
 3927
 3928    fn dismiss_zoomed_items_to_reveal(
 3929        &mut self,
 3930        dock_to_reveal: Option<DockPosition>,
 3931        window: &mut Window,
 3932        cx: &mut Context<Self>,
 3933    ) {
 3934        // If a center pane is zoomed, unzoom it.
 3935        for pane in &self.panes {
 3936            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3937                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3938            }
 3939        }
 3940
 3941        // If another dock is zoomed, hide it.
 3942        let mut focus_center = false;
 3943        for dock in self.all_docks() {
 3944            dock.update(cx, |dock, cx| {
 3945                if Some(dock.position()) != dock_to_reveal
 3946                    && let Some(panel) = dock.active_panel()
 3947                    && panel.is_zoomed(window, cx)
 3948                {
 3949                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3950                    dock.set_open(false, window, cx);
 3951                }
 3952            });
 3953        }
 3954
 3955        if focus_center {
 3956            self.active_pane
 3957                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3958        }
 3959
 3960        if self.zoomed_position != dock_to_reveal {
 3961            self.zoomed = None;
 3962            self.zoomed_position = None;
 3963            cx.emit(Event::ZoomChanged);
 3964        }
 3965
 3966        cx.notify();
 3967    }
 3968
 3969    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3970        let pane = cx.new(|cx| {
 3971            let mut pane = Pane::new(
 3972                self.weak_handle(),
 3973                self.project.clone(),
 3974                self.pane_history_timestamp.clone(),
 3975                None,
 3976                NewFile.boxed_clone(),
 3977                true,
 3978                window,
 3979                cx,
 3980            );
 3981            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3982            pane
 3983        });
 3984        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3985            .detach();
 3986        self.panes.push(pane.clone());
 3987
 3988        window.focus(&pane.focus_handle(cx), cx);
 3989
 3990        cx.emit(Event::PaneAdded(pane.clone()));
 3991        pane
 3992    }
 3993
 3994    pub fn add_item_to_center(
 3995        &mut self,
 3996        item: Box<dyn ItemHandle>,
 3997        window: &mut Window,
 3998        cx: &mut Context<Self>,
 3999    ) -> bool {
 4000        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4001            if let Some(center_pane) = center_pane.upgrade() {
 4002                center_pane.update(cx, |pane, cx| {
 4003                    pane.add_item(item, true, true, None, window, cx)
 4004                });
 4005                true
 4006            } else {
 4007                false
 4008            }
 4009        } else {
 4010            false
 4011        }
 4012    }
 4013
 4014    pub fn add_item_to_active_pane(
 4015        &mut self,
 4016        item: Box<dyn ItemHandle>,
 4017        destination_index: Option<usize>,
 4018        focus_item: bool,
 4019        window: &mut Window,
 4020        cx: &mut App,
 4021    ) {
 4022        self.add_item(
 4023            self.active_pane.clone(),
 4024            item,
 4025            destination_index,
 4026            false,
 4027            focus_item,
 4028            window,
 4029            cx,
 4030        )
 4031    }
 4032
 4033    pub fn add_item(
 4034        &mut self,
 4035        pane: Entity<Pane>,
 4036        item: Box<dyn ItemHandle>,
 4037        destination_index: Option<usize>,
 4038        activate_pane: bool,
 4039        focus_item: bool,
 4040        window: &mut Window,
 4041        cx: &mut App,
 4042    ) {
 4043        pane.update(cx, |pane, cx| {
 4044            pane.add_item(
 4045                item,
 4046                activate_pane,
 4047                focus_item,
 4048                destination_index,
 4049                window,
 4050                cx,
 4051            )
 4052        });
 4053    }
 4054
 4055    pub fn split_item(
 4056        &mut self,
 4057        split_direction: SplitDirection,
 4058        item: Box<dyn ItemHandle>,
 4059        window: &mut Window,
 4060        cx: &mut Context<Self>,
 4061    ) {
 4062        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4063        self.add_item(new_pane, item, None, true, true, window, cx);
 4064    }
 4065
 4066    pub fn open_abs_path(
 4067        &mut self,
 4068        abs_path: PathBuf,
 4069        options: OpenOptions,
 4070        window: &mut Window,
 4071        cx: &mut Context<Self>,
 4072    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4073        cx.spawn_in(window, async move |workspace, cx| {
 4074            let open_paths_task_result = workspace
 4075                .update_in(cx, |workspace, window, cx| {
 4076                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4077                })
 4078                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4079                .await;
 4080            anyhow::ensure!(
 4081                open_paths_task_result.len() == 1,
 4082                "open abs path {abs_path:?} task returned incorrect number of results"
 4083            );
 4084            match open_paths_task_result
 4085                .into_iter()
 4086                .next()
 4087                .expect("ensured single task result")
 4088            {
 4089                Some(open_result) => {
 4090                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4091                }
 4092                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4093            }
 4094        })
 4095    }
 4096
 4097    pub fn split_abs_path(
 4098        &mut self,
 4099        abs_path: PathBuf,
 4100        visible: bool,
 4101        window: &mut Window,
 4102        cx: &mut Context<Self>,
 4103    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4104        let project_path_task =
 4105            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4106        cx.spawn_in(window, async move |this, cx| {
 4107            let (_, path) = project_path_task.await?;
 4108            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4109                .await
 4110        })
 4111    }
 4112
 4113    pub fn open_path(
 4114        &mut self,
 4115        path: impl Into<ProjectPath>,
 4116        pane: Option<WeakEntity<Pane>>,
 4117        focus_item: bool,
 4118        window: &mut Window,
 4119        cx: &mut App,
 4120    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4121        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4122    }
 4123
 4124    pub fn open_path_preview(
 4125        &mut self,
 4126        path: impl Into<ProjectPath>,
 4127        pane: Option<WeakEntity<Pane>>,
 4128        focus_item: bool,
 4129        allow_preview: bool,
 4130        activate: bool,
 4131        window: &mut Window,
 4132        cx: &mut App,
 4133    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4134        let pane = pane.unwrap_or_else(|| {
 4135            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4136                self.panes
 4137                    .first()
 4138                    .expect("There must be an active pane")
 4139                    .downgrade()
 4140            })
 4141        });
 4142
 4143        let project_path = path.into();
 4144        let task = self.load_path(project_path.clone(), window, cx);
 4145        window.spawn(cx, async move |cx| {
 4146            let (project_entry_id, build_item) = task.await?;
 4147
 4148            pane.update_in(cx, |pane, window, cx| {
 4149                pane.open_item(
 4150                    project_entry_id,
 4151                    project_path,
 4152                    focus_item,
 4153                    allow_preview,
 4154                    activate,
 4155                    None,
 4156                    window,
 4157                    cx,
 4158                    build_item,
 4159                )
 4160            })
 4161        })
 4162    }
 4163
 4164    pub fn split_path(
 4165        &mut self,
 4166        path: impl Into<ProjectPath>,
 4167        window: &mut Window,
 4168        cx: &mut Context<Self>,
 4169    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4170        self.split_path_preview(path, false, None, window, cx)
 4171    }
 4172
 4173    pub fn split_path_preview(
 4174        &mut self,
 4175        path: impl Into<ProjectPath>,
 4176        allow_preview: bool,
 4177        split_direction: Option<SplitDirection>,
 4178        window: &mut Window,
 4179        cx: &mut Context<Self>,
 4180    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4181        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4182            self.panes
 4183                .first()
 4184                .expect("There must be an active pane")
 4185                .downgrade()
 4186        });
 4187
 4188        if let Member::Pane(center_pane) = &self.center.root
 4189            && center_pane.read(cx).items_len() == 0
 4190        {
 4191            return self.open_path(path, Some(pane), true, window, cx);
 4192        }
 4193
 4194        let project_path = path.into();
 4195        let task = self.load_path(project_path.clone(), window, cx);
 4196        cx.spawn_in(window, async move |this, cx| {
 4197            let (project_entry_id, build_item) = task.await?;
 4198            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4199                let pane = pane.upgrade()?;
 4200                let new_pane = this.split_pane(
 4201                    pane,
 4202                    split_direction.unwrap_or(SplitDirection::Right),
 4203                    window,
 4204                    cx,
 4205                );
 4206                new_pane.update(cx, |new_pane, cx| {
 4207                    Some(new_pane.open_item(
 4208                        project_entry_id,
 4209                        project_path,
 4210                        true,
 4211                        allow_preview,
 4212                        true,
 4213                        None,
 4214                        window,
 4215                        cx,
 4216                        build_item,
 4217                    ))
 4218                })
 4219            })
 4220            .map(|option| option.context("pane was dropped"))?
 4221        })
 4222    }
 4223
 4224    fn load_path(
 4225        &mut self,
 4226        path: ProjectPath,
 4227        window: &mut Window,
 4228        cx: &mut App,
 4229    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4230        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4231        registry.open_path(self.project(), &path, window, cx)
 4232    }
 4233
 4234    pub fn find_project_item<T>(
 4235        &self,
 4236        pane: &Entity<Pane>,
 4237        project_item: &Entity<T::Item>,
 4238        cx: &App,
 4239    ) -> Option<Entity<T>>
 4240    where
 4241        T: ProjectItem,
 4242    {
 4243        use project::ProjectItem as _;
 4244        let project_item = project_item.read(cx);
 4245        let entry_id = project_item.entry_id(cx);
 4246        let project_path = project_item.project_path(cx);
 4247
 4248        let mut item = None;
 4249        if let Some(entry_id) = entry_id {
 4250            item = pane.read(cx).item_for_entry(entry_id, cx);
 4251        }
 4252        if item.is_none()
 4253            && let Some(project_path) = project_path
 4254        {
 4255            item = pane.read(cx).item_for_path(project_path, cx);
 4256        }
 4257
 4258        item.and_then(|item| item.downcast::<T>())
 4259    }
 4260
 4261    pub fn is_project_item_open<T>(
 4262        &self,
 4263        pane: &Entity<Pane>,
 4264        project_item: &Entity<T::Item>,
 4265        cx: &App,
 4266    ) -> bool
 4267    where
 4268        T: ProjectItem,
 4269    {
 4270        self.find_project_item::<T>(pane, project_item, cx)
 4271            .is_some()
 4272    }
 4273
 4274    pub fn open_project_item<T>(
 4275        &mut self,
 4276        pane: Entity<Pane>,
 4277        project_item: Entity<T::Item>,
 4278        activate_pane: bool,
 4279        focus_item: bool,
 4280        keep_old_preview: bool,
 4281        allow_new_preview: bool,
 4282        window: &mut Window,
 4283        cx: &mut Context<Self>,
 4284    ) -> Entity<T>
 4285    where
 4286        T: ProjectItem,
 4287    {
 4288        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4289
 4290        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4291            if !keep_old_preview
 4292                && let Some(old_id) = old_item_id
 4293                && old_id != item.item_id()
 4294            {
 4295                // switching to a different item, so unpreview old active item
 4296                pane.update(cx, |pane, _| {
 4297                    pane.unpreview_item_if_preview(old_id);
 4298                });
 4299            }
 4300
 4301            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4302            if !allow_new_preview {
 4303                pane.update(cx, |pane, _| {
 4304                    pane.unpreview_item_if_preview(item.item_id());
 4305                });
 4306            }
 4307            return item;
 4308        }
 4309
 4310        let item = pane.update(cx, |pane, cx| {
 4311            cx.new(|cx| {
 4312                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4313            })
 4314        });
 4315        let mut destination_index = None;
 4316        pane.update(cx, |pane, cx| {
 4317            if !keep_old_preview && let Some(old_id) = old_item_id {
 4318                pane.unpreview_item_if_preview(old_id);
 4319            }
 4320            if allow_new_preview {
 4321                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4322            }
 4323        });
 4324
 4325        self.add_item(
 4326            pane,
 4327            Box::new(item.clone()),
 4328            destination_index,
 4329            activate_pane,
 4330            focus_item,
 4331            window,
 4332            cx,
 4333        );
 4334        item
 4335    }
 4336
 4337    pub fn open_shared_screen(
 4338        &mut self,
 4339        peer_id: PeerId,
 4340        window: &mut Window,
 4341        cx: &mut Context<Self>,
 4342    ) {
 4343        if let Some(shared_screen) =
 4344            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4345        {
 4346            self.active_pane.update(cx, |pane, cx| {
 4347                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4348            });
 4349        }
 4350    }
 4351
 4352    pub fn activate_item(
 4353        &mut self,
 4354        item: &dyn ItemHandle,
 4355        activate_pane: bool,
 4356        focus_item: bool,
 4357        window: &mut Window,
 4358        cx: &mut App,
 4359    ) -> bool {
 4360        let result = self.panes.iter().find_map(|pane| {
 4361            pane.read(cx)
 4362                .index_for_item(item)
 4363                .map(|ix| (pane.clone(), ix))
 4364        });
 4365        if let Some((pane, ix)) = result {
 4366            pane.update(cx, |pane, cx| {
 4367                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4368            });
 4369            true
 4370        } else {
 4371            false
 4372        }
 4373    }
 4374
 4375    fn activate_pane_at_index(
 4376        &mut self,
 4377        action: &ActivatePane,
 4378        window: &mut Window,
 4379        cx: &mut Context<Self>,
 4380    ) {
 4381        let panes = self.center.panes();
 4382        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4383            window.focus(&pane.focus_handle(cx), cx);
 4384        } else {
 4385            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4386                .detach();
 4387        }
 4388    }
 4389
 4390    fn move_item_to_pane_at_index(
 4391        &mut self,
 4392        action: &MoveItemToPane,
 4393        window: &mut Window,
 4394        cx: &mut Context<Self>,
 4395    ) {
 4396        let panes = self.center.panes();
 4397        let destination = match panes.get(action.destination) {
 4398            Some(&destination) => destination.clone(),
 4399            None => {
 4400                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4401                    return;
 4402                }
 4403                let direction = SplitDirection::Right;
 4404                let split_off_pane = self
 4405                    .find_pane_in_direction(direction, cx)
 4406                    .unwrap_or_else(|| self.active_pane.clone());
 4407                let new_pane = self.add_pane(window, cx);
 4408                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4409                new_pane
 4410            }
 4411        };
 4412
 4413        if action.clone {
 4414            if self
 4415                .active_pane
 4416                .read(cx)
 4417                .active_item()
 4418                .is_some_and(|item| item.can_split(cx))
 4419            {
 4420                clone_active_item(
 4421                    self.database_id(),
 4422                    &self.active_pane,
 4423                    &destination,
 4424                    action.focus,
 4425                    window,
 4426                    cx,
 4427                );
 4428                return;
 4429            }
 4430        }
 4431        move_active_item(
 4432            &self.active_pane,
 4433            &destination,
 4434            action.focus,
 4435            true,
 4436            window,
 4437            cx,
 4438        )
 4439    }
 4440
 4441    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4442        let panes = self.center.panes();
 4443        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4444            let next_ix = (ix + 1) % panes.len();
 4445            let next_pane = panes[next_ix].clone();
 4446            window.focus(&next_pane.focus_handle(cx), cx);
 4447        }
 4448    }
 4449
 4450    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4451        let panes = self.center.panes();
 4452        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4453            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4454            let prev_pane = panes[prev_ix].clone();
 4455            window.focus(&prev_pane.focus_handle(cx), cx);
 4456        }
 4457    }
 4458
 4459    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4460        let last_pane = self.center.last_pane();
 4461        window.focus(&last_pane.focus_handle(cx), cx);
 4462    }
 4463
 4464    pub fn activate_pane_in_direction(
 4465        &mut self,
 4466        direction: SplitDirection,
 4467        window: &mut Window,
 4468        cx: &mut App,
 4469    ) {
 4470        use ActivateInDirectionTarget as Target;
 4471        enum Origin {
 4472            LeftDock,
 4473            RightDock,
 4474            BottomDock,
 4475            Center,
 4476        }
 4477
 4478        let origin: Origin = [
 4479            (&self.left_dock, Origin::LeftDock),
 4480            (&self.right_dock, Origin::RightDock),
 4481            (&self.bottom_dock, Origin::BottomDock),
 4482        ]
 4483        .into_iter()
 4484        .find_map(|(dock, origin)| {
 4485            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4486                Some(origin)
 4487            } else {
 4488                None
 4489            }
 4490        })
 4491        .unwrap_or(Origin::Center);
 4492
 4493        let get_last_active_pane = || {
 4494            let pane = self
 4495                .last_active_center_pane
 4496                .clone()
 4497                .unwrap_or_else(|| {
 4498                    self.panes
 4499                        .first()
 4500                        .expect("There must be an active pane")
 4501                        .downgrade()
 4502                })
 4503                .upgrade()?;
 4504            (pane.read(cx).items_len() != 0).then_some(pane)
 4505        };
 4506
 4507        let try_dock =
 4508            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4509
 4510        let target = match (origin, direction) {
 4511            // We're in the center, so we first try to go to a different pane,
 4512            // otherwise try to go to a dock.
 4513            (Origin::Center, direction) => {
 4514                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4515                    Some(Target::Pane(pane))
 4516                } else {
 4517                    match direction {
 4518                        SplitDirection::Up => None,
 4519                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4520                        SplitDirection::Left => try_dock(&self.left_dock),
 4521                        SplitDirection::Right => try_dock(&self.right_dock),
 4522                    }
 4523                }
 4524            }
 4525
 4526            (Origin::LeftDock, SplitDirection::Right) => {
 4527                if let Some(last_active_pane) = get_last_active_pane() {
 4528                    Some(Target::Pane(last_active_pane))
 4529                } else {
 4530                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4531                }
 4532            }
 4533
 4534            (Origin::LeftDock, SplitDirection::Down)
 4535            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4536
 4537            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4538            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4539            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4540
 4541            (Origin::RightDock, SplitDirection::Left) => {
 4542                if let Some(last_active_pane) = get_last_active_pane() {
 4543                    Some(Target::Pane(last_active_pane))
 4544                } else {
 4545                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4546                }
 4547            }
 4548
 4549            _ => None,
 4550        };
 4551
 4552        match target {
 4553            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4554                let pane = pane.read(cx);
 4555                if let Some(item) = pane.active_item() {
 4556                    item.item_focus_handle(cx).focus(window, cx);
 4557                } else {
 4558                    log::error!(
 4559                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4560                    );
 4561                }
 4562            }
 4563            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4564                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4565                window.defer(cx, move |window, cx| {
 4566                    let dock = dock.read(cx);
 4567                    if let Some(panel) = dock.active_panel() {
 4568                        panel.panel_focus_handle(cx).focus(window, cx);
 4569                    } else {
 4570                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4571                    }
 4572                })
 4573            }
 4574            None => {}
 4575        }
 4576    }
 4577
 4578    pub fn move_item_to_pane_in_direction(
 4579        &mut self,
 4580        action: &MoveItemToPaneInDirection,
 4581        window: &mut Window,
 4582        cx: &mut Context<Self>,
 4583    ) {
 4584        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4585            Some(destination) => destination,
 4586            None => {
 4587                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4588                    return;
 4589                }
 4590                let new_pane = self.add_pane(window, cx);
 4591                self.center
 4592                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4593                new_pane
 4594            }
 4595        };
 4596
 4597        if action.clone {
 4598            if self
 4599                .active_pane
 4600                .read(cx)
 4601                .active_item()
 4602                .is_some_and(|item| item.can_split(cx))
 4603            {
 4604                clone_active_item(
 4605                    self.database_id(),
 4606                    &self.active_pane,
 4607                    &destination,
 4608                    action.focus,
 4609                    window,
 4610                    cx,
 4611                );
 4612                return;
 4613            }
 4614        }
 4615        move_active_item(
 4616            &self.active_pane,
 4617            &destination,
 4618            action.focus,
 4619            true,
 4620            window,
 4621            cx,
 4622        );
 4623    }
 4624
 4625    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4626        self.center.bounding_box_for_pane(pane)
 4627    }
 4628
 4629    pub fn find_pane_in_direction(
 4630        &mut self,
 4631        direction: SplitDirection,
 4632        cx: &App,
 4633    ) -> Option<Entity<Pane>> {
 4634        self.center
 4635            .find_pane_in_direction(&self.active_pane, direction, cx)
 4636            .cloned()
 4637    }
 4638
 4639    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4640        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4641            self.center.swap(&self.active_pane, &to, cx);
 4642            cx.notify();
 4643        }
 4644    }
 4645
 4646    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4647        if self
 4648            .center
 4649            .move_to_border(&self.active_pane, direction, cx)
 4650            .unwrap()
 4651        {
 4652            cx.notify();
 4653        }
 4654    }
 4655
 4656    pub fn resize_pane(
 4657        &mut self,
 4658        axis: gpui::Axis,
 4659        amount: Pixels,
 4660        window: &mut Window,
 4661        cx: &mut Context<Self>,
 4662    ) {
 4663        let docks = self.all_docks();
 4664        let active_dock = docks
 4665            .into_iter()
 4666            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4667
 4668        if let Some(dock) = active_dock {
 4669            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4670                return;
 4671            };
 4672            match dock.read(cx).position() {
 4673                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4674                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4675                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4676            }
 4677        } else {
 4678            self.center
 4679                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4680        }
 4681        cx.notify();
 4682    }
 4683
 4684    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4685        self.center.reset_pane_sizes(cx);
 4686        cx.notify();
 4687    }
 4688
 4689    fn handle_pane_focused(
 4690        &mut self,
 4691        pane: Entity<Pane>,
 4692        window: &mut Window,
 4693        cx: &mut Context<Self>,
 4694    ) {
 4695        // This is explicitly hoisted out of the following check for pane identity as
 4696        // terminal panel panes are not registered as a center panes.
 4697        self.status_bar.update(cx, |status_bar, cx| {
 4698            status_bar.set_active_pane(&pane, window, cx);
 4699        });
 4700        if self.active_pane != pane {
 4701            self.set_active_pane(&pane, window, cx);
 4702        }
 4703
 4704        if self.last_active_center_pane.is_none() {
 4705            self.last_active_center_pane = Some(pane.downgrade());
 4706        }
 4707
 4708        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4709        // This prevents the dock from closing when focus events fire during window activation.
 4710        // We also preserve any dock whose active panel itself has focus — this covers
 4711        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4712        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4713            let dock_read = dock.read(cx);
 4714            if let Some(panel) = dock_read.active_panel() {
 4715                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4716                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4717                {
 4718                    return Some(dock_read.position());
 4719                }
 4720            }
 4721            None
 4722        });
 4723
 4724        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4725        if pane.read(cx).is_zoomed() {
 4726            self.zoomed = Some(pane.downgrade().into());
 4727        } else {
 4728            self.zoomed = None;
 4729        }
 4730        self.zoomed_position = None;
 4731        cx.emit(Event::ZoomChanged);
 4732        self.update_active_view_for_followers(window, cx);
 4733        pane.update(cx, |pane, _| {
 4734            pane.track_alternate_file_items();
 4735        });
 4736
 4737        cx.notify();
 4738    }
 4739
 4740    fn set_active_pane(
 4741        &mut self,
 4742        pane: &Entity<Pane>,
 4743        window: &mut Window,
 4744        cx: &mut Context<Self>,
 4745    ) {
 4746        self.active_pane = pane.clone();
 4747        self.active_item_path_changed(true, window, cx);
 4748        self.last_active_center_pane = Some(pane.downgrade());
 4749    }
 4750
 4751    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4752        self.update_active_view_for_followers(window, cx);
 4753    }
 4754
 4755    fn handle_pane_event(
 4756        &mut self,
 4757        pane: &Entity<Pane>,
 4758        event: &pane::Event,
 4759        window: &mut Window,
 4760        cx: &mut Context<Self>,
 4761    ) {
 4762        let mut serialize_workspace = true;
 4763        match event {
 4764            pane::Event::AddItem { item } => {
 4765                item.added_to_pane(self, pane.clone(), window, cx);
 4766                cx.emit(Event::ItemAdded {
 4767                    item: item.boxed_clone(),
 4768                });
 4769            }
 4770            pane::Event::Split { direction, mode } => {
 4771                match mode {
 4772                    SplitMode::ClonePane => {
 4773                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4774                            .detach();
 4775                    }
 4776                    SplitMode::EmptyPane => {
 4777                        self.split_pane(pane.clone(), *direction, window, cx);
 4778                    }
 4779                    SplitMode::MovePane => {
 4780                        self.split_and_move(pane.clone(), *direction, window, cx);
 4781                    }
 4782                };
 4783            }
 4784            pane::Event::JoinIntoNext => {
 4785                self.join_pane_into_next(pane.clone(), window, cx);
 4786            }
 4787            pane::Event::JoinAll => {
 4788                self.join_all_panes(window, cx);
 4789            }
 4790            pane::Event::Remove { focus_on_pane } => {
 4791                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4792            }
 4793            pane::Event::ActivateItem {
 4794                local,
 4795                focus_changed,
 4796            } => {
 4797                window.invalidate_character_coordinates();
 4798
 4799                pane.update(cx, |pane, _| {
 4800                    pane.track_alternate_file_items();
 4801                });
 4802                if *local {
 4803                    self.unfollow_in_pane(pane, window, cx);
 4804                }
 4805                serialize_workspace = *focus_changed || pane != self.active_pane();
 4806                if pane == self.active_pane() {
 4807                    self.active_item_path_changed(*focus_changed, window, cx);
 4808                    self.update_active_view_for_followers(window, cx);
 4809                } else if *local {
 4810                    self.set_active_pane(pane, window, cx);
 4811                }
 4812            }
 4813            pane::Event::UserSavedItem { item, save_intent } => {
 4814                cx.emit(Event::UserSavedItem {
 4815                    pane: pane.downgrade(),
 4816                    item: item.boxed_clone(),
 4817                    save_intent: *save_intent,
 4818                });
 4819                serialize_workspace = false;
 4820            }
 4821            pane::Event::ChangeItemTitle => {
 4822                if *pane == self.active_pane {
 4823                    self.active_item_path_changed(false, window, cx);
 4824                }
 4825                serialize_workspace = false;
 4826            }
 4827            pane::Event::RemovedItem { item } => {
 4828                cx.emit(Event::ActiveItemChanged);
 4829                self.update_window_edited(window, cx);
 4830                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4831                    && entry.get().entity_id() == pane.entity_id()
 4832                {
 4833                    entry.remove();
 4834                }
 4835                cx.emit(Event::ItemRemoved {
 4836                    item_id: item.item_id(),
 4837                });
 4838            }
 4839            pane::Event::Focus => {
 4840                window.invalidate_character_coordinates();
 4841                self.handle_pane_focused(pane.clone(), window, cx);
 4842            }
 4843            pane::Event::ZoomIn => {
 4844                if *pane == self.active_pane {
 4845                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4846                    if pane.read(cx).has_focus(window, cx) {
 4847                        self.zoomed = Some(pane.downgrade().into());
 4848                        self.zoomed_position = None;
 4849                        cx.emit(Event::ZoomChanged);
 4850                    }
 4851                    cx.notify();
 4852                }
 4853            }
 4854            pane::Event::ZoomOut => {
 4855                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4856                if self.zoomed_position.is_none() {
 4857                    self.zoomed = None;
 4858                    cx.emit(Event::ZoomChanged);
 4859                }
 4860                cx.notify();
 4861            }
 4862            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4863        }
 4864
 4865        if serialize_workspace {
 4866            self.serialize_workspace(window, cx);
 4867        }
 4868    }
 4869
 4870    pub fn unfollow_in_pane(
 4871        &mut self,
 4872        pane: &Entity<Pane>,
 4873        window: &mut Window,
 4874        cx: &mut Context<Workspace>,
 4875    ) -> Option<CollaboratorId> {
 4876        let leader_id = self.leader_for_pane(pane)?;
 4877        self.unfollow(leader_id, window, cx);
 4878        Some(leader_id)
 4879    }
 4880
 4881    pub fn split_pane(
 4882        &mut self,
 4883        pane_to_split: Entity<Pane>,
 4884        split_direction: SplitDirection,
 4885        window: &mut Window,
 4886        cx: &mut Context<Self>,
 4887    ) -> Entity<Pane> {
 4888        let new_pane = self.add_pane(window, cx);
 4889        self.center
 4890            .split(&pane_to_split, &new_pane, split_direction, cx);
 4891        cx.notify();
 4892        new_pane
 4893    }
 4894
 4895    pub fn split_and_move(
 4896        &mut self,
 4897        pane: Entity<Pane>,
 4898        direction: SplitDirection,
 4899        window: &mut Window,
 4900        cx: &mut Context<Self>,
 4901    ) {
 4902        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4903            return;
 4904        };
 4905        let new_pane = self.add_pane(window, cx);
 4906        new_pane.update(cx, |pane, cx| {
 4907            pane.add_item(item, true, true, None, window, cx)
 4908        });
 4909        self.center.split(&pane, &new_pane, direction, cx);
 4910        cx.notify();
 4911    }
 4912
 4913    pub fn split_and_clone(
 4914        &mut self,
 4915        pane: Entity<Pane>,
 4916        direction: SplitDirection,
 4917        window: &mut Window,
 4918        cx: &mut Context<Self>,
 4919    ) -> Task<Option<Entity<Pane>>> {
 4920        let Some(item) = pane.read(cx).active_item() else {
 4921            return Task::ready(None);
 4922        };
 4923        if !item.can_split(cx) {
 4924            return Task::ready(None);
 4925        }
 4926        let task = item.clone_on_split(self.database_id(), window, cx);
 4927        cx.spawn_in(window, async move |this, cx| {
 4928            if let Some(clone) = task.await {
 4929                this.update_in(cx, |this, window, cx| {
 4930                    let new_pane = this.add_pane(window, cx);
 4931                    let nav_history = pane.read(cx).fork_nav_history();
 4932                    new_pane.update(cx, |pane, cx| {
 4933                        pane.set_nav_history(nav_history, cx);
 4934                        pane.add_item(clone, true, true, None, window, cx)
 4935                    });
 4936                    this.center.split(&pane, &new_pane, direction, cx);
 4937                    cx.notify();
 4938                    new_pane
 4939                })
 4940                .ok()
 4941            } else {
 4942                None
 4943            }
 4944        })
 4945    }
 4946
 4947    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4948        let active_item = self.active_pane.read(cx).active_item();
 4949        for pane in &self.panes {
 4950            join_pane_into_active(&self.active_pane, pane, window, cx);
 4951        }
 4952        if let Some(active_item) = active_item {
 4953            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4954        }
 4955        cx.notify();
 4956    }
 4957
 4958    pub fn join_pane_into_next(
 4959        &mut self,
 4960        pane: Entity<Pane>,
 4961        window: &mut Window,
 4962        cx: &mut Context<Self>,
 4963    ) {
 4964        let next_pane = self
 4965            .find_pane_in_direction(SplitDirection::Right, cx)
 4966            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4967            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4968            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4969        let Some(next_pane) = next_pane else {
 4970            return;
 4971        };
 4972        move_all_items(&pane, &next_pane, window, cx);
 4973        cx.notify();
 4974    }
 4975
 4976    fn remove_pane(
 4977        &mut self,
 4978        pane: Entity<Pane>,
 4979        focus_on: Option<Entity<Pane>>,
 4980        window: &mut Window,
 4981        cx: &mut Context<Self>,
 4982    ) {
 4983        if self.center.remove(&pane, cx).unwrap() {
 4984            self.force_remove_pane(&pane, &focus_on, window, cx);
 4985            self.unfollow_in_pane(&pane, window, cx);
 4986            self.last_leaders_by_pane.remove(&pane.downgrade());
 4987            for removed_item in pane.read(cx).items() {
 4988                self.panes_by_item.remove(&removed_item.item_id());
 4989            }
 4990
 4991            cx.notify();
 4992        } else {
 4993            self.active_item_path_changed(true, window, cx);
 4994        }
 4995        cx.emit(Event::PaneRemoved);
 4996    }
 4997
 4998    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4999        &mut self.panes
 5000    }
 5001
 5002    pub fn panes(&self) -> &[Entity<Pane>] {
 5003        &self.panes
 5004    }
 5005
 5006    pub fn active_pane(&self) -> &Entity<Pane> {
 5007        &self.active_pane
 5008    }
 5009
 5010    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5011        for dock in self.all_docks() {
 5012            if dock.focus_handle(cx).contains_focused(window, cx)
 5013                && let Some(pane) = dock
 5014                    .read(cx)
 5015                    .active_panel()
 5016                    .and_then(|panel| panel.pane(cx))
 5017            {
 5018                return pane;
 5019            }
 5020        }
 5021        self.active_pane().clone()
 5022    }
 5023
 5024    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5025        self.find_pane_in_direction(SplitDirection::Right, cx)
 5026            .unwrap_or_else(|| {
 5027                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5028            })
 5029    }
 5030
 5031    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5032        self.pane_for_item_id(handle.item_id())
 5033    }
 5034
 5035    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5036        let weak_pane = self.panes_by_item.get(&item_id)?;
 5037        weak_pane.upgrade()
 5038    }
 5039
 5040    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5041        self.panes
 5042            .iter()
 5043            .find(|pane| pane.entity_id() == entity_id)
 5044            .cloned()
 5045    }
 5046
 5047    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5048        self.follower_states.retain(|leader_id, state| {
 5049            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5050                for item in state.items_by_leader_view_id.values() {
 5051                    item.view.set_leader_id(None, window, cx);
 5052                }
 5053                false
 5054            } else {
 5055                true
 5056            }
 5057        });
 5058        cx.notify();
 5059    }
 5060
 5061    pub fn start_following(
 5062        &mut self,
 5063        leader_id: impl Into<CollaboratorId>,
 5064        window: &mut Window,
 5065        cx: &mut Context<Self>,
 5066    ) -> Option<Task<Result<()>>> {
 5067        let leader_id = leader_id.into();
 5068        let pane = self.active_pane().clone();
 5069
 5070        self.last_leaders_by_pane
 5071            .insert(pane.downgrade(), leader_id);
 5072        self.unfollow(leader_id, window, cx);
 5073        self.unfollow_in_pane(&pane, window, cx);
 5074        self.follower_states.insert(
 5075            leader_id,
 5076            FollowerState {
 5077                center_pane: pane.clone(),
 5078                dock_pane: None,
 5079                active_view_id: None,
 5080                items_by_leader_view_id: Default::default(),
 5081            },
 5082        );
 5083        cx.notify();
 5084
 5085        match leader_id {
 5086            CollaboratorId::PeerId(leader_peer_id) => {
 5087                let room_id = self.active_call()?.room_id(cx)?;
 5088                let project_id = self.project.read(cx).remote_id();
 5089                let request = self.app_state.client.request(proto::Follow {
 5090                    room_id,
 5091                    project_id,
 5092                    leader_id: Some(leader_peer_id),
 5093                });
 5094
 5095                Some(cx.spawn_in(window, async move |this, cx| {
 5096                    let response = request.await?;
 5097                    this.update(cx, |this, _| {
 5098                        let state = this
 5099                            .follower_states
 5100                            .get_mut(&leader_id)
 5101                            .context("following interrupted")?;
 5102                        state.active_view_id = response
 5103                            .active_view
 5104                            .as_ref()
 5105                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5106                        anyhow::Ok(())
 5107                    })??;
 5108                    if let Some(view) = response.active_view {
 5109                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5110                    }
 5111                    this.update_in(cx, |this, window, cx| {
 5112                        this.leader_updated(leader_id, window, cx)
 5113                    })?;
 5114                    Ok(())
 5115                }))
 5116            }
 5117            CollaboratorId::Agent => {
 5118                self.leader_updated(leader_id, window, cx)?;
 5119                Some(Task::ready(Ok(())))
 5120            }
 5121        }
 5122    }
 5123
 5124    pub fn follow_next_collaborator(
 5125        &mut self,
 5126        _: &FollowNextCollaborator,
 5127        window: &mut Window,
 5128        cx: &mut Context<Self>,
 5129    ) {
 5130        let collaborators = self.project.read(cx).collaborators();
 5131        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5132            let mut collaborators = collaborators.keys().copied();
 5133            for peer_id in collaborators.by_ref() {
 5134                if CollaboratorId::PeerId(peer_id) == leader_id {
 5135                    break;
 5136                }
 5137            }
 5138            collaborators.next().map(CollaboratorId::PeerId)
 5139        } else if let Some(last_leader_id) =
 5140            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5141        {
 5142            match last_leader_id {
 5143                CollaboratorId::PeerId(peer_id) => {
 5144                    if collaborators.contains_key(peer_id) {
 5145                        Some(*last_leader_id)
 5146                    } else {
 5147                        None
 5148                    }
 5149                }
 5150                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5151            }
 5152        } else {
 5153            None
 5154        };
 5155
 5156        let pane = self.active_pane.clone();
 5157        let Some(leader_id) = next_leader_id.or_else(|| {
 5158            Some(CollaboratorId::PeerId(
 5159                collaborators.keys().copied().next()?,
 5160            ))
 5161        }) else {
 5162            return;
 5163        };
 5164        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5165            return;
 5166        }
 5167        if let Some(task) = self.start_following(leader_id, window, cx) {
 5168            task.detach_and_log_err(cx)
 5169        }
 5170    }
 5171
 5172    pub fn follow(
 5173        &mut self,
 5174        leader_id: impl Into<CollaboratorId>,
 5175        window: &mut Window,
 5176        cx: &mut Context<Self>,
 5177    ) {
 5178        let leader_id = leader_id.into();
 5179
 5180        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5181            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5182                return;
 5183            };
 5184            let Some(remote_participant) =
 5185                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5186            else {
 5187                return;
 5188            };
 5189
 5190            let project = self.project.read(cx);
 5191
 5192            let other_project_id = match remote_participant.location {
 5193                ParticipantLocation::External => None,
 5194                ParticipantLocation::UnsharedProject => None,
 5195                ParticipantLocation::SharedProject { project_id } => {
 5196                    if Some(project_id) == project.remote_id() {
 5197                        None
 5198                    } else {
 5199                        Some(project_id)
 5200                    }
 5201                }
 5202            };
 5203
 5204            // if they are active in another project, follow there.
 5205            if let Some(project_id) = other_project_id {
 5206                let app_state = self.app_state.clone();
 5207                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5208                    .detach_and_log_err(cx);
 5209            }
 5210        }
 5211
 5212        // if you're already following, find the right pane and focus it.
 5213        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5214            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5215
 5216            return;
 5217        }
 5218
 5219        // Otherwise, follow.
 5220        if let Some(task) = self.start_following(leader_id, window, cx) {
 5221            task.detach_and_log_err(cx)
 5222        }
 5223    }
 5224
 5225    pub fn unfollow(
 5226        &mut self,
 5227        leader_id: impl Into<CollaboratorId>,
 5228        window: &mut Window,
 5229        cx: &mut Context<Self>,
 5230    ) -> Option<()> {
 5231        cx.notify();
 5232
 5233        let leader_id = leader_id.into();
 5234        let state = self.follower_states.remove(&leader_id)?;
 5235        for (_, item) in state.items_by_leader_view_id {
 5236            item.view.set_leader_id(None, window, cx);
 5237        }
 5238
 5239        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5240            let project_id = self.project.read(cx).remote_id();
 5241            let room_id = self.active_call()?.room_id(cx)?;
 5242            self.app_state
 5243                .client
 5244                .send(proto::Unfollow {
 5245                    room_id,
 5246                    project_id,
 5247                    leader_id: Some(leader_peer_id),
 5248                })
 5249                .log_err();
 5250        }
 5251
 5252        Some(())
 5253    }
 5254
 5255    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5256        self.follower_states.contains_key(&id.into())
 5257    }
 5258
 5259    fn active_item_path_changed(
 5260        &mut self,
 5261        focus_changed: bool,
 5262        window: &mut Window,
 5263        cx: &mut Context<Self>,
 5264    ) {
 5265        cx.emit(Event::ActiveItemChanged);
 5266        let active_entry = self.active_project_path(cx);
 5267        self.project.update(cx, |project, cx| {
 5268            project.set_active_path(active_entry.clone(), cx)
 5269        });
 5270
 5271        if focus_changed && let Some(project_path) = &active_entry {
 5272            let git_store_entity = self.project.read(cx).git_store().clone();
 5273            git_store_entity.update(cx, |git_store, cx| {
 5274                git_store.set_active_repo_for_path(project_path, cx);
 5275            });
 5276        }
 5277
 5278        self.update_window_title(window, cx);
 5279    }
 5280
 5281    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5282        let project = self.project().read(cx);
 5283        let mut title = String::new();
 5284
 5285        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5286            let name = {
 5287                let settings_location = SettingsLocation {
 5288                    worktree_id: worktree.read(cx).id(),
 5289                    path: RelPath::empty(),
 5290                };
 5291
 5292                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5293                match &settings.project_name {
 5294                    Some(name) => name.as_str(),
 5295                    None => worktree.read(cx).root_name_str(),
 5296                }
 5297            };
 5298            if i > 0 {
 5299                title.push_str(", ");
 5300            }
 5301            title.push_str(name);
 5302        }
 5303
 5304        if title.is_empty() {
 5305            title = "empty project".to_string();
 5306        }
 5307
 5308        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5309            let filename = path.path.file_name().or_else(|| {
 5310                Some(
 5311                    project
 5312                        .worktree_for_id(path.worktree_id, cx)?
 5313                        .read(cx)
 5314                        .root_name_str(),
 5315                )
 5316            });
 5317
 5318            if let Some(filename) = filename {
 5319                title.push_str("");
 5320                title.push_str(filename.as_ref());
 5321            }
 5322        }
 5323
 5324        if project.is_via_collab() {
 5325            title.push_str("");
 5326        } else if project.is_shared() {
 5327            title.push_str("");
 5328        }
 5329
 5330        if let Some(last_title) = self.last_window_title.as_ref()
 5331            && &title == last_title
 5332        {
 5333            return;
 5334        }
 5335        window.set_window_title(&title);
 5336        SystemWindowTabController::update_tab_title(
 5337            cx,
 5338            window.window_handle().window_id(),
 5339            SharedString::from(&title),
 5340        );
 5341        self.last_window_title = Some(title);
 5342    }
 5343
 5344    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5345        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5346        if is_edited != self.window_edited {
 5347            self.window_edited = is_edited;
 5348            window.set_window_edited(self.window_edited)
 5349        }
 5350    }
 5351
 5352    fn update_item_dirty_state(
 5353        &mut self,
 5354        item: &dyn ItemHandle,
 5355        window: &mut Window,
 5356        cx: &mut App,
 5357    ) {
 5358        let is_dirty = item.is_dirty(cx);
 5359        let item_id = item.item_id();
 5360        let was_dirty = self.dirty_items.contains_key(&item_id);
 5361        if is_dirty == was_dirty {
 5362            return;
 5363        }
 5364        if was_dirty {
 5365            self.dirty_items.remove(&item_id);
 5366            self.update_window_edited(window, cx);
 5367            return;
 5368        }
 5369
 5370        let workspace = self.weak_handle();
 5371        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5372            return;
 5373        };
 5374        let on_release_callback = Box::new(move |cx: &mut App| {
 5375            window_handle
 5376                .update(cx, |_, window, cx| {
 5377                    workspace
 5378                        .update(cx, |workspace, cx| {
 5379                            workspace.dirty_items.remove(&item_id);
 5380                            workspace.update_window_edited(window, cx)
 5381                        })
 5382                        .ok();
 5383                })
 5384                .ok();
 5385        });
 5386
 5387        let s = item.on_release(cx, on_release_callback);
 5388        self.dirty_items.insert(item_id, s);
 5389        self.update_window_edited(window, cx);
 5390    }
 5391
 5392    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5393        if self.notifications.is_empty() {
 5394            None
 5395        } else {
 5396            Some(
 5397                div()
 5398                    .absolute()
 5399                    .right_3()
 5400                    .bottom_3()
 5401                    .w_112()
 5402                    .h_full()
 5403                    .flex()
 5404                    .flex_col()
 5405                    .justify_end()
 5406                    .gap_2()
 5407                    .children(
 5408                        self.notifications
 5409                            .iter()
 5410                            .map(|(_, notification)| notification.clone().into_any()),
 5411                    ),
 5412            )
 5413        }
 5414    }
 5415
 5416    // RPC handlers
 5417
 5418    fn active_view_for_follower(
 5419        &self,
 5420        follower_project_id: Option<u64>,
 5421        window: &mut Window,
 5422        cx: &mut Context<Self>,
 5423    ) -> Option<proto::View> {
 5424        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5425        let item = item?;
 5426        let leader_id = self
 5427            .pane_for(&*item)
 5428            .and_then(|pane| self.leader_for_pane(&pane));
 5429        let leader_peer_id = match leader_id {
 5430            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5431            Some(CollaboratorId::Agent) | None => None,
 5432        };
 5433
 5434        let item_handle = item.to_followable_item_handle(cx)?;
 5435        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5436        let variant = item_handle.to_state_proto(window, cx)?;
 5437
 5438        if item_handle.is_project_item(window, cx)
 5439            && (follower_project_id.is_none()
 5440                || follower_project_id != self.project.read(cx).remote_id())
 5441        {
 5442            return None;
 5443        }
 5444
 5445        Some(proto::View {
 5446            id: id.to_proto(),
 5447            leader_id: leader_peer_id,
 5448            variant: Some(variant),
 5449            panel_id: panel_id.map(|id| id as i32),
 5450        })
 5451    }
 5452
 5453    fn handle_follow(
 5454        &mut self,
 5455        follower_project_id: Option<u64>,
 5456        window: &mut Window,
 5457        cx: &mut Context<Self>,
 5458    ) -> proto::FollowResponse {
 5459        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5460
 5461        cx.notify();
 5462        proto::FollowResponse {
 5463            views: active_view.iter().cloned().collect(),
 5464            active_view,
 5465        }
 5466    }
 5467
 5468    fn handle_update_followers(
 5469        &mut self,
 5470        leader_id: PeerId,
 5471        message: proto::UpdateFollowers,
 5472        _window: &mut Window,
 5473        _cx: &mut Context<Self>,
 5474    ) {
 5475        self.leader_updates_tx
 5476            .unbounded_send((leader_id, message))
 5477            .ok();
 5478    }
 5479
 5480    async fn process_leader_update(
 5481        this: &WeakEntity<Self>,
 5482        leader_id: PeerId,
 5483        update: proto::UpdateFollowers,
 5484        cx: &mut AsyncWindowContext,
 5485    ) -> Result<()> {
 5486        match update.variant.context("invalid update")? {
 5487            proto::update_followers::Variant::CreateView(view) => {
 5488                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5489                let should_add_view = this.update(cx, |this, _| {
 5490                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5491                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5492                    } else {
 5493                        anyhow::Ok(false)
 5494                    }
 5495                })??;
 5496
 5497                if should_add_view {
 5498                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5499                }
 5500            }
 5501            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5502                let should_add_view = this.update(cx, |this, _| {
 5503                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5504                        state.active_view_id = update_active_view
 5505                            .view
 5506                            .as_ref()
 5507                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5508
 5509                        if state.active_view_id.is_some_and(|view_id| {
 5510                            !state.items_by_leader_view_id.contains_key(&view_id)
 5511                        }) {
 5512                            anyhow::Ok(true)
 5513                        } else {
 5514                            anyhow::Ok(false)
 5515                        }
 5516                    } else {
 5517                        anyhow::Ok(false)
 5518                    }
 5519                })??;
 5520
 5521                if should_add_view && let Some(view) = update_active_view.view {
 5522                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5523                }
 5524            }
 5525            proto::update_followers::Variant::UpdateView(update_view) => {
 5526                let variant = update_view.variant.context("missing update view variant")?;
 5527                let id = update_view.id.context("missing update view id")?;
 5528                let mut tasks = Vec::new();
 5529                this.update_in(cx, |this, window, cx| {
 5530                    let project = this.project.clone();
 5531                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5532                        let view_id = ViewId::from_proto(id.clone())?;
 5533                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5534                            tasks.push(item.view.apply_update_proto(
 5535                                &project,
 5536                                variant.clone(),
 5537                                window,
 5538                                cx,
 5539                            ));
 5540                        }
 5541                    }
 5542                    anyhow::Ok(())
 5543                })??;
 5544                try_join_all(tasks).await.log_err();
 5545            }
 5546        }
 5547        this.update_in(cx, |this, window, cx| {
 5548            this.leader_updated(leader_id, window, cx)
 5549        })?;
 5550        Ok(())
 5551    }
 5552
 5553    async fn add_view_from_leader(
 5554        this: WeakEntity<Self>,
 5555        leader_id: PeerId,
 5556        view: &proto::View,
 5557        cx: &mut AsyncWindowContext,
 5558    ) -> Result<()> {
 5559        let this = this.upgrade().context("workspace dropped")?;
 5560
 5561        let Some(id) = view.id.clone() else {
 5562            anyhow::bail!("no id for view");
 5563        };
 5564        let id = ViewId::from_proto(id)?;
 5565        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5566
 5567        let pane = this.update(cx, |this, _cx| {
 5568            let state = this
 5569                .follower_states
 5570                .get(&leader_id.into())
 5571                .context("stopped following")?;
 5572            anyhow::Ok(state.pane().clone())
 5573        })?;
 5574        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5575            let client = this.read(cx).client().clone();
 5576            pane.items().find_map(|item| {
 5577                let item = item.to_followable_item_handle(cx)?;
 5578                if item.remote_id(&client, window, cx) == Some(id) {
 5579                    Some(item)
 5580                } else {
 5581                    None
 5582                }
 5583            })
 5584        })?;
 5585        let item = if let Some(existing_item) = existing_item {
 5586            existing_item
 5587        } else {
 5588            let variant = view.variant.clone();
 5589            anyhow::ensure!(variant.is_some(), "missing view variant");
 5590
 5591            let task = cx.update(|window, cx| {
 5592                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5593            })?;
 5594
 5595            let Some(task) = task else {
 5596                anyhow::bail!(
 5597                    "failed to construct view from leader (maybe from a different version of zed?)"
 5598                );
 5599            };
 5600
 5601            let mut new_item = task.await?;
 5602            pane.update_in(cx, |pane, window, cx| {
 5603                let mut item_to_remove = None;
 5604                for (ix, item) in pane.items().enumerate() {
 5605                    if let Some(item) = item.to_followable_item_handle(cx) {
 5606                        match new_item.dedup(item.as_ref(), window, cx) {
 5607                            Some(item::Dedup::KeepExisting) => {
 5608                                new_item =
 5609                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5610                                break;
 5611                            }
 5612                            Some(item::Dedup::ReplaceExisting) => {
 5613                                item_to_remove = Some((ix, item.item_id()));
 5614                                break;
 5615                            }
 5616                            None => {}
 5617                        }
 5618                    }
 5619                }
 5620
 5621                if let Some((ix, id)) = item_to_remove {
 5622                    pane.remove_item(id, false, false, window, cx);
 5623                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5624                }
 5625            })?;
 5626
 5627            new_item
 5628        };
 5629
 5630        this.update_in(cx, |this, window, cx| {
 5631            let state = this.follower_states.get_mut(&leader_id.into())?;
 5632            item.set_leader_id(Some(leader_id.into()), window, cx);
 5633            state.items_by_leader_view_id.insert(
 5634                id,
 5635                FollowerView {
 5636                    view: item,
 5637                    location: panel_id,
 5638                },
 5639            );
 5640
 5641            Some(())
 5642        })
 5643        .context("no follower state")?;
 5644
 5645        Ok(())
 5646    }
 5647
 5648    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5649        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5650            return;
 5651        };
 5652
 5653        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5654            let buffer_entity_id = agent_location.buffer.entity_id();
 5655            let view_id = ViewId {
 5656                creator: CollaboratorId::Agent,
 5657                id: buffer_entity_id.as_u64(),
 5658            };
 5659            follower_state.active_view_id = Some(view_id);
 5660
 5661            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5662                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5663                hash_map::Entry::Vacant(entry) => {
 5664                    let existing_view =
 5665                        follower_state
 5666                            .center_pane
 5667                            .read(cx)
 5668                            .items()
 5669                            .find_map(|item| {
 5670                                let item = item.to_followable_item_handle(cx)?;
 5671                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5672                                    && item.project_item_model_ids(cx).as_slice()
 5673                                        == [buffer_entity_id]
 5674                                {
 5675                                    Some(item)
 5676                                } else {
 5677                                    None
 5678                                }
 5679                            });
 5680                    let view = existing_view.or_else(|| {
 5681                        agent_location.buffer.upgrade().and_then(|buffer| {
 5682                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5683                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5684                            })?
 5685                            .to_followable_item_handle(cx)
 5686                        })
 5687                    });
 5688
 5689                    view.map(|view| {
 5690                        entry.insert(FollowerView {
 5691                            view,
 5692                            location: None,
 5693                        })
 5694                    })
 5695                }
 5696            };
 5697
 5698            if let Some(item) = item {
 5699                item.view
 5700                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5701                item.view
 5702                    .update_agent_location(agent_location.position, window, cx);
 5703            }
 5704        } else {
 5705            follower_state.active_view_id = None;
 5706        }
 5707
 5708        self.leader_updated(CollaboratorId::Agent, window, cx);
 5709    }
 5710
 5711    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5712        let mut is_project_item = true;
 5713        let mut update = proto::UpdateActiveView::default();
 5714        if window.is_window_active() {
 5715            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5716
 5717            if let Some(item) = active_item
 5718                && item.item_focus_handle(cx).contains_focused(window, cx)
 5719            {
 5720                let leader_id = self
 5721                    .pane_for(&*item)
 5722                    .and_then(|pane| self.leader_for_pane(&pane));
 5723                let leader_peer_id = match leader_id {
 5724                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5725                    Some(CollaboratorId::Agent) | None => None,
 5726                };
 5727
 5728                if let Some(item) = item.to_followable_item_handle(cx) {
 5729                    let id = item
 5730                        .remote_id(&self.app_state.client, window, cx)
 5731                        .map(|id| id.to_proto());
 5732
 5733                    if let Some(id) = id
 5734                        && let Some(variant) = item.to_state_proto(window, cx)
 5735                    {
 5736                        let view = Some(proto::View {
 5737                            id,
 5738                            leader_id: leader_peer_id,
 5739                            variant: Some(variant),
 5740                            panel_id: panel_id.map(|id| id as i32),
 5741                        });
 5742
 5743                        is_project_item = item.is_project_item(window, cx);
 5744                        update = proto::UpdateActiveView { view };
 5745                    };
 5746                }
 5747            }
 5748        }
 5749
 5750        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5751        if active_view_id != self.last_active_view_id.as_ref() {
 5752            self.last_active_view_id = active_view_id.cloned();
 5753            self.update_followers(
 5754                is_project_item,
 5755                proto::update_followers::Variant::UpdateActiveView(update),
 5756                window,
 5757                cx,
 5758            );
 5759        }
 5760    }
 5761
 5762    fn active_item_for_followers(
 5763        &self,
 5764        window: &mut Window,
 5765        cx: &mut App,
 5766    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5767        let mut active_item = None;
 5768        let mut panel_id = None;
 5769        for dock in self.all_docks() {
 5770            if dock.focus_handle(cx).contains_focused(window, cx)
 5771                && let Some(panel) = dock.read(cx).active_panel()
 5772                && let Some(pane) = panel.pane(cx)
 5773                && let Some(item) = pane.read(cx).active_item()
 5774            {
 5775                active_item = Some(item);
 5776                panel_id = panel.remote_id();
 5777                break;
 5778            }
 5779        }
 5780
 5781        if active_item.is_none() {
 5782            active_item = self.active_pane().read(cx).active_item();
 5783        }
 5784        (active_item, panel_id)
 5785    }
 5786
 5787    fn update_followers(
 5788        &self,
 5789        project_only: bool,
 5790        update: proto::update_followers::Variant,
 5791        _: &mut Window,
 5792        cx: &mut App,
 5793    ) -> Option<()> {
 5794        // If this update only applies to for followers in the current project,
 5795        // then skip it unless this project is shared. If it applies to all
 5796        // followers, regardless of project, then set `project_id` to none,
 5797        // indicating that it goes to all followers.
 5798        let project_id = if project_only {
 5799            Some(self.project.read(cx).remote_id()?)
 5800        } else {
 5801            None
 5802        };
 5803        self.app_state().workspace_store.update(cx, |store, cx| {
 5804            store.update_followers(project_id, update, cx)
 5805        })
 5806    }
 5807
 5808    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5809        self.follower_states.iter().find_map(|(leader_id, state)| {
 5810            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5811                Some(*leader_id)
 5812            } else {
 5813                None
 5814            }
 5815        })
 5816    }
 5817
 5818    fn leader_updated(
 5819        &mut self,
 5820        leader_id: impl Into<CollaboratorId>,
 5821        window: &mut Window,
 5822        cx: &mut Context<Self>,
 5823    ) -> Option<Box<dyn ItemHandle>> {
 5824        cx.notify();
 5825
 5826        let leader_id = leader_id.into();
 5827        let (panel_id, item) = match leader_id {
 5828            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5829            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5830        };
 5831
 5832        let state = self.follower_states.get(&leader_id)?;
 5833        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5834        let pane;
 5835        if let Some(panel_id) = panel_id {
 5836            pane = self
 5837                .activate_panel_for_proto_id(panel_id, window, cx)?
 5838                .pane(cx)?;
 5839            let state = self.follower_states.get_mut(&leader_id)?;
 5840            state.dock_pane = Some(pane.clone());
 5841        } else {
 5842            pane = state.center_pane.clone();
 5843            let state = self.follower_states.get_mut(&leader_id)?;
 5844            if let Some(dock_pane) = state.dock_pane.take() {
 5845                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5846            }
 5847        }
 5848
 5849        pane.update(cx, |pane, cx| {
 5850            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5851            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5852                pane.activate_item(index, false, false, window, cx);
 5853            } else {
 5854                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5855            }
 5856
 5857            if focus_active_item {
 5858                pane.focus_active_item(window, cx)
 5859            }
 5860        });
 5861
 5862        Some(item)
 5863    }
 5864
 5865    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5866        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5867        let active_view_id = state.active_view_id?;
 5868        Some(
 5869            state
 5870                .items_by_leader_view_id
 5871                .get(&active_view_id)?
 5872                .view
 5873                .boxed_clone(),
 5874        )
 5875    }
 5876
 5877    fn active_item_for_peer(
 5878        &self,
 5879        peer_id: PeerId,
 5880        window: &mut Window,
 5881        cx: &mut Context<Self>,
 5882    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5883        let call = self.active_call()?;
 5884        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5885        let leader_in_this_app;
 5886        let leader_in_this_project;
 5887        match participant.location {
 5888            ParticipantLocation::SharedProject { project_id } => {
 5889                leader_in_this_app = true;
 5890                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5891            }
 5892            ParticipantLocation::UnsharedProject => {
 5893                leader_in_this_app = true;
 5894                leader_in_this_project = false;
 5895            }
 5896            ParticipantLocation::External => {
 5897                leader_in_this_app = false;
 5898                leader_in_this_project = false;
 5899            }
 5900        };
 5901        let state = self.follower_states.get(&peer_id.into())?;
 5902        let mut item_to_activate = None;
 5903        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5904            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5905                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5906            {
 5907                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5908            }
 5909        } else if let Some(shared_screen) =
 5910            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5911        {
 5912            item_to_activate = Some((None, Box::new(shared_screen)));
 5913        }
 5914        item_to_activate
 5915    }
 5916
 5917    fn shared_screen_for_peer(
 5918        &self,
 5919        peer_id: PeerId,
 5920        pane: &Entity<Pane>,
 5921        window: &mut Window,
 5922        cx: &mut App,
 5923    ) -> Option<Entity<SharedScreen>> {
 5924        self.active_call()?
 5925            .create_shared_screen(peer_id, pane, window, cx)
 5926    }
 5927
 5928    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5929        if window.is_window_active() {
 5930            self.update_active_view_for_followers(window, cx);
 5931
 5932            if let Some(database_id) = self.database_id {
 5933                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5934                    .detach();
 5935            }
 5936        } else {
 5937            for pane in &self.panes {
 5938                pane.update(cx, |pane, cx| {
 5939                    if let Some(item) = pane.active_item() {
 5940                        item.workspace_deactivated(window, cx);
 5941                    }
 5942                    for item in pane.items() {
 5943                        if matches!(
 5944                            item.workspace_settings(cx).autosave,
 5945                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5946                        ) {
 5947                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5948                                .detach_and_log_err(cx);
 5949                        }
 5950                    }
 5951                });
 5952            }
 5953        }
 5954    }
 5955
 5956    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5957        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5958    }
 5959
 5960    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5961        self.active_call.as_ref().map(|(call, _)| call.clone())
 5962    }
 5963
 5964    fn on_active_call_event(
 5965        &mut self,
 5966        event: &ActiveCallEvent,
 5967        window: &mut Window,
 5968        cx: &mut Context<Self>,
 5969    ) {
 5970        match event {
 5971            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 5972            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 5973                self.leader_updated(participant_id, window, cx);
 5974            }
 5975        }
 5976    }
 5977
 5978    pub fn database_id(&self) -> Option<WorkspaceId> {
 5979        self.database_id
 5980    }
 5981
 5982    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 5983        self.database_id = Some(id);
 5984    }
 5985
 5986    pub fn session_id(&self) -> Option<String> {
 5987        self.session_id.clone()
 5988    }
 5989
 5990    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5991        let Some(display) = window.display(cx) else {
 5992            return Task::ready(());
 5993        };
 5994        let Ok(display_uuid) = display.uuid() else {
 5995            return Task::ready(());
 5996        };
 5997
 5998        let window_bounds = window.inner_window_bounds();
 5999        let database_id = self.database_id;
 6000        let has_paths = !self.root_paths(cx).is_empty();
 6001
 6002        cx.background_executor().spawn(async move {
 6003            if !has_paths {
 6004                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6005                    .await
 6006                    .log_err();
 6007            }
 6008            if let Some(database_id) = database_id {
 6009                DB.set_window_open_status(
 6010                    database_id,
 6011                    SerializedWindowBounds(window_bounds),
 6012                    display_uuid,
 6013                )
 6014                .await
 6015                .log_err();
 6016            } else {
 6017                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6018                    .await
 6019                    .log_err();
 6020            }
 6021        })
 6022    }
 6023
 6024    /// Bypass the 200ms serialization throttle and write workspace state to
 6025    /// the DB immediately. Returns a task the caller can await to ensure the
 6026    /// write completes. Used by the quit handler so the most recent state
 6027    /// isn't lost to a pending throttle timer when the process exits.
 6028    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6029        self._schedule_serialize_workspace.take();
 6030        self._serialize_workspace_task.take();
 6031        self.bounds_save_task_queued.take();
 6032
 6033        let bounds_task = self.save_window_bounds(window, cx);
 6034        let serialize_task = self.serialize_workspace_internal(window, cx);
 6035        cx.spawn(async move |_| {
 6036            bounds_task.await;
 6037            serialize_task.await;
 6038        })
 6039    }
 6040
 6041    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6042        let project = self.project().read(cx);
 6043        project
 6044            .visible_worktrees(cx)
 6045            .map(|worktree| worktree.read(cx).abs_path())
 6046            .collect::<Vec<_>>()
 6047    }
 6048
 6049    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6050        match member {
 6051            Member::Axis(PaneAxis { members, .. }) => {
 6052                for child in members.iter() {
 6053                    self.remove_panes(child.clone(), window, cx)
 6054                }
 6055            }
 6056            Member::Pane(pane) => {
 6057                self.force_remove_pane(&pane, &None, window, cx);
 6058            }
 6059        }
 6060    }
 6061
 6062    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6063        self.session_id.take();
 6064        self.serialize_workspace_internal(window, cx)
 6065    }
 6066
 6067    fn force_remove_pane(
 6068        &mut self,
 6069        pane: &Entity<Pane>,
 6070        focus_on: &Option<Entity<Pane>>,
 6071        window: &mut Window,
 6072        cx: &mut Context<Workspace>,
 6073    ) {
 6074        self.panes.retain(|p| p != pane);
 6075        if let Some(focus_on) = focus_on {
 6076            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6077        } else if self.active_pane() == pane {
 6078            self.panes
 6079                .last()
 6080                .unwrap()
 6081                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6082        }
 6083        if self.last_active_center_pane == Some(pane.downgrade()) {
 6084            self.last_active_center_pane = None;
 6085        }
 6086        cx.notify();
 6087    }
 6088
 6089    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6090        if self._schedule_serialize_workspace.is_none() {
 6091            self._schedule_serialize_workspace =
 6092                Some(cx.spawn_in(window, async move |this, cx| {
 6093                    cx.background_executor()
 6094                        .timer(SERIALIZATION_THROTTLE_TIME)
 6095                        .await;
 6096                    this.update_in(cx, |this, window, cx| {
 6097                        this._serialize_workspace_task =
 6098                            Some(this.serialize_workspace_internal(window, cx));
 6099                        this._schedule_serialize_workspace.take();
 6100                    })
 6101                    .log_err();
 6102                }));
 6103        }
 6104    }
 6105
 6106    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6107        let Some(database_id) = self.database_id() else {
 6108            return Task::ready(());
 6109        };
 6110
 6111        fn serialize_pane_handle(
 6112            pane_handle: &Entity<Pane>,
 6113            window: &mut Window,
 6114            cx: &mut App,
 6115        ) -> SerializedPane {
 6116            let (items, active, pinned_count) = {
 6117                let pane = pane_handle.read(cx);
 6118                let active_item_id = pane.active_item().map(|item| item.item_id());
 6119                (
 6120                    pane.items()
 6121                        .filter_map(|handle| {
 6122                            let handle = handle.to_serializable_item_handle(cx)?;
 6123
 6124                            Some(SerializedItem {
 6125                                kind: Arc::from(handle.serialized_item_kind()),
 6126                                item_id: handle.item_id().as_u64(),
 6127                                active: Some(handle.item_id()) == active_item_id,
 6128                                preview: pane.is_active_preview_item(handle.item_id()),
 6129                            })
 6130                        })
 6131                        .collect::<Vec<_>>(),
 6132                    pane.has_focus(window, cx),
 6133                    pane.pinned_count(),
 6134                )
 6135            };
 6136
 6137            SerializedPane::new(items, active, pinned_count)
 6138        }
 6139
 6140        fn build_serialized_pane_group(
 6141            pane_group: &Member,
 6142            window: &mut Window,
 6143            cx: &mut App,
 6144        ) -> SerializedPaneGroup {
 6145            match pane_group {
 6146                Member::Axis(PaneAxis {
 6147                    axis,
 6148                    members,
 6149                    flexes,
 6150                    bounding_boxes: _,
 6151                }) => SerializedPaneGroup::Group {
 6152                    axis: SerializedAxis(*axis),
 6153                    children: members
 6154                        .iter()
 6155                        .map(|member| build_serialized_pane_group(member, window, cx))
 6156                        .collect::<Vec<_>>(),
 6157                    flexes: Some(flexes.lock().clone()),
 6158                },
 6159                Member::Pane(pane_handle) => {
 6160                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6161                }
 6162            }
 6163        }
 6164
 6165        fn build_serialized_docks(
 6166            this: &Workspace,
 6167            window: &mut Window,
 6168            cx: &mut App,
 6169        ) -> DockStructure {
 6170            this.capture_dock_state(window, cx)
 6171        }
 6172
 6173        match self.workspace_location(cx) {
 6174            WorkspaceLocation::Location(location, paths) => {
 6175                let breakpoints = self.project.update(cx, |project, cx| {
 6176                    project
 6177                        .breakpoint_store()
 6178                        .read(cx)
 6179                        .all_source_breakpoints(cx)
 6180                });
 6181                let user_toolchains = self
 6182                    .project
 6183                    .read(cx)
 6184                    .user_toolchains(cx)
 6185                    .unwrap_or_default();
 6186
 6187                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6188                let docks = build_serialized_docks(self, window, cx);
 6189                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6190
 6191                let serialized_workspace = SerializedWorkspace {
 6192                    id: database_id,
 6193                    location,
 6194                    paths,
 6195                    center_group,
 6196                    window_bounds,
 6197                    display: Default::default(),
 6198                    docks,
 6199                    centered_layout: self.centered_layout,
 6200                    session_id: self.session_id.clone(),
 6201                    breakpoints,
 6202                    window_id: Some(window.window_handle().window_id().as_u64()),
 6203                    user_toolchains,
 6204                };
 6205
 6206                window.spawn(cx, async move |_| {
 6207                    persistence::DB.save_workspace(serialized_workspace).await;
 6208                })
 6209            }
 6210            WorkspaceLocation::DetachFromSession => {
 6211                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6212                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6213                // Save dock state for empty local workspaces
 6214                let docks = build_serialized_docks(self, window, cx);
 6215                window.spawn(cx, async move |_| {
 6216                    persistence::DB
 6217                        .set_window_open_status(
 6218                            database_id,
 6219                            window_bounds,
 6220                            display.unwrap_or_default(),
 6221                        )
 6222                        .await
 6223                        .log_err();
 6224                    persistence::DB
 6225                        .set_session_id(database_id, None)
 6226                        .await
 6227                        .log_err();
 6228                    persistence::write_default_dock_state(docks).await.log_err();
 6229                })
 6230            }
 6231            WorkspaceLocation::None => {
 6232                // Save dock state for empty non-local workspaces
 6233                let docks = build_serialized_docks(self, window, cx);
 6234                window.spawn(cx, async move |_| {
 6235                    persistence::write_default_dock_state(docks).await.log_err();
 6236                })
 6237            }
 6238        }
 6239    }
 6240
 6241    fn has_any_items_open(&self, cx: &App) -> bool {
 6242        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6243    }
 6244
 6245    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6246        let paths = PathList::new(&self.root_paths(cx));
 6247        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6248            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6249        } else if self.project.read(cx).is_local() {
 6250            if !paths.is_empty() || self.has_any_items_open(cx) {
 6251                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6252            } else {
 6253                WorkspaceLocation::DetachFromSession
 6254            }
 6255        } else {
 6256            WorkspaceLocation::None
 6257        }
 6258    }
 6259
 6260    fn update_history(&self, cx: &mut App) {
 6261        let Some(id) = self.database_id() else {
 6262            return;
 6263        };
 6264        if !self.project.read(cx).is_local() {
 6265            return;
 6266        }
 6267        if let Some(manager) = HistoryManager::global(cx) {
 6268            let paths = PathList::new(&self.root_paths(cx));
 6269            manager.update(cx, |this, cx| {
 6270                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6271            });
 6272        }
 6273    }
 6274
 6275    async fn serialize_items(
 6276        this: &WeakEntity<Self>,
 6277        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6278        cx: &mut AsyncWindowContext,
 6279    ) -> Result<()> {
 6280        const CHUNK_SIZE: usize = 200;
 6281
 6282        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6283
 6284        while let Some(items_received) = serializable_items.next().await {
 6285            let unique_items =
 6286                items_received
 6287                    .into_iter()
 6288                    .fold(HashMap::default(), |mut acc, item| {
 6289                        acc.entry(item.item_id()).or_insert(item);
 6290                        acc
 6291                    });
 6292
 6293            // We use into_iter() here so that the references to the items are moved into
 6294            // the tasks and not kept alive while we're sleeping.
 6295            for (_, item) in unique_items.into_iter() {
 6296                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6297                    item.serialize(workspace, false, window, cx)
 6298                }) {
 6299                    cx.background_spawn(async move { task.await.log_err() })
 6300                        .detach();
 6301                }
 6302            }
 6303
 6304            cx.background_executor()
 6305                .timer(SERIALIZATION_THROTTLE_TIME)
 6306                .await;
 6307        }
 6308
 6309        Ok(())
 6310    }
 6311
 6312    pub(crate) fn enqueue_item_serialization(
 6313        &mut self,
 6314        item: Box<dyn SerializableItemHandle>,
 6315    ) -> Result<()> {
 6316        self.serializable_items_tx
 6317            .unbounded_send(item)
 6318            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6319    }
 6320
 6321    pub(crate) fn load_workspace(
 6322        serialized_workspace: SerializedWorkspace,
 6323        paths_to_open: Vec<Option<ProjectPath>>,
 6324        window: &mut Window,
 6325        cx: &mut Context<Workspace>,
 6326    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6327        cx.spawn_in(window, async move |workspace, cx| {
 6328            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6329
 6330            let mut center_group = None;
 6331            let mut center_items = None;
 6332
 6333            // Traverse the splits tree and add to things
 6334            if let Some((group, active_pane, items)) = serialized_workspace
 6335                .center_group
 6336                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6337                .await
 6338            {
 6339                center_items = Some(items);
 6340                center_group = Some((group, active_pane))
 6341            }
 6342
 6343            let mut items_by_project_path = HashMap::default();
 6344            let mut item_ids_by_kind = HashMap::default();
 6345            let mut all_deserialized_items = Vec::default();
 6346            cx.update(|_, cx| {
 6347                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6348                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6349                        item_ids_by_kind
 6350                            .entry(serializable_item_handle.serialized_item_kind())
 6351                            .or_insert(Vec::new())
 6352                            .push(item.item_id().as_u64() as ItemId);
 6353                    }
 6354
 6355                    if let Some(project_path) = item.project_path(cx) {
 6356                        items_by_project_path.insert(project_path, item.clone());
 6357                    }
 6358                    all_deserialized_items.push(item);
 6359                }
 6360            })?;
 6361
 6362            let opened_items = paths_to_open
 6363                .into_iter()
 6364                .map(|path_to_open| {
 6365                    path_to_open
 6366                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6367                })
 6368                .collect::<Vec<_>>();
 6369
 6370            // Remove old panes from workspace panes list
 6371            workspace.update_in(cx, |workspace, window, cx| {
 6372                if let Some((center_group, active_pane)) = center_group {
 6373                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6374
 6375                    // Swap workspace center group
 6376                    workspace.center = PaneGroup::with_root(center_group);
 6377                    workspace.center.set_is_center(true);
 6378                    workspace.center.mark_positions(cx);
 6379
 6380                    if let Some(active_pane) = active_pane {
 6381                        workspace.set_active_pane(&active_pane, window, cx);
 6382                        cx.focus_self(window);
 6383                    } else {
 6384                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6385                    }
 6386                }
 6387
 6388                let docks = serialized_workspace.docks;
 6389
 6390                for (dock, serialized_dock) in [
 6391                    (&mut workspace.right_dock, docks.right),
 6392                    (&mut workspace.left_dock, docks.left),
 6393                    (&mut workspace.bottom_dock, docks.bottom),
 6394                ]
 6395                .iter_mut()
 6396                {
 6397                    dock.update(cx, |dock, cx| {
 6398                        dock.serialized_dock = Some(serialized_dock.clone());
 6399                        dock.restore_state(window, cx);
 6400                    });
 6401                }
 6402
 6403                cx.notify();
 6404            })?;
 6405
 6406            let _ = project
 6407                .update(cx, |project, cx| {
 6408                    project
 6409                        .breakpoint_store()
 6410                        .update(cx, |breakpoint_store, cx| {
 6411                            breakpoint_store
 6412                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6413                        })
 6414                })
 6415                .await;
 6416
 6417            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6418            // after loading the items, we might have different items and in order to avoid
 6419            // the database filling up, we delete items that haven't been loaded now.
 6420            //
 6421            // The items that have been loaded, have been saved after they've been added to the workspace.
 6422            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6423                item_ids_by_kind
 6424                    .into_iter()
 6425                    .map(|(item_kind, loaded_items)| {
 6426                        SerializableItemRegistry::cleanup(
 6427                            item_kind,
 6428                            serialized_workspace.id,
 6429                            loaded_items,
 6430                            window,
 6431                            cx,
 6432                        )
 6433                        .log_err()
 6434                    })
 6435                    .collect::<Vec<_>>()
 6436            })?;
 6437
 6438            futures::future::join_all(clean_up_tasks).await;
 6439
 6440            workspace
 6441                .update_in(cx, |workspace, window, cx| {
 6442                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6443                    workspace.serialize_workspace_internal(window, cx).detach();
 6444
 6445                    // Ensure that we mark the window as edited if we did load dirty items
 6446                    workspace.update_window_edited(window, cx);
 6447                })
 6448                .ok();
 6449
 6450            Ok(opened_items)
 6451        })
 6452    }
 6453
 6454    pub fn key_context(&self, cx: &App) -> KeyContext {
 6455        let mut context = KeyContext::new_with_defaults();
 6456        context.add("Workspace");
 6457        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6458        if let Some(status) = self
 6459            .debugger_provider
 6460            .as_ref()
 6461            .and_then(|provider| provider.active_thread_state(cx))
 6462        {
 6463            match status {
 6464                ThreadStatus::Running | ThreadStatus::Stepping => {
 6465                    context.add("debugger_running");
 6466                }
 6467                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6468                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6469            }
 6470        }
 6471
 6472        if self.left_dock.read(cx).is_open() {
 6473            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6474                context.set("left_dock", active_panel.panel_key());
 6475            }
 6476        }
 6477
 6478        if self.right_dock.read(cx).is_open() {
 6479            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6480                context.set("right_dock", active_panel.panel_key());
 6481            }
 6482        }
 6483
 6484        if self.bottom_dock.read(cx).is_open() {
 6485            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6486                context.set("bottom_dock", active_panel.panel_key());
 6487            }
 6488        }
 6489
 6490        context
 6491    }
 6492
 6493    /// Multiworkspace uses this to add workspace action handling to itself
 6494    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6495        self.add_workspace_actions_listeners(div, window, cx)
 6496            .on_action(cx.listener(
 6497                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6498                    for action in &action_sequence.0 {
 6499                        window.dispatch_action(action.boxed_clone(), cx);
 6500                    }
 6501                },
 6502            ))
 6503            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6504            .on_action(cx.listener(Self::close_all_items_and_panes))
 6505            .on_action(cx.listener(Self::close_item_in_all_panes))
 6506            .on_action(cx.listener(Self::save_all))
 6507            .on_action(cx.listener(Self::send_keystrokes))
 6508            .on_action(cx.listener(Self::add_folder_to_project))
 6509            .on_action(cx.listener(Self::follow_next_collaborator))
 6510            .on_action(cx.listener(Self::activate_pane_at_index))
 6511            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6512            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6513            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6514            .on_action(cx.listener(Self::toggle_theme_mode))
 6515            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6516                let pane = workspace.active_pane().clone();
 6517                workspace.unfollow_in_pane(&pane, window, cx);
 6518            }))
 6519            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6520                workspace
 6521                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6522                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6523            }))
 6524            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6525                workspace
 6526                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6527                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6528            }))
 6529            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6530                workspace
 6531                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6532                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6533            }))
 6534            .on_action(
 6535                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6536                    workspace.activate_previous_pane(window, cx)
 6537                }),
 6538            )
 6539            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6540                workspace.activate_next_pane(window, cx)
 6541            }))
 6542            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6543                workspace.activate_last_pane(window, cx)
 6544            }))
 6545            .on_action(
 6546                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6547                    workspace.activate_next_window(cx)
 6548                }),
 6549            )
 6550            .on_action(
 6551                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6552                    workspace.activate_previous_window(cx)
 6553                }),
 6554            )
 6555            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6556                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6557            }))
 6558            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6559                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6560            }))
 6561            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6562                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6563            }))
 6564            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6565                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6566            }))
 6567            .on_action(cx.listener(
 6568                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6569                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6570                },
 6571            ))
 6572            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6573                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6574            }))
 6575            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6576                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6577            }))
 6578            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6579                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6580            }))
 6581            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6582                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6583            }))
 6584            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6585                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6586                    SplitDirection::Down,
 6587                    SplitDirection::Up,
 6588                    SplitDirection::Right,
 6589                    SplitDirection::Left,
 6590                ];
 6591                for dir in DIRECTION_PRIORITY {
 6592                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6593                        workspace.swap_pane_in_direction(dir, cx);
 6594                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6595                        break;
 6596                    }
 6597                }
 6598            }))
 6599            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6600                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6601            }))
 6602            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6603                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6604            }))
 6605            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6606                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6607            }))
 6608            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6609                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6610            }))
 6611            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6612                this.toggle_dock(DockPosition::Left, window, cx);
 6613            }))
 6614            .on_action(cx.listener(
 6615                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6616                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6617                },
 6618            ))
 6619            .on_action(cx.listener(
 6620                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6621                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6622                },
 6623            ))
 6624            .on_action(cx.listener(
 6625                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6626                    if !workspace.close_active_dock(window, cx) {
 6627                        cx.propagate();
 6628                    }
 6629                },
 6630            ))
 6631            .on_action(
 6632                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6633                    workspace.close_all_docks(window, cx);
 6634                }),
 6635            )
 6636            .on_action(cx.listener(Self::toggle_all_docks))
 6637            .on_action(cx.listener(
 6638                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6639                    workspace.clear_all_notifications(cx);
 6640                },
 6641            ))
 6642            .on_action(cx.listener(
 6643                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6644                    workspace.clear_navigation_history(window, cx);
 6645                },
 6646            ))
 6647            .on_action(cx.listener(
 6648                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6649                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6650                        workspace.suppress_notification(&notification_id, cx);
 6651                    }
 6652                },
 6653            ))
 6654            .on_action(cx.listener(
 6655                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6656                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6657                },
 6658            ))
 6659            .on_action(
 6660                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6661                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6662                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6663                            trusted_worktrees.clear_trusted_paths()
 6664                        });
 6665                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6666                        cx.spawn(async move |_, cx| {
 6667                            if clear_task.await.log_err().is_some() {
 6668                                cx.update(|cx| reload(cx));
 6669                            }
 6670                        })
 6671                        .detach();
 6672                    }
 6673                }),
 6674            )
 6675            .on_action(cx.listener(
 6676                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6677                    workspace.reopen_closed_item(window, cx).detach();
 6678                },
 6679            ))
 6680            .on_action(cx.listener(
 6681                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6682                    for dock in workspace.all_docks() {
 6683                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6684                            let Some(panel) = dock.read(cx).active_panel() else {
 6685                                return;
 6686                            };
 6687
 6688                            // Set to `None`, then the size will fall back to the default.
 6689                            panel.clone().set_size(None, window, cx);
 6690
 6691                            return;
 6692                        }
 6693                    }
 6694                },
 6695            ))
 6696            .on_action(cx.listener(
 6697                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6698                    for dock in workspace.all_docks() {
 6699                        if let Some(panel) = dock.read(cx).visible_panel() {
 6700                            // Set to `None`, then the size will fall back to the default.
 6701                            panel.clone().set_size(None, window, cx);
 6702                        }
 6703                    }
 6704                },
 6705            ))
 6706            .on_action(cx.listener(
 6707                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6708                    adjust_active_dock_size_by_px(
 6709                        px_with_ui_font_fallback(act.px, cx),
 6710                        workspace,
 6711                        window,
 6712                        cx,
 6713                    );
 6714                },
 6715            ))
 6716            .on_action(cx.listener(
 6717                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6718                    adjust_active_dock_size_by_px(
 6719                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6720                        workspace,
 6721                        window,
 6722                        cx,
 6723                    );
 6724                },
 6725            ))
 6726            .on_action(cx.listener(
 6727                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6728                    adjust_open_docks_size_by_px(
 6729                        px_with_ui_font_fallback(act.px, cx),
 6730                        workspace,
 6731                        window,
 6732                        cx,
 6733                    );
 6734                },
 6735            ))
 6736            .on_action(cx.listener(
 6737                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6738                    adjust_open_docks_size_by_px(
 6739                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6740                        workspace,
 6741                        window,
 6742                        cx,
 6743                    );
 6744                },
 6745            ))
 6746            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6747            .on_action(cx.listener(
 6748                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6749                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6750                        let dock = active_dock.read(cx);
 6751                        if let Some(active_panel) = dock.active_panel() {
 6752                            if active_panel.pane(cx).is_none() {
 6753                                let mut recent_pane: Option<Entity<Pane>> = None;
 6754                                let mut recent_timestamp = 0;
 6755                                for pane_handle in workspace.panes() {
 6756                                    let pane = pane_handle.read(cx);
 6757                                    for entry in pane.activation_history() {
 6758                                        if entry.timestamp > recent_timestamp {
 6759                                            recent_timestamp = entry.timestamp;
 6760                                            recent_pane = Some(pane_handle.clone());
 6761                                        }
 6762                                    }
 6763                                }
 6764
 6765                                if let Some(pane) = recent_pane {
 6766                                    pane.update(cx, |pane, cx| {
 6767                                        let current_index = pane.active_item_index();
 6768                                        let items_len = pane.items_len();
 6769                                        if items_len > 0 {
 6770                                            let next_index = if current_index + 1 < items_len {
 6771                                                current_index + 1
 6772                                            } else {
 6773                                                0
 6774                                            };
 6775                                            pane.activate_item(
 6776                                                next_index, false, false, window, cx,
 6777                                            );
 6778                                        }
 6779                                    });
 6780                                    return;
 6781                                }
 6782                            }
 6783                        }
 6784                    }
 6785                    cx.propagate();
 6786                },
 6787            ))
 6788            .on_action(cx.listener(
 6789                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6790                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6791                        let dock = active_dock.read(cx);
 6792                        if let Some(active_panel) = dock.active_panel() {
 6793                            if active_panel.pane(cx).is_none() {
 6794                                let mut recent_pane: Option<Entity<Pane>> = None;
 6795                                let mut recent_timestamp = 0;
 6796                                for pane_handle in workspace.panes() {
 6797                                    let pane = pane_handle.read(cx);
 6798                                    for entry in pane.activation_history() {
 6799                                        if entry.timestamp > recent_timestamp {
 6800                                            recent_timestamp = entry.timestamp;
 6801                                            recent_pane = Some(pane_handle.clone());
 6802                                        }
 6803                                    }
 6804                                }
 6805
 6806                                if let Some(pane) = recent_pane {
 6807                                    pane.update(cx, |pane, cx| {
 6808                                        let current_index = pane.active_item_index();
 6809                                        let items_len = pane.items_len();
 6810                                        if items_len > 0 {
 6811                                            let prev_index = if current_index > 0 {
 6812                                                current_index - 1
 6813                                            } else {
 6814                                                items_len.saturating_sub(1)
 6815                                            };
 6816                                            pane.activate_item(
 6817                                                prev_index, false, false, window, cx,
 6818                                            );
 6819                                        }
 6820                                    });
 6821                                    return;
 6822                                }
 6823                            }
 6824                        }
 6825                    }
 6826                    cx.propagate();
 6827                },
 6828            ))
 6829            .on_action(cx.listener(
 6830                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6831                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6832                        let dock = active_dock.read(cx);
 6833                        if let Some(active_panel) = dock.active_panel() {
 6834                            if active_panel.pane(cx).is_none() {
 6835                                let active_pane = workspace.active_pane().clone();
 6836                                active_pane.update(cx, |pane, cx| {
 6837                                    pane.close_active_item(action, window, cx)
 6838                                        .detach_and_log_err(cx);
 6839                                });
 6840                                return;
 6841                            }
 6842                        }
 6843                    }
 6844                    cx.propagate();
 6845                },
 6846            ))
 6847            .on_action(
 6848                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6849                    let pane = workspace.active_pane().clone();
 6850                    if let Some(item) = pane.read(cx).active_item() {
 6851                        item.toggle_read_only(window, cx);
 6852                    }
 6853                }),
 6854            )
 6855            .on_action(cx.listener(Workspace::cancel))
 6856    }
 6857
 6858    #[cfg(any(test, feature = "test-support"))]
 6859    pub fn set_random_database_id(&mut self) {
 6860        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6861    }
 6862
 6863    #[cfg(any(test, feature = "test-support"))]
 6864    pub(crate) fn test_new(
 6865        project: Entity<Project>,
 6866        window: &mut Window,
 6867        cx: &mut Context<Self>,
 6868    ) -> Self {
 6869        use node_runtime::NodeRuntime;
 6870        use session::Session;
 6871
 6872        let client = project.read(cx).client();
 6873        let user_store = project.read(cx).user_store();
 6874        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6875        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6876        window.activate_window();
 6877        let app_state = Arc::new(AppState {
 6878            languages: project.read(cx).languages().clone(),
 6879            workspace_store,
 6880            client,
 6881            user_store,
 6882            fs: project.read(cx).fs().clone(),
 6883            build_window_options: |_, _| Default::default(),
 6884            node_runtime: NodeRuntime::unavailable(),
 6885            session,
 6886        });
 6887        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6888        workspace
 6889            .active_pane
 6890            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6891        workspace
 6892    }
 6893
 6894    pub fn register_action<A: Action>(
 6895        &mut self,
 6896        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6897    ) -> &mut Self {
 6898        let callback = Arc::new(callback);
 6899
 6900        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6901            let callback = callback.clone();
 6902            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6903                (callback)(workspace, event, window, cx)
 6904            }))
 6905        }));
 6906        self
 6907    }
 6908    pub fn register_action_renderer(
 6909        &mut self,
 6910        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6911    ) -> &mut Self {
 6912        self.workspace_actions.push(Box::new(callback));
 6913        self
 6914    }
 6915
 6916    fn add_workspace_actions_listeners(
 6917        &self,
 6918        mut div: Div,
 6919        window: &mut Window,
 6920        cx: &mut Context<Self>,
 6921    ) -> Div {
 6922        for action in self.workspace_actions.iter() {
 6923            div = (action)(div, self, window, cx)
 6924        }
 6925        div
 6926    }
 6927
 6928    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6929        self.modal_layer.read(cx).has_active_modal()
 6930    }
 6931
 6932    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6933        self.modal_layer.read(cx).active_modal()
 6934    }
 6935
 6936    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6937    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6938    /// If no modal is active, the new modal will be shown.
 6939    ///
 6940    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6941    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6942    /// will not be shown.
 6943    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6944    where
 6945        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6946    {
 6947        self.modal_layer.update(cx, |modal_layer, cx| {
 6948            modal_layer.toggle_modal(window, cx, build)
 6949        })
 6950    }
 6951
 6952    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6953        self.modal_layer
 6954            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6955    }
 6956
 6957    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6958        self.toast_layer
 6959            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6960    }
 6961
 6962    pub fn toggle_centered_layout(
 6963        &mut self,
 6964        _: &ToggleCenteredLayout,
 6965        _: &mut Window,
 6966        cx: &mut Context<Self>,
 6967    ) {
 6968        self.centered_layout = !self.centered_layout;
 6969        if let Some(database_id) = self.database_id() {
 6970            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6971                .detach_and_log_err(cx);
 6972        }
 6973        cx.notify();
 6974    }
 6975
 6976    fn adjust_padding(padding: Option<f32>) -> f32 {
 6977        padding
 6978            .unwrap_or(CenteredPaddingSettings::default().0)
 6979            .clamp(
 6980                CenteredPaddingSettings::MIN_PADDING,
 6981                CenteredPaddingSettings::MAX_PADDING,
 6982            )
 6983    }
 6984
 6985    fn render_dock(
 6986        &self,
 6987        position: DockPosition,
 6988        dock: &Entity<Dock>,
 6989        window: &mut Window,
 6990        cx: &mut App,
 6991    ) -> Option<Div> {
 6992        if self.zoomed_position == Some(position) {
 6993            return None;
 6994        }
 6995
 6996        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6997            let pane = panel.pane(cx)?;
 6998            let follower_states = &self.follower_states;
 6999            leader_border_for_pane(follower_states, &pane, window, cx)
 7000        });
 7001
 7002        Some(
 7003            div()
 7004                .flex()
 7005                .flex_none()
 7006                .overflow_hidden()
 7007                .child(dock.clone())
 7008                .children(leader_border),
 7009        )
 7010    }
 7011
 7012    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7013        window
 7014            .root::<MultiWorkspace>()
 7015            .flatten()
 7016            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7017    }
 7018
 7019    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7020        self.zoomed.as_ref()
 7021    }
 7022
 7023    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7024        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7025            return;
 7026        };
 7027        let windows = cx.windows();
 7028        let next_window =
 7029            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7030                || {
 7031                    windows
 7032                        .iter()
 7033                        .cycle()
 7034                        .skip_while(|window| window.window_id() != current_window_id)
 7035                        .nth(1)
 7036                },
 7037            );
 7038
 7039        if let Some(window) = next_window {
 7040            window
 7041                .update(cx, |_, window, _| window.activate_window())
 7042                .ok();
 7043        }
 7044    }
 7045
 7046    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7047        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7048            return;
 7049        };
 7050        let windows = cx.windows();
 7051        let prev_window =
 7052            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7053                || {
 7054                    windows
 7055                        .iter()
 7056                        .rev()
 7057                        .cycle()
 7058                        .skip_while(|window| window.window_id() != current_window_id)
 7059                        .nth(1)
 7060                },
 7061            );
 7062
 7063        if let Some(window) = prev_window {
 7064            window
 7065                .update(cx, |_, window, _| window.activate_window())
 7066                .ok();
 7067        }
 7068    }
 7069
 7070    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7071        if cx.stop_active_drag(window) {
 7072        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7073            dismiss_app_notification(&notification_id, cx);
 7074        } else {
 7075            cx.propagate();
 7076        }
 7077    }
 7078
 7079    fn adjust_dock_size_by_px(
 7080        &mut self,
 7081        panel_size: Pixels,
 7082        dock_pos: DockPosition,
 7083        px: Pixels,
 7084        window: &mut Window,
 7085        cx: &mut Context<Self>,
 7086    ) {
 7087        match dock_pos {
 7088            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7089            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7090            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7091        }
 7092    }
 7093
 7094    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7095        let workspace_width = self.bounds.size.width;
 7096        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7097
 7098        self.right_dock.read_with(cx, |right_dock, cx| {
 7099            let right_dock_size = right_dock
 7100                .active_panel_size(window, cx)
 7101                .unwrap_or(Pixels::ZERO);
 7102            if right_dock_size + size > workspace_width {
 7103                size = workspace_width - right_dock_size
 7104            }
 7105        });
 7106
 7107        self.left_dock.update(cx, |left_dock, cx| {
 7108            if WorkspaceSettings::get_global(cx)
 7109                .resize_all_panels_in_dock
 7110                .contains(&DockPosition::Left)
 7111            {
 7112                left_dock.resize_all_panels(Some(size), window, cx);
 7113            } else {
 7114                left_dock.resize_active_panel(Some(size), window, cx);
 7115            }
 7116        });
 7117    }
 7118
 7119    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7120        let workspace_width = self.bounds.size.width;
 7121        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7122        self.left_dock.read_with(cx, |left_dock, cx| {
 7123            let left_dock_size = left_dock
 7124                .active_panel_size(window, cx)
 7125                .unwrap_or(Pixels::ZERO);
 7126            if left_dock_size + size > workspace_width {
 7127                size = workspace_width - left_dock_size
 7128            }
 7129        });
 7130        self.right_dock.update(cx, |right_dock, cx| {
 7131            if WorkspaceSettings::get_global(cx)
 7132                .resize_all_panels_in_dock
 7133                .contains(&DockPosition::Right)
 7134            {
 7135                right_dock.resize_all_panels(Some(size), window, cx);
 7136            } else {
 7137                right_dock.resize_active_panel(Some(size), window, cx);
 7138            }
 7139        });
 7140    }
 7141
 7142    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7143        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7144        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7145            if WorkspaceSettings::get_global(cx)
 7146                .resize_all_panels_in_dock
 7147                .contains(&DockPosition::Bottom)
 7148            {
 7149                bottom_dock.resize_all_panels(Some(size), window, cx);
 7150            } else {
 7151                bottom_dock.resize_active_panel(Some(size), window, cx);
 7152            }
 7153        });
 7154    }
 7155
 7156    fn toggle_edit_predictions_all_files(
 7157        &mut self,
 7158        _: &ToggleEditPrediction,
 7159        _window: &mut Window,
 7160        cx: &mut Context<Self>,
 7161    ) {
 7162        let fs = self.project().read(cx).fs().clone();
 7163        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7164        update_settings_file(fs, cx, move |file, _| {
 7165            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7166        });
 7167    }
 7168
 7169    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7170        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7171        let next_mode = match current_mode {
 7172            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7173            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7174            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7175                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7176                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7177            },
 7178        };
 7179
 7180        let fs = self.project().read(cx).fs().clone();
 7181        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7182            theme::set_mode(settings, next_mode);
 7183        });
 7184    }
 7185
 7186    pub fn show_worktree_trust_security_modal(
 7187        &mut self,
 7188        toggle: bool,
 7189        window: &mut Window,
 7190        cx: &mut Context<Self>,
 7191    ) {
 7192        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7193            if toggle {
 7194                security_modal.update(cx, |security_modal, cx| {
 7195                    security_modal.dismiss(cx);
 7196                })
 7197            } else {
 7198                security_modal.update(cx, |security_modal, cx| {
 7199                    security_modal.refresh_restricted_paths(cx);
 7200                });
 7201            }
 7202        } else {
 7203            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7204                .map(|trusted_worktrees| {
 7205                    trusted_worktrees
 7206                        .read(cx)
 7207                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7208                })
 7209                .unwrap_or(false);
 7210            if has_restricted_worktrees {
 7211                let project = self.project().read(cx);
 7212                let remote_host = project
 7213                    .remote_connection_options(cx)
 7214                    .map(RemoteHostLocation::from);
 7215                let worktree_store = project.worktree_store().downgrade();
 7216                self.toggle_modal(window, cx, |_, cx| {
 7217                    SecurityModal::new(worktree_store, remote_host, cx)
 7218                });
 7219            }
 7220        }
 7221    }
 7222}
 7223
 7224pub trait AnyActiveCall {
 7225    fn entity(&self) -> AnyEntity;
 7226    fn is_in_room(&self, _: &App) -> bool;
 7227    fn room_id(&self, _: &App) -> Option<u64>;
 7228    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7229    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7230    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7231    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7232    fn is_sharing_project(&self, _: &App) -> bool;
 7233    fn has_remote_participants(&self, _: &App) -> bool;
 7234    fn local_participant_is_guest(&self, _: &App) -> bool;
 7235    fn client(&self, _: &App) -> Arc<Client>;
 7236    fn share_on_join(&self, _: &App) -> bool;
 7237    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7238    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7239    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7240    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7241    fn join_project(
 7242        &self,
 7243        _: u64,
 7244        _: Arc<LanguageRegistry>,
 7245        _: Arc<dyn Fs>,
 7246        _: &mut App,
 7247    ) -> Task<Result<Entity<Project>>>;
 7248    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7249    fn subscribe(
 7250        &self,
 7251        _: &mut Window,
 7252        _: &mut Context<Workspace>,
 7253        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7254    ) -> Subscription;
 7255    fn create_shared_screen(
 7256        &self,
 7257        _: PeerId,
 7258        _: &Entity<Pane>,
 7259        _: &mut Window,
 7260        _: &mut App,
 7261    ) -> Option<Entity<SharedScreen>>;
 7262}
 7263
 7264#[derive(Clone)]
 7265pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7266impl Global for GlobalAnyActiveCall {}
 7267
 7268impl GlobalAnyActiveCall {
 7269    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7270        cx.try_global()
 7271    }
 7272
 7273    pub(crate) fn global(cx: &App) -> &Self {
 7274        cx.global()
 7275    }
 7276}
 7277
 7278pub fn merge_conflict_notification_id() -> NotificationId {
 7279    struct MergeConflictNotification;
 7280    NotificationId::unique::<MergeConflictNotification>()
 7281}
 7282
 7283/// Workspace-local view of a remote participant's location.
 7284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7285pub enum ParticipantLocation {
 7286    SharedProject { project_id: u64 },
 7287    UnsharedProject,
 7288    External,
 7289}
 7290
 7291impl ParticipantLocation {
 7292    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7293        match location
 7294            .and_then(|l| l.variant)
 7295            .context("participant location was not provided")?
 7296        {
 7297            proto::participant_location::Variant::SharedProject(project) => {
 7298                Ok(Self::SharedProject {
 7299                    project_id: project.id,
 7300                })
 7301            }
 7302            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7303            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7304        }
 7305    }
 7306}
 7307/// Workspace-local view of a remote collaborator's state.
 7308/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7309#[derive(Clone)]
 7310pub struct RemoteCollaborator {
 7311    pub user: Arc<User>,
 7312    pub peer_id: PeerId,
 7313    pub location: ParticipantLocation,
 7314    pub participant_index: ParticipantIndex,
 7315}
 7316
 7317pub enum ActiveCallEvent {
 7318    ParticipantLocationChanged { participant_id: PeerId },
 7319    RemoteVideoTracksChanged { participant_id: PeerId },
 7320}
 7321
 7322fn leader_border_for_pane(
 7323    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7324    pane: &Entity<Pane>,
 7325    _: &Window,
 7326    cx: &App,
 7327) -> Option<Div> {
 7328    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7329        if state.pane() == pane {
 7330            Some((*leader_id, state))
 7331        } else {
 7332            None
 7333        }
 7334    })?;
 7335
 7336    let mut leader_color = match leader_id {
 7337        CollaboratorId::PeerId(leader_peer_id) => {
 7338            let leader = GlobalAnyActiveCall::try_global(cx)?
 7339                .0
 7340                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7341
 7342            cx.theme()
 7343                .players()
 7344                .color_for_participant(leader.participant_index.0)
 7345                .cursor
 7346        }
 7347        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7348    };
 7349    leader_color.fade_out(0.3);
 7350    Some(
 7351        div()
 7352            .absolute()
 7353            .size_full()
 7354            .left_0()
 7355            .top_0()
 7356            .border_2()
 7357            .border_color(leader_color),
 7358    )
 7359}
 7360
 7361fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7362    ZED_WINDOW_POSITION
 7363        .zip(*ZED_WINDOW_SIZE)
 7364        .map(|(position, size)| Bounds {
 7365            origin: position,
 7366            size,
 7367        })
 7368}
 7369
 7370fn open_items(
 7371    serialized_workspace: Option<SerializedWorkspace>,
 7372    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7373    window: &mut Window,
 7374    cx: &mut Context<Workspace>,
 7375) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7376    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7377        Workspace::load_workspace(
 7378            serialized_workspace,
 7379            project_paths_to_open
 7380                .iter()
 7381                .map(|(_, project_path)| project_path)
 7382                .cloned()
 7383                .collect(),
 7384            window,
 7385            cx,
 7386        )
 7387    });
 7388
 7389    cx.spawn_in(window, async move |workspace, cx| {
 7390        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7391
 7392        if let Some(restored_items) = restored_items {
 7393            let restored_items = restored_items.await?;
 7394
 7395            let restored_project_paths = restored_items
 7396                .iter()
 7397                .filter_map(|item| {
 7398                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7399                        .ok()
 7400                        .flatten()
 7401                })
 7402                .collect::<HashSet<_>>();
 7403
 7404            for restored_item in restored_items {
 7405                opened_items.push(restored_item.map(Ok));
 7406            }
 7407
 7408            project_paths_to_open
 7409                .iter_mut()
 7410                .for_each(|(_, project_path)| {
 7411                    if let Some(project_path_to_open) = project_path
 7412                        && restored_project_paths.contains(project_path_to_open)
 7413                    {
 7414                        *project_path = None;
 7415                    }
 7416                });
 7417        } else {
 7418            for _ in 0..project_paths_to_open.len() {
 7419                opened_items.push(None);
 7420            }
 7421        }
 7422        assert!(opened_items.len() == project_paths_to_open.len());
 7423
 7424        let tasks =
 7425            project_paths_to_open
 7426                .into_iter()
 7427                .enumerate()
 7428                .map(|(ix, (abs_path, project_path))| {
 7429                    let workspace = workspace.clone();
 7430                    cx.spawn(async move |cx| {
 7431                        let file_project_path = project_path?;
 7432                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7433                            workspace.project().update(cx, |project, cx| {
 7434                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7435                            })
 7436                        });
 7437
 7438                        // We only want to open file paths here. If one of the items
 7439                        // here is a directory, it was already opened further above
 7440                        // with a `find_or_create_worktree`.
 7441                        if let Ok(task) = abs_path_task
 7442                            && task.await.is_none_or(|p| p.is_file())
 7443                        {
 7444                            return Some((
 7445                                ix,
 7446                                workspace
 7447                                    .update_in(cx, |workspace, window, cx| {
 7448                                        workspace.open_path(
 7449                                            file_project_path,
 7450                                            None,
 7451                                            true,
 7452                                            window,
 7453                                            cx,
 7454                                        )
 7455                                    })
 7456                                    .log_err()?
 7457                                    .await,
 7458                            ));
 7459                        }
 7460                        None
 7461                    })
 7462                });
 7463
 7464        let tasks = tasks.collect::<Vec<_>>();
 7465
 7466        let tasks = futures::future::join_all(tasks);
 7467        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7468            opened_items[ix] = Some(path_open_result);
 7469        }
 7470
 7471        Ok(opened_items)
 7472    })
 7473}
 7474
 7475enum ActivateInDirectionTarget {
 7476    Pane(Entity<Pane>),
 7477    Dock(Entity<Dock>),
 7478}
 7479
 7480fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7481    window
 7482        .update(cx, |multi_workspace, _, cx| {
 7483            let workspace = multi_workspace.workspace().clone();
 7484            workspace.update(cx, |workspace, cx| {
 7485                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7486                    struct DatabaseFailedNotification;
 7487
 7488                    workspace.show_notification(
 7489                        NotificationId::unique::<DatabaseFailedNotification>(),
 7490                        cx,
 7491                        |cx| {
 7492                            cx.new(|cx| {
 7493                                MessageNotification::new("Failed to load the database file.", cx)
 7494                                    .primary_message("File an Issue")
 7495                                    .primary_icon(IconName::Plus)
 7496                                    .primary_on_click(|window, cx| {
 7497                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7498                                    })
 7499                            })
 7500                        },
 7501                    );
 7502                }
 7503            });
 7504        })
 7505        .log_err();
 7506}
 7507
 7508fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7509    if val == 0 {
 7510        ThemeSettings::get_global(cx).ui_font_size(cx)
 7511    } else {
 7512        px(val as f32)
 7513    }
 7514}
 7515
 7516fn adjust_active_dock_size_by_px(
 7517    px: Pixels,
 7518    workspace: &mut Workspace,
 7519    window: &mut Window,
 7520    cx: &mut Context<Workspace>,
 7521) {
 7522    let Some(active_dock) = workspace
 7523        .all_docks()
 7524        .into_iter()
 7525        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7526    else {
 7527        return;
 7528    };
 7529    let dock = active_dock.read(cx);
 7530    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7531        return;
 7532    };
 7533    let dock_pos = dock.position();
 7534    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7535}
 7536
 7537fn adjust_open_docks_size_by_px(
 7538    px: Pixels,
 7539    workspace: &mut Workspace,
 7540    window: &mut Window,
 7541    cx: &mut Context<Workspace>,
 7542) {
 7543    let docks = workspace
 7544        .all_docks()
 7545        .into_iter()
 7546        .filter_map(|dock| {
 7547            if dock.read(cx).is_open() {
 7548                let dock = dock.read(cx);
 7549                let panel_size = dock.active_panel_size(window, cx)?;
 7550                let dock_pos = dock.position();
 7551                Some((panel_size, dock_pos, px))
 7552            } else {
 7553                None
 7554            }
 7555        })
 7556        .collect::<Vec<_>>();
 7557
 7558    docks
 7559        .into_iter()
 7560        .for_each(|(panel_size, dock_pos, offset)| {
 7561            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7562        });
 7563}
 7564
 7565impl Focusable for Workspace {
 7566    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7567        self.active_pane.focus_handle(cx)
 7568    }
 7569}
 7570
 7571#[derive(Clone)]
 7572struct DraggedDock(DockPosition);
 7573
 7574impl Render for DraggedDock {
 7575    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7576        gpui::Empty
 7577    }
 7578}
 7579
 7580impl Render for Workspace {
 7581    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7582        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7583        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7584            log::info!("Rendered first frame");
 7585        }
 7586
 7587        let centered_layout = self.centered_layout
 7588            && self.center.panes().len() == 1
 7589            && self.active_item(cx).is_some();
 7590        let render_padding = |size| {
 7591            (size > 0.0).then(|| {
 7592                div()
 7593                    .h_full()
 7594                    .w(relative(size))
 7595                    .bg(cx.theme().colors().editor_background)
 7596                    .border_color(cx.theme().colors().pane_group_border)
 7597            })
 7598        };
 7599        let paddings = if centered_layout {
 7600            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7601            (
 7602                render_padding(Self::adjust_padding(
 7603                    settings.left_padding.map(|padding| padding.0),
 7604                )),
 7605                render_padding(Self::adjust_padding(
 7606                    settings.right_padding.map(|padding| padding.0),
 7607                )),
 7608            )
 7609        } else {
 7610            (None, None)
 7611        };
 7612        let ui_font = theme::setup_ui_font(window, cx);
 7613
 7614        let theme = cx.theme().clone();
 7615        let colors = theme.colors();
 7616        let notification_entities = self
 7617            .notifications
 7618            .iter()
 7619            .map(|(_, notification)| notification.entity_id())
 7620            .collect::<Vec<_>>();
 7621        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7622
 7623        div()
 7624            .relative()
 7625            .size_full()
 7626            .flex()
 7627            .flex_col()
 7628            .font(ui_font)
 7629            .gap_0()
 7630                .justify_start()
 7631                .items_start()
 7632                .text_color(colors.text)
 7633                .overflow_hidden()
 7634                .children(self.titlebar_item.clone())
 7635                .on_modifiers_changed(move |_, _, cx| {
 7636                    for &id in &notification_entities {
 7637                        cx.notify(id);
 7638                    }
 7639                })
 7640                .child(
 7641                    div()
 7642                        .size_full()
 7643                        .relative()
 7644                        .flex_1()
 7645                        .flex()
 7646                        .flex_col()
 7647                        .child(
 7648                            div()
 7649                                .id("workspace")
 7650                                .bg(colors.background)
 7651                                .relative()
 7652                                .flex_1()
 7653                                .w_full()
 7654                                .flex()
 7655                                .flex_col()
 7656                                .overflow_hidden()
 7657                                .border_t_1()
 7658                                .border_b_1()
 7659                                .border_color(colors.border)
 7660                                .child({
 7661                                    let this = cx.entity();
 7662                                    canvas(
 7663                                        move |bounds, window, cx| {
 7664                                            this.update(cx, |this, cx| {
 7665                                                let bounds_changed = this.bounds != bounds;
 7666                                                this.bounds = bounds;
 7667
 7668                                                if bounds_changed {
 7669                                                    this.left_dock.update(cx, |dock, cx| {
 7670                                                        dock.clamp_panel_size(
 7671                                                            bounds.size.width,
 7672                                                            window,
 7673                                                            cx,
 7674                                                        )
 7675                                                    });
 7676
 7677                                                    this.right_dock.update(cx, |dock, cx| {
 7678                                                        dock.clamp_panel_size(
 7679                                                            bounds.size.width,
 7680                                                            window,
 7681                                                            cx,
 7682                                                        )
 7683                                                    });
 7684
 7685                                                    this.bottom_dock.update(cx, |dock, cx| {
 7686                                                        dock.clamp_panel_size(
 7687                                                            bounds.size.height,
 7688                                                            window,
 7689                                                            cx,
 7690                                                        )
 7691                                                    });
 7692                                                }
 7693                                            })
 7694                                        },
 7695                                        |_, _, _, _| {},
 7696                                    )
 7697                                    .absolute()
 7698                                    .size_full()
 7699                                })
 7700                                .when(self.zoomed.is_none(), |this| {
 7701                                    this.on_drag_move(cx.listener(
 7702                                        move |workspace,
 7703                                              e: &DragMoveEvent<DraggedDock>,
 7704                                              window,
 7705                                              cx| {
 7706                                            if workspace.previous_dock_drag_coordinates
 7707                                                != Some(e.event.position)
 7708                                            {
 7709                                                workspace.previous_dock_drag_coordinates =
 7710                                                    Some(e.event.position);
 7711
 7712                                                match e.drag(cx).0 {
 7713                                                    DockPosition::Left => {
 7714                                                        workspace.resize_left_dock(
 7715                                                            e.event.position.x
 7716                                                                - workspace.bounds.left(),
 7717                                                            window,
 7718                                                            cx,
 7719                                                        );
 7720                                                    }
 7721                                                    DockPosition::Right => {
 7722                                                        workspace.resize_right_dock(
 7723                                                            workspace.bounds.right()
 7724                                                                - e.event.position.x,
 7725                                                            window,
 7726                                                            cx,
 7727                                                        );
 7728                                                    }
 7729                                                    DockPosition::Bottom => {
 7730                                                        workspace.resize_bottom_dock(
 7731                                                            workspace.bounds.bottom()
 7732                                                                - e.event.position.y,
 7733                                                            window,
 7734                                                            cx,
 7735                                                        );
 7736                                                    }
 7737                                                };
 7738                                                workspace.serialize_workspace(window, cx);
 7739                                            }
 7740                                        },
 7741                                    ))
 7742
 7743                                })
 7744                                .child({
 7745                                    match bottom_dock_layout {
 7746                                        BottomDockLayout::Full => div()
 7747                                            .flex()
 7748                                            .flex_col()
 7749                                            .h_full()
 7750                                            .child(
 7751                                                div()
 7752                                                    .flex()
 7753                                                    .flex_row()
 7754                                                    .flex_1()
 7755                                                    .overflow_hidden()
 7756                                                    .children(self.render_dock(
 7757                                                        DockPosition::Left,
 7758                                                        &self.left_dock,
 7759                                                        window,
 7760                                                        cx,
 7761                                                    ))
 7762
 7763                                                    .child(
 7764                                                        div()
 7765                                                            .flex()
 7766                                                            .flex_col()
 7767                                                            .flex_1()
 7768                                                            .overflow_hidden()
 7769                                                            .child(
 7770                                                                h_flex()
 7771                                                                    .flex_1()
 7772                                                                    .when_some(
 7773                                                                        paddings.0,
 7774                                                                        |this, p| {
 7775                                                                            this.child(
 7776                                                                                p.border_r_1(),
 7777                                                                            )
 7778                                                                        },
 7779                                                                    )
 7780                                                                    .child(self.center.render(
 7781                                                                        self.zoomed.as_ref(),
 7782                                                                        &PaneRenderContext {
 7783                                                                            follower_states:
 7784                                                                                &self.follower_states,
 7785                                                                            active_call: self.active_call(),
 7786                                                                            active_pane: &self.active_pane,
 7787                                                                            app_state: &self.app_state,
 7788                                                                            project: &self.project,
 7789                                                                            workspace: &self.weak_self,
 7790                                                                        },
 7791                                                                        window,
 7792                                                                        cx,
 7793                                                                    ))
 7794                                                                    .when_some(
 7795                                                                        paddings.1,
 7796                                                                        |this, p| {
 7797                                                                            this.child(
 7798                                                                                p.border_l_1(),
 7799                                                                            )
 7800                                                                        },
 7801                                                                    ),
 7802                                                            ),
 7803                                                    )
 7804
 7805                                                    .children(self.render_dock(
 7806                                                        DockPosition::Right,
 7807                                                        &self.right_dock,
 7808                                                        window,
 7809                                                        cx,
 7810                                                    )),
 7811                                            )
 7812                                            .child(div().w_full().children(self.render_dock(
 7813                                                DockPosition::Bottom,
 7814                                                &self.bottom_dock,
 7815                                                window,
 7816                                                cx
 7817                                            ))),
 7818
 7819                                        BottomDockLayout::LeftAligned => div()
 7820                                            .flex()
 7821                                            .flex_row()
 7822                                            .h_full()
 7823                                            .child(
 7824                                                div()
 7825                                                    .flex()
 7826                                                    .flex_col()
 7827                                                    .flex_1()
 7828                                                    .h_full()
 7829                                                    .child(
 7830                                                        div()
 7831                                                            .flex()
 7832                                                            .flex_row()
 7833                                                            .flex_1()
 7834                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7835
 7836                                                            .child(
 7837                                                                div()
 7838                                                                    .flex()
 7839                                                                    .flex_col()
 7840                                                                    .flex_1()
 7841                                                                    .overflow_hidden()
 7842                                                                    .child(
 7843                                                                        h_flex()
 7844                                                                            .flex_1()
 7845                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7846                                                                            .child(self.center.render(
 7847                                                                                self.zoomed.as_ref(),
 7848                                                                                &PaneRenderContext {
 7849                                                                                    follower_states:
 7850                                                                                        &self.follower_states,
 7851                                                                                    active_call: self.active_call(),
 7852                                                                                    active_pane: &self.active_pane,
 7853                                                                                    app_state: &self.app_state,
 7854                                                                                    project: &self.project,
 7855                                                                                    workspace: &self.weak_self,
 7856                                                                                },
 7857                                                                                window,
 7858                                                                                cx,
 7859                                                                            ))
 7860                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7861                                                                    )
 7862                                                            )
 7863
 7864                                                    )
 7865                                                    .child(
 7866                                                        div()
 7867                                                            .w_full()
 7868                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7869                                                    ),
 7870                                            )
 7871                                            .children(self.render_dock(
 7872                                                DockPosition::Right,
 7873                                                &self.right_dock,
 7874                                                window,
 7875                                                cx,
 7876                                            )),
 7877                                        BottomDockLayout::RightAligned => div()
 7878                                            .flex()
 7879                                            .flex_row()
 7880                                            .h_full()
 7881                                            .children(self.render_dock(
 7882                                                DockPosition::Left,
 7883                                                &self.left_dock,
 7884                                                window,
 7885                                                cx,
 7886                                            ))
 7887
 7888                                            .child(
 7889                                                div()
 7890                                                    .flex()
 7891                                                    .flex_col()
 7892                                                    .flex_1()
 7893                                                    .h_full()
 7894                                                    .child(
 7895                                                        div()
 7896                                                            .flex()
 7897                                                            .flex_row()
 7898                                                            .flex_1()
 7899                                                            .child(
 7900                                                                div()
 7901                                                                    .flex()
 7902                                                                    .flex_col()
 7903                                                                    .flex_1()
 7904                                                                    .overflow_hidden()
 7905                                                                    .child(
 7906                                                                        h_flex()
 7907                                                                            .flex_1()
 7908                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7909                                                                            .child(self.center.render(
 7910                                                                                self.zoomed.as_ref(),
 7911                                                                                &PaneRenderContext {
 7912                                                                                    follower_states:
 7913                                                                                        &self.follower_states,
 7914                                                                                    active_call: self.active_call(),
 7915                                                                                    active_pane: &self.active_pane,
 7916                                                                                    app_state: &self.app_state,
 7917                                                                                    project: &self.project,
 7918                                                                                    workspace: &self.weak_self,
 7919                                                                                },
 7920                                                                                window,
 7921                                                                                cx,
 7922                                                                            ))
 7923                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7924                                                                    )
 7925                                                            )
 7926
 7927                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7928                                                    )
 7929                                                    .child(
 7930                                                        div()
 7931                                                            .w_full()
 7932                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7933                                                    ),
 7934                                            ),
 7935                                        BottomDockLayout::Contained => div()
 7936                                            .flex()
 7937                                            .flex_row()
 7938                                            .h_full()
 7939                                            .children(self.render_dock(
 7940                                                DockPosition::Left,
 7941                                                &self.left_dock,
 7942                                                window,
 7943                                                cx,
 7944                                            ))
 7945
 7946                                            .child(
 7947                                                div()
 7948                                                    .flex()
 7949                                                    .flex_col()
 7950                                                    .flex_1()
 7951                                                    .overflow_hidden()
 7952                                                    .child(
 7953                                                        h_flex()
 7954                                                            .flex_1()
 7955                                                            .when_some(paddings.0, |this, p| {
 7956                                                                this.child(p.border_r_1())
 7957                                                            })
 7958                                                            .child(self.center.render(
 7959                                                                self.zoomed.as_ref(),
 7960                                                                &PaneRenderContext {
 7961                                                                    follower_states:
 7962                                                                        &self.follower_states,
 7963                                                                    active_call: self.active_call(),
 7964                                                                    active_pane: &self.active_pane,
 7965                                                                    app_state: &self.app_state,
 7966                                                                    project: &self.project,
 7967                                                                    workspace: &self.weak_self,
 7968                                                                },
 7969                                                                window,
 7970                                                                cx,
 7971                                                            ))
 7972                                                            .when_some(paddings.1, |this, p| {
 7973                                                                this.child(p.border_l_1())
 7974                                                            }),
 7975                                                    )
 7976                                                    .children(self.render_dock(
 7977                                                        DockPosition::Bottom,
 7978                                                        &self.bottom_dock,
 7979                                                        window,
 7980                                                        cx,
 7981                                                    )),
 7982                                            )
 7983
 7984                                            .children(self.render_dock(
 7985                                                DockPosition::Right,
 7986                                                &self.right_dock,
 7987                                                window,
 7988                                                cx,
 7989                                            )),
 7990                                    }
 7991                                })
 7992                                .children(self.zoomed.as_ref().and_then(|view| {
 7993                                    let zoomed_view = view.upgrade()?;
 7994                                    let div = div()
 7995                                        .occlude()
 7996                                        .absolute()
 7997                                        .overflow_hidden()
 7998                                        .border_color(colors.border)
 7999                                        .bg(colors.background)
 8000                                        .child(zoomed_view)
 8001                                        .inset_0()
 8002                                        .shadow_lg();
 8003
 8004                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8005                                       return Some(div);
 8006                                    }
 8007
 8008                                    Some(match self.zoomed_position {
 8009                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8010                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8011                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8012                                        None => {
 8013                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8014                                        }
 8015                                    })
 8016                                }))
 8017                                .children(self.render_notifications(window, cx)),
 8018                        )
 8019                        .when(self.status_bar_visible(cx), |parent| {
 8020                            parent.child(self.status_bar.clone())
 8021                        })
 8022                        .child(self.toast_layer.clone()),
 8023                )
 8024    }
 8025}
 8026
 8027impl WorkspaceStore {
 8028    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8029        Self {
 8030            workspaces: Default::default(),
 8031            _subscriptions: vec![
 8032                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8033                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8034            ],
 8035            client,
 8036        }
 8037    }
 8038
 8039    pub fn update_followers(
 8040        &self,
 8041        project_id: Option<u64>,
 8042        update: proto::update_followers::Variant,
 8043        cx: &App,
 8044    ) -> Option<()> {
 8045        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8046        let room_id = active_call.0.room_id(cx)?;
 8047        self.client
 8048            .send(proto::UpdateFollowers {
 8049                room_id,
 8050                project_id,
 8051                variant: Some(update),
 8052            })
 8053            .log_err()
 8054    }
 8055
 8056    pub async fn handle_follow(
 8057        this: Entity<Self>,
 8058        envelope: TypedEnvelope<proto::Follow>,
 8059        mut cx: AsyncApp,
 8060    ) -> Result<proto::FollowResponse> {
 8061        this.update(&mut cx, |this, cx| {
 8062            let follower = Follower {
 8063                project_id: envelope.payload.project_id,
 8064                peer_id: envelope.original_sender_id()?,
 8065            };
 8066
 8067            let mut response = proto::FollowResponse::default();
 8068
 8069            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8070                let Some(workspace) = weak_workspace.upgrade() else {
 8071                    return false;
 8072                };
 8073                window_handle
 8074                    .update(cx, |_, window, cx| {
 8075                        workspace.update(cx, |workspace, cx| {
 8076                            let handler_response =
 8077                                workspace.handle_follow(follower.project_id, window, cx);
 8078                            if let Some(active_view) = handler_response.active_view
 8079                                && workspace.project.read(cx).remote_id() == follower.project_id
 8080                            {
 8081                                response.active_view = Some(active_view)
 8082                            }
 8083                        });
 8084                    })
 8085                    .is_ok()
 8086            });
 8087
 8088            Ok(response)
 8089        })
 8090    }
 8091
 8092    async fn handle_update_followers(
 8093        this: Entity<Self>,
 8094        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8095        mut cx: AsyncApp,
 8096    ) -> Result<()> {
 8097        let leader_id = envelope.original_sender_id()?;
 8098        let update = envelope.payload;
 8099
 8100        this.update(&mut cx, |this, cx| {
 8101            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8102                let Some(workspace) = weak_workspace.upgrade() else {
 8103                    return false;
 8104                };
 8105                window_handle
 8106                    .update(cx, |_, window, cx| {
 8107                        workspace.update(cx, |workspace, cx| {
 8108                            let project_id = workspace.project.read(cx).remote_id();
 8109                            if update.project_id != project_id && update.project_id.is_some() {
 8110                                return;
 8111                            }
 8112                            workspace.handle_update_followers(
 8113                                leader_id,
 8114                                update.clone(),
 8115                                window,
 8116                                cx,
 8117                            );
 8118                        });
 8119                    })
 8120                    .is_ok()
 8121            });
 8122            Ok(())
 8123        })
 8124    }
 8125
 8126    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8127        self.workspaces.iter().map(|(_, weak)| weak)
 8128    }
 8129
 8130    pub fn workspaces_with_windows(
 8131        &self,
 8132    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8133        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8134    }
 8135}
 8136
 8137impl ViewId {
 8138    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8139        Ok(Self {
 8140            creator: message
 8141                .creator
 8142                .map(CollaboratorId::PeerId)
 8143                .context("creator is missing")?,
 8144            id: message.id,
 8145        })
 8146    }
 8147
 8148    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8149        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8150            Some(proto::ViewId {
 8151                creator: Some(peer_id),
 8152                id: self.id,
 8153            })
 8154        } else {
 8155            None
 8156        }
 8157    }
 8158}
 8159
 8160impl FollowerState {
 8161    fn pane(&self) -> &Entity<Pane> {
 8162        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8163    }
 8164}
 8165
 8166pub trait WorkspaceHandle {
 8167    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8168}
 8169
 8170impl WorkspaceHandle for Entity<Workspace> {
 8171    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8172        self.read(cx)
 8173            .worktrees(cx)
 8174            .flat_map(|worktree| {
 8175                let worktree_id = worktree.read(cx).id();
 8176                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8177                    worktree_id,
 8178                    path: f.path.clone(),
 8179                })
 8180            })
 8181            .collect::<Vec<_>>()
 8182    }
 8183}
 8184
 8185pub async fn last_opened_workspace_location(
 8186    fs: &dyn fs::Fs,
 8187) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8188    DB.last_workspace(fs)
 8189        .await
 8190        .log_err()
 8191        .flatten()
 8192        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8193}
 8194
 8195pub async fn last_session_workspace_locations(
 8196    last_session_id: &str,
 8197    last_session_window_stack: Option<Vec<WindowId>>,
 8198    fs: &dyn fs::Fs,
 8199) -> Option<Vec<SessionWorkspace>> {
 8200    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8201        .await
 8202        .log_err()
 8203}
 8204
 8205pub struct MultiWorkspaceRestoreResult {
 8206    pub window_handle: WindowHandle<MultiWorkspace>,
 8207    pub errors: Vec<anyhow::Error>,
 8208}
 8209
 8210pub async fn restore_multiworkspace(
 8211    multi_workspace: SerializedMultiWorkspace,
 8212    app_state: Arc<AppState>,
 8213    cx: &mut AsyncApp,
 8214) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8215    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8216    let mut group_iter = workspaces.into_iter();
 8217    let first = group_iter
 8218        .next()
 8219        .context("window group must not be empty")?;
 8220
 8221    let window_handle = if first.paths.is_empty() {
 8222        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8223            .await?
 8224    } else {
 8225        let OpenResult { window, .. } = cx
 8226            .update(|cx| {
 8227                Workspace::new_local(
 8228                    first.paths.paths().to_vec(),
 8229                    app_state.clone(),
 8230                    None,
 8231                    None,
 8232                    None,
 8233                    true,
 8234                    cx,
 8235                )
 8236            })
 8237            .await?;
 8238        window
 8239    };
 8240
 8241    let mut errors = Vec::new();
 8242
 8243    for session_workspace in group_iter {
 8244        let error = if session_workspace.paths.is_empty() {
 8245            cx.update(|cx| {
 8246                open_workspace_by_id(
 8247                    session_workspace.workspace_id,
 8248                    app_state.clone(),
 8249                    Some(window_handle),
 8250                    cx,
 8251                )
 8252            })
 8253            .await
 8254            .err()
 8255        } else {
 8256            cx.update(|cx| {
 8257                Workspace::new_local(
 8258                    session_workspace.paths.paths().to_vec(),
 8259                    app_state.clone(),
 8260                    Some(window_handle),
 8261                    None,
 8262                    None,
 8263                    true,
 8264                    cx,
 8265                )
 8266            })
 8267            .await
 8268            .err()
 8269        };
 8270
 8271        if let Some(error) = error {
 8272            errors.push(error);
 8273        }
 8274    }
 8275
 8276    if let Some(target_id) = state.active_workspace_id {
 8277        window_handle
 8278            .update(cx, |multi_workspace, window, cx| {
 8279                let target_index = multi_workspace
 8280                    .workspaces()
 8281                    .iter()
 8282                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8283                if let Some(index) = target_index {
 8284                    multi_workspace.activate_index(index, window, cx);
 8285                } else if !multi_workspace.workspaces().is_empty() {
 8286                    multi_workspace.activate_index(0, window, cx);
 8287                }
 8288            })
 8289            .ok();
 8290    } else {
 8291        window_handle
 8292            .update(cx, |multi_workspace, window, cx| {
 8293                if !multi_workspace.workspaces().is_empty() {
 8294                    multi_workspace.activate_index(0, window, cx);
 8295                }
 8296            })
 8297            .ok();
 8298    }
 8299
 8300    if state.sidebar_open {
 8301        window_handle
 8302            .update(cx, |multi_workspace, _, cx| {
 8303                multi_workspace.open_sidebar(cx);
 8304            })
 8305            .ok();
 8306    }
 8307
 8308    window_handle
 8309        .update(cx, |_, window, _cx| {
 8310            window.activate_window();
 8311        })
 8312        .ok();
 8313
 8314    Ok(MultiWorkspaceRestoreResult {
 8315        window_handle,
 8316        errors,
 8317    })
 8318}
 8319
 8320actions!(
 8321    collab,
 8322    [
 8323        /// Opens the channel notes for the current call.
 8324        ///
 8325        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8326        /// channel in the collab panel.
 8327        ///
 8328        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8329        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8330        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8331        OpenChannelNotes,
 8332        /// Mutes your microphone.
 8333        Mute,
 8334        /// Deafens yourself (mute both microphone and speakers).
 8335        Deafen,
 8336        /// Leaves the current call.
 8337        LeaveCall,
 8338        /// Shares the current project with collaborators.
 8339        ShareProject,
 8340        /// Shares your screen with collaborators.
 8341        ScreenShare,
 8342        /// Copies the current room name and session id for debugging purposes.
 8343        CopyRoomId,
 8344    ]
 8345);
 8346
 8347/// Opens the channel notes for a specific channel by its ID.
 8348#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8349#[action(namespace = collab)]
 8350#[serde(deny_unknown_fields)]
 8351pub struct OpenChannelNotesById {
 8352    pub channel_id: u64,
 8353}
 8354
 8355actions!(
 8356    zed,
 8357    [
 8358        /// Opens the Zed log file.
 8359        OpenLog,
 8360        /// Reveals the Zed log file in the system file manager.
 8361        RevealLogInFileManager
 8362    ]
 8363);
 8364
 8365async fn join_channel_internal(
 8366    channel_id: ChannelId,
 8367    app_state: &Arc<AppState>,
 8368    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8369    requesting_workspace: Option<WeakEntity<Workspace>>,
 8370    active_call: &dyn AnyActiveCall,
 8371    cx: &mut AsyncApp,
 8372) -> Result<bool> {
 8373    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8374        if !active_call.is_in_room(cx) {
 8375            return (false, false);
 8376        }
 8377
 8378        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8379        let should_prompt = active_call.is_sharing_project(cx)
 8380            && active_call.has_remote_participants(cx)
 8381            && !already_in_channel;
 8382        (should_prompt, already_in_channel)
 8383    });
 8384
 8385    if already_in_channel {
 8386        let task = cx.update(|cx| {
 8387            if let Some((project, host)) = active_call.most_active_project(cx) {
 8388                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8389            } else {
 8390                None
 8391            }
 8392        });
 8393        if let Some(task) = task {
 8394            task.await?;
 8395        }
 8396        return anyhow::Ok(true);
 8397    }
 8398
 8399    if should_prompt {
 8400        if let Some(multi_workspace) = requesting_window {
 8401            let answer = multi_workspace
 8402                .update(cx, |_, window, cx| {
 8403                    window.prompt(
 8404                        PromptLevel::Warning,
 8405                        "Do you want to switch channels?",
 8406                        Some("Leaving this call will unshare your current project."),
 8407                        &["Yes, Join Channel", "Cancel"],
 8408                        cx,
 8409                    )
 8410                })?
 8411                .await;
 8412
 8413            if answer == Ok(1) {
 8414                return Ok(false);
 8415            }
 8416        } else {
 8417            return Ok(false);
 8418        }
 8419    }
 8420
 8421    let client = cx.update(|cx| active_call.client(cx));
 8422
 8423    let mut client_status = client.status();
 8424
 8425    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8426    'outer: loop {
 8427        let Some(status) = client_status.recv().await else {
 8428            anyhow::bail!("error connecting");
 8429        };
 8430
 8431        match status {
 8432            Status::Connecting
 8433            | Status::Authenticating
 8434            | Status::Authenticated
 8435            | Status::Reconnecting
 8436            | Status::Reauthenticating
 8437            | Status::Reauthenticated => continue,
 8438            Status::Connected { .. } => break 'outer,
 8439            Status::SignedOut | Status::AuthenticationError => {
 8440                return Err(ErrorCode::SignedOut.into());
 8441            }
 8442            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8443            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8444                return Err(ErrorCode::Disconnected.into());
 8445            }
 8446        }
 8447    }
 8448
 8449    let joined = cx
 8450        .update(|cx| active_call.join_channel(channel_id, cx))
 8451        .await?;
 8452
 8453    if !joined {
 8454        return anyhow::Ok(true);
 8455    }
 8456
 8457    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8458
 8459    let task = cx.update(|cx| {
 8460        if let Some((project, host)) = active_call.most_active_project(cx) {
 8461            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8462        }
 8463
 8464        // If you are the first to join a channel, see if you should share your project.
 8465        if !active_call.has_remote_participants(cx)
 8466            && !active_call.local_participant_is_guest(cx)
 8467            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8468        {
 8469            let project = workspace.update(cx, |workspace, cx| {
 8470                let project = workspace.project.read(cx);
 8471
 8472                if !active_call.share_on_join(cx) {
 8473                    return None;
 8474                }
 8475
 8476                if (project.is_local() || project.is_via_remote_server())
 8477                    && project.visible_worktrees(cx).any(|tree| {
 8478                        tree.read(cx)
 8479                            .root_entry()
 8480                            .is_some_and(|entry| entry.is_dir())
 8481                    })
 8482                {
 8483                    Some(workspace.project.clone())
 8484                } else {
 8485                    None
 8486                }
 8487            });
 8488            if let Some(project) = project {
 8489                let share_task = active_call.share_project(project, cx);
 8490                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8491                    share_task.await?;
 8492                    Ok(())
 8493                }));
 8494            }
 8495        }
 8496
 8497        None
 8498    });
 8499    if let Some(task) = task {
 8500        task.await?;
 8501        return anyhow::Ok(true);
 8502    }
 8503    anyhow::Ok(false)
 8504}
 8505
 8506pub fn join_channel(
 8507    channel_id: ChannelId,
 8508    app_state: Arc<AppState>,
 8509    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8510    requesting_workspace: Option<WeakEntity<Workspace>>,
 8511    cx: &mut App,
 8512) -> Task<Result<()>> {
 8513    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8514    cx.spawn(async move |cx| {
 8515        let result = join_channel_internal(
 8516            channel_id,
 8517            &app_state,
 8518            requesting_window,
 8519            requesting_workspace,
 8520            &*active_call.0,
 8521            cx,
 8522        )
 8523        .await;
 8524
 8525        // join channel succeeded, and opened a window
 8526        if matches!(result, Ok(true)) {
 8527            return anyhow::Ok(());
 8528        }
 8529
 8530        // find an existing workspace to focus and show call controls
 8531        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8532        if active_window.is_none() {
 8533            // no open workspaces, make one to show the error in (blergh)
 8534            let OpenResult {
 8535                window: window_handle,
 8536                ..
 8537            } = cx
 8538                .update(|cx| {
 8539                    Workspace::new_local(
 8540                        vec![],
 8541                        app_state.clone(),
 8542                        requesting_window,
 8543                        None,
 8544                        None,
 8545                        true,
 8546                        cx,
 8547                    )
 8548                })
 8549                .await?;
 8550
 8551            window_handle
 8552                .update(cx, |_, window, _cx| {
 8553                    window.activate_window();
 8554                })
 8555                .ok();
 8556
 8557            if result.is_ok() {
 8558                cx.update(|cx| {
 8559                    cx.dispatch_action(&OpenChannelNotes);
 8560                });
 8561            }
 8562
 8563            active_window = Some(window_handle);
 8564        }
 8565
 8566        if let Err(err) = result {
 8567            log::error!("failed to join channel: {}", err);
 8568            if let Some(active_window) = active_window {
 8569                active_window
 8570                    .update(cx, |_, window, cx| {
 8571                        let detail: SharedString = match err.error_code() {
 8572                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8573                            ErrorCode::UpgradeRequired => concat!(
 8574                                "Your are running an unsupported version of Zed. ",
 8575                                "Please update to continue."
 8576                            )
 8577                            .into(),
 8578                            ErrorCode::NoSuchChannel => concat!(
 8579                                "No matching channel was found. ",
 8580                                "Please check the link and try again."
 8581                            )
 8582                            .into(),
 8583                            ErrorCode::Forbidden => concat!(
 8584                                "This channel is private, and you do not have access. ",
 8585                                "Please ask someone to add you and try again."
 8586                            )
 8587                            .into(),
 8588                            ErrorCode::Disconnected => {
 8589                                "Please check your internet connection and try again.".into()
 8590                            }
 8591                            _ => format!("{}\n\nPlease try again.", err).into(),
 8592                        };
 8593                        window.prompt(
 8594                            PromptLevel::Critical,
 8595                            "Failed to join channel",
 8596                            Some(&detail),
 8597                            &["Ok"],
 8598                            cx,
 8599                        )
 8600                    })?
 8601                    .await
 8602                    .ok();
 8603            }
 8604        }
 8605
 8606        // return ok, we showed the error to the user.
 8607        anyhow::Ok(())
 8608    })
 8609}
 8610
 8611pub async fn get_any_active_multi_workspace(
 8612    app_state: Arc<AppState>,
 8613    mut cx: AsyncApp,
 8614) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8615    // find an existing workspace to focus and show call controls
 8616    let active_window = activate_any_workspace_window(&mut cx);
 8617    if active_window.is_none() {
 8618        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8619            .await?;
 8620    }
 8621    activate_any_workspace_window(&mut cx).context("could not open zed")
 8622}
 8623
 8624fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8625    cx.update(|cx| {
 8626        if let Some(workspace_window) = cx
 8627            .active_window()
 8628            .and_then(|window| window.downcast::<MultiWorkspace>())
 8629        {
 8630            return Some(workspace_window);
 8631        }
 8632
 8633        for window in cx.windows() {
 8634            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8635                workspace_window
 8636                    .update(cx, |_, window, _| window.activate_window())
 8637                    .ok();
 8638                return Some(workspace_window);
 8639            }
 8640        }
 8641        None
 8642    })
 8643}
 8644
 8645pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8646    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8647}
 8648
 8649pub fn workspace_windows_for_location(
 8650    serialized_location: &SerializedWorkspaceLocation,
 8651    cx: &App,
 8652) -> Vec<WindowHandle<MultiWorkspace>> {
 8653    cx.windows()
 8654        .into_iter()
 8655        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8656        .filter(|multi_workspace| {
 8657            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8658                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8659                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8660                }
 8661                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8662                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8663                    a.distro_name == b.distro_name
 8664                }
 8665                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8666                    a.container_id == b.container_id
 8667                }
 8668                #[cfg(any(test, feature = "test-support"))]
 8669                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8670                    a.id == b.id
 8671                }
 8672                _ => false,
 8673            };
 8674
 8675            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8676                multi_workspace.workspaces().iter().any(|workspace| {
 8677                    match workspace.read(cx).workspace_location(cx) {
 8678                        WorkspaceLocation::Location(location, _) => {
 8679                            match (&location, serialized_location) {
 8680                                (
 8681                                    SerializedWorkspaceLocation::Local,
 8682                                    SerializedWorkspaceLocation::Local,
 8683                                ) => true,
 8684                                (
 8685                                    SerializedWorkspaceLocation::Remote(a),
 8686                                    SerializedWorkspaceLocation::Remote(b),
 8687                                ) => same_host(a, b),
 8688                                _ => false,
 8689                            }
 8690                        }
 8691                        _ => false,
 8692                    }
 8693                })
 8694            })
 8695        })
 8696        .collect()
 8697}
 8698
 8699pub async fn find_existing_workspace(
 8700    abs_paths: &[PathBuf],
 8701    open_options: &OpenOptions,
 8702    location: &SerializedWorkspaceLocation,
 8703    cx: &mut AsyncApp,
 8704) -> (
 8705    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8706    OpenVisible,
 8707) {
 8708    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8709    let mut open_visible = OpenVisible::All;
 8710    let mut best_match = None;
 8711
 8712    if open_options.open_new_workspace != Some(true) {
 8713        cx.update(|cx| {
 8714            for window in workspace_windows_for_location(location, cx) {
 8715                if let Ok(multi_workspace) = window.read(cx) {
 8716                    for workspace in multi_workspace.workspaces() {
 8717                        let project = workspace.read(cx).project.read(cx);
 8718                        let m = project.visibility_for_paths(
 8719                            abs_paths,
 8720                            open_options.open_new_workspace == None,
 8721                            cx,
 8722                        );
 8723                        if m > best_match {
 8724                            existing = Some((window, workspace.clone()));
 8725                            best_match = m;
 8726                        } else if best_match.is_none()
 8727                            && open_options.open_new_workspace == Some(false)
 8728                        {
 8729                            existing = Some((window, workspace.clone()))
 8730                        }
 8731                    }
 8732                }
 8733            }
 8734        });
 8735
 8736        let all_paths_are_files = existing
 8737            .as_ref()
 8738            .and_then(|(_, target_workspace)| {
 8739                cx.update(|cx| {
 8740                    let workspace = target_workspace.read(cx);
 8741                    let project = workspace.project.read(cx);
 8742                    let path_style = workspace.path_style(cx);
 8743                    Some(!abs_paths.iter().any(|path| {
 8744                        let path = util::paths::SanitizedPath::new(path);
 8745                        project.worktrees(cx).any(|worktree| {
 8746                            let worktree = worktree.read(cx);
 8747                            let abs_path = worktree.abs_path();
 8748                            path_style
 8749                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8750                                .and_then(|rel| worktree.entry_for_path(&rel))
 8751                                .is_some_and(|e| e.is_dir())
 8752                        })
 8753                    }))
 8754                })
 8755            })
 8756            .unwrap_or(false);
 8757
 8758        if open_options.open_new_workspace.is_none()
 8759            && existing.is_some()
 8760            && open_options.wait
 8761            && all_paths_are_files
 8762        {
 8763            cx.update(|cx| {
 8764                let windows = workspace_windows_for_location(location, cx);
 8765                let window = cx
 8766                    .active_window()
 8767                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8768                    .filter(|window| windows.contains(window))
 8769                    .or_else(|| windows.into_iter().next());
 8770                if let Some(window) = window {
 8771                    if let Ok(multi_workspace) = window.read(cx) {
 8772                        let active_workspace = multi_workspace.workspace().clone();
 8773                        existing = Some((window, active_workspace));
 8774                        open_visible = OpenVisible::None;
 8775                    }
 8776                }
 8777            });
 8778        }
 8779    }
 8780    (existing, open_visible)
 8781}
 8782
 8783#[derive(Default, Clone)]
 8784pub struct OpenOptions {
 8785    pub visible: Option<OpenVisible>,
 8786    pub focus: Option<bool>,
 8787    pub open_new_workspace: Option<bool>,
 8788    pub wait: bool,
 8789    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8790    pub env: Option<HashMap<String, String>>,
 8791}
 8792
 8793/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 8794/// or [`Workspace::open_workspace_for_paths`].
 8795pub struct OpenResult {
 8796    pub window: WindowHandle<MultiWorkspace>,
 8797    pub workspace: Entity<Workspace>,
 8798    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8799}
 8800
 8801/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8802pub fn open_workspace_by_id(
 8803    workspace_id: WorkspaceId,
 8804    app_state: Arc<AppState>,
 8805    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8806    cx: &mut App,
 8807) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8808    let project_handle = Project::local(
 8809        app_state.client.clone(),
 8810        app_state.node_runtime.clone(),
 8811        app_state.user_store.clone(),
 8812        app_state.languages.clone(),
 8813        app_state.fs.clone(),
 8814        None,
 8815        project::LocalProjectFlags {
 8816            init_worktree_trust: true,
 8817            ..project::LocalProjectFlags::default()
 8818        },
 8819        cx,
 8820    );
 8821
 8822    cx.spawn(async move |cx| {
 8823        let serialized_workspace = persistence::DB
 8824            .workspace_for_id(workspace_id)
 8825            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8826
 8827        let centered_layout = serialized_workspace.centered_layout;
 8828
 8829        let (window, workspace) = if let Some(window) = requesting_window {
 8830            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8831                let workspace = cx.new(|cx| {
 8832                    let mut workspace = Workspace::new(
 8833                        Some(workspace_id),
 8834                        project_handle.clone(),
 8835                        app_state.clone(),
 8836                        window,
 8837                        cx,
 8838                    );
 8839                    workspace.centered_layout = centered_layout;
 8840                    workspace
 8841                });
 8842                multi_workspace.add_workspace(workspace.clone(), cx);
 8843                workspace
 8844            })?;
 8845            (window, workspace)
 8846        } else {
 8847            let window_bounds_override = window_bounds_env_override();
 8848
 8849            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8850                (Some(WindowBounds::Windowed(bounds)), None)
 8851            } else if let Some(display) = serialized_workspace.display
 8852                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8853            {
 8854                (Some(bounds.0), Some(display))
 8855            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8856                (Some(bounds), Some(display))
 8857            } else {
 8858                (None, None)
 8859            };
 8860
 8861            let options = cx.update(|cx| {
 8862                let mut options = (app_state.build_window_options)(display, cx);
 8863                options.window_bounds = window_bounds;
 8864                options
 8865            });
 8866
 8867            let window = cx.open_window(options, {
 8868                let app_state = app_state.clone();
 8869                let project_handle = project_handle.clone();
 8870                move |window, cx| {
 8871                    let workspace = cx.new(|cx| {
 8872                        let mut workspace = Workspace::new(
 8873                            Some(workspace_id),
 8874                            project_handle,
 8875                            app_state,
 8876                            window,
 8877                            cx,
 8878                        );
 8879                        workspace.centered_layout = centered_layout;
 8880                        workspace
 8881                    });
 8882                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8883                }
 8884            })?;
 8885
 8886            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8887                multi_workspace.workspace().clone()
 8888            })?;
 8889
 8890            (window, workspace)
 8891        };
 8892
 8893        notify_if_database_failed(window, cx);
 8894
 8895        // Restore items from the serialized workspace
 8896        window
 8897            .update(cx, |_, window, cx| {
 8898                workspace.update(cx, |_workspace, cx| {
 8899                    open_items(Some(serialized_workspace), vec![], window, cx)
 8900                })
 8901            })?
 8902            .await?;
 8903
 8904        window.update(cx, |_, window, cx| {
 8905            workspace.update(cx, |workspace, cx| {
 8906                workspace.serialize_workspace(window, cx);
 8907            });
 8908        })?;
 8909
 8910        Ok(window)
 8911    })
 8912}
 8913
 8914#[allow(clippy::type_complexity)]
 8915pub fn open_paths(
 8916    abs_paths: &[PathBuf],
 8917    app_state: Arc<AppState>,
 8918    open_options: OpenOptions,
 8919    cx: &mut App,
 8920) -> Task<anyhow::Result<OpenResult>> {
 8921    let abs_paths = abs_paths.to_vec();
 8922    #[cfg(target_os = "windows")]
 8923    let wsl_path = abs_paths
 8924        .iter()
 8925        .find_map(|p| util::paths::WslPath::from_path(p));
 8926
 8927    cx.spawn(async move |cx| {
 8928        let (mut existing, mut open_visible) = find_existing_workspace(
 8929            &abs_paths,
 8930            &open_options,
 8931            &SerializedWorkspaceLocation::Local,
 8932            cx,
 8933        )
 8934        .await;
 8935
 8936        // Fallback: if no workspace contains the paths and all paths are files,
 8937        // prefer an existing local workspace window (active window first).
 8938        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8939            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8940            let all_metadatas = futures::future::join_all(all_paths)
 8941                .await
 8942                .into_iter()
 8943                .filter_map(|result| result.ok().flatten())
 8944                .collect::<Vec<_>>();
 8945
 8946            if all_metadatas.iter().all(|file| !file.is_dir) {
 8947                cx.update(|cx| {
 8948                    let windows = workspace_windows_for_location(
 8949                        &SerializedWorkspaceLocation::Local,
 8950                        cx,
 8951                    );
 8952                    let window = cx
 8953                        .active_window()
 8954                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8955                        .filter(|window| windows.contains(window))
 8956                        .or_else(|| windows.into_iter().next());
 8957                    if let Some(window) = window {
 8958                        if let Ok(multi_workspace) = window.read(cx) {
 8959                            let active_workspace = multi_workspace.workspace().clone();
 8960                            existing = Some((window, active_workspace));
 8961                            open_visible = OpenVisible::None;
 8962                        }
 8963                    }
 8964                });
 8965            }
 8966        }
 8967
 8968        let result = if let Some((existing, target_workspace)) = existing {
 8969            let open_task = existing
 8970                .update(cx, |multi_workspace, window, cx| {
 8971                    window.activate_window();
 8972                    multi_workspace.activate(target_workspace.clone(), cx);
 8973                    target_workspace.update(cx, |workspace, cx| {
 8974                        workspace.open_paths(
 8975                            abs_paths,
 8976                            OpenOptions {
 8977                                visible: Some(open_visible),
 8978                                ..Default::default()
 8979                            },
 8980                            None,
 8981                            window,
 8982                            cx,
 8983                        )
 8984                    })
 8985                })?
 8986                .await;
 8987
 8988            _ = existing.update(cx, |multi_workspace, _, cx| {
 8989                let workspace = multi_workspace.workspace().clone();
 8990                workspace.update(cx, |workspace, cx| {
 8991                    for item in open_task.iter().flatten() {
 8992                        if let Err(e) = item {
 8993                            workspace.show_error(&e, cx);
 8994                        }
 8995                    }
 8996                });
 8997            });
 8998
 8999            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9000        } else {
 9001            let result = cx
 9002                .update(move |cx| {
 9003                    Workspace::new_local(
 9004                        abs_paths,
 9005                        app_state.clone(),
 9006                        open_options.replace_window,
 9007                        open_options.env,
 9008                        None,
 9009                        true,
 9010                        cx,
 9011                    )
 9012                })
 9013                .await;
 9014
 9015            if let Ok(ref result) = result {
 9016                result.window
 9017                    .update(cx, |_, window, _cx| {
 9018                        window.activate_window();
 9019                    })
 9020                    .log_err();
 9021            }
 9022
 9023            result
 9024        };
 9025
 9026        #[cfg(target_os = "windows")]
 9027        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9028            && let Ok(ref result) = result
 9029        {
 9030            result.window
 9031                .update(cx, move |multi_workspace, _window, cx| {
 9032                    struct OpenInWsl;
 9033                    let workspace = multi_workspace.workspace().clone();
 9034                    workspace.update(cx, |workspace, cx| {
 9035                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9036                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9037                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9038                            cx.new(move |cx| {
 9039                                MessageNotification::new(msg, cx)
 9040                                    .primary_message("Open in WSL")
 9041                                    .primary_icon(IconName::FolderOpen)
 9042                                    .primary_on_click(move |window, cx| {
 9043                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9044                                                distro: remote::WslConnectionOptions {
 9045                                                        distro_name: distro.clone(),
 9046                                                    user: None,
 9047                                                },
 9048                                                paths: vec![path.clone().into()],
 9049                                            }), cx)
 9050                                    })
 9051                            })
 9052                        });
 9053                    });
 9054                })
 9055                .unwrap();
 9056        };
 9057        result
 9058    })
 9059}
 9060
 9061pub fn open_new(
 9062    open_options: OpenOptions,
 9063    app_state: Arc<AppState>,
 9064    cx: &mut App,
 9065    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9066) -> Task<anyhow::Result<()>> {
 9067    let task = Workspace::new_local(
 9068        Vec::new(),
 9069        app_state,
 9070        open_options.replace_window,
 9071        open_options.env,
 9072        Some(Box::new(init)),
 9073        true,
 9074        cx,
 9075    );
 9076    cx.spawn(async move |cx| {
 9077        let OpenResult { window, .. } = task.await?;
 9078        window
 9079            .update(cx, |_, window, _cx| {
 9080                window.activate_window();
 9081            })
 9082            .ok();
 9083        Ok(())
 9084    })
 9085}
 9086
 9087pub fn create_and_open_local_file(
 9088    path: &'static Path,
 9089    window: &mut Window,
 9090    cx: &mut Context<Workspace>,
 9091    default_content: impl 'static + Send + FnOnce() -> Rope,
 9092) -> Task<Result<Box<dyn ItemHandle>>> {
 9093    cx.spawn_in(window, async move |workspace, cx| {
 9094        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9095        if !fs.is_file(path).await {
 9096            fs.create_file(path, Default::default()).await?;
 9097            fs.save(path, &default_content(), Default::default())
 9098                .await?;
 9099        }
 9100
 9101        workspace
 9102            .update_in(cx, |workspace, window, cx| {
 9103                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9104                    let path = workspace
 9105                        .project
 9106                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9107                    cx.spawn_in(window, async move |workspace, cx| {
 9108                        let path = path.await?;
 9109                        let mut items = workspace
 9110                            .update_in(cx, |workspace, window, cx| {
 9111                                workspace.open_paths(
 9112                                    vec![path.to_path_buf()],
 9113                                    OpenOptions {
 9114                                        visible: Some(OpenVisible::None),
 9115                                        ..Default::default()
 9116                                    },
 9117                                    None,
 9118                                    window,
 9119                                    cx,
 9120                                )
 9121                            })?
 9122                            .await;
 9123                        let item = items.pop().flatten();
 9124                        item.with_context(|| format!("path {path:?} is not a file"))?
 9125                    })
 9126                })
 9127            })?
 9128            .await?
 9129            .await
 9130    })
 9131}
 9132
 9133pub fn open_remote_project_with_new_connection(
 9134    window: WindowHandle<MultiWorkspace>,
 9135    remote_connection: Arc<dyn RemoteConnection>,
 9136    cancel_rx: oneshot::Receiver<()>,
 9137    delegate: Arc<dyn RemoteClientDelegate>,
 9138    app_state: Arc<AppState>,
 9139    paths: Vec<PathBuf>,
 9140    cx: &mut App,
 9141) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9142    cx.spawn(async move |cx| {
 9143        let (workspace_id, serialized_workspace) =
 9144            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9145                .await?;
 9146
 9147        let session = match cx
 9148            .update(|cx| {
 9149                remote::RemoteClient::new(
 9150                    ConnectionIdentifier::Workspace(workspace_id.0),
 9151                    remote_connection,
 9152                    cancel_rx,
 9153                    delegate,
 9154                    cx,
 9155                )
 9156            })
 9157            .await?
 9158        {
 9159            Some(result) => result,
 9160            None => return Ok(Vec::new()),
 9161        };
 9162
 9163        let project = cx.update(|cx| {
 9164            project::Project::remote(
 9165                session,
 9166                app_state.client.clone(),
 9167                app_state.node_runtime.clone(),
 9168                app_state.user_store.clone(),
 9169                app_state.languages.clone(),
 9170                app_state.fs.clone(),
 9171                true,
 9172                cx,
 9173            )
 9174        });
 9175
 9176        open_remote_project_inner(
 9177            project,
 9178            paths,
 9179            workspace_id,
 9180            serialized_workspace,
 9181            app_state,
 9182            window,
 9183            cx,
 9184        )
 9185        .await
 9186    })
 9187}
 9188
 9189pub fn open_remote_project_with_existing_connection(
 9190    connection_options: RemoteConnectionOptions,
 9191    project: Entity<Project>,
 9192    paths: Vec<PathBuf>,
 9193    app_state: Arc<AppState>,
 9194    window: WindowHandle<MultiWorkspace>,
 9195    cx: &mut AsyncApp,
 9196) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9197    cx.spawn(async move |cx| {
 9198        let (workspace_id, serialized_workspace) =
 9199            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9200
 9201        open_remote_project_inner(
 9202            project,
 9203            paths,
 9204            workspace_id,
 9205            serialized_workspace,
 9206            app_state,
 9207            window,
 9208            cx,
 9209        )
 9210        .await
 9211    })
 9212}
 9213
 9214async fn open_remote_project_inner(
 9215    project: Entity<Project>,
 9216    paths: Vec<PathBuf>,
 9217    workspace_id: WorkspaceId,
 9218    serialized_workspace: Option<SerializedWorkspace>,
 9219    app_state: Arc<AppState>,
 9220    window: WindowHandle<MultiWorkspace>,
 9221    cx: &mut AsyncApp,
 9222) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9223    let toolchains = DB.toolchains(workspace_id).await?;
 9224    for (toolchain, worktree_path, path) in toolchains {
 9225        project
 9226            .update(cx, |this, cx| {
 9227                let Some(worktree_id) =
 9228                    this.find_worktree(&worktree_path, cx)
 9229                        .and_then(|(worktree, rel_path)| {
 9230                            if rel_path.is_empty() {
 9231                                Some(worktree.read(cx).id())
 9232                            } else {
 9233                                None
 9234                            }
 9235                        })
 9236                else {
 9237                    return Task::ready(None);
 9238                };
 9239
 9240                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9241            })
 9242            .await;
 9243    }
 9244    let mut project_paths_to_open = vec![];
 9245    let mut project_path_errors = vec![];
 9246
 9247    for path in paths {
 9248        let result = cx
 9249            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9250            .await;
 9251        match result {
 9252            Ok((_, project_path)) => {
 9253                project_paths_to_open.push((path.clone(), Some(project_path)));
 9254            }
 9255            Err(error) => {
 9256                project_path_errors.push(error);
 9257            }
 9258        };
 9259    }
 9260
 9261    if project_paths_to_open.is_empty() {
 9262        return Err(project_path_errors.pop().context("no paths given")?);
 9263    }
 9264
 9265    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9266        telemetry::event!("SSH Project Opened");
 9267
 9268        let new_workspace = cx.new(|cx| {
 9269            let mut workspace =
 9270                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9271            workspace.update_history(cx);
 9272
 9273            if let Some(ref serialized) = serialized_workspace {
 9274                workspace.centered_layout = serialized.centered_layout;
 9275            }
 9276
 9277            workspace
 9278        });
 9279
 9280        multi_workspace.activate(new_workspace.clone(), cx);
 9281        new_workspace
 9282    })?;
 9283
 9284    let items = window
 9285        .update(cx, |_, window, cx| {
 9286            window.activate_window();
 9287            workspace.update(cx, |_workspace, cx| {
 9288                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9289            })
 9290        })?
 9291        .await?;
 9292
 9293    workspace.update(cx, |workspace, cx| {
 9294        for error in project_path_errors {
 9295            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9296                if let Some(path) = error.error_tag("path") {
 9297                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9298                }
 9299            } else {
 9300                workspace.show_error(&error, cx)
 9301            }
 9302        }
 9303    });
 9304
 9305    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9306}
 9307
 9308fn deserialize_remote_project(
 9309    connection_options: RemoteConnectionOptions,
 9310    paths: Vec<PathBuf>,
 9311    cx: &AsyncApp,
 9312) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9313    cx.background_spawn(async move {
 9314        let remote_connection_id = persistence::DB
 9315            .get_or_create_remote_connection(connection_options)
 9316            .await?;
 9317
 9318        let serialized_workspace =
 9319            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9320
 9321        let workspace_id = if let Some(workspace_id) =
 9322            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9323        {
 9324            workspace_id
 9325        } else {
 9326            persistence::DB.next_id().await?
 9327        };
 9328
 9329        Ok((workspace_id, serialized_workspace))
 9330    })
 9331}
 9332
 9333pub fn join_in_room_project(
 9334    project_id: u64,
 9335    follow_user_id: u64,
 9336    app_state: Arc<AppState>,
 9337    cx: &mut App,
 9338) -> Task<Result<()>> {
 9339    let windows = cx.windows();
 9340    cx.spawn(async move |cx| {
 9341        let existing_window_and_workspace: Option<(
 9342            WindowHandle<MultiWorkspace>,
 9343            Entity<Workspace>,
 9344        )> = windows.into_iter().find_map(|window_handle| {
 9345            window_handle
 9346                .downcast::<MultiWorkspace>()
 9347                .and_then(|window_handle| {
 9348                    window_handle
 9349                        .update(cx, |multi_workspace, _window, cx| {
 9350                            for workspace in multi_workspace.workspaces() {
 9351                                if workspace.read(cx).project().read(cx).remote_id()
 9352                                    == Some(project_id)
 9353                                {
 9354                                    return Some((window_handle, workspace.clone()));
 9355                                }
 9356                            }
 9357                            None
 9358                        })
 9359                        .unwrap_or(None)
 9360                })
 9361        });
 9362
 9363        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9364            existing_window_and_workspace
 9365        {
 9366            existing_window
 9367                .update(cx, |multi_workspace, _, cx| {
 9368                    multi_workspace.activate(target_workspace, cx);
 9369                })
 9370                .ok();
 9371            existing_window
 9372        } else {
 9373            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9374            let project = cx
 9375                .update(|cx| {
 9376                    active_call.0.join_project(
 9377                        project_id,
 9378                        app_state.languages.clone(),
 9379                        app_state.fs.clone(),
 9380                        cx,
 9381                    )
 9382                })
 9383                .await?;
 9384
 9385            let window_bounds_override = window_bounds_env_override();
 9386            cx.update(|cx| {
 9387                let mut options = (app_state.build_window_options)(None, cx);
 9388                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9389                cx.open_window(options, |window, cx| {
 9390                    let workspace = cx.new(|cx| {
 9391                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9392                    });
 9393                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9394                })
 9395            })?
 9396        };
 9397
 9398        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9399            cx.activate(true);
 9400            window.activate_window();
 9401
 9402            // We set the active workspace above, so this is the correct workspace.
 9403            let workspace = multi_workspace.workspace().clone();
 9404            workspace.update(cx, |workspace, cx| {
 9405                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9406                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9407                    .or_else(|| {
 9408                        // If we couldn't follow the given user, follow the host instead.
 9409                        let collaborator = workspace
 9410                            .project()
 9411                            .read(cx)
 9412                            .collaborators()
 9413                            .values()
 9414                            .find(|collaborator| collaborator.is_host)?;
 9415                        Some(collaborator.peer_id)
 9416                    });
 9417
 9418                if let Some(follow_peer_id) = follow_peer_id {
 9419                    workspace.follow(follow_peer_id, window, cx);
 9420                }
 9421            });
 9422        })?;
 9423
 9424        anyhow::Ok(())
 9425    })
 9426}
 9427
 9428pub fn reload(cx: &mut App) {
 9429    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9430    let mut workspace_windows = cx
 9431        .windows()
 9432        .into_iter()
 9433        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9434        .collect::<Vec<_>>();
 9435
 9436    // If multiple windows have unsaved changes, and need a save prompt,
 9437    // prompt in the active window before switching to a different window.
 9438    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9439
 9440    let mut prompt = None;
 9441    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9442        prompt = window
 9443            .update(cx, |_, window, cx| {
 9444                window.prompt(
 9445                    PromptLevel::Info,
 9446                    "Are you sure you want to restart?",
 9447                    None,
 9448                    &["Restart", "Cancel"],
 9449                    cx,
 9450                )
 9451            })
 9452            .ok();
 9453    }
 9454
 9455    cx.spawn(async move |cx| {
 9456        if let Some(prompt) = prompt {
 9457            let answer = prompt.await?;
 9458            if answer != 0 {
 9459                return anyhow::Ok(());
 9460            }
 9461        }
 9462
 9463        // If the user cancels any save prompt, then keep the app open.
 9464        for window in workspace_windows {
 9465            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9466                let workspace = multi_workspace.workspace().clone();
 9467                workspace.update(cx, |workspace, cx| {
 9468                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9469                })
 9470            }) && !should_close.await?
 9471            {
 9472                return anyhow::Ok(());
 9473            }
 9474        }
 9475        cx.update(|cx| cx.restart());
 9476        anyhow::Ok(())
 9477    })
 9478    .detach_and_log_err(cx);
 9479}
 9480
 9481fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9482    let mut parts = value.split(',');
 9483    let x: usize = parts.next()?.parse().ok()?;
 9484    let y: usize = parts.next()?.parse().ok()?;
 9485    Some(point(px(x as f32), px(y as f32)))
 9486}
 9487
 9488fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9489    let mut parts = value.split(',');
 9490    let width: usize = parts.next()?.parse().ok()?;
 9491    let height: usize = parts.next()?.parse().ok()?;
 9492    Some(size(px(width as f32), px(height as f32)))
 9493}
 9494
 9495/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9496/// appropriate.
 9497///
 9498/// The `border_radius_tiling` parameter allows overriding which corners get
 9499/// rounded, independently of the actual window tiling state. This is used
 9500/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9501/// we want square corners on the left (so the sidebar appears flush with the
 9502/// window edge) but we still need the shadow padding for proper visual
 9503/// appearance. Unlike actual window tiling, this only affects border radius -
 9504/// not padding or shadows.
 9505pub fn client_side_decorations(
 9506    element: impl IntoElement,
 9507    window: &mut Window,
 9508    cx: &mut App,
 9509    border_radius_tiling: Tiling,
 9510) -> Stateful<Div> {
 9511    const BORDER_SIZE: Pixels = px(1.0);
 9512    let decorations = window.window_decorations();
 9513    let tiling = match decorations {
 9514        Decorations::Server => Tiling::default(),
 9515        Decorations::Client { tiling } => tiling,
 9516    };
 9517
 9518    match decorations {
 9519        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9520        Decorations::Server => window.set_client_inset(px(0.0)),
 9521    }
 9522
 9523    struct GlobalResizeEdge(ResizeEdge);
 9524    impl Global for GlobalResizeEdge {}
 9525
 9526    div()
 9527        .id("window-backdrop")
 9528        .bg(transparent_black())
 9529        .map(|div| match decorations {
 9530            Decorations::Server => div,
 9531            Decorations::Client { .. } => div
 9532                .when(
 9533                    !(tiling.top
 9534                        || tiling.right
 9535                        || border_radius_tiling.top
 9536                        || border_radius_tiling.right),
 9537                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9538                )
 9539                .when(
 9540                    !(tiling.top
 9541                        || tiling.left
 9542                        || border_radius_tiling.top
 9543                        || border_radius_tiling.left),
 9544                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9545                )
 9546                .when(
 9547                    !(tiling.bottom
 9548                        || tiling.right
 9549                        || border_radius_tiling.bottom
 9550                        || border_radius_tiling.right),
 9551                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9552                )
 9553                .when(
 9554                    !(tiling.bottom
 9555                        || tiling.left
 9556                        || border_radius_tiling.bottom
 9557                        || border_radius_tiling.left),
 9558                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9559                )
 9560                .when(!tiling.top, |div| {
 9561                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9562                })
 9563                .when(!tiling.bottom, |div| {
 9564                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9565                })
 9566                .when(!tiling.left, |div| {
 9567                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9568                })
 9569                .when(!tiling.right, |div| {
 9570                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9571                })
 9572                .on_mouse_move(move |e, window, cx| {
 9573                    let size = window.window_bounds().get_bounds().size;
 9574                    let pos = e.position;
 9575
 9576                    let new_edge =
 9577                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9578
 9579                    let edge = cx.try_global::<GlobalResizeEdge>();
 9580                    if new_edge != edge.map(|edge| edge.0) {
 9581                        window
 9582                            .window_handle()
 9583                            .update(cx, |workspace, _, cx| {
 9584                                cx.notify(workspace.entity_id());
 9585                            })
 9586                            .ok();
 9587                    }
 9588                })
 9589                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9590                    let size = window.window_bounds().get_bounds().size;
 9591                    let pos = e.position;
 9592
 9593                    let edge = match resize_edge(
 9594                        pos,
 9595                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9596                        size,
 9597                        tiling,
 9598                    ) {
 9599                        Some(value) => value,
 9600                        None => return,
 9601                    };
 9602
 9603                    window.start_window_resize(edge);
 9604                }),
 9605        })
 9606        .size_full()
 9607        .child(
 9608            div()
 9609                .cursor(CursorStyle::Arrow)
 9610                .map(|div| match decorations {
 9611                    Decorations::Server => div,
 9612                    Decorations::Client { .. } => div
 9613                        .border_color(cx.theme().colors().border)
 9614                        .when(
 9615                            !(tiling.top
 9616                                || tiling.right
 9617                                || border_radius_tiling.top
 9618                                || border_radius_tiling.right),
 9619                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9620                        )
 9621                        .when(
 9622                            !(tiling.top
 9623                                || tiling.left
 9624                                || border_radius_tiling.top
 9625                                || border_radius_tiling.left),
 9626                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9627                        )
 9628                        .when(
 9629                            !(tiling.bottom
 9630                                || tiling.right
 9631                                || border_radius_tiling.bottom
 9632                                || border_radius_tiling.right),
 9633                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9634                        )
 9635                        .when(
 9636                            !(tiling.bottom
 9637                                || tiling.left
 9638                                || border_radius_tiling.bottom
 9639                                || border_radius_tiling.left),
 9640                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9641                        )
 9642                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9643                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9644                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9645                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9646                        .when(!tiling.is_tiled(), |div| {
 9647                            div.shadow(vec![gpui::BoxShadow {
 9648                                color: Hsla {
 9649                                    h: 0.,
 9650                                    s: 0.,
 9651                                    l: 0.,
 9652                                    a: 0.4,
 9653                                },
 9654                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9655                                spread_radius: px(0.),
 9656                                offset: point(px(0.0), px(0.0)),
 9657                            }])
 9658                        }),
 9659                })
 9660                .on_mouse_move(|_e, _, cx| {
 9661                    cx.stop_propagation();
 9662                })
 9663                .size_full()
 9664                .child(element),
 9665        )
 9666        .map(|div| match decorations {
 9667            Decorations::Server => div,
 9668            Decorations::Client { tiling, .. } => div.child(
 9669                canvas(
 9670                    |_bounds, window, _| {
 9671                        window.insert_hitbox(
 9672                            Bounds::new(
 9673                                point(px(0.0), px(0.0)),
 9674                                window.window_bounds().get_bounds().size,
 9675                            ),
 9676                            HitboxBehavior::Normal,
 9677                        )
 9678                    },
 9679                    move |_bounds, hitbox, window, cx| {
 9680                        let mouse = window.mouse_position();
 9681                        let size = window.window_bounds().get_bounds().size;
 9682                        let Some(edge) =
 9683                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9684                        else {
 9685                            return;
 9686                        };
 9687                        cx.set_global(GlobalResizeEdge(edge));
 9688                        window.set_cursor_style(
 9689                            match edge {
 9690                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9691                                ResizeEdge::Left | ResizeEdge::Right => {
 9692                                    CursorStyle::ResizeLeftRight
 9693                                }
 9694                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9695                                    CursorStyle::ResizeUpLeftDownRight
 9696                                }
 9697                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9698                                    CursorStyle::ResizeUpRightDownLeft
 9699                                }
 9700                            },
 9701                            &hitbox,
 9702                        );
 9703                    },
 9704                )
 9705                .size_full()
 9706                .absolute(),
 9707            ),
 9708        })
 9709}
 9710
 9711fn resize_edge(
 9712    pos: Point<Pixels>,
 9713    shadow_size: Pixels,
 9714    window_size: Size<Pixels>,
 9715    tiling: Tiling,
 9716) -> Option<ResizeEdge> {
 9717    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9718    if bounds.contains(&pos) {
 9719        return None;
 9720    }
 9721
 9722    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9723    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9724    if !tiling.top && top_left_bounds.contains(&pos) {
 9725        return Some(ResizeEdge::TopLeft);
 9726    }
 9727
 9728    let top_right_bounds = Bounds::new(
 9729        Point::new(window_size.width - corner_size.width, px(0.)),
 9730        corner_size,
 9731    );
 9732    if !tiling.top && top_right_bounds.contains(&pos) {
 9733        return Some(ResizeEdge::TopRight);
 9734    }
 9735
 9736    let bottom_left_bounds = Bounds::new(
 9737        Point::new(px(0.), window_size.height - corner_size.height),
 9738        corner_size,
 9739    );
 9740    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9741        return Some(ResizeEdge::BottomLeft);
 9742    }
 9743
 9744    let bottom_right_bounds = Bounds::new(
 9745        Point::new(
 9746            window_size.width - corner_size.width,
 9747            window_size.height - corner_size.height,
 9748        ),
 9749        corner_size,
 9750    );
 9751    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9752        return Some(ResizeEdge::BottomRight);
 9753    }
 9754
 9755    if !tiling.top && pos.y < shadow_size {
 9756        Some(ResizeEdge::Top)
 9757    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9758        Some(ResizeEdge::Bottom)
 9759    } else if !tiling.left && pos.x < shadow_size {
 9760        Some(ResizeEdge::Left)
 9761    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9762        Some(ResizeEdge::Right)
 9763    } else {
 9764        None
 9765    }
 9766}
 9767
 9768fn join_pane_into_active(
 9769    active_pane: &Entity<Pane>,
 9770    pane: &Entity<Pane>,
 9771    window: &mut Window,
 9772    cx: &mut App,
 9773) {
 9774    if pane == active_pane {
 9775    } else if pane.read(cx).items_len() == 0 {
 9776        pane.update(cx, |_, cx| {
 9777            cx.emit(pane::Event::Remove {
 9778                focus_on_pane: None,
 9779            });
 9780        })
 9781    } else {
 9782        move_all_items(pane, active_pane, window, cx);
 9783    }
 9784}
 9785
 9786fn move_all_items(
 9787    from_pane: &Entity<Pane>,
 9788    to_pane: &Entity<Pane>,
 9789    window: &mut Window,
 9790    cx: &mut App,
 9791) {
 9792    let destination_is_different = from_pane != to_pane;
 9793    let mut moved_items = 0;
 9794    for (item_ix, item_handle) in from_pane
 9795        .read(cx)
 9796        .items()
 9797        .enumerate()
 9798        .map(|(ix, item)| (ix, item.clone()))
 9799        .collect::<Vec<_>>()
 9800    {
 9801        let ix = item_ix - moved_items;
 9802        if destination_is_different {
 9803            // Close item from previous pane
 9804            from_pane.update(cx, |source, cx| {
 9805                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9806            });
 9807            moved_items += 1;
 9808        }
 9809
 9810        // This automatically removes duplicate items in the pane
 9811        to_pane.update(cx, |destination, cx| {
 9812            destination.add_item(item_handle, true, true, None, window, cx);
 9813            window.focus(&destination.focus_handle(cx), cx)
 9814        });
 9815    }
 9816}
 9817
 9818pub fn move_item(
 9819    source: &Entity<Pane>,
 9820    destination: &Entity<Pane>,
 9821    item_id_to_move: EntityId,
 9822    destination_index: usize,
 9823    activate: bool,
 9824    window: &mut Window,
 9825    cx: &mut App,
 9826) {
 9827    let Some((item_ix, item_handle)) = source
 9828        .read(cx)
 9829        .items()
 9830        .enumerate()
 9831        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9832        .map(|(ix, item)| (ix, item.clone()))
 9833    else {
 9834        // Tab was closed during drag
 9835        return;
 9836    };
 9837
 9838    if source != destination {
 9839        // Close item from previous pane
 9840        source.update(cx, |source, cx| {
 9841            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9842        });
 9843    }
 9844
 9845    // This automatically removes duplicate items in the pane
 9846    destination.update(cx, |destination, cx| {
 9847        destination.add_item_inner(
 9848            item_handle,
 9849            activate,
 9850            activate,
 9851            activate,
 9852            Some(destination_index),
 9853            window,
 9854            cx,
 9855        );
 9856        if activate {
 9857            window.focus(&destination.focus_handle(cx), cx)
 9858        }
 9859    });
 9860}
 9861
 9862pub fn move_active_item(
 9863    source: &Entity<Pane>,
 9864    destination: &Entity<Pane>,
 9865    focus_destination: bool,
 9866    close_if_empty: bool,
 9867    window: &mut Window,
 9868    cx: &mut App,
 9869) {
 9870    if source == destination {
 9871        return;
 9872    }
 9873    let Some(active_item) = source.read(cx).active_item() else {
 9874        return;
 9875    };
 9876    source.update(cx, |source_pane, cx| {
 9877        let item_id = active_item.item_id();
 9878        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9879        destination.update(cx, |target_pane, cx| {
 9880            target_pane.add_item(
 9881                active_item,
 9882                focus_destination,
 9883                focus_destination,
 9884                Some(target_pane.items_len()),
 9885                window,
 9886                cx,
 9887            );
 9888        });
 9889    });
 9890}
 9891
 9892pub fn clone_active_item(
 9893    workspace_id: Option<WorkspaceId>,
 9894    source: &Entity<Pane>,
 9895    destination: &Entity<Pane>,
 9896    focus_destination: bool,
 9897    window: &mut Window,
 9898    cx: &mut App,
 9899) {
 9900    if source == destination {
 9901        return;
 9902    }
 9903    let Some(active_item) = source.read(cx).active_item() else {
 9904        return;
 9905    };
 9906    if !active_item.can_split(cx) {
 9907        return;
 9908    }
 9909    let destination = destination.downgrade();
 9910    let task = active_item.clone_on_split(workspace_id, window, cx);
 9911    window
 9912        .spawn(cx, async move |cx| {
 9913            let Some(clone) = task.await else {
 9914                return;
 9915            };
 9916            destination
 9917                .update_in(cx, |target_pane, window, cx| {
 9918                    target_pane.add_item(
 9919                        clone,
 9920                        focus_destination,
 9921                        focus_destination,
 9922                        Some(target_pane.items_len()),
 9923                        window,
 9924                        cx,
 9925                    );
 9926                })
 9927                .log_err();
 9928        })
 9929        .detach();
 9930}
 9931
 9932#[derive(Debug)]
 9933pub struct WorkspacePosition {
 9934    pub window_bounds: Option<WindowBounds>,
 9935    pub display: Option<Uuid>,
 9936    pub centered_layout: bool,
 9937}
 9938
 9939pub fn remote_workspace_position_from_db(
 9940    connection_options: RemoteConnectionOptions,
 9941    paths_to_open: &[PathBuf],
 9942    cx: &App,
 9943) -> Task<Result<WorkspacePosition>> {
 9944    let paths = paths_to_open.to_vec();
 9945
 9946    cx.background_spawn(async move {
 9947        let remote_connection_id = persistence::DB
 9948            .get_or_create_remote_connection(connection_options)
 9949            .await
 9950            .context("fetching serialized ssh project")?;
 9951        let serialized_workspace =
 9952            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9953
 9954        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9955            (Some(WindowBounds::Windowed(bounds)), None)
 9956        } else {
 9957            let restorable_bounds = serialized_workspace
 9958                .as_ref()
 9959                .and_then(|workspace| {
 9960                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9961                })
 9962                .or_else(|| persistence::read_default_window_bounds());
 9963
 9964            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9965                (Some(serialized_bounds), Some(serialized_display))
 9966            } else {
 9967                (None, None)
 9968            }
 9969        };
 9970
 9971        let centered_layout = serialized_workspace
 9972            .as_ref()
 9973            .map(|w| w.centered_layout)
 9974            .unwrap_or(false);
 9975
 9976        Ok(WorkspacePosition {
 9977            window_bounds,
 9978            display,
 9979            centered_layout,
 9980        })
 9981    })
 9982}
 9983
 9984pub fn with_active_or_new_workspace(
 9985    cx: &mut App,
 9986    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9987) {
 9988    match cx
 9989        .active_window()
 9990        .and_then(|w| w.downcast::<MultiWorkspace>())
 9991    {
 9992        Some(multi_workspace) => {
 9993            cx.defer(move |cx| {
 9994                multi_workspace
 9995                    .update(cx, |multi_workspace, window, cx| {
 9996                        let workspace = multi_workspace.workspace().clone();
 9997                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9998                    })
 9999                    .log_err();
10000            });
10001        }
10002        None => {
10003            let app_state = AppState::global(cx);
10004            if let Some(app_state) = app_state.upgrade() {
10005                open_new(
10006                    OpenOptions::default(),
10007                    app_state,
10008                    cx,
10009                    move |workspace, window, cx| f(workspace, window, cx),
10010                )
10011                .detach_and_log_err(cx);
10012            }
10013        }
10014    }
10015}
10016
10017#[cfg(test)]
10018mod tests {
10019    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10020
10021    use super::*;
10022    use crate::{
10023        dock::{PanelEvent, test::TestPanel},
10024        item::{
10025            ItemBufferKind, ItemEvent,
10026            test::{TestItem, TestProjectItem},
10027        },
10028    };
10029    use fs::FakeFs;
10030    use gpui::{
10031        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10032        UpdateGlobal, VisualTestContext, px,
10033    };
10034    use project::{Project, ProjectEntryId};
10035    use serde_json::json;
10036    use settings::SettingsStore;
10037    use util::path;
10038    use util::rel_path::rel_path;
10039
10040    #[gpui::test]
10041    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10042        init_test(cx);
10043
10044        let fs = FakeFs::new(cx.executor());
10045        let project = Project::test(fs, [], cx).await;
10046        let (workspace, cx) =
10047            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10048
10049        // Adding an item with no ambiguity renders the tab without detail.
10050        let item1 = cx.new(|cx| {
10051            let mut item = TestItem::new(cx);
10052            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10053            item
10054        });
10055        workspace.update_in(cx, |workspace, window, cx| {
10056            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10057        });
10058        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10059
10060        // Adding an item that creates ambiguity increases the level of detail on
10061        // both tabs.
10062        let item2 = cx.new_window_entity(|_window, cx| {
10063            let mut item = TestItem::new(cx);
10064            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10065            item
10066        });
10067        workspace.update_in(cx, |workspace, window, cx| {
10068            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10069        });
10070        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10071        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10072
10073        // Adding an item that creates ambiguity increases the level of detail only
10074        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10075        // we stop at the highest detail available.
10076        let item3 = cx.new(|cx| {
10077            let mut item = TestItem::new(cx);
10078            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10079            item
10080        });
10081        workspace.update_in(cx, |workspace, window, cx| {
10082            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10083        });
10084        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10085        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10086        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10087    }
10088
10089    #[gpui::test]
10090    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10091        init_test(cx);
10092
10093        let fs = FakeFs::new(cx.executor());
10094        fs.insert_tree(
10095            "/root1",
10096            json!({
10097                "one.txt": "",
10098                "two.txt": "",
10099            }),
10100        )
10101        .await;
10102        fs.insert_tree(
10103            "/root2",
10104            json!({
10105                "three.txt": "",
10106            }),
10107        )
10108        .await;
10109
10110        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10111        let (workspace, cx) =
10112            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10113        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10114        let worktree_id = project.update(cx, |project, cx| {
10115            project.worktrees(cx).next().unwrap().read(cx).id()
10116        });
10117
10118        let item1 = cx.new(|cx| {
10119            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10120        });
10121        let item2 = cx.new(|cx| {
10122            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10123        });
10124
10125        // Add an item to an empty pane
10126        workspace.update_in(cx, |workspace, window, cx| {
10127            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10128        });
10129        project.update(cx, |project, cx| {
10130            assert_eq!(
10131                project.active_entry(),
10132                project
10133                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10134                    .map(|e| e.id)
10135            );
10136        });
10137        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10138
10139        // Add a second item to a non-empty pane
10140        workspace.update_in(cx, |workspace, window, cx| {
10141            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10142        });
10143        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10144        project.update(cx, |project, cx| {
10145            assert_eq!(
10146                project.active_entry(),
10147                project
10148                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10149                    .map(|e| e.id)
10150            );
10151        });
10152
10153        // Close the active item
10154        pane.update_in(cx, |pane, window, cx| {
10155            pane.close_active_item(&Default::default(), window, cx)
10156        })
10157        .await
10158        .unwrap();
10159        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10160        project.update(cx, |project, cx| {
10161            assert_eq!(
10162                project.active_entry(),
10163                project
10164                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10165                    .map(|e| e.id)
10166            );
10167        });
10168
10169        // Add a project folder
10170        project
10171            .update(cx, |project, cx| {
10172                project.find_or_create_worktree("root2", true, cx)
10173            })
10174            .await
10175            .unwrap();
10176        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10177
10178        // Remove a project folder
10179        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10180        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10181    }
10182
10183    #[gpui::test]
10184    async fn test_close_window(cx: &mut TestAppContext) {
10185        init_test(cx);
10186
10187        let fs = FakeFs::new(cx.executor());
10188        fs.insert_tree("/root", json!({ "one": "" })).await;
10189
10190        let project = Project::test(fs, ["root".as_ref()], cx).await;
10191        let (workspace, cx) =
10192            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10193
10194        // When there are no dirty items, there's nothing to do.
10195        let item1 = cx.new(TestItem::new);
10196        workspace.update_in(cx, |w, window, cx| {
10197            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10198        });
10199        let task = workspace.update_in(cx, |w, window, cx| {
10200            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10201        });
10202        assert!(task.await.unwrap());
10203
10204        // When there are dirty untitled items, prompt to save each one. If the user
10205        // cancels any prompt, then abort.
10206        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10207        let item3 = cx.new(|cx| {
10208            TestItem::new(cx)
10209                .with_dirty(true)
10210                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10211        });
10212        workspace.update_in(cx, |w, window, cx| {
10213            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10214            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10215        });
10216        let task = workspace.update_in(cx, |w, window, cx| {
10217            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10218        });
10219        cx.executor().run_until_parked();
10220        cx.simulate_prompt_answer("Cancel"); // cancel save all
10221        cx.executor().run_until_parked();
10222        assert!(!cx.has_pending_prompt());
10223        assert!(!task.await.unwrap());
10224    }
10225
10226    #[gpui::test]
10227    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10228        init_test(cx);
10229
10230        let fs = FakeFs::new(cx.executor());
10231        fs.insert_tree("/root", json!({ "one": "" })).await;
10232
10233        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10234        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10235        let multi_workspace_handle =
10236            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10237        cx.run_until_parked();
10238
10239        let workspace_a = multi_workspace_handle
10240            .read_with(cx, |mw, _| mw.workspace().clone())
10241            .unwrap();
10242
10243        let workspace_b = multi_workspace_handle
10244            .update(cx, |mw, window, cx| {
10245                mw.test_add_workspace(project_b, window, cx)
10246            })
10247            .unwrap();
10248
10249        // Activate workspace A
10250        multi_workspace_handle
10251            .update(cx, |mw, window, cx| {
10252                mw.activate_index(0, window, cx);
10253            })
10254            .unwrap();
10255
10256        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10257
10258        // Workspace A has a clean item
10259        let item_a = cx.new(TestItem::new);
10260        workspace_a.update_in(cx, |w, window, cx| {
10261            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10262        });
10263
10264        // Workspace B has a dirty item
10265        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10266        workspace_b.update_in(cx, |w, window, cx| {
10267            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10268        });
10269
10270        // Verify workspace A is active
10271        multi_workspace_handle
10272            .read_with(cx, |mw, _| {
10273                assert_eq!(mw.active_workspace_index(), 0);
10274            })
10275            .unwrap();
10276
10277        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10278        multi_workspace_handle
10279            .update(cx, |mw, window, cx| {
10280                mw.close_window(&CloseWindow, window, cx);
10281            })
10282            .unwrap();
10283        cx.run_until_parked();
10284
10285        // Workspace B should now be active since it has dirty items that need attention
10286        multi_workspace_handle
10287            .read_with(cx, |mw, _| {
10288                assert_eq!(
10289                    mw.active_workspace_index(),
10290                    1,
10291                    "workspace B should be activated when it prompts"
10292                );
10293            })
10294            .unwrap();
10295
10296        // User cancels the save prompt from workspace B
10297        cx.simulate_prompt_answer("Cancel");
10298        cx.run_until_parked();
10299
10300        // Window should still exist because workspace B's close was cancelled
10301        assert!(
10302            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10303            "window should still exist after cancelling one workspace's close"
10304        );
10305    }
10306
10307    #[gpui::test]
10308    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10309        init_test(cx);
10310
10311        // Register TestItem as a serializable item
10312        cx.update(|cx| {
10313            register_serializable_item::<TestItem>(cx);
10314        });
10315
10316        let fs = FakeFs::new(cx.executor());
10317        fs.insert_tree("/root", json!({ "one": "" })).await;
10318
10319        let project = Project::test(fs, ["root".as_ref()], cx).await;
10320        let (workspace, cx) =
10321            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10322
10323        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10324        let item1 = cx.new(|cx| {
10325            TestItem::new(cx)
10326                .with_dirty(true)
10327                .with_serialize(|| Some(Task::ready(Ok(()))))
10328        });
10329        let item2 = cx.new(|cx| {
10330            TestItem::new(cx)
10331                .with_dirty(true)
10332                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10333                .with_serialize(|| Some(Task::ready(Ok(()))))
10334        });
10335        workspace.update_in(cx, |w, window, cx| {
10336            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10337            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10338        });
10339        let task = workspace.update_in(cx, |w, window, cx| {
10340            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10341        });
10342        assert!(task.await.unwrap());
10343    }
10344
10345    #[gpui::test]
10346    async fn test_close_pane_items(cx: &mut TestAppContext) {
10347        init_test(cx);
10348
10349        let fs = FakeFs::new(cx.executor());
10350
10351        let project = Project::test(fs, None, cx).await;
10352        let (workspace, cx) =
10353            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10354
10355        let item1 = cx.new(|cx| {
10356            TestItem::new(cx)
10357                .with_dirty(true)
10358                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10359        });
10360        let item2 = cx.new(|cx| {
10361            TestItem::new(cx)
10362                .with_dirty(true)
10363                .with_conflict(true)
10364                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10365        });
10366        let item3 = cx.new(|cx| {
10367            TestItem::new(cx)
10368                .with_dirty(true)
10369                .with_conflict(true)
10370                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10371        });
10372        let item4 = cx.new(|cx| {
10373            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10374                let project_item = TestProjectItem::new_untitled(cx);
10375                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10376                project_item
10377            }])
10378        });
10379        let pane = workspace.update_in(cx, |workspace, window, cx| {
10380            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10381            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10382            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10383            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10384            workspace.active_pane().clone()
10385        });
10386
10387        let close_items = pane.update_in(cx, |pane, window, cx| {
10388            pane.activate_item(1, true, true, window, cx);
10389            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10390            let item1_id = item1.item_id();
10391            let item3_id = item3.item_id();
10392            let item4_id = item4.item_id();
10393            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10394                [item1_id, item3_id, item4_id].contains(&id)
10395            })
10396        });
10397        cx.executor().run_until_parked();
10398
10399        assert!(cx.has_pending_prompt());
10400        cx.simulate_prompt_answer("Save all");
10401
10402        cx.executor().run_until_parked();
10403
10404        // Item 1 is saved. There's a prompt to save item 3.
10405        pane.update(cx, |pane, cx| {
10406            assert_eq!(item1.read(cx).save_count, 1);
10407            assert_eq!(item1.read(cx).save_as_count, 0);
10408            assert_eq!(item1.read(cx).reload_count, 0);
10409            assert_eq!(pane.items_len(), 3);
10410            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10411        });
10412        assert!(cx.has_pending_prompt());
10413
10414        // Cancel saving item 3.
10415        cx.simulate_prompt_answer("Discard");
10416        cx.executor().run_until_parked();
10417
10418        // Item 3 is reloaded. There's a prompt to save item 4.
10419        pane.update(cx, |pane, cx| {
10420            assert_eq!(item3.read(cx).save_count, 0);
10421            assert_eq!(item3.read(cx).save_as_count, 0);
10422            assert_eq!(item3.read(cx).reload_count, 1);
10423            assert_eq!(pane.items_len(), 2);
10424            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10425        });
10426
10427        // There's a prompt for a path for item 4.
10428        cx.simulate_new_path_selection(|_| Some(Default::default()));
10429        close_items.await.unwrap();
10430
10431        // The requested items are closed.
10432        pane.update(cx, |pane, cx| {
10433            assert_eq!(item4.read(cx).save_count, 0);
10434            assert_eq!(item4.read(cx).save_as_count, 1);
10435            assert_eq!(item4.read(cx).reload_count, 0);
10436            assert_eq!(pane.items_len(), 1);
10437            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10438        });
10439    }
10440
10441    #[gpui::test]
10442    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10443        init_test(cx);
10444
10445        let fs = FakeFs::new(cx.executor());
10446        let project = Project::test(fs, [], cx).await;
10447        let (workspace, cx) =
10448            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10449
10450        // Create several workspace items with single project entries, and two
10451        // workspace items with multiple project entries.
10452        let single_entry_items = (0..=4)
10453            .map(|project_entry_id| {
10454                cx.new(|cx| {
10455                    TestItem::new(cx)
10456                        .with_dirty(true)
10457                        .with_project_items(&[dirty_project_item(
10458                            project_entry_id,
10459                            &format!("{project_entry_id}.txt"),
10460                            cx,
10461                        )])
10462                })
10463            })
10464            .collect::<Vec<_>>();
10465        let item_2_3 = cx.new(|cx| {
10466            TestItem::new(cx)
10467                .with_dirty(true)
10468                .with_buffer_kind(ItemBufferKind::Multibuffer)
10469                .with_project_items(&[
10470                    single_entry_items[2].read(cx).project_items[0].clone(),
10471                    single_entry_items[3].read(cx).project_items[0].clone(),
10472                ])
10473        });
10474        let item_3_4 = cx.new(|cx| {
10475            TestItem::new(cx)
10476                .with_dirty(true)
10477                .with_buffer_kind(ItemBufferKind::Multibuffer)
10478                .with_project_items(&[
10479                    single_entry_items[3].read(cx).project_items[0].clone(),
10480                    single_entry_items[4].read(cx).project_items[0].clone(),
10481                ])
10482        });
10483
10484        // Create two panes that contain the following project entries:
10485        //   left pane:
10486        //     multi-entry items:   (2, 3)
10487        //     single-entry items:  0, 2, 3, 4
10488        //   right pane:
10489        //     single-entry items:  4, 1
10490        //     multi-entry items:   (3, 4)
10491        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10492            let left_pane = workspace.active_pane().clone();
10493            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10494            workspace.add_item_to_active_pane(
10495                single_entry_items[0].boxed_clone(),
10496                None,
10497                true,
10498                window,
10499                cx,
10500            );
10501            workspace.add_item_to_active_pane(
10502                single_entry_items[2].boxed_clone(),
10503                None,
10504                true,
10505                window,
10506                cx,
10507            );
10508            workspace.add_item_to_active_pane(
10509                single_entry_items[3].boxed_clone(),
10510                None,
10511                true,
10512                window,
10513                cx,
10514            );
10515            workspace.add_item_to_active_pane(
10516                single_entry_items[4].boxed_clone(),
10517                None,
10518                true,
10519                window,
10520                cx,
10521            );
10522
10523            let right_pane =
10524                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10525
10526            let boxed_clone = single_entry_items[1].boxed_clone();
10527            let right_pane = window.spawn(cx, async move |cx| {
10528                right_pane.await.inspect(|right_pane| {
10529                    right_pane
10530                        .update_in(cx, |pane, window, cx| {
10531                            pane.add_item(boxed_clone, true, true, None, window, cx);
10532                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10533                        })
10534                        .unwrap();
10535                })
10536            });
10537
10538            (left_pane, right_pane)
10539        });
10540        let right_pane = right_pane.await.unwrap();
10541        cx.focus(&right_pane);
10542
10543        let close = right_pane.update_in(cx, |pane, window, cx| {
10544            pane.close_all_items(&CloseAllItems::default(), window, cx)
10545                .unwrap()
10546        });
10547        cx.executor().run_until_parked();
10548
10549        let msg = cx.pending_prompt().unwrap().0;
10550        assert!(msg.contains("1.txt"));
10551        assert!(!msg.contains("2.txt"));
10552        assert!(!msg.contains("3.txt"));
10553        assert!(!msg.contains("4.txt"));
10554
10555        // With best-effort close, cancelling item 1 keeps it open but items 4
10556        // and (3,4) still close since their entries exist in left pane.
10557        cx.simulate_prompt_answer("Cancel");
10558        close.await;
10559
10560        right_pane.read_with(cx, |pane, _| {
10561            assert_eq!(pane.items_len(), 1);
10562        });
10563
10564        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10565        left_pane
10566            .update_in(cx, |left_pane, window, cx| {
10567                left_pane.close_item_by_id(
10568                    single_entry_items[3].entity_id(),
10569                    SaveIntent::Skip,
10570                    window,
10571                    cx,
10572                )
10573            })
10574            .await
10575            .unwrap();
10576
10577        let close = left_pane.update_in(cx, |pane, window, cx| {
10578            pane.close_all_items(&CloseAllItems::default(), window, cx)
10579                .unwrap()
10580        });
10581        cx.executor().run_until_parked();
10582
10583        let details = cx.pending_prompt().unwrap().1;
10584        assert!(details.contains("0.txt"));
10585        assert!(details.contains("3.txt"));
10586        assert!(details.contains("4.txt"));
10587        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10588        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10589        // assert!(!details.contains("2.txt"));
10590
10591        cx.simulate_prompt_answer("Save all");
10592        cx.executor().run_until_parked();
10593        close.await;
10594
10595        left_pane.read_with(cx, |pane, _| {
10596            assert_eq!(pane.items_len(), 0);
10597        });
10598    }
10599
10600    #[gpui::test]
10601    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10602        init_test(cx);
10603
10604        let fs = FakeFs::new(cx.executor());
10605        let project = Project::test(fs, [], cx).await;
10606        let (workspace, cx) =
10607            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10608        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10609
10610        let item = cx.new(|cx| {
10611            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10612        });
10613        let item_id = item.entity_id();
10614        workspace.update_in(cx, |workspace, window, cx| {
10615            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10616        });
10617
10618        // Autosave on window change.
10619        item.update(cx, |item, cx| {
10620            SettingsStore::update_global(cx, |settings, cx| {
10621                settings.update_user_settings(cx, |settings| {
10622                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10623                })
10624            });
10625            item.is_dirty = true;
10626        });
10627
10628        // Deactivating the window saves the file.
10629        cx.deactivate_window();
10630        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10631
10632        // Re-activating the window doesn't save the file.
10633        cx.update(|window, _| window.activate_window());
10634        cx.executor().run_until_parked();
10635        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10636
10637        // Autosave on focus change.
10638        item.update_in(cx, |item, window, cx| {
10639            cx.focus_self(window);
10640            SettingsStore::update_global(cx, |settings, cx| {
10641                settings.update_user_settings(cx, |settings| {
10642                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10643                })
10644            });
10645            item.is_dirty = true;
10646        });
10647        // Blurring the item saves the file.
10648        item.update_in(cx, |_, window, _| window.blur());
10649        cx.executor().run_until_parked();
10650        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10651
10652        // Deactivating the window still saves the file.
10653        item.update_in(cx, |item, window, cx| {
10654            cx.focus_self(window);
10655            item.is_dirty = true;
10656        });
10657        cx.deactivate_window();
10658        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10659
10660        // Autosave after delay.
10661        item.update(cx, |item, cx| {
10662            SettingsStore::update_global(cx, |settings, cx| {
10663                settings.update_user_settings(cx, |settings| {
10664                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10665                        milliseconds: 500.into(),
10666                    });
10667                })
10668            });
10669            item.is_dirty = true;
10670            cx.emit(ItemEvent::Edit);
10671        });
10672
10673        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10674        cx.executor().advance_clock(Duration::from_millis(250));
10675        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10676
10677        // After delay expires, the file is saved.
10678        cx.executor().advance_clock(Duration::from_millis(250));
10679        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10680
10681        // Autosave after delay, should save earlier than delay if tab is closed
10682        item.update(cx, |item, cx| {
10683            item.is_dirty = true;
10684            cx.emit(ItemEvent::Edit);
10685        });
10686        cx.executor().advance_clock(Duration::from_millis(250));
10687        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10688
10689        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10690        pane.update_in(cx, |pane, window, cx| {
10691            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10692        })
10693        .await
10694        .unwrap();
10695        assert!(!cx.has_pending_prompt());
10696        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10697
10698        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10699        workspace.update_in(cx, |workspace, window, cx| {
10700            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10701        });
10702        item.update_in(cx, |item, _window, cx| {
10703            item.is_dirty = true;
10704            for project_item in &mut item.project_items {
10705                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10706            }
10707        });
10708        cx.run_until_parked();
10709        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10710
10711        // Autosave on focus change, ensuring closing the tab counts as such.
10712        item.update(cx, |item, cx| {
10713            SettingsStore::update_global(cx, |settings, cx| {
10714                settings.update_user_settings(cx, |settings| {
10715                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10716                })
10717            });
10718            item.is_dirty = true;
10719            for project_item in &mut item.project_items {
10720                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10721            }
10722        });
10723
10724        pane.update_in(cx, |pane, window, cx| {
10725            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10726        })
10727        .await
10728        .unwrap();
10729        assert!(!cx.has_pending_prompt());
10730        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10731
10732        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10733        workspace.update_in(cx, |workspace, window, cx| {
10734            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10735        });
10736        item.update_in(cx, |item, window, cx| {
10737            item.project_items[0].update(cx, |item, _| {
10738                item.entry_id = None;
10739            });
10740            item.is_dirty = true;
10741            window.blur();
10742        });
10743        cx.run_until_parked();
10744        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10745
10746        // Ensure autosave is prevented for deleted files also when closing the buffer.
10747        let _close_items = pane.update_in(cx, |pane, window, cx| {
10748            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10749        });
10750        cx.run_until_parked();
10751        assert!(cx.has_pending_prompt());
10752        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10753    }
10754
10755    #[gpui::test]
10756    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10757        init_test(cx);
10758
10759        let fs = FakeFs::new(cx.executor());
10760        let project = Project::test(fs, [], cx).await;
10761        let (workspace, cx) =
10762            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10763
10764        // Create a multibuffer-like item with two child focus handles,
10765        // simulating individual buffer editors within a multibuffer.
10766        let item = cx.new(|cx| {
10767            TestItem::new(cx)
10768                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10769                .with_child_focus_handles(2, cx)
10770        });
10771        workspace.update_in(cx, |workspace, window, cx| {
10772            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10773        });
10774
10775        // Set autosave to OnFocusChange and focus the first child handle,
10776        // simulating the user's cursor being inside one of the multibuffer's excerpts.
10777        item.update_in(cx, |item, window, cx| {
10778            SettingsStore::update_global(cx, |settings, cx| {
10779                settings.update_user_settings(cx, |settings| {
10780                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10781                })
10782            });
10783            item.is_dirty = true;
10784            window.focus(&item.child_focus_handles[0], cx);
10785        });
10786        cx.executor().run_until_parked();
10787        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10788
10789        // Moving focus from one child to another within the same item should
10790        // NOT trigger autosave — focus is still within the item's focus hierarchy.
10791        item.update_in(cx, |item, window, cx| {
10792            window.focus(&item.child_focus_handles[1], cx);
10793        });
10794        cx.executor().run_until_parked();
10795        item.read_with(cx, |item, _| {
10796            assert_eq!(
10797                item.save_count, 0,
10798                "Switching focus between children within the same item should not autosave"
10799            );
10800        });
10801
10802        // Blurring the item saves the file. This is the core regression scenario:
10803        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10804        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10805        // the leaf is always a child focus handle, so `on_blur` never detected
10806        // focus leaving the item.
10807        item.update_in(cx, |_, window, _| window.blur());
10808        cx.executor().run_until_parked();
10809        item.read_with(cx, |item, _| {
10810            assert_eq!(
10811                item.save_count, 1,
10812                "Blurring should trigger autosave when focus was on a child of the item"
10813            );
10814        });
10815
10816        // Deactivating the window should also trigger autosave when a child of
10817        // the multibuffer item currently owns focus.
10818        item.update_in(cx, |item, window, cx| {
10819            item.is_dirty = true;
10820            window.focus(&item.child_focus_handles[0], cx);
10821        });
10822        cx.executor().run_until_parked();
10823        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10824
10825        cx.deactivate_window();
10826        item.read_with(cx, |item, _| {
10827            assert_eq!(
10828                item.save_count, 2,
10829                "Deactivating window should trigger autosave when focus was on a child"
10830            );
10831        });
10832    }
10833
10834    #[gpui::test]
10835    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10836        init_test(cx);
10837
10838        let fs = FakeFs::new(cx.executor());
10839
10840        let project = Project::test(fs, [], cx).await;
10841        let (workspace, cx) =
10842            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10843
10844        let item = cx.new(|cx| {
10845            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10846        });
10847        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10848        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10849        let toolbar_notify_count = Rc::new(RefCell::new(0));
10850
10851        workspace.update_in(cx, |workspace, window, cx| {
10852            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10853            let toolbar_notification_count = toolbar_notify_count.clone();
10854            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10855                *toolbar_notification_count.borrow_mut() += 1
10856            })
10857            .detach();
10858        });
10859
10860        pane.read_with(cx, |pane, _| {
10861            assert!(!pane.can_navigate_backward());
10862            assert!(!pane.can_navigate_forward());
10863        });
10864
10865        item.update_in(cx, |item, _, cx| {
10866            item.set_state("one".to_string(), cx);
10867        });
10868
10869        // Toolbar must be notified to re-render the navigation buttons
10870        assert_eq!(*toolbar_notify_count.borrow(), 1);
10871
10872        pane.read_with(cx, |pane, _| {
10873            assert!(pane.can_navigate_backward());
10874            assert!(!pane.can_navigate_forward());
10875        });
10876
10877        workspace
10878            .update_in(cx, |workspace, window, cx| {
10879                workspace.go_back(pane.downgrade(), window, cx)
10880            })
10881            .await
10882            .unwrap();
10883
10884        assert_eq!(*toolbar_notify_count.borrow(), 2);
10885        pane.read_with(cx, |pane, _| {
10886            assert!(!pane.can_navigate_backward());
10887            assert!(pane.can_navigate_forward());
10888        });
10889    }
10890
10891    #[gpui::test]
10892    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10893        init_test(cx);
10894        let fs = FakeFs::new(cx.executor());
10895        let project = Project::test(fs, [], cx).await;
10896        let (multi_workspace, cx) =
10897            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10898        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10899
10900        workspace.update_in(cx, |workspace, window, cx| {
10901            let first_item = cx.new(|cx| {
10902                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10903            });
10904            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10905            workspace.split_pane(
10906                workspace.active_pane().clone(),
10907                SplitDirection::Right,
10908                window,
10909                cx,
10910            );
10911            workspace.split_pane(
10912                workspace.active_pane().clone(),
10913                SplitDirection::Right,
10914                window,
10915                cx,
10916            );
10917        });
10918
10919        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10920            let panes = workspace.center.panes();
10921            assert!(panes.len() >= 2);
10922            (
10923                panes.first().expect("at least one pane").entity_id(),
10924                panes.last().expect("at least one pane").entity_id(),
10925            )
10926        });
10927
10928        workspace.update_in(cx, |workspace, window, cx| {
10929            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10930        });
10931        workspace.update(cx, |workspace, _| {
10932            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10933            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10934        });
10935
10936        cx.dispatch_action(ActivateLastPane);
10937
10938        workspace.update(cx, |workspace, _| {
10939            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10940        });
10941    }
10942
10943    #[gpui::test]
10944    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10945        init_test(cx);
10946        let fs = FakeFs::new(cx.executor());
10947
10948        let project = Project::test(fs, [], cx).await;
10949        let (workspace, cx) =
10950            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10951
10952        let panel = workspace.update_in(cx, |workspace, window, cx| {
10953            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10954            workspace.add_panel(panel.clone(), window, cx);
10955
10956            workspace
10957                .right_dock()
10958                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10959
10960            panel
10961        });
10962
10963        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10964        pane.update_in(cx, |pane, window, cx| {
10965            let item = cx.new(TestItem::new);
10966            pane.add_item(Box::new(item), true, true, None, window, cx);
10967        });
10968
10969        // Transfer focus from center to panel
10970        workspace.update_in(cx, |workspace, window, cx| {
10971            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10972        });
10973
10974        workspace.update_in(cx, |workspace, window, cx| {
10975            assert!(workspace.right_dock().read(cx).is_open());
10976            assert!(!panel.is_zoomed(window, cx));
10977            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10978        });
10979
10980        // Transfer focus from panel to center
10981        workspace.update_in(cx, |workspace, window, cx| {
10982            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10983        });
10984
10985        workspace.update_in(cx, |workspace, window, cx| {
10986            assert!(workspace.right_dock().read(cx).is_open());
10987            assert!(!panel.is_zoomed(window, cx));
10988            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10989        });
10990
10991        // Close the dock
10992        workspace.update_in(cx, |workspace, window, cx| {
10993            workspace.toggle_dock(DockPosition::Right, window, cx);
10994        });
10995
10996        workspace.update_in(cx, |workspace, window, cx| {
10997            assert!(!workspace.right_dock().read(cx).is_open());
10998            assert!(!panel.is_zoomed(window, cx));
10999            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11000        });
11001
11002        // Open the dock
11003        workspace.update_in(cx, |workspace, window, cx| {
11004            workspace.toggle_dock(DockPosition::Right, window, cx);
11005        });
11006
11007        workspace.update_in(cx, |workspace, window, cx| {
11008            assert!(workspace.right_dock().read(cx).is_open());
11009            assert!(!panel.is_zoomed(window, cx));
11010            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11011        });
11012
11013        // Focus and zoom panel
11014        panel.update_in(cx, |panel, window, cx| {
11015            cx.focus_self(window);
11016            panel.set_zoomed(true, window, cx)
11017        });
11018
11019        workspace.update_in(cx, |workspace, window, cx| {
11020            assert!(workspace.right_dock().read(cx).is_open());
11021            assert!(panel.is_zoomed(window, cx));
11022            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11023        });
11024
11025        // Transfer focus to the center closes the dock
11026        workspace.update_in(cx, |workspace, window, cx| {
11027            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11028        });
11029
11030        workspace.update_in(cx, |workspace, window, cx| {
11031            assert!(!workspace.right_dock().read(cx).is_open());
11032            assert!(panel.is_zoomed(window, cx));
11033            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11034        });
11035
11036        // Transferring focus back to the panel keeps it zoomed
11037        workspace.update_in(cx, |workspace, window, cx| {
11038            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11039        });
11040
11041        workspace.update_in(cx, |workspace, window, cx| {
11042            assert!(workspace.right_dock().read(cx).is_open());
11043            assert!(panel.is_zoomed(window, cx));
11044            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11045        });
11046
11047        // Close the dock while it is zoomed
11048        workspace.update_in(cx, |workspace, window, cx| {
11049            workspace.toggle_dock(DockPosition::Right, window, cx)
11050        });
11051
11052        workspace.update_in(cx, |workspace, window, cx| {
11053            assert!(!workspace.right_dock().read(cx).is_open());
11054            assert!(panel.is_zoomed(window, cx));
11055            assert!(workspace.zoomed.is_none());
11056            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11057        });
11058
11059        // Opening the dock, when it's zoomed, retains focus
11060        workspace.update_in(cx, |workspace, window, cx| {
11061            workspace.toggle_dock(DockPosition::Right, window, cx)
11062        });
11063
11064        workspace.update_in(cx, |workspace, window, cx| {
11065            assert!(workspace.right_dock().read(cx).is_open());
11066            assert!(panel.is_zoomed(window, cx));
11067            assert!(workspace.zoomed.is_some());
11068            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11069        });
11070
11071        // Unzoom and close the panel, zoom the active pane.
11072        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11073        workspace.update_in(cx, |workspace, window, cx| {
11074            workspace.toggle_dock(DockPosition::Right, window, cx)
11075        });
11076        pane.update_in(cx, |pane, window, cx| {
11077            pane.toggle_zoom(&Default::default(), window, cx)
11078        });
11079
11080        // Opening a dock unzooms the pane.
11081        workspace.update_in(cx, |workspace, window, cx| {
11082            workspace.toggle_dock(DockPosition::Right, window, cx)
11083        });
11084        workspace.update_in(cx, |workspace, window, cx| {
11085            let pane = pane.read(cx);
11086            assert!(!pane.is_zoomed());
11087            assert!(!pane.focus_handle(cx).is_focused(window));
11088            assert!(workspace.right_dock().read(cx).is_open());
11089            assert!(workspace.zoomed.is_none());
11090        });
11091    }
11092
11093    #[gpui::test]
11094    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11095        init_test(cx);
11096        let fs = FakeFs::new(cx.executor());
11097
11098        let project = Project::test(fs, [], cx).await;
11099        let (workspace, cx) =
11100            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11101
11102        let panel = workspace.update_in(cx, |workspace, window, cx| {
11103            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11104            workspace.add_panel(panel.clone(), window, cx);
11105            panel
11106        });
11107
11108        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11109        pane.update_in(cx, |pane, window, cx| {
11110            let item = cx.new(TestItem::new);
11111            pane.add_item(Box::new(item), true, true, None, window, cx);
11112        });
11113
11114        // Enable close_panel_on_toggle
11115        cx.update_global(|store: &mut SettingsStore, cx| {
11116            store.update_user_settings(cx, |settings| {
11117                settings.workspace.close_panel_on_toggle = Some(true);
11118            });
11119        });
11120
11121        // Panel starts closed. Toggling should open and focus it.
11122        workspace.update_in(cx, |workspace, window, cx| {
11123            assert!(!workspace.right_dock().read(cx).is_open());
11124            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11125        });
11126
11127        workspace.update_in(cx, |workspace, window, cx| {
11128            assert!(
11129                workspace.right_dock().read(cx).is_open(),
11130                "Dock should be open after toggling from center"
11131            );
11132            assert!(
11133                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11134                "Panel should be focused after toggling from center"
11135            );
11136        });
11137
11138        // Panel is open and focused. Toggling should close the panel and
11139        // return focus to the center.
11140        workspace.update_in(cx, |workspace, window, cx| {
11141            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11142        });
11143
11144        workspace.update_in(cx, |workspace, window, cx| {
11145            assert!(
11146                !workspace.right_dock().read(cx).is_open(),
11147                "Dock should be closed after toggling from focused panel"
11148            );
11149            assert!(
11150                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11151                "Panel should not be focused after toggling from focused panel"
11152            );
11153        });
11154
11155        // Open the dock and focus something else so the panel is open but not
11156        // focused. Toggling should focus the panel (not close it).
11157        workspace.update_in(cx, |workspace, window, cx| {
11158            workspace
11159                .right_dock()
11160                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11161            window.focus(&pane.read(cx).focus_handle(cx), cx);
11162        });
11163
11164        workspace.update_in(cx, |workspace, window, cx| {
11165            assert!(workspace.right_dock().read(cx).is_open());
11166            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11167            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11168        });
11169
11170        workspace.update_in(cx, |workspace, window, cx| {
11171            assert!(
11172                workspace.right_dock().read(cx).is_open(),
11173                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11174            );
11175            assert!(
11176                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11177                "Panel should be focused after toggling an open-but-unfocused panel"
11178            );
11179        });
11180
11181        // Now disable the setting and verify the original behavior: toggling
11182        // from a focused panel moves focus to center but leaves the dock open.
11183        cx.update_global(|store: &mut SettingsStore, cx| {
11184            store.update_user_settings(cx, |settings| {
11185                settings.workspace.close_panel_on_toggle = Some(false);
11186            });
11187        });
11188
11189        workspace.update_in(cx, |workspace, window, cx| {
11190            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11191        });
11192
11193        workspace.update_in(cx, |workspace, window, cx| {
11194            assert!(
11195                workspace.right_dock().read(cx).is_open(),
11196                "Dock should remain open when setting is disabled"
11197            );
11198            assert!(
11199                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11200                "Panel should not be focused after toggling with setting disabled"
11201            );
11202        });
11203    }
11204
11205    #[gpui::test]
11206    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11207        init_test(cx);
11208        let fs = FakeFs::new(cx.executor());
11209
11210        let project = Project::test(fs, [], cx).await;
11211        let (workspace, cx) =
11212            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11213
11214        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11215            workspace.active_pane().clone()
11216        });
11217
11218        // Add an item to the pane so it can be zoomed
11219        workspace.update_in(cx, |workspace, window, cx| {
11220            let item = cx.new(TestItem::new);
11221            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11222        });
11223
11224        // Initially not zoomed
11225        workspace.update_in(cx, |workspace, _window, cx| {
11226            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11227            assert!(
11228                workspace.zoomed.is_none(),
11229                "Workspace should track no zoomed pane"
11230            );
11231            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11232        });
11233
11234        // Zoom In
11235        pane.update_in(cx, |pane, window, cx| {
11236            pane.zoom_in(&crate::ZoomIn, window, cx);
11237        });
11238
11239        workspace.update_in(cx, |workspace, window, cx| {
11240            assert!(
11241                pane.read(cx).is_zoomed(),
11242                "Pane should be zoomed after ZoomIn"
11243            );
11244            assert!(
11245                workspace.zoomed.is_some(),
11246                "Workspace should track the zoomed pane"
11247            );
11248            assert!(
11249                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11250                "ZoomIn should focus the pane"
11251            );
11252        });
11253
11254        // Zoom In again is a no-op
11255        pane.update_in(cx, |pane, window, cx| {
11256            pane.zoom_in(&crate::ZoomIn, window, cx);
11257        });
11258
11259        workspace.update_in(cx, |workspace, window, cx| {
11260            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11261            assert!(
11262                workspace.zoomed.is_some(),
11263                "Workspace still tracks zoomed pane"
11264            );
11265            assert!(
11266                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11267                "Pane remains focused after repeated ZoomIn"
11268            );
11269        });
11270
11271        // Zoom Out
11272        pane.update_in(cx, |pane, window, cx| {
11273            pane.zoom_out(&crate::ZoomOut, window, cx);
11274        });
11275
11276        workspace.update_in(cx, |workspace, _window, cx| {
11277            assert!(
11278                !pane.read(cx).is_zoomed(),
11279                "Pane should unzoom after ZoomOut"
11280            );
11281            assert!(
11282                workspace.zoomed.is_none(),
11283                "Workspace clears zoom tracking after ZoomOut"
11284            );
11285        });
11286
11287        // Zoom Out again is a no-op
11288        pane.update_in(cx, |pane, window, cx| {
11289            pane.zoom_out(&crate::ZoomOut, window, cx);
11290        });
11291
11292        workspace.update_in(cx, |workspace, _window, cx| {
11293            assert!(
11294                !pane.read(cx).is_zoomed(),
11295                "Second ZoomOut keeps pane unzoomed"
11296            );
11297            assert!(
11298                workspace.zoomed.is_none(),
11299                "Workspace remains without zoomed pane"
11300            );
11301        });
11302    }
11303
11304    #[gpui::test]
11305    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11306        init_test(cx);
11307        let fs = FakeFs::new(cx.executor());
11308
11309        let project = Project::test(fs, [], cx).await;
11310        let (workspace, cx) =
11311            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11312        workspace.update_in(cx, |workspace, window, cx| {
11313            // Open two docks
11314            let left_dock = workspace.dock_at_position(DockPosition::Left);
11315            let right_dock = workspace.dock_at_position(DockPosition::Right);
11316
11317            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11318            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11319
11320            assert!(left_dock.read(cx).is_open());
11321            assert!(right_dock.read(cx).is_open());
11322        });
11323
11324        workspace.update_in(cx, |workspace, window, cx| {
11325            // Toggle all docks - should close both
11326            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11327
11328            let left_dock = workspace.dock_at_position(DockPosition::Left);
11329            let right_dock = workspace.dock_at_position(DockPosition::Right);
11330            assert!(!left_dock.read(cx).is_open());
11331            assert!(!right_dock.read(cx).is_open());
11332        });
11333
11334        workspace.update_in(cx, |workspace, window, cx| {
11335            // Toggle again - should reopen both
11336            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11337
11338            let left_dock = workspace.dock_at_position(DockPosition::Left);
11339            let right_dock = workspace.dock_at_position(DockPosition::Right);
11340            assert!(left_dock.read(cx).is_open());
11341            assert!(right_dock.read(cx).is_open());
11342        });
11343    }
11344
11345    #[gpui::test]
11346    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11347        init_test(cx);
11348        let fs = FakeFs::new(cx.executor());
11349
11350        let project = Project::test(fs, [], cx).await;
11351        let (workspace, cx) =
11352            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11353        workspace.update_in(cx, |workspace, window, cx| {
11354            // Open two docks
11355            let left_dock = workspace.dock_at_position(DockPosition::Left);
11356            let right_dock = workspace.dock_at_position(DockPosition::Right);
11357
11358            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11359            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11360
11361            assert!(left_dock.read(cx).is_open());
11362            assert!(right_dock.read(cx).is_open());
11363        });
11364
11365        workspace.update_in(cx, |workspace, window, cx| {
11366            // Close them manually
11367            workspace.toggle_dock(DockPosition::Left, window, cx);
11368            workspace.toggle_dock(DockPosition::Right, window, cx);
11369
11370            let left_dock = workspace.dock_at_position(DockPosition::Left);
11371            let right_dock = workspace.dock_at_position(DockPosition::Right);
11372            assert!(!left_dock.read(cx).is_open());
11373            assert!(!right_dock.read(cx).is_open());
11374        });
11375
11376        workspace.update_in(cx, |workspace, window, cx| {
11377            // Toggle all docks - only last closed (right dock) should reopen
11378            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11379
11380            let left_dock = workspace.dock_at_position(DockPosition::Left);
11381            let right_dock = workspace.dock_at_position(DockPosition::Right);
11382            assert!(!left_dock.read(cx).is_open());
11383            assert!(right_dock.read(cx).is_open());
11384        });
11385    }
11386
11387    #[gpui::test]
11388    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11389        init_test(cx);
11390        let fs = FakeFs::new(cx.executor());
11391        let project = Project::test(fs, [], cx).await;
11392        let (multi_workspace, cx) =
11393            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11394        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11395
11396        // Open two docks (left and right) with one panel each
11397        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11398            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11399            workspace.add_panel(left_panel.clone(), window, cx);
11400
11401            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11402            workspace.add_panel(right_panel.clone(), window, cx);
11403
11404            workspace.toggle_dock(DockPosition::Left, window, cx);
11405            workspace.toggle_dock(DockPosition::Right, window, cx);
11406
11407            // Verify initial state
11408            assert!(
11409                workspace.left_dock().read(cx).is_open(),
11410                "Left dock should be open"
11411            );
11412            assert_eq!(
11413                workspace
11414                    .left_dock()
11415                    .read(cx)
11416                    .visible_panel()
11417                    .unwrap()
11418                    .panel_id(),
11419                left_panel.panel_id(),
11420                "Left panel should be visible in left dock"
11421            );
11422            assert!(
11423                workspace.right_dock().read(cx).is_open(),
11424                "Right dock should be open"
11425            );
11426            assert_eq!(
11427                workspace
11428                    .right_dock()
11429                    .read(cx)
11430                    .visible_panel()
11431                    .unwrap()
11432                    .panel_id(),
11433                right_panel.panel_id(),
11434                "Right panel should be visible in right dock"
11435            );
11436            assert!(
11437                !workspace.bottom_dock().read(cx).is_open(),
11438                "Bottom dock should be closed"
11439            );
11440
11441            (left_panel, right_panel)
11442        });
11443
11444        // Focus the left panel and move it to the next position (bottom dock)
11445        workspace.update_in(cx, |workspace, window, cx| {
11446            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11447            assert!(
11448                left_panel.read(cx).focus_handle(cx).is_focused(window),
11449                "Left panel should be focused"
11450            );
11451        });
11452
11453        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11454
11455        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11456        workspace.update(cx, |workspace, cx| {
11457            assert!(
11458                !workspace.left_dock().read(cx).is_open(),
11459                "Left dock should be closed"
11460            );
11461            assert!(
11462                workspace.bottom_dock().read(cx).is_open(),
11463                "Bottom dock should now be open"
11464            );
11465            assert_eq!(
11466                left_panel.read(cx).position,
11467                DockPosition::Bottom,
11468                "Left panel should now be in the bottom dock"
11469            );
11470            assert_eq!(
11471                workspace
11472                    .bottom_dock()
11473                    .read(cx)
11474                    .visible_panel()
11475                    .unwrap()
11476                    .panel_id(),
11477                left_panel.panel_id(),
11478                "Left panel should be the visible panel in the bottom dock"
11479            );
11480        });
11481
11482        // Toggle all docks off
11483        workspace.update_in(cx, |workspace, window, cx| {
11484            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11485            assert!(
11486                !workspace.left_dock().read(cx).is_open(),
11487                "Left dock should be closed"
11488            );
11489            assert!(
11490                !workspace.right_dock().read(cx).is_open(),
11491                "Right dock should be closed"
11492            );
11493            assert!(
11494                !workspace.bottom_dock().read(cx).is_open(),
11495                "Bottom dock should be closed"
11496            );
11497        });
11498
11499        // Toggle all docks back on and verify positions are restored
11500        workspace.update_in(cx, |workspace, window, cx| {
11501            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11502            assert!(
11503                !workspace.left_dock().read(cx).is_open(),
11504                "Left dock should remain closed"
11505            );
11506            assert!(
11507                workspace.right_dock().read(cx).is_open(),
11508                "Right dock should remain open"
11509            );
11510            assert!(
11511                workspace.bottom_dock().read(cx).is_open(),
11512                "Bottom dock should remain open"
11513            );
11514            assert_eq!(
11515                left_panel.read(cx).position,
11516                DockPosition::Bottom,
11517                "Left panel should remain in the bottom dock"
11518            );
11519            assert_eq!(
11520                right_panel.read(cx).position,
11521                DockPosition::Right,
11522                "Right panel should remain in the right dock"
11523            );
11524            assert_eq!(
11525                workspace
11526                    .bottom_dock()
11527                    .read(cx)
11528                    .visible_panel()
11529                    .unwrap()
11530                    .panel_id(),
11531                left_panel.panel_id(),
11532                "Left panel should be the visible panel in the right dock"
11533            );
11534        });
11535    }
11536
11537    #[gpui::test]
11538    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11539        init_test(cx);
11540
11541        let fs = FakeFs::new(cx.executor());
11542
11543        let project = Project::test(fs, None, cx).await;
11544        let (workspace, cx) =
11545            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11546
11547        // Let's arrange the panes like this:
11548        //
11549        // +-----------------------+
11550        // |         top           |
11551        // +------+--------+-------+
11552        // | left | center | right |
11553        // +------+--------+-------+
11554        // |        bottom         |
11555        // +-----------------------+
11556
11557        let top_item = cx.new(|cx| {
11558            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11559        });
11560        let bottom_item = cx.new(|cx| {
11561            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11562        });
11563        let left_item = cx.new(|cx| {
11564            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11565        });
11566        let right_item = cx.new(|cx| {
11567            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11568        });
11569        let center_item = cx.new(|cx| {
11570            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11571        });
11572
11573        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11574            let top_pane_id = workspace.active_pane().entity_id();
11575            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11576            workspace.split_pane(
11577                workspace.active_pane().clone(),
11578                SplitDirection::Down,
11579                window,
11580                cx,
11581            );
11582            top_pane_id
11583        });
11584        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11585            let bottom_pane_id = workspace.active_pane().entity_id();
11586            workspace.add_item_to_active_pane(
11587                Box::new(bottom_item.clone()),
11588                None,
11589                false,
11590                window,
11591                cx,
11592            );
11593            workspace.split_pane(
11594                workspace.active_pane().clone(),
11595                SplitDirection::Up,
11596                window,
11597                cx,
11598            );
11599            bottom_pane_id
11600        });
11601        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11602            let left_pane_id = workspace.active_pane().entity_id();
11603            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11604            workspace.split_pane(
11605                workspace.active_pane().clone(),
11606                SplitDirection::Right,
11607                window,
11608                cx,
11609            );
11610            left_pane_id
11611        });
11612        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11613            let right_pane_id = workspace.active_pane().entity_id();
11614            workspace.add_item_to_active_pane(
11615                Box::new(right_item.clone()),
11616                None,
11617                false,
11618                window,
11619                cx,
11620            );
11621            workspace.split_pane(
11622                workspace.active_pane().clone(),
11623                SplitDirection::Left,
11624                window,
11625                cx,
11626            );
11627            right_pane_id
11628        });
11629        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11630            let center_pane_id = workspace.active_pane().entity_id();
11631            workspace.add_item_to_active_pane(
11632                Box::new(center_item.clone()),
11633                None,
11634                false,
11635                window,
11636                cx,
11637            );
11638            center_pane_id
11639        });
11640        cx.executor().run_until_parked();
11641
11642        workspace.update_in(cx, |workspace, window, cx| {
11643            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11644
11645            // Join into next from center pane into right
11646            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11647        });
11648
11649        workspace.update_in(cx, |workspace, window, cx| {
11650            let active_pane = workspace.active_pane();
11651            assert_eq!(right_pane_id, active_pane.entity_id());
11652            assert_eq!(2, active_pane.read(cx).items_len());
11653            let item_ids_in_pane =
11654                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11655            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11656            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11657
11658            // Join into next from right pane into bottom
11659            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11660        });
11661
11662        workspace.update_in(cx, |workspace, window, cx| {
11663            let active_pane = workspace.active_pane();
11664            assert_eq!(bottom_pane_id, active_pane.entity_id());
11665            assert_eq!(3, active_pane.read(cx).items_len());
11666            let item_ids_in_pane =
11667                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11668            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11669            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11670            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11671
11672            // Join into next from bottom pane into left
11673            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11674        });
11675
11676        workspace.update_in(cx, |workspace, window, cx| {
11677            let active_pane = workspace.active_pane();
11678            assert_eq!(left_pane_id, active_pane.entity_id());
11679            assert_eq!(4, active_pane.read(cx).items_len());
11680            let item_ids_in_pane =
11681                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11682            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11683            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11684            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11685            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11686
11687            // Join into next from left pane into top
11688            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11689        });
11690
11691        workspace.update_in(cx, |workspace, window, cx| {
11692            let active_pane = workspace.active_pane();
11693            assert_eq!(top_pane_id, active_pane.entity_id());
11694            assert_eq!(5, active_pane.read(cx).items_len());
11695            let item_ids_in_pane =
11696                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11697            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11698            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11699            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11700            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11701            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11702
11703            // Single pane left: no-op
11704            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11705        });
11706
11707        workspace.update(cx, |workspace, _cx| {
11708            let active_pane = workspace.active_pane();
11709            assert_eq!(top_pane_id, active_pane.entity_id());
11710        });
11711    }
11712
11713    fn add_an_item_to_active_pane(
11714        cx: &mut VisualTestContext,
11715        workspace: &Entity<Workspace>,
11716        item_id: u64,
11717    ) -> Entity<TestItem> {
11718        let item = cx.new(|cx| {
11719            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11720                item_id,
11721                "item{item_id}.txt",
11722                cx,
11723            )])
11724        });
11725        workspace.update_in(cx, |workspace, window, cx| {
11726            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11727        });
11728        item
11729    }
11730
11731    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11732        workspace.update_in(cx, |workspace, window, cx| {
11733            workspace.split_pane(
11734                workspace.active_pane().clone(),
11735                SplitDirection::Right,
11736                window,
11737                cx,
11738            )
11739        })
11740    }
11741
11742    #[gpui::test]
11743    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11744        init_test(cx);
11745        let fs = FakeFs::new(cx.executor());
11746        let project = Project::test(fs, None, cx).await;
11747        let (workspace, cx) =
11748            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11749
11750        add_an_item_to_active_pane(cx, &workspace, 1);
11751        split_pane(cx, &workspace);
11752        add_an_item_to_active_pane(cx, &workspace, 2);
11753        split_pane(cx, &workspace); // empty pane
11754        split_pane(cx, &workspace);
11755        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11756
11757        cx.executor().run_until_parked();
11758
11759        workspace.update(cx, |workspace, cx| {
11760            let num_panes = workspace.panes().len();
11761            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11762            let active_item = workspace
11763                .active_pane()
11764                .read(cx)
11765                .active_item()
11766                .expect("item is in focus");
11767
11768            assert_eq!(num_panes, 4);
11769            assert_eq!(num_items_in_current_pane, 1);
11770            assert_eq!(active_item.item_id(), last_item.item_id());
11771        });
11772
11773        workspace.update_in(cx, |workspace, window, cx| {
11774            workspace.join_all_panes(window, cx);
11775        });
11776
11777        workspace.update(cx, |workspace, cx| {
11778            let num_panes = workspace.panes().len();
11779            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11780            let active_item = workspace
11781                .active_pane()
11782                .read(cx)
11783                .active_item()
11784                .expect("item is in focus");
11785
11786            assert_eq!(num_panes, 1);
11787            assert_eq!(num_items_in_current_pane, 3);
11788            assert_eq!(active_item.item_id(), last_item.item_id());
11789        });
11790    }
11791    struct TestModal(FocusHandle);
11792
11793    impl TestModal {
11794        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11795            Self(cx.focus_handle())
11796        }
11797    }
11798
11799    impl EventEmitter<DismissEvent> for TestModal {}
11800
11801    impl Focusable for TestModal {
11802        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11803            self.0.clone()
11804        }
11805    }
11806
11807    impl ModalView for TestModal {}
11808
11809    impl Render for TestModal {
11810        fn render(
11811            &mut self,
11812            _window: &mut Window,
11813            _cx: &mut Context<TestModal>,
11814        ) -> impl IntoElement {
11815            div().track_focus(&self.0)
11816        }
11817    }
11818
11819    #[gpui::test]
11820    async fn test_panels(cx: &mut gpui::TestAppContext) {
11821        init_test(cx);
11822        let fs = FakeFs::new(cx.executor());
11823
11824        let project = Project::test(fs, [], cx).await;
11825        let (multi_workspace, cx) =
11826            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11827        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11828
11829        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11830            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11831            workspace.add_panel(panel_1.clone(), window, cx);
11832            workspace.toggle_dock(DockPosition::Left, window, cx);
11833            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11834            workspace.add_panel(panel_2.clone(), window, cx);
11835            workspace.toggle_dock(DockPosition::Right, window, cx);
11836
11837            let left_dock = workspace.left_dock();
11838            assert_eq!(
11839                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11840                panel_1.panel_id()
11841            );
11842            assert_eq!(
11843                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11844                panel_1.size(window, cx)
11845            );
11846
11847            left_dock.update(cx, |left_dock, cx| {
11848                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11849            });
11850            assert_eq!(
11851                workspace
11852                    .right_dock()
11853                    .read(cx)
11854                    .visible_panel()
11855                    .unwrap()
11856                    .panel_id(),
11857                panel_2.panel_id(),
11858            );
11859
11860            (panel_1, panel_2)
11861        });
11862
11863        // Move panel_1 to the right
11864        panel_1.update_in(cx, |panel_1, window, cx| {
11865            panel_1.set_position(DockPosition::Right, window, cx)
11866        });
11867
11868        workspace.update_in(cx, |workspace, window, cx| {
11869            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11870            // Since it was the only panel on the left, the left dock should now be closed.
11871            assert!(!workspace.left_dock().read(cx).is_open());
11872            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11873            let right_dock = workspace.right_dock();
11874            assert_eq!(
11875                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11876                panel_1.panel_id()
11877            );
11878            assert_eq!(
11879                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11880                px(1337.)
11881            );
11882
11883            // Now we move panel_2 to the left
11884            panel_2.set_position(DockPosition::Left, window, cx);
11885        });
11886
11887        workspace.update(cx, |workspace, cx| {
11888            // Since panel_2 was not visible on the right, we don't open the left dock.
11889            assert!(!workspace.left_dock().read(cx).is_open());
11890            // And the right dock is unaffected in its displaying of panel_1
11891            assert!(workspace.right_dock().read(cx).is_open());
11892            assert_eq!(
11893                workspace
11894                    .right_dock()
11895                    .read(cx)
11896                    .visible_panel()
11897                    .unwrap()
11898                    .panel_id(),
11899                panel_1.panel_id(),
11900            );
11901        });
11902
11903        // Move panel_1 back to the left
11904        panel_1.update_in(cx, |panel_1, window, cx| {
11905            panel_1.set_position(DockPosition::Left, window, cx)
11906        });
11907
11908        workspace.update_in(cx, |workspace, window, cx| {
11909            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11910            let left_dock = workspace.left_dock();
11911            assert!(left_dock.read(cx).is_open());
11912            assert_eq!(
11913                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11914                panel_1.panel_id()
11915            );
11916            assert_eq!(
11917                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11918                px(1337.)
11919            );
11920            // And the right dock should be closed as it no longer has any panels.
11921            assert!(!workspace.right_dock().read(cx).is_open());
11922
11923            // Now we move panel_1 to the bottom
11924            panel_1.set_position(DockPosition::Bottom, window, cx);
11925        });
11926
11927        workspace.update_in(cx, |workspace, window, cx| {
11928            // Since panel_1 was visible on the left, we close the left dock.
11929            assert!(!workspace.left_dock().read(cx).is_open());
11930            // The bottom dock is sized based on the panel's default size,
11931            // since the panel orientation changed from vertical to horizontal.
11932            let bottom_dock = workspace.bottom_dock();
11933            assert_eq!(
11934                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11935                panel_1.size(window, cx),
11936            );
11937            // Close bottom dock and move panel_1 back to the left.
11938            bottom_dock.update(cx, |bottom_dock, cx| {
11939                bottom_dock.set_open(false, window, cx)
11940            });
11941            panel_1.set_position(DockPosition::Left, window, cx);
11942        });
11943
11944        // Emit activated event on panel 1
11945        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11946
11947        // Now the left dock is open and panel_1 is active and focused.
11948        workspace.update_in(cx, |workspace, window, cx| {
11949            let left_dock = workspace.left_dock();
11950            assert!(left_dock.read(cx).is_open());
11951            assert_eq!(
11952                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11953                panel_1.panel_id(),
11954            );
11955            assert!(panel_1.focus_handle(cx).is_focused(window));
11956        });
11957
11958        // Emit closed event on panel 2, which is not active
11959        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11960
11961        // Wo don't close the left dock, because panel_2 wasn't the active panel
11962        workspace.update(cx, |workspace, cx| {
11963            let left_dock = workspace.left_dock();
11964            assert!(left_dock.read(cx).is_open());
11965            assert_eq!(
11966                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11967                panel_1.panel_id(),
11968            );
11969        });
11970
11971        // Emitting a ZoomIn event shows the panel as zoomed.
11972        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11973        workspace.read_with(cx, |workspace, _| {
11974            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11975            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11976        });
11977
11978        // Move panel to another dock while it is zoomed
11979        panel_1.update_in(cx, |panel, window, cx| {
11980            panel.set_position(DockPosition::Right, window, cx)
11981        });
11982        workspace.read_with(cx, |workspace, _| {
11983            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11984
11985            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11986        });
11987
11988        // This is a helper for getting a:
11989        // - valid focus on an element,
11990        // - that isn't a part of the panes and panels system of the Workspace,
11991        // - and doesn't trigger the 'on_focus_lost' API.
11992        let focus_other_view = {
11993            let workspace = workspace.clone();
11994            move |cx: &mut VisualTestContext| {
11995                workspace.update_in(cx, |workspace, window, cx| {
11996                    if workspace.active_modal::<TestModal>(cx).is_some() {
11997                        workspace.toggle_modal(window, cx, TestModal::new);
11998                        workspace.toggle_modal(window, cx, TestModal::new);
11999                    } else {
12000                        workspace.toggle_modal(window, cx, TestModal::new);
12001                    }
12002                })
12003            }
12004        };
12005
12006        // If focus is transferred to another view that's not a panel or another pane, we still show
12007        // the panel as zoomed.
12008        focus_other_view(cx);
12009        workspace.read_with(cx, |workspace, _| {
12010            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12011            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12012        });
12013
12014        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12015        workspace.update_in(cx, |_workspace, window, cx| {
12016            cx.focus_self(window);
12017        });
12018        workspace.read_with(cx, |workspace, _| {
12019            assert_eq!(workspace.zoomed, None);
12020            assert_eq!(workspace.zoomed_position, None);
12021        });
12022
12023        // If focus is transferred again to another view that's not a panel or a pane, we won't
12024        // show the panel as zoomed because it wasn't zoomed before.
12025        focus_other_view(cx);
12026        workspace.read_with(cx, |workspace, _| {
12027            assert_eq!(workspace.zoomed, None);
12028            assert_eq!(workspace.zoomed_position, None);
12029        });
12030
12031        // When the panel is activated, it is zoomed again.
12032        cx.dispatch_action(ToggleRightDock);
12033        workspace.read_with(cx, |workspace, _| {
12034            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12035            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12036        });
12037
12038        // Emitting a ZoomOut event unzooms the panel.
12039        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12040        workspace.read_with(cx, |workspace, _| {
12041            assert_eq!(workspace.zoomed, None);
12042            assert_eq!(workspace.zoomed_position, None);
12043        });
12044
12045        // Emit closed event on panel 1, which is active
12046        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12047
12048        // Now the left dock is closed, because panel_1 was the active panel
12049        workspace.update(cx, |workspace, cx| {
12050            let right_dock = workspace.right_dock();
12051            assert!(!right_dock.read(cx).is_open());
12052        });
12053    }
12054
12055    #[gpui::test]
12056    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12057        init_test(cx);
12058
12059        let fs = FakeFs::new(cx.background_executor.clone());
12060        let project = Project::test(fs, [], cx).await;
12061        let (workspace, cx) =
12062            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12063        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12064
12065        let dirty_regular_buffer = cx.new(|cx| {
12066            TestItem::new(cx)
12067                .with_dirty(true)
12068                .with_label("1.txt")
12069                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12070        });
12071        let dirty_regular_buffer_2 = cx.new(|cx| {
12072            TestItem::new(cx)
12073                .with_dirty(true)
12074                .with_label("2.txt")
12075                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12076        });
12077        let dirty_multi_buffer_with_both = cx.new(|cx| {
12078            TestItem::new(cx)
12079                .with_dirty(true)
12080                .with_buffer_kind(ItemBufferKind::Multibuffer)
12081                .with_label("Fake Project Search")
12082                .with_project_items(&[
12083                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12084                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12085                ])
12086        });
12087        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12088        workspace.update_in(cx, |workspace, window, cx| {
12089            workspace.add_item(
12090                pane.clone(),
12091                Box::new(dirty_regular_buffer.clone()),
12092                None,
12093                false,
12094                false,
12095                window,
12096                cx,
12097            );
12098            workspace.add_item(
12099                pane.clone(),
12100                Box::new(dirty_regular_buffer_2.clone()),
12101                None,
12102                false,
12103                false,
12104                window,
12105                cx,
12106            );
12107            workspace.add_item(
12108                pane.clone(),
12109                Box::new(dirty_multi_buffer_with_both.clone()),
12110                None,
12111                false,
12112                false,
12113                window,
12114                cx,
12115            );
12116        });
12117
12118        pane.update_in(cx, |pane, window, cx| {
12119            pane.activate_item(2, true, true, window, cx);
12120            assert_eq!(
12121                pane.active_item().unwrap().item_id(),
12122                multi_buffer_with_both_files_id,
12123                "Should select the multi buffer in the pane"
12124            );
12125        });
12126        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12127            pane.close_other_items(
12128                &CloseOtherItems {
12129                    save_intent: Some(SaveIntent::Save),
12130                    close_pinned: true,
12131                },
12132                None,
12133                window,
12134                cx,
12135            )
12136        });
12137        cx.background_executor.run_until_parked();
12138        assert!(!cx.has_pending_prompt());
12139        close_all_but_multi_buffer_task
12140            .await
12141            .expect("Closing all buffers but the multi buffer failed");
12142        pane.update(cx, |pane, cx| {
12143            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12144            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12145            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12146            assert_eq!(pane.items_len(), 1);
12147            assert_eq!(
12148                pane.active_item().unwrap().item_id(),
12149                multi_buffer_with_both_files_id,
12150                "Should have only the multi buffer left in the pane"
12151            );
12152            assert!(
12153                dirty_multi_buffer_with_both.read(cx).is_dirty,
12154                "The multi buffer containing the unsaved buffer should still be dirty"
12155            );
12156        });
12157
12158        dirty_regular_buffer.update(cx, |buffer, cx| {
12159            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12160        });
12161
12162        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12163            pane.close_active_item(
12164                &CloseActiveItem {
12165                    save_intent: Some(SaveIntent::Close),
12166                    close_pinned: false,
12167                },
12168                window,
12169                cx,
12170            )
12171        });
12172        cx.background_executor.run_until_parked();
12173        assert!(
12174            cx.has_pending_prompt(),
12175            "Dirty multi buffer should prompt a save dialog"
12176        );
12177        cx.simulate_prompt_answer("Save");
12178        cx.background_executor.run_until_parked();
12179        close_multi_buffer_task
12180            .await
12181            .expect("Closing the multi buffer failed");
12182        pane.update(cx, |pane, cx| {
12183            assert_eq!(
12184                dirty_multi_buffer_with_both.read(cx).save_count,
12185                1,
12186                "Multi buffer item should get be saved"
12187            );
12188            // Test impl does not save inner items, so we do not assert them
12189            assert_eq!(
12190                pane.items_len(),
12191                0,
12192                "No more items should be left in the pane"
12193            );
12194            assert!(pane.active_item().is_none());
12195        });
12196    }
12197
12198    #[gpui::test]
12199    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12200        cx: &mut TestAppContext,
12201    ) {
12202        init_test(cx);
12203
12204        let fs = FakeFs::new(cx.background_executor.clone());
12205        let project = Project::test(fs, [], cx).await;
12206        let (workspace, cx) =
12207            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12208        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12209
12210        let dirty_regular_buffer = cx.new(|cx| {
12211            TestItem::new(cx)
12212                .with_dirty(true)
12213                .with_label("1.txt")
12214                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12215        });
12216        let dirty_regular_buffer_2 = cx.new(|cx| {
12217            TestItem::new(cx)
12218                .with_dirty(true)
12219                .with_label("2.txt")
12220                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12221        });
12222        let clear_regular_buffer = cx.new(|cx| {
12223            TestItem::new(cx)
12224                .with_label("3.txt")
12225                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12226        });
12227
12228        let dirty_multi_buffer_with_both = cx.new(|cx| {
12229            TestItem::new(cx)
12230                .with_dirty(true)
12231                .with_buffer_kind(ItemBufferKind::Multibuffer)
12232                .with_label("Fake Project Search")
12233                .with_project_items(&[
12234                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12235                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12236                    clear_regular_buffer.read(cx).project_items[0].clone(),
12237                ])
12238        });
12239        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12240        workspace.update_in(cx, |workspace, window, cx| {
12241            workspace.add_item(
12242                pane.clone(),
12243                Box::new(dirty_regular_buffer.clone()),
12244                None,
12245                false,
12246                false,
12247                window,
12248                cx,
12249            );
12250            workspace.add_item(
12251                pane.clone(),
12252                Box::new(dirty_multi_buffer_with_both.clone()),
12253                None,
12254                false,
12255                false,
12256                window,
12257                cx,
12258            );
12259        });
12260
12261        pane.update_in(cx, |pane, window, cx| {
12262            pane.activate_item(1, true, true, window, cx);
12263            assert_eq!(
12264                pane.active_item().unwrap().item_id(),
12265                multi_buffer_with_both_files_id,
12266                "Should select the multi buffer in the pane"
12267            );
12268        });
12269        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12270            pane.close_active_item(
12271                &CloseActiveItem {
12272                    save_intent: None,
12273                    close_pinned: false,
12274                },
12275                window,
12276                cx,
12277            )
12278        });
12279        cx.background_executor.run_until_parked();
12280        assert!(
12281            cx.has_pending_prompt(),
12282            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12283        );
12284    }
12285
12286    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12287    /// closed when they are deleted from disk.
12288    #[gpui::test]
12289    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12290        init_test(cx);
12291
12292        // Enable the close_on_disk_deletion setting
12293        cx.update_global(|store: &mut SettingsStore, cx| {
12294            store.update_user_settings(cx, |settings| {
12295                settings.workspace.close_on_file_delete = Some(true);
12296            });
12297        });
12298
12299        let fs = FakeFs::new(cx.background_executor.clone());
12300        let project = Project::test(fs, [], cx).await;
12301        let (workspace, cx) =
12302            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12303        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12304
12305        // Create a test item that simulates a file
12306        let item = cx.new(|cx| {
12307            TestItem::new(cx)
12308                .with_label("test.txt")
12309                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12310        });
12311
12312        // Add item to workspace
12313        workspace.update_in(cx, |workspace, window, cx| {
12314            workspace.add_item(
12315                pane.clone(),
12316                Box::new(item.clone()),
12317                None,
12318                false,
12319                false,
12320                window,
12321                cx,
12322            );
12323        });
12324
12325        // Verify the item is in the pane
12326        pane.read_with(cx, |pane, _| {
12327            assert_eq!(pane.items().count(), 1);
12328        });
12329
12330        // Simulate file deletion by setting the item's deleted state
12331        item.update(cx, |item, _| {
12332            item.set_has_deleted_file(true);
12333        });
12334
12335        // Emit UpdateTab event to trigger the close behavior
12336        cx.run_until_parked();
12337        item.update(cx, |_, cx| {
12338            cx.emit(ItemEvent::UpdateTab);
12339        });
12340
12341        // Allow the close operation to complete
12342        cx.run_until_parked();
12343
12344        // Verify the item was automatically closed
12345        pane.read_with(cx, |pane, _| {
12346            assert_eq!(
12347                pane.items().count(),
12348                0,
12349                "Item should be automatically closed when file is deleted"
12350            );
12351        });
12352    }
12353
12354    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12355    /// open with a strikethrough when they are deleted from disk.
12356    #[gpui::test]
12357    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12358        init_test(cx);
12359
12360        // Ensure close_on_disk_deletion is disabled (default)
12361        cx.update_global(|store: &mut SettingsStore, cx| {
12362            store.update_user_settings(cx, |settings| {
12363                settings.workspace.close_on_file_delete = Some(false);
12364            });
12365        });
12366
12367        let fs = FakeFs::new(cx.background_executor.clone());
12368        let project = Project::test(fs, [], cx).await;
12369        let (workspace, cx) =
12370            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12371        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12372
12373        // Create a test item that simulates a file
12374        let item = cx.new(|cx| {
12375            TestItem::new(cx)
12376                .with_label("test.txt")
12377                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12378        });
12379
12380        // Add item to workspace
12381        workspace.update_in(cx, |workspace, window, cx| {
12382            workspace.add_item(
12383                pane.clone(),
12384                Box::new(item.clone()),
12385                None,
12386                false,
12387                false,
12388                window,
12389                cx,
12390            );
12391        });
12392
12393        // Verify the item is in the pane
12394        pane.read_with(cx, |pane, _| {
12395            assert_eq!(pane.items().count(), 1);
12396        });
12397
12398        // Simulate file deletion
12399        item.update(cx, |item, _| {
12400            item.set_has_deleted_file(true);
12401        });
12402
12403        // Emit UpdateTab event
12404        cx.run_until_parked();
12405        item.update(cx, |_, cx| {
12406            cx.emit(ItemEvent::UpdateTab);
12407        });
12408
12409        // Allow any potential close operation to complete
12410        cx.run_until_parked();
12411
12412        // Verify the item remains open (with strikethrough)
12413        pane.read_with(cx, |pane, _| {
12414            assert_eq!(
12415                pane.items().count(),
12416                1,
12417                "Item should remain open when close_on_disk_deletion is disabled"
12418            );
12419        });
12420
12421        // Verify the item shows as deleted
12422        item.read_with(cx, |item, _| {
12423            assert!(
12424                item.has_deleted_file,
12425                "Item should be marked as having deleted file"
12426            );
12427        });
12428    }
12429
12430    /// Tests that dirty files are not automatically closed when deleted from disk,
12431    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12432    /// unsaved changes without being prompted.
12433    #[gpui::test]
12434    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12435        init_test(cx);
12436
12437        // Enable the close_on_file_delete setting
12438        cx.update_global(|store: &mut SettingsStore, cx| {
12439            store.update_user_settings(cx, |settings| {
12440                settings.workspace.close_on_file_delete = Some(true);
12441            });
12442        });
12443
12444        let fs = FakeFs::new(cx.background_executor.clone());
12445        let project = Project::test(fs, [], cx).await;
12446        let (workspace, cx) =
12447            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12448        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12449
12450        // Create a dirty test item
12451        let item = cx.new(|cx| {
12452            TestItem::new(cx)
12453                .with_dirty(true)
12454                .with_label("test.txt")
12455                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12456        });
12457
12458        // Add item to workspace
12459        workspace.update_in(cx, |workspace, window, cx| {
12460            workspace.add_item(
12461                pane.clone(),
12462                Box::new(item.clone()),
12463                None,
12464                false,
12465                false,
12466                window,
12467                cx,
12468            );
12469        });
12470
12471        // Simulate file deletion
12472        item.update(cx, |item, _| {
12473            item.set_has_deleted_file(true);
12474        });
12475
12476        // Emit UpdateTab event to trigger the close behavior
12477        cx.run_until_parked();
12478        item.update(cx, |_, cx| {
12479            cx.emit(ItemEvent::UpdateTab);
12480        });
12481
12482        // Allow any potential close operation to complete
12483        cx.run_until_parked();
12484
12485        // Verify the item remains open (dirty files are not auto-closed)
12486        pane.read_with(cx, |pane, _| {
12487            assert_eq!(
12488                pane.items().count(),
12489                1,
12490                "Dirty items should not be automatically closed even when file is deleted"
12491            );
12492        });
12493
12494        // Verify the item is marked as deleted and still dirty
12495        item.read_with(cx, |item, _| {
12496            assert!(
12497                item.has_deleted_file,
12498                "Item should be marked as having deleted file"
12499            );
12500            assert!(item.is_dirty, "Item should still be dirty");
12501        });
12502    }
12503
12504    /// Tests that navigation history is cleaned up when files are auto-closed
12505    /// due to deletion from disk.
12506    #[gpui::test]
12507    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12508        init_test(cx);
12509
12510        // Enable the close_on_file_delete setting
12511        cx.update_global(|store: &mut SettingsStore, cx| {
12512            store.update_user_settings(cx, |settings| {
12513                settings.workspace.close_on_file_delete = Some(true);
12514            });
12515        });
12516
12517        let fs = FakeFs::new(cx.background_executor.clone());
12518        let project = Project::test(fs, [], cx).await;
12519        let (workspace, cx) =
12520            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12521        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12522
12523        // Create test items
12524        let item1 = cx.new(|cx| {
12525            TestItem::new(cx)
12526                .with_label("test1.txt")
12527                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12528        });
12529        let item1_id = item1.item_id();
12530
12531        let item2 = cx.new(|cx| {
12532            TestItem::new(cx)
12533                .with_label("test2.txt")
12534                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12535        });
12536
12537        // Add items to workspace
12538        workspace.update_in(cx, |workspace, window, cx| {
12539            workspace.add_item(
12540                pane.clone(),
12541                Box::new(item1.clone()),
12542                None,
12543                false,
12544                false,
12545                window,
12546                cx,
12547            );
12548            workspace.add_item(
12549                pane.clone(),
12550                Box::new(item2.clone()),
12551                None,
12552                false,
12553                false,
12554                window,
12555                cx,
12556            );
12557        });
12558
12559        // Activate item1 to ensure it gets navigation entries
12560        pane.update_in(cx, |pane, window, cx| {
12561            pane.activate_item(0, true, true, window, cx);
12562        });
12563
12564        // Switch to item2 and back to create navigation history
12565        pane.update_in(cx, |pane, window, cx| {
12566            pane.activate_item(1, true, true, window, cx);
12567        });
12568        cx.run_until_parked();
12569
12570        pane.update_in(cx, |pane, window, cx| {
12571            pane.activate_item(0, true, true, window, cx);
12572        });
12573        cx.run_until_parked();
12574
12575        // Simulate file deletion for item1
12576        item1.update(cx, |item, _| {
12577            item.set_has_deleted_file(true);
12578        });
12579
12580        // Emit UpdateTab event to trigger the close behavior
12581        item1.update(cx, |_, cx| {
12582            cx.emit(ItemEvent::UpdateTab);
12583        });
12584        cx.run_until_parked();
12585
12586        // Verify item1 was closed
12587        pane.read_with(cx, |pane, _| {
12588            assert_eq!(
12589                pane.items().count(),
12590                1,
12591                "Should have 1 item remaining after auto-close"
12592            );
12593        });
12594
12595        // Check navigation history after close
12596        let has_item = pane.read_with(cx, |pane, cx| {
12597            let mut has_item = false;
12598            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12599                if entry.item.id() == item1_id {
12600                    has_item = true;
12601                }
12602            });
12603            has_item
12604        });
12605
12606        assert!(
12607            !has_item,
12608            "Navigation history should not contain closed item entries"
12609        );
12610    }
12611
12612    #[gpui::test]
12613    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12614        cx: &mut TestAppContext,
12615    ) {
12616        init_test(cx);
12617
12618        let fs = FakeFs::new(cx.background_executor.clone());
12619        let project = Project::test(fs, [], cx).await;
12620        let (workspace, cx) =
12621            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12622        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12623
12624        let dirty_regular_buffer = cx.new(|cx| {
12625            TestItem::new(cx)
12626                .with_dirty(true)
12627                .with_label("1.txt")
12628                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12629        });
12630        let dirty_regular_buffer_2 = cx.new(|cx| {
12631            TestItem::new(cx)
12632                .with_dirty(true)
12633                .with_label("2.txt")
12634                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12635        });
12636        let clear_regular_buffer = cx.new(|cx| {
12637            TestItem::new(cx)
12638                .with_label("3.txt")
12639                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12640        });
12641
12642        let dirty_multi_buffer = cx.new(|cx| {
12643            TestItem::new(cx)
12644                .with_dirty(true)
12645                .with_buffer_kind(ItemBufferKind::Multibuffer)
12646                .with_label("Fake Project Search")
12647                .with_project_items(&[
12648                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12649                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12650                    clear_regular_buffer.read(cx).project_items[0].clone(),
12651                ])
12652        });
12653        workspace.update_in(cx, |workspace, window, cx| {
12654            workspace.add_item(
12655                pane.clone(),
12656                Box::new(dirty_regular_buffer.clone()),
12657                None,
12658                false,
12659                false,
12660                window,
12661                cx,
12662            );
12663            workspace.add_item(
12664                pane.clone(),
12665                Box::new(dirty_regular_buffer_2.clone()),
12666                None,
12667                false,
12668                false,
12669                window,
12670                cx,
12671            );
12672            workspace.add_item(
12673                pane.clone(),
12674                Box::new(dirty_multi_buffer.clone()),
12675                None,
12676                false,
12677                false,
12678                window,
12679                cx,
12680            );
12681        });
12682
12683        pane.update_in(cx, |pane, window, cx| {
12684            pane.activate_item(2, true, true, window, cx);
12685            assert_eq!(
12686                pane.active_item().unwrap().item_id(),
12687                dirty_multi_buffer.item_id(),
12688                "Should select the multi buffer in the pane"
12689            );
12690        });
12691        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12692            pane.close_active_item(
12693                &CloseActiveItem {
12694                    save_intent: None,
12695                    close_pinned: false,
12696                },
12697                window,
12698                cx,
12699            )
12700        });
12701        cx.background_executor.run_until_parked();
12702        assert!(
12703            !cx.has_pending_prompt(),
12704            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12705        );
12706        close_multi_buffer_task
12707            .await
12708            .expect("Closing multi buffer failed");
12709        pane.update(cx, |pane, cx| {
12710            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12711            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12712            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12713            assert_eq!(
12714                pane.items()
12715                    .map(|item| item.item_id())
12716                    .sorted()
12717                    .collect::<Vec<_>>(),
12718                vec![
12719                    dirty_regular_buffer.item_id(),
12720                    dirty_regular_buffer_2.item_id(),
12721                ],
12722                "Should have no multi buffer left in the pane"
12723            );
12724            assert!(dirty_regular_buffer.read(cx).is_dirty);
12725            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12726        });
12727    }
12728
12729    #[gpui::test]
12730    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12731        init_test(cx);
12732        let fs = FakeFs::new(cx.executor());
12733        let project = Project::test(fs, [], cx).await;
12734        let (multi_workspace, cx) =
12735            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12736        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12737
12738        // Add a new panel to the right dock, opening the dock and setting the
12739        // focus to the new panel.
12740        let panel = workspace.update_in(cx, |workspace, window, cx| {
12741            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12742            workspace.add_panel(panel.clone(), window, cx);
12743
12744            workspace
12745                .right_dock()
12746                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12747
12748            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12749
12750            panel
12751        });
12752
12753        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12754        // panel to the next valid position which, in this case, is the left
12755        // dock.
12756        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12757        workspace.update(cx, |workspace, cx| {
12758            assert!(workspace.left_dock().read(cx).is_open());
12759            assert_eq!(panel.read(cx).position, DockPosition::Left);
12760        });
12761
12762        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12763        // panel to the next valid position which, in this case, is the bottom
12764        // dock.
12765        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12766        workspace.update(cx, |workspace, cx| {
12767            assert!(workspace.bottom_dock().read(cx).is_open());
12768            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12769        });
12770
12771        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12772        // around moving the panel to its initial position, the right dock.
12773        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12774        workspace.update(cx, |workspace, cx| {
12775            assert!(workspace.right_dock().read(cx).is_open());
12776            assert_eq!(panel.read(cx).position, DockPosition::Right);
12777        });
12778
12779        // Remove focus from the panel, ensuring that, if the panel is not
12780        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12781        // the panel's position, so the panel is still in the right dock.
12782        workspace.update_in(cx, |workspace, window, cx| {
12783            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12784        });
12785
12786        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12787        workspace.update(cx, |workspace, cx| {
12788            assert!(workspace.right_dock().read(cx).is_open());
12789            assert_eq!(panel.read(cx).position, DockPosition::Right);
12790        });
12791    }
12792
12793    #[gpui::test]
12794    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12795        init_test(cx);
12796
12797        let fs = FakeFs::new(cx.executor());
12798        let project = Project::test(fs, [], cx).await;
12799        let (workspace, cx) =
12800            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12801
12802        let item_1 = cx.new(|cx| {
12803            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12804        });
12805        workspace.update_in(cx, |workspace, window, cx| {
12806            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12807            workspace.move_item_to_pane_in_direction(
12808                &MoveItemToPaneInDirection {
12809                    direction: SplitDirection::Right,
12810                    focus: true,
12811                    clone: false,
12812                },
12813                window,
12814                cx,
12815            );
12816            workspace.move_item_to_pane_at_index(
12817                &MoveItemToPane {
12818                    destination: 3,
12819                    focus: true,
12820                    clone: false,
12821                },
12822                window,
12823                cx,
12824            );
12825
12826            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12827            assert_eq!(
12828                pane_items_paths(&workspace.active_pane, cx),
12829                vec!["first.txt".to_string()],
12830                "Single item was not moved anywhere"
12831            );
12832        });
12833
12834        let item_2 = cx.new(|cx| {
12835            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12836        });
12837        workspace.update_in(cx, |workspace, window, cx| {
12838            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12839            assert_eq!(
12840                pane_items_paths(&workspace.panes[0], cx),
12841                vec!["first.txt".to_string(), "second.txt".to_string()],
12842            );
12843            workspace.move_item_to_pane_in_direction(
12844                &MoveItemToPaneInDirection {
12845                    direction: SplitDirection::Right,
12846                    focus: true,
12847                    clone: false,
12848                },
12849                window,
12850                cx,
12851            );
12852
12853            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12854            assert_eq!(
12855                pane_items_paths(&workspace.panes[0], cx),
12856                vec!["first.txt".to_string()],
12857                "After moving, one item should be left in the original pane"
12858            );
12859            assert_eq!(
12860                pane_items_paths(&workspace.panes[1], cx),
12861                vec!["second.txt".to_string()],
12862                "New item should have been moved to the new pane"
12863            );
12864        });
12865
12866        let item_3 = cx.new(|cx| {
12867            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12868        });
12869        workspace.update_in(cx, |workspace, window, cx| {
12870            let original_pane = workspace.panes[0].clone();
12871            workspace.set_active_pane(&original_pane, window, cx);
12872            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12873            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12874            assert_eq!(
12875                pane_items_paths(&workspace.active_pane, cx),
12876                vec!["first.txt".to_string(), "third.txt".to_string()],
12877                "New pane should be ready to move one item out"
12878            );
12879
12880            workspace.move_item_to_pane_at_index(
12881                &MoveItemToPane {
12882                    destination: 3,
12883                    focus: true,
12884                    clone: false,
12885                },
12886                window,
12887                cx,
12888            );
12889            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12890            assert_eq!(
12891                pane_items_paths(&workspace.active_pane, cx),
12892                vec!["first.txt".to_string()],
12893                "After moving, one item should be left in the original pane"
12894            );
12895            assert_eq!(
12896                pane_items_paths(&workspace.panes[1], cx),
12897                vec!["second.txt".to_string()],
12898                "Previously created pane should be unchanged"
12899            );
12900            assert_eq!(
12901                pane_items_paths(&workspace.panes[2], cx),
12902                vec!["third.txt".to_string()],
12903                "New item should have been moved to the new pane"
12904            );
12905        });
12906    }
12907
12908    #[gpui::test]
12909    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12910        init_test(cx);
12911
12912        let fs = FakeFs::new(cx.executor());
12913        let project = Project::test(fs, [], cx).await;
12914        let (workspace, cx) =
12915            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12916
12917        let item_1 = cx.new(|cx| {
12918            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12919        });
12920        workspace.update_in(cx, |workspace, window, cx| {
12921            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12922            workspace.move_item_to_pane_in_direction(
12923                &MoveItemToPaneInDirection {
12924                    direction: SplitDirection::Right,
12925                    focus: true,
12926                    clone: true,
12927                },
12928                window,
12929                cx,
12930            );
12931        });
12932        cx.run_until_parked();
12933        workspace.update_in(cx, |workspace, window, cx| {
12934            workspace.move_item_to_pane_at_index(
12935                &MoveItemToPane {
12936                    destination: 3,
12937                    focus: true,
12938                    clone: true,
12939                },
12940                window,
12941                cx,
12942            );
12943        });
12944        cx.run_until_parked();
12945
12946        workspace.update(cx, |workspace, cx| {
12947            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12948            for pane in workspace.panes() {
12949                assert_eq!(
12950                    pane_items_paths(pane, cx),
12951                    vec!["first.txt".to_string()],
12952                    "Single item exists in all panes"
12953                );
12954            }
12955        });
12956
12957        // verify that the active pane has been updated after waiting for the
12958        // pane focus event to fire and resolve
12959        workspace.read_with(cx, |workspace, _app| {
12960            assert_eq!(
12961                workspace.active_pane(),
12962                &workspace.panes[2],
12963                "The third pane should be the active one: {:?}",
12964                workspace.panes
12965            );
12966        })
12967    }
12968
12969    #[gpui::test]
12970    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12971        init_test(cx);
12972
12973        let fs = FakeFs::new(cx.executor());
12974        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12975
12976        let project = Project::test(fs, ["root".as_ref()], cx).await;
12977        let (workspace, cx) =
12978            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12979
12980        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12981        // Add item to pane A with project path
12982        let item_a = cx.new(|cx| {
12983            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12984        });
12985        workspace.update_in(cx, |workspace, window, cx| {
12986            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12987        });
12988
12989        // Split to create pane B
12990        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12991            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12992        });
12993
12994        // Add item with SAME project path to pane B, and pin it
12995        let item_b = cx.new(|cx| {
12996            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12997        });
12998        pane_b.update_in(cx, |pane, window, cx| {
12999            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13000            pane.set_pinned_count(1);
13001        });
13002
13003        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13004        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13005
13006        // close_pinned: false should only close the unpinned copy
13007        workspace.update_in(cx, |workspace, window, cx| {
13008            workspace.close_item_in_all_panes(
13009                &CloseItemInAllPanes {
13010                    save_intent: Some(SaveIntent::Close),
13011                    close_pinned: false,
13012                },
13013                window,
13014                cx,
13015            )
13016        });
13017        cx.executor().run_until_parked();
13018
13019        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13020        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13021        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13022        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13023
13024        // Split again, seeing as closing the previous item also closed its
13025        // pane, so only pane remains, which does not allow us to properly test
13026        // that both items close when `close_pinned: true`.
13027        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13028            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13029        });
13030
13031        // Add an item with the same project path to pane C so that
13032        // close_item_in_all_panes can determine what to close across all panes
13033        // (it reads the active item from the active pane, and split_pane
13034        // creates an empty pane).
13035        let item_c = cx.new(|cx| {
13036            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13037        });
13038        pane_c.update_in(cx, |pane, window, cx| {
13039            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13040        });
13041
13042        // close_pinned: true should close the pinned copy too
13043        workspace.update_in(cx, |workspace, window, cx| {
13044            let panes_count = workspace.panes().len();
13045            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13046
13047            workspace.close_item_in_all_panes(
13048                &CloseItemInAllPanes {
13049                    save_intent: Some(SaveIntent::Close),
13050                    close_pinned: true,
13051                },
13052                window,
13053                cx,
13054            )
13055        });
13056        cx.executor().run_until_parked();
13057
13058        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13059        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13060        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13061        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13062    }
13063
13064    mod register_project_item_tests {
13065
13066        use super::*;
13067
13068        // View
13069        struct TestPngItemView {
13070            focus_handle: FocusHandle,
13071        }
13072        // Model
13073        struct TestPngItem {}
13074
13075        impl project::ProjectItem for TestPngItem {
13076            fn try_open(
13077                _project: &Entity<Project>,
13078                path: &ProjectPath,
13079                cx: &mut App,
13080            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13081                if path.path.extension().unwrap() == "png" {
13082                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13083                } else {
13084                    None
13085                }
13086            }
13087
13088            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13089                None
13090            }
13091
13092            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13093                None
13094            }
13095
13096            fn is_dirty(&self) -> bool {
13097                false
13098            }
13099        }
13100
13101        impl Item for TestPngItemView {
13102            type Event = ();
13103            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13104                "".into()
13105            }
13106        }
13107        impl EventEmitter<()> for TestPngItemView {}
13108        impl Focusable for TestPngItemView {
13109            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13110                self.focus_handle.clone()
13111            }
13112        }
13113
13114        impl Render for TestPngItemView {
13115            fn render(
13116                &mut self,
13117                _window: &mut Window,
13118                _cx: &mut Context<Self>,
13119            ) -> impl IntoElement {
13120                Empty
13121            }
13122        }
13123
13124        impl ProjectItem for TestPngItemView {
13125            type Item = TestPngItem;
13126
13127            fn for_project_item(
13128                _project: Entity<Project>,
13129                _pane: Option<&Pane>,
13130                _item: Entity<Self::Item>,
13131                _: &mut Window,
13132                cx: &mut Context<Self>,
13133            ) -> Self
13134            where
13135                Self: Sized,
13136            {
13137                Self {
13138                    focus_handle: cx.focus_handle(),
13139                }
13140            }
13141        }
13142
13143        // View
13144        struct TestIpynbItemView {
13145            focus_handle: FocusHandle,
13146        }
13147        // Model
13148        struct TestIpynbItem {}
13149
13150        impl project::ProjectItem for TestIpynbItem {
13151            fn try_open(
13152                _project: &Entity<Project>,
13153                path: &ProjectPath,
13154                cx: &mut App,
13155            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13156                if path.path.extension().unwrap() == "ipynb" {
13157                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13158                } else {
13159                    None
13160                }
13161            }
13162
13163            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13164                None
13165            }
13166
13167            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13168                None
13169            }
13170
13171            fn is_dirty(&self) -> bool {
13172                false
13173            }
13174        }
13175
13176        impl Item for TestIpynbItemView {
13177            type Event = ();
13178            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13179                "".into()
13180            }
13181        }
13182        impl EventEmitter<()> for TestIpynbItemView {}
13183        impl Focusable for TestIpynbItemView {
13184            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13185                self.focus_handle.clone()
13186            }
13187        }
13188
13189        impl Render for TestIpynbItemView {
13190            fn render(
13191                &mut self,
13192                _window: &mut Window,
13193                _cx: &mut Context<Self>,
13194            ) -> impl IntoElement {
13195                Empty
13196            }
13197        }
13198
13199        impl ProjectItem for TestIpynbItemView {
13200            type Item = TestIpynbItem;
13201
13202            fn for_project_item(
13203                _project: Entity<Project>,
13204                _pane: Option<&Pane>,
13205                _item: Entity<Self::Item>,
13206                _: &mut Window,
13207                cx: &mut Context<Self>,
13208            ) -> Self
13209            where
13210                Self: Sized,
13211            {
13212                Self {
13213                    focus_handle: cx.focus_handle(),
13214                }
13215            }
13216        }
13217
13218        struct TestAlternatePngItemView {
13219            focus_handle: FocusHandle,
13220        }
13221
13222        impl Item for TestAlternatePngItemView {
13223            type Event = ();
13224            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13225                "".into()
13226            }
13227        }
13228
13229        impl EventEmitter<()> for TestAlternatePngItemView {}
13230        impl Focusable for TestAlternatePngItemView {
13231            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13232                self.focus_handle.clone()
13233            }
13234        }
13235
13236        impl Render for TestAlternatePngItemView {
13237            fn render(
13238                &mut self,
13239                _window: &mut Window,
13240                _cx: &mut Context<Self>,
13241            ) -> impl IntoElement {
13242                Empty
13243            }
13244        }
13245
13246        impl ProjectItem for TestAlternatePngItemView {
13247            type Item = TestPngItem;
13248
13249            fn for_project_item(
13250                _project: Entity<Project>,
13251                _pane: Option<&Pane>,
13252                _item: Entity<Self::Item>,
13253                _: &mut Window,
13254                cx: &mut Context<Self>,
13255            ) -> Self
13256            where
13257                Self: Sized,
13258            {
13259                Self {
13260                    focus_handle: cx.focus_handle(),
13261                }
13262            }
13263        }
13264
13265        #[gpui::test]
13266        async fn test_register_project_item(cx: &mut TestAppContext) {
13267            init_test(cx);
13268
13269            cx.update(|cx| {
13270                register_project_item::<TestPngItemView>(cx);
13271                register_project_item::<TestIpynbItemView>(cx);
13272            });
13273
13274            let fs = FakeFs::new(cx.executor());
13275            fs.insert_tree(
13276                "/root1",
13277                json!({
13278                    "one.png": "BINARYDATAHERE",
13279                    "two.ipynb": "{ totally a notebook }",
13280                    "three.txt": "editing text, sure why not?"
13281                }),
13282            )
13283            .await;
13284
13285            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13286            let (workspace, cx) =
13287                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13288
13289            let worktree_id = project.update(cx, |project, cx| {
13290                project.worktrees(cx).next().unwrap().read(cx).id()
13291            });
13292
13293            let handle = workspace
13294                .update_in(cx, |workspace, window, cx| {
13295                    let project_path = (worktree_id, rel_path("one.png"));
13296                    workspace.open_path(project_path, None, true, window, cx)
13297                })
13298                .await
13299                .unwrap();
13300
13301            // Now we can check if the handle we got back errored or not
13302            assert_eq!(
13303                handle.to_any_view().entity_type(),
13304                TypeId::of::<TestPngItemView>()
13305            );
13306
13307            let handle = workspace
13308                .update_in(cx, |workspace, window, cx| {
13309                    let project_path = (worktree_id, rel_path("two.ipynb"));
13310                    workspace.open_path(project_path, None, true, window, cx)
13311                })
13312                .await
13313                .unwrap();
13314
13315            assert_eq!(
13316                handle.to_any_view().entity_type(),
13317                TypeId::of::<TestIpynbItemView>()
13318            );
13319
13320            let handle = workspace
13321                .update_in(cx, |workspace, window, cx| {
13322                    let project_path = (worktree_id, rel_path("three.txt"));
13323                    workspace.open_path(project_path, None, true, window, cx)
13324                })
13325                .await;
13326            assert!(handle.is_err());
13327        }
13328
13329        #[gpui::test]
13330        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13331            init_test(cx);
13332
13333            cx.update(|cx| {
13334                register_project_item::<TestPngItemView>(cx);
13335                register_project_item::<TestAlternatePngItemView>(cx);
13336            });
13337
13338            let fs = FakeFs::new(cx.executor());
13339            fs.insert_tree(
13340                "/root1",
13341                json!({
13342                    "one.png": "BINARYDATAHERE",
13343                    "two.ipynb": "{ totally a notebook }",
13344                    "three.txt": "editing text, sure why not?"
13345                }),
13346            )
13347            .await;
13348            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13349            let (workspace, cx) =
13350                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13351            let worktree_id = project.update(cx, |project, cx| {
13352                project.worktrees(cx).next().unwrap().read(cx).id()
13353            });
13354
13355            let handle = workspace
13356                .update_in(cx, |workspace, window, cx| {
13357                    let project_path = (worktree_id, rel_path("one.png"));
13358                    workspace.open_path(project_path, None, true, window, cx)
13359                })
13360                .await
13361                .unwrap();
13362
13363            // This _must_ be the second item registered
13364            assert_eq!(
13365                handle.to_any_view().entity_type(),
13366                TypeId::of::<TestAlternatePngItemView>()
13367            );
13368
13369            let handle = workspace
13370                .update_in(cx, |workspace, window, cx| {
13371                    let project_path = (worktree_id, rel_path("three.txt"));
13372                    workspace.open_path(project_path, None, true, window, cx)
13373                })
13374                .await;
13375            assert!(handle.is_err());
13376        }
13377    }
13378
13379    #[gpui::test]
13380    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13381        init_test(cx);
13382
13383        let fs = FakeFs::new(cx.executor());
13384        let project = Project::test(fs, [], cx).await;
13385        let (workspace, _cx) =
13386            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13387
13388        // Test with status bar shown (default)
13389        workspace.read_with(cx, |workspace, cx| {
13390            let visible = workspace.status_bar_visible(cx);
13391            assert!(visible, "Status bar should be visible by default");
13392        });
13393
13394        // Test with status bar hidden
13395        cx.update_global(|store: &mut SettingsStore, cx| {
13396            store.update_user_settings(cx, |settings| {
13397                settings.status_bar.get_or_insert_default().show = Some(false);
13398            });
13399        });
13400
13401        workspace.read_with(cx, |workspace, cx| {
13402            let visible = workspace.status_bar_visible(cx);
13403            assert!(!visible, "Status bar should be hidden when show is false");
13404        });
13405
13406        // Test with status bar shown explicitly
13407        cx.update_global(|store: &mut SettingsStore, cx| {
13408            store.update_user_settings(cx, |settings| {
13409                settings.status_bar.get_or_insert_default().show = Some(true);
13410            });
13411        });
13412
13413        workspace.read_with(cx, |workspace, cx| {
13414            let visible = workspace.status_bar_visible(cx);
13415            assert!(visible, "Status bar should be visible when show is true");
13416        });
13417    }
13418
13419    #[gpui::test]
13420    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13421        init_test(cx);
13422
13423        let fs = FakeFs::new(cx.executor());
13424        let project = Project::test(fs, [], cx).await;
13425        let (multi_workspace, cx) =
13426            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13427        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13428        let panel = workspace.update_in(cx, |workspace, window, cx| {
13429            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13430            workspace.add_panel(panel.clone(), window, cx);
13431
13432            workspace
13433                .right_dock()
13434                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13435
13436            panel
13437        });
13438
13439        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13440        let item_a = cx.new(TestItem::new);
13441        let item_b = cx.new(TestItem::new);
13442        let item_a_id = item_a.entity_id();
13443        let item_b_id = item_b.entity_id();
13444
13445        pane.update_in(cx, |pane, window, cx| {
13446            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13447            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13448        });
13449
13450        pane.read_with(cx, |pane, _| {
13451            assert_eq!(pane.items_len(), 2);
13452            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13453        });
13454
13455        workspace.update_in(cx, |workspace, window, cx| {
13456            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13457        });
13458
13459        workspace.update_in(cx, |_, window, cx| {
13460            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13461        });
13462
13463        // Assert that the `pane::CloseActiveItem` action is handled at the
13464        // workspace level when one of the dock panels is focused and, in that
13465        // case, the center pane's active item is closed but the focus is not
13466        // moved.
13467        cx.dispatch_action(pane::CloseActiveItem::default());
13468        cx.run_until_parked();
13469
13470        pane.read_with(cx, |pane, _| {
13471            assert_eq!(pane.items_len(), 1);
13472            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13473        });
13474
13475        workspace.update_in(cx, |workspace, window, cx| {
13476            assert!(workspace.right_dock().read(cx).is_open());
13477            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13478        });
13479    }
13480
13481    #[gpui::test]
13482    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13483        init_test(cx);
13484        let fs = FakeFs::new(cx.executor());
13485
13486        let project_a = Project::test(fs.clone(), [], cx).await;
13487        let project_b = Project::test(fs, [], cx).await;
13488
13489        let multi_workspace_handle =
13490            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13491        cx.run_until_parked();
13492
13493        let workspace_a = multi_workspace_handle
13494            .read_with(cx, |mw, _| mw.workspace().clone())
13495            .unwrap();
13496
13497        let _workspace_b = multi_workspace_handle
13498            .update(cx, |mw, window, cx| {
13499                mw.test_add_workspace(project_b, window, cx)
13500            })
13501            .unwrap();
13502
13503        // Switch to workspace A
13504        multi_workspace_handle
13505            .update(cx, |mw, window, cx| {
13506                mw.activate_index(0, window, cx);
13507            })
13508            .unwrap();
13509
13510        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13511
13512        // Add a panel to workspace A's right dock and open the dock
13513        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13514            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13515            workspace.add_panel(panel.clone(), window, cx);
13516            workspace
13517                .right_dock()
13518                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13519            panel
13520        });
13521
13522        // Focus the panel through the workspace (matching existing test pattern)
13523        workspace_a.update_in(cx, |workspace, window, cx| {
13524            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13525        });
13526
13527        // Zoom the panel
13528        panel.update_in(cx, |panel, window, cx| {
13529            panel.set_zoomed(true, window, cx);
13530        });
13531
13532        // Verify the panel is zoomed and the dock is open
13533        workspace_a.update_in(cx, |workspace, window, cx| {
13534            assert!(
13535                workspace.right_dock().read(cx).is_open(),
13536                "dock should be open before switch"
13537            );
13538            assert!(
13539                panel.is_zoomed(window, cx),
13540                "panel should be zoomed before switch"
13541            );
13542            assert!(
13543                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13544                "panel should be focused before switch"
13545            );
13546        });
13547
13548        // Switch to workspace B
13549        multi_workspace_handle
13550            .update(cx, |mw, window, cx| {
13551                mw.activate_index(1, window, cx);
13552            })
13553            .unwrap();
13554        cx.run_until_parked();
13555
13556        // Switch back to workspace A
13557        multi_workspace_handle
13558            .update(cx, |mw, window, cx| {
13559                mw.activate_index(0, window, cx);
13560            })
13561            .unwrap();
13562        cx.run_until_parked();
13563
13564        // Verify the panel is still zoomed and the dock is still open
13565        workspace_a.update_in(cx, |workspace, window, cx| {
13566            assert!(
13567                workspace.right_dock().read(cx).is_open(),
13568                "dock should still be open after switching back"
13569            );
13570            assert!(
13571                panel.is_zoomed(window, cx),
13572                "panel should still be zoomed after switching back"
13573            );
13574        });
13575    }
13576
13577    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13578        pane.read(cx)
13579            .items()
13580            .flat_map(|item| {
13581                item.project_paths(cx)
13582                    .into_iter()
13583                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13584            })
13585            .collect()
13586    }
13587
13588    pub fn init_test(cx: &mut TestAppContext) {
13589        cx.update(|cx| {
13590            let settings_store = SettingsStore::test(cx);
13591            cx.set_global(settings_store);
13592            theme::init(theme::LoadThemes::JustBase, cx);
13593        });
13594    }
13595
13596    #[gpui::test]
13597    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13598        use settings::{ThemeName, ThemeSelection};
13599        use theme::SystemAppearance;
13600        use zed_actions::theme::ToggleMode;
13601
13602        init_test(cx);
13603
13604        let fs = FakeFs::new(cx.executor());
13605        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13606
13607        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13608            .await;
13609
13610        // Build a test project and workspace view so the test can invoke
13611        // the workspace action handler the same way the UI would.
13612        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13613        let (workspace, cx) =
13614            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13615
13616        // Seed the settings file with a plain static light theme so the
13617        // first toggle always starts from a known persisted state.
13618        workspace.update_in(cx, |_workspace, _window, cx| {
13619            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13620            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13621                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13622            });
13623        });
13624        cx.executor().advance_clock(Duration::from_millis(200));
13625        cx.run_until_parked();
13626
13627        // Confirm the initial persisted settings contain the static theme
13628        // we just wrote before any toggling happens.
13629        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13630        assert!(settings_text.contains(r#""theme": "One Light""#));
13631
13632        // Toggle once. This should migrate the persisted theme settings
13633        // into light/dark slots and enable system mode.
13634        workspace.update_in(cx, |workspace, window, cx| {
13635            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13636        });
13637        cx.executor().advance_clock(Duration::from_millis(200));
13638        cx.run_until_parked();
13639
13640        // 1. Static -> Dynamic
13641        // this assertion checks theme changed from static to dynamic.
13642        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13643        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13644        assert_eq!(
13645            parsed["theme"],
13646            serde_json::json!({
13647                "mode": "system",
13648                "light": "One Light",
13649                "dark": "One Dark"
13650            })
13651        );
13652
13653        // 2. Toggle again, suppose it will change the mode to light
13654        workspace.update_in(cx, |workspace, window, cx| {
13655            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13656        });
13657        cx.executor().advance_clock(Duration::from_millis(200));
13658        cx.run_until_parked();
13659
13660        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13661        assert!(settings_text.contains(r#""mode": "light""#));
13662    }
13663
13664    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13665        let item = TestProjectItem::new(id, path, cx);
13666        item.update(cx, |item, _| {
13667            item.is_dirty = true;
13668        });
13669        item
13670    }
13671
13672    #[gpui::test]
13673    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13674        cx: &mut gpui::TestAppContext,
13675    ) {
13676        init_test(cx);
13677        let fs = FakeFs::new(cx.executor());
13678
13679        let project = Project::test(fs, [], cx).await;
13680        let (workspace, cx) =
13681            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13682
13683        let panel = workspace.update_in(cx, |workspace, window, cx| {
13684            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13685            workspace.add_panel(panel.clone(), window, cx);
13686            workspace
13687                .right_dock()
13688                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13689            panel
13690        });
13691
13692        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13693        pane.update_in(cx, |pane, window, cx| {
13694            let item = cx.new(TestItem::new);
13695            pane.add_item(Box::new(item), true, true, None, window, cx);
13696        });
13697
13698        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13699        // mirrors the real-world flow and avoids side effects from directly
13700        // focusing the panel while the center pane is active.
13701        workspace.update_in(cx, |workspace, window, cx| {
13702            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13703        });
13704
13705        panel.update_in(cx, |panel, window, cx| {
13706            panel.set_zoomed(true, window, cx);
13707        });
13708
13709        workspace.update_in(cx, |workspace, window, cx| {
13710            assert!(workspace.right_dock().read(cx).is_open());
13711            assert!(panel.is_zoomed(window, cx));
13712            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13713        });
13714
13715        // Simulate a spurious pane::Event::Focus on the center pane while the
13716        // panel still has focus. This mirrors what happens during macOS window
13717        // activation: the center pane fires a focus event even though actual
13718        // focus remains on the dock panel.
13719        pane.update_in(cx, |_, _, cx| {
13720            cx.emit(pane::Event::Focus);
13721        });
13722
13723        // The dock must remain open because the panel had focus at the time the
13724        // event was processed. Before the fix, dock_to_preserve was None for
13725        // panels that don't implement pane(), causing the dock to close.
13726        workspace.update_in(cx, |workspace, window, cx| {
13727            assert!(
13728                workspace.right_dock().read(cx).is_open(),
13729                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13730            );
13731            assert!(panel.is_zoomed(window, cx));
13732        });
13733    }
13734}