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,
   32    SIDEBAR_RESIZE_HANDLE_SIZE, ToggleWorkspaceSidebar, multi_workspace_enabled,
   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, MultiWorkspaceId, SerializedMultiWorkspace,
   84        SerializedWorkspaceLocation, 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 status_bar_visible(&self, cx: &App) -> bool {
 2157        StatusBarSettings::get_global(cx).show
 2158    }
 2159
 2160    pub fn app_state(&self) -> &Arc<AppState> {
 2161        &self.app_state
 2162    }
 2163
 2164    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2165        self._panels_task = Some(task);
 2166    }
 2167
 2168    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2169        self._panels_task.take()
 2170    }
 2171
 2172    pub fn user_store(&self) -> &Entity<UserStore> {
 2173        &self.app_state.user_store
 2174    }
 2175
 2176    pub fn project(&self) -> &Entity<Project> {
 2177        &self.project
 2178    }
 2179
 2180    pub fn path_style(&self, cx: &App) -> PathStyle {
 2181        self.project.read(cx).path_style(cx)
 2182    }
 2183
 2184    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2185        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2186
 2187        for pane_handle in &self.panes {
 2188            let pane = pane_handle.read(cx);
 2189
 2190            for entry in pane.activation_history() {
 2191                history.insert(
 2192                    entry.entity_id,
 2193                    history
 2194                        .get(&entry.entity_id)
 2195                        .cloned()
 2196                        .unwrap_or(0)
 2197                        .max(entry.timestamp),
 2198                );
 2199            }
 2200        }
 2201
 2202        history
 2203    }
 2204
 2205    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2206        let mut recent_item: Option<Entity<T>> = None;
 2207        let mut recent_timestamp = 0;
 2208        for pane_handle in &self.panes {
 2209            let pane = pane_handle.read(cx);
 2210            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2211                pane.items().map(|item| (item.item_id(), item)).collect();
 2212            for entry in pane.activation_history() {
 2213                if entry.timestamp > recent_timestamp
 2214                    && let Some(&item) = item_map.get(&entry.entity_id)
 2215                    && let Some(typed_item) = item.act_as::<T>(cx)
 2216                {
 2217                    recent_timestamp = entry.timestamp;
 2218                    recent_item = Some(typed_item);
 2219                }
 2220            }
 2221        }
 2222        recent_item
 2223    }
 2224
 2225    pub fn recent_navigation_history_iter(
 2226        &self,
 2227        cx: &App,
 2228    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2229        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2230        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2231
 2232        for pane in &self.panes {
 2233            let pane = pane.read(cx);
 2234
 2235            pane.nav_history()
 2236                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2237                    if let Some(fs_path) = &fs_path {
 2238                        abs_paths_opened
 2239                            .entry(fs_path.clone())
 2240                            .or_default()
 2241                            .insert(project_path.clone());
 2242                    }
 2243                    let timestamp = entry.timestamp;
 2244                    match history.entry(project_path) {
 2245                        hash_map::Entry::Occupied(mut entry) => {
 2246                            let (_, old_timestamp) = entry.get();
 2247                            if &timestamp > old_timestamp {
 2248                                entry.insert((fs_path, timestamp));
 2249                            }
 2250                        }
 2251                        hash_map::Entry::Vacant(entry) => {
 2252                            entry.insert((fs_path, timestamp));
 2253                        }
 2254                    }
 2255                });
 2256
 2257            if let Some(item) = pane.active_item()
 2258                && let Some(project_path) = item.project_path(cx)
 2259            {
 2260                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2261
 2262                if let Some(fs_path) = &fs_path {
 2263                    abs_paths_opened
 2264                        .entry(fs_path.clone())
 2265                        .or_default()
 2266                        .insert(project_path.clone());
 2267                }
 2268
 2269                history.insert(project_path, (fs_path, std::usize::MAX));
 2270            }
 2271        }
 2272
 2273        history
 2274            .into_iter()
 2275            .sorted_by_key(|(_, (_, order))| *order)
 2276            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2277            .rev()
 2278            .filter(move |(history_path, abs_path)| {
 2279                let latest_project_path_opened = abs_path
 2280                    .as_ref()
 2281                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2282                    .and_then(|project_paths| {
 2283                        project_paths
 2284                            .iter()
 2285                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2286                    });
 2287
 2288                latest_project_path_opened.is_none_or(|path| path == history_path)
 2289            })
 2290    }
 2291
 2292    pub fn recent_navigation_history(
 2293        &self,
 2294        limit: Option<usize>,
 2295        cx: &App,
 2296    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2297        self.recent_navigation_history_iter(cx)
 2298            .take(limit.unwrap_or(usize::MAX))
 2299            .collect()
 2300    }
 2301
 2302    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2303        for pane in &self.panes {
 2304            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2305        }
 2306    }
 2307
 2308    fn navigate_history(
 2309        &mut self,
 2310        pane: WeakEntity<Pane>,
 2311        mode: NavigationMode,
 2312        window: &mut Window,
 2313        cx: &mut Context<Workspace>,
 2314    ) -> Task<Result<()>> {
 2315        self.navigate_history_impl(
 2316            pane,
 2317            mode,
 2318            window,
 2319            &mut |history, cx| history.pop(mode, cx),
 2320            cx,
 2321        )
 2322    }
 2323
 2324    fn navigate_tag_history(
 2325        &mut self,
 2326        pane: WeakEntity<Pane>,
 2327        mode: TagNavigationMode,
 2328        window: &mut Window,
 2329        cx: &mut Context<Workspace>,
 2330    ) -> Task<Result<()>> {
 2331        self.navigate_history_impl(
 2332            pane,
 2333            NavigationMode::Normal,
 2334            window,
 2335            &mut |history, _cx| history.pop_tag(mode),
 2336            cx,
 2337        )
 2338    }
 2339
 2340    fn navigate_history_impl(
 2341        &mut self,
 2342        pane: WeakEntity<Pane>,
 2343        mode: NavigationMode,
 2344        window: &mut Window,
 2345        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2346        cx: &mut Context<Workspace>,
 2347    ) -> Task<Result<()>> {
 2348        let to_load = if let Some(pane) = pane.upgrade() {
 2349            pane.update(cx, |pane, cx| {
 2350                window.focus(&pane.focus_handle(cx), cx);
 2351                loop {
 2352                    // Retrieve the weak item handle from the history.
 2353                    let entry = cb(pane.nav_history_mut(), cx)?;
 2354
 2355                    // If the item is still present in this pane, then activate it.
 2356                    if let Some(index) = entry
 2357                        .item
 2358                        .upgrade()
 2359                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2360                    {
 2361                        let prev_active_item_index = pane.active_item_index();
 2362                        pane.nav_history_mut().set_mode(mode);
 2363                        pane.activate_item(index, true, true, window, cx);
 2364                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2365
 2366                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2367                        if let Some(data) = entry.data {
 2368                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2369                        }
 2370
 2371                        if navigated {
 2372                            break None;
 2373                        }
 2374                    } else {
 2375                        // If the item is no longer present in this pane, then retrieve its
 2376                        // path info in order to reopen it.
 2377                        break pane
 2378                            .nav_history()
 2379                            .path_for_item(entry.item.id())
 2380                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2381                    }
 2382                }
 2383            })
 2384        } else {
 2385            None
 2386        };
 2387
 2388        if let Some((project_path, abs_path, entry)) = to_load {
 2389            // If the item was no longer present, then load it again from its previous path, first try the local path
 2390            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2391
 2392            cx.spawn_in(window, async move  |workspace, cx| {
 2393                let open_by_project_path = open_by_project_path.await;
 2394                let mut navigated = false;
 2395                match open_by_project_path
 2396                    .with_context(|| format!("Navigating to {project_path:?}"))
 2397                {
 2398                    Ok((project_entry_id, build_item)) => {
 2399                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2400                            pane.nav_history_mut().set_mode(mode);
 2401                            pane.active_item().map(|p| p.item_id())
 2402                        })?;
 2403
 2404                        pane.update_in(cx, |pane, window, cx| {
 2405                            let item = pane.open_item(
 2406                                project_entry_id,
 2407                                project_path,
 2408                                true,
 2409                                entry.is_preview,
 2410                                true,
 2411                                None,
 2412                                window, cx,
 2413                                build_item,
 2414                            );
 2415                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2416                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2417                            if let Some(data) = entry.data {
 2418                                navigated |= item.navigate(data, window, cx);
 2419                            }
 2420                        })?;
 2421                    }
 2422                    Err(open_by_project_path_e) => {
 2423                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2424                        // and its worktree is now dropped
 2425                        if let Some(abs_path) = abs_path {
 2426                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2427                                pane.nav_history_mut().set_mode(mode);
 2428                                pane.active_item().map(|p| p.item_id())
 2429                            })?;
 2430                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2431                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2432                            })?;
 2433                            match open_by_abs_path
 2434                                .await
 2435                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2436                            {
 2437                                Ok(item) => {
 2438                                    pane.update_in(cx, |pane, window, cx| {
 2439                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2440                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2441                                        if let Some(data) = entry.data {
 2442                                            navigated |= item.navigate(data, window, cx);
 2443                                        }
 2444                                    })?;
 2445                                }
 2446                                Err(open_by_abs_path_e) => {
 2447                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2448                                }
 2449                            }
 2450                        }
 2451                    }
 2452                }
 2453
 2454                if !navigated {
 2455                    workspace
 2456                        .update_in(cx, |workspace, window, cx| {
 2457                            Self::navigate_history(workspace, pane, mode, window, cx)
 2458                        })?
 2459                        .await?;
 2460                }
 2461
 2462                Ok(())
 2463            })
 2464        } else {
 2465            Task::ready(Ok(()))
 2466        }
 2467    }
 2468
 2469    pub fn go_back(
 2470        &mut self,
 2471        pane: WeakEntity<Pane>,
 2472        window: &mut Window,
 2473        cx: &mut Context<Workspace>,
 2474    ) -> Task<Result<()>> {
 2475        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2476    }
 2477
 2478    pub fn go_forward(
 2479        &mut self,
 2480        pane: WeakEntity<Pane>,
 2481        window: &mut Window,
 2482        cx: &mut Context<Workspace>,
 2483    ) -> Task<Result<()>> {
 2484        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2485    }
 2486
 2487    pub fn reopen_closed_item(
 2488        &mut self,
 2489        window: &mut Window,
 2490        cx: &mut Context<Workspace>,
 2491    ) -> Task<Result<()>> {
 2492        self.navigate_history(
 2493            self.active_pane().downgrade(),
 2494            NavigationMode::ReopeningClosedItem,
 2495            window,
 2496            cx,
 2497        )
 2498    }
 2499
 2500    pub fn client(&self) -> &Arc<Client> {
 2501        &self.app_state.client
 2502    }
 2503
 2504    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2505        self.titlebar_item = Some(item);
 2506        cx.notify();
 2507    }
 2508
 2509    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2510        self.on_prompt_for_new_path = Some(prompt)
 2511    }
 2512
 2513    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2514        self.on_prompt_for_open_path = Some(prompt)
 2515    }
 2516
 2517    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2518        self.terminal_provider = Some(Box::new(provider));
 2519    }
 2520
 2521    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2522        self.debugger_provider = Some(Arc::new(provider));
 2523    }
 2524
 2525    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2526        self.debugger_provider.clone()
 2527    }
 2528
 2529    pub fn prompt_for_open_path(
 2530        &mut self,
 2531        path_prompt_options: PathPromptOptions,
 2532        lister: DirectoryLister,
 2533        window: &mut Window,
 2534        cx: &mut Context<Self>,
 2535    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2536        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2537            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2538            let rx = prompt(self, lister, window, cx);
 2539            self.on_prompt_for_open_path = Some(prompt);
 2540            rx
 2541        } else {
 2542            let (tx, rx) = oneshot::channel();
 2543            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2544
 2545            cx.spawn_in(window, async move |workspace, cx| {
 2546                let Ok(result) = abs_path.await else {
 2547                    return Ok(());
 2548                };
 2549
 2550                match result {
 2551                    Ok(result) => {
 2552                        tx.send(result).ok();
 2553                    }
 2554                    Err(err) => {
 2555                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2556                            workspace.show_portal_error(err.to_string(), cx);
 2557                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2558                            let rx = prompt(workspace, lister, window, cx);
 2559                            workspace.on_prompt_for_open_path = Some(prompt);
 2560                            rx
 2561                        })?;
 2562                        if let Ok(path) = rx.await {
 2563                            tx.send(path).ok();
 2564                        }
 2565                    }
 2566                };
 2567                anyhow::Ok(())
 2568            })
 2569            .detach();
 2570
 2571            rx
 2572        }
 2573    }
 2574
 2575    pub fn prompt_for_new_path(
 2576        &mut self,
 2577        lister: DirectoryLister,
 2578        suggested_name: Option<String>,
 2579        window: &mut Window,
 2580        cx: &mut Context<Self>,
 2581    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2582        if self.project.read(cx).is_via_collab()
 2583            || self.project.read(cx).is_via_remote_server()
 2584            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2585        {
 2586            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2587            let rx = prompt(self, lister, suggested_name, window, cx);
 2588            self.on_prompt_for_new_path = Some(prompt);
 2589            return rx;
 2590        }
 2591
 2592        let (tx, rx) = oneshot::channel();
 2593        cx.spawn_in(window, async move |workspace, cx| {
 2594            let abs_path = workspace.update(cx, |workspace, cx| {
 2595                let relative_to = workspace
 2596                    .most_recent_active_path(cx)
 2597                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2598                    .or_else(|| {
 2599                        let project = workspace.project.read(cx);
 2600                        project.visible_worktrees(cx).find_map(|worktree| {
 2601                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2602                        })
 2603                    })
 2604                    .or_else(std::env::home_dir)
 2605                    .unwrap_or_else(|| PathBuf::from(""));
 2606                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2607            })?;
 2608            let abs_path = match abs_path.await? {
 2609                Ok(path) => path,
 2610                Err(err) => {
 2611                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2612                        workspace.show_portal_error(err.to_string(), cx);
 2613
 2614                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2615                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2616                        workspace.on_prompt_for_new_path = Some(prompt);
 2617                        rx
 2618                    })?;
 2619                    if let Ok(path) = rx.await {
 2620                        tx.send(path).ok();
 2621                    }
 2622                    return anyhow::Ok(());
 2623                }
 2624            };
 2625
 2626            tx.send(abs_path.map(|path| vec![path])).ok();
 2627            anyhow::Ok(())
 2628        })
 2629        .detach();
 2630
 2631        rx
 2632    }
 2633
 2634    pub fn titlebar_item(&self) -> Option<AnyView> {
 2635        self.titlebar_item.clone()
 2636    }
 2637
 2638    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2639    /// When set, git-related operations should use this worktree instead of deriving
 2640    /// the active worktree from the focused file.
 2641    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2642        self.active_worktree_override
 2643    }
 2644
 2645    pub fn set_active_worktree_override(
 2646        &mut self,
 2647        worktree_id: Option<WorktreeId>,
 2648        cx: &mut Context<Self>,
 2649    ) {
 2650        self.active_worktree_override = worktree_id;
 2651        cx.notify();
 2652    }
 2653
 2654    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2655        self.active_worktree_override = None;
 2656        cx.notify();
 2657    }
 2658
 2659    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2660    ///
 2661    /// If the given workspace has a local project, then it will be passed
 2662    /// to the callback. Otherwise, a new empty window will be created.
 2663    pub fn with_local_workspace<T, F>(
 2664        &mut self,
 2665        window: &mut Window,
 2666        cx: &mut Context<Self>,
 2667        callback: F,
 2668    ) -> Task<Result<T>>
 2669    where
 2670        T: 'static,
 2671        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2672    {
 2673        if self.project.read(cx).is_local() {
 2674            Task::ready(Ok(callback(self, window, cx)))
 2675        } else {
 2676            let env = self.project.read(cx).cli_environment(cx);
 2677            let task = Self::new_local(
 2678                Vec::new(),
 2679                self.app_state.clone(),
 2680                None,
 2681                env,
 2682                None,
 2683                true,
 2684                cx,
 2685            );
 2686            cx.spawn_in(window, async move |_vh, cx| {
 2687                let OpenResult {
 2688                    window: multi_workspace_window,
 2689                    ..
 2690                } = task.await?;
 2691                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2692                    let workspace = multi_workspace.workspace().clone();
 2693                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2694                })
 2695            })
 2696        }
 2697    }
 2698
 2699    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2700    ///
 2701    /// If the given workspace has a local project, then it will be passed
 2702    /// to the callback. Otherwise, a new empty window will be created.
 2703    pub fn with_local_or_wsl_workspace<T, F>(
 2704        &mut self,
 2705        window: &mut Window,
 2706        cx: &mut Context<Self>,
 2707        callback: F,
 2708    ) -> Task<Result<T>>
 2709    where
 2710        T: 'static,
 2711        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2712    {
 2713        let project = self.project.read(cx);
 2714        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2715            Task::ready(Ok(callback(self, window, cx)))
 2716        } else {
 2717            let env = self.project.read(cx).cli_environment(cx);
 2718            let task = Self::new_local(
 2719                Vec::new(),
 2720                self.app_state.clone(),
 2721                None,
 2722                env,
 2723                None,
 2724                true,
 2725                cx,
 2726            );
 2727            cx.spawn_in(window, async move |_vh, cx| {
 2728                let OpenResult {
 2729                    window: multi_workspace_window,
 2730                    ..
 2731                } = task.await?;
 2732                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2733                    let workspace = multi_workspace.workspace().clone();
 2734                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2735                })
 2736            })
 2737        }
 2738    }
 2739
 2740    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2741        self.project.read(cx).worktrees(cx)
 2742    }
 2743
 2744    pub fn visible_worktrees<'a>(
 2745        &self,
 2746        cx: &'a App,
 2747    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2748        self.project.read(cx).visible_worktrees(cx)
 2749    }
 2750
 2751    #[cfg(any(test, feature = "test-support"))]
 2752    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2753        let futures = self
 2754            .worktrees(cx)
 2755            .filter_map(|worktree| worktree.read(cx).as_local())
 2756            .map(|worktree| worktree.scan_complete())
 2757            .collect::<Vec<_>>();
 2758        async move {
 2759            for future in futures {
 2760                future.await;
 2761            }
 2762        }
 2763    }
 2764
 2765    pub fn close_global(cx: &mut App) {
 2766        cx.defer(|cx| {
 2767            cx.windows().iter().find(|window| {
 2768                window
 2769                    .update(cx, |_, window, _| {
 2770                        if window.is_window_active() {
 2771                            //This can only get called when the window's project connection has been lost
 2772                            //so we don't need to prompt the user for anything and instead just close the window
 2773                            window.remove_window();
 2774                            true
 2775                        } else {
 2776                            false
 2777                        }
 2778                    })
 2779                    .unwrap_or(false)
 2780            });
 2781        });
 2782    }
 2783
 2784    pub fn move_focused_panel_to_next_position(
 2785        &mut self,
 2786        _: &MoveFocusedPanelToNextPosition,
 2787        window: &mut Window,
 2788        cx: &mut Context<Self>,
 2789    ) {
 2790        let docks = self.all_docks();
 2791        let active_dock = docks
 2792            .into_iter()
 2793            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2794
 2795        if let Some(dock) = active_dock {
 2796            dock.update(cx, |dock, cx| {
 2797                let active_panel = dock
 2798                    .active_panel()
 2799                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2800
 2801                if let Some(panel) = active_panel {
 2802                    panel.move_to_next_position(window, cx);
 2803                }
 2804            })
 2805        }
 2806    }
 2807
 2808    pub fn prepare_to_close(
 2809        &mut self,
 2810        close_intent: CloseIntent,
 2811        window: &mut Window,
 2812        cx: &mut Context<Self>,
 2813    ) -> Task<Result<bool>> {
 2814        let active_call = self.active_global_call();
 2815
 2816        cx.spawn_in(window, async move |this, cx| {
 2817            this.update(cx, |this, _| {
 2818                if close_intent == CloseIntent::CloseWindow {
 2819                    this.removing = true;
 2820                }
 2821            })?;
 2822
 2823            let workspace_count = cx.update(|_window, cx| {
 2824                cx.windows()
 2825                    .iter()
 2826                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2827                    .count()
 2828            })?;
 2829
 2830            #[cfg(target_os = "macos")]
 2831            let save_last_workspace = false;
 2832
 2833            // On Linux and Windows, closing the last window should restore the last workspace.
 2834            #[cfg(not(target_os = "macos"))]
 2835            let save_last_workspace = {
 2836                let remaining_workspaces = cx.update(|_window, cx| {
 2837                    cx.windows()
 2838                        .iter()
 2839                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2840                        .filter_map(|multi_workspace| {
 2841                            multi_workspace
 2842                                .update(cx, |multi_workspace, _, cx| {
 2843                                    multi_workspace.workspace().read(cx).removing
 2844                                })
 2845                                .ok()
 2846                        })
 2847                        .filter(|removing| !removing)
 2848                        .count()
 2849                })?;
 2850
 2851                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2852            };
 2853
 2854            if let Some(active_call) = active_call
 2855                && workspace_count == 1
 2856                && cx
 2857                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2858                    .unwrap_or(false)
 2859            {
 2860                if close_intent == CloseIntent::CloseWindow {
 2861                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2862                    let answer = cx.update(|window, cx| {
 2863                        window.prompt(
 2864                            PromptLevel::Warning,
 2865                            "Do you want to leave the current call?",
 2866                            None,
 2867                            &["Close window and hang up", "Cancel"],
 2868                            cx,
 2869                        )
 2870                    })?;
 2871
 2872                    if answer.await.log_err() == Some(1) {
 2873                        return anyhow::Ok(false);
 2874                    } else {
 2875                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2876                            task.await.log_err();
 2877                        }
 2878                    }
 2879                }
 2880                if close_intent == CloseIntent::ReplaceWindow {
 2881                    _ = cx.update(|_window, cx| {
 2882                        let multi_workspace = cx
 2883                            .windows()
 2884                            .iter()
 2885                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2886                            .next()
 2887                            .unwrap();
 2888                        let project = multi_workspace
 2889                            .read(cx)?
 2890                            .workspace()
 2891                            .read(cx)
 2892                            .project
 2893                            .clone();
 2894                        if project.read(cx).is_shared() {
 2895                            active_call.0.unshare_project(project, cx)?;
 2896                        }
 2897                        Ok::<_, anyhow::Error>(())
 2898                    });
 2899                }
 2900            }
 2901
 2902            let save_result = this
 2903                .update_in(cx, |this, window, cx| {
 2904                    this.save_all_internal(SaveIntent::Close, window, cx)
 2905                })?
 2906                .await;
 2907
 2908            // If we're not quitting, but closing, we remove the workspace from
 2909            // the current session.
 2910            if close_intent != CloseIntent::Quit
 2911                && !save_last_workspace
 2912                && save_result.as_ref().is_ok_and(|&res| res)
 2913            {
 2914                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2915                    .await;
 2916            }
 2917
 2918            save_result
 2919        })
 2920    }
 2921
 2922    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2923        self.save_all_internal(
 2924            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2925            window,
 2926            cx,
 2927        )
 2928        .detach_and_log_err(cx);
 2929    }
 2930
 2931    fn send_keystrokes(
 2932        &mut self,
 2933        action: &SendKeystrokes,
 2934        window: &mut Window,
 2935        cx: &mut Context<Self>,
 2936    ) {
 2937        let keystrokes: Vec<Keystroke> = action
 2938            .0
 2939            .split(' ')
 2940            .flat_map(|k| Keystroke::parse(k).log_err())
 2941            .map(|k| {
 2942                cx.keyboard_mapper()
 2943                    .map_key_equivalent(k, false)
 2944                    .inner()
 2945                    .clone()
 2946            })
 2947            .collect();
 2948        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2949    }
 2950
 2951    pub fn send_keystrokes_impl(
 2952        &mut self,
 2953        keystrokes: Vec<Keystroke>,
 2954        window: &mut Window,
 2955        cx: &mut Context<Self>,
 2956    ) -> Shared<Task<()>> {
 2957        let mut state = self.dispatching_keystrokes.borrow_mut();
 2958        if !state.dispatched.insert(keystrokes.clone()) {
 2959            cx.propagate();
 2960            return state.task.clone().unwrap();
 2961        }
 2962
 2963        state.queue.extend(keystrokes);
 2964
 2965        let keystrokes = self.dispatching_keystrokes.clone();
 2966        if state.task.is_none() {
 2967            state.task = Some(
 2968                window
 2969                    .spawn(cx, async move |cx| {
 2970                        // limit to 100 keystrokes to avoid infinite recursion.
 2971                        for _ in 0..100 {
 2972                            let keystroke = {
 2973                                let mut state = keystrokes.borrow_mut();
 2974                                let Some(keystroke) = state.queue.pop_front() else {
 2975                                    state.dispatched.clear();
 2976                                    state.task.take();
 2977                                    return;
 2978                                };
 2979                                keystroke
 2980                            };
 2981                            cx.update(|window, cx| {
 2982                                let focused = window.focused(cx);
 2983                                window.dispatch_keystroke(keystroke.clone(), cx);
 2984                                if window.focused(cx) != focused {
 2985                                    // dispatch_keystroke may cause the focus to change.
 2986                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2987                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2988                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2989                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2990                                    // )
 2991                                    window.draw(cx).clear();
 2992                                }
 2993                            })
 2994                            .ok();
 2995
 2996                            // Yield between synthetic keystrokes so deferred focus and
 2997                            // other effects can settle before dispatching the next key.
 2998                            yield_now().await;
 2999                        }
 3000
 3001                        *keystrokes.borrow_mut() = Default::default();
 3002                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3003                    })
 3004                    .shared(),
 3005            );
 3006        }
 3007        state.task.clone().unwrap()
 3008    }
 3009
 3010    fn save_all_internal(
 3011        &mut self,
 3012        mut save_intent: SaveIntent,
 3013        window: &mut Window,
 3014        cx: &mut Context<Self>,
 3015    ) -> Task<Result<bool>> {
 3016        if self.project.read(cx).is_disconnected(cx) {
 3017            return Task::ready(Ok(true));
 3018        }
 3019        let dirty_items = self
 3020            .panes
 3021            .iter()
 3022            .flat_map(|pane| {
 3023                pane.read(cx).items().filter_map(|item| {
 3024                    if item.is_dirty(cx) {
 3025                        item.tab_content_text(0, cx);
 3026                        Some((pane.downgrade(), item.boxed_clone()))
 3027                    } else {
 3028                        None
 3029                    }
 3030                })
 3031            })
 3032            .collect::<Vec<_>>();
 3033
 3034        let project = self.project.clone();
 3035        cx.spawn_in(window, async move |workspace, cx| {
 3036            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3037                let (serialize_tasks, remaining_dirty_items) =
 3038                    workspace.update_in(cx, |workspace, window, cx| {
 3039                        let mut remaining_dirty_items = Vec::new();
 3040                        let mut serialize_tasks = Vec::new();
 3041                        for (pane, item) in dirty_items {
 3042                            if let Some(task) = item
 3043                                .to_serializable_item_handle(cx)
 3044                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3045                            {
 3046                                serialize_tasks.push(task);
 3047                            } else {
 3048                                remaining_dirty_items.push((pane, item));
 3049                            }
 3050                        }
 3051                        (serialize_tasks, remaining_dirty_items)
 3052                    })?;
 3053
 3054                futures::future::try_join_all(serialize_tasks).await?;
 3055
 3056                if !remaining_dirty_items.is_empty() {
 3057                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3058                }
 3059
 3060                if remaining_dirty_items.len() > 1 {
 3061                    let answer = workspace.update_in(cx, |_, window, cx| {
 3062                        let detail = Pane::file_names_for_prompt(
 3063                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3064                            cx,
 3065                        );
 3066                        window.prompt(
 3067                            PromptLevel::Warning,
 3068                            "Do you want to save all changes in the following files?",
 3069                            Some(&detail),
 3070                            &["Save all", "Discard all", "Cancel"],
 3071                            cx,
 3072                        )
 3073                    })?;
 3074                    match answer.await.log_err() {
 3075                        Some(0) => save_intent = SaveIntent::SaveAll,
 3076                        Some(1) => save_intent = SaveIntent::Skip,
 3077                        Some(2) => return Ok(false),
 3078                        _ => {}
 3079                    }
 3080                }
 3081
 3082                remaining_dirty_items
 3083            } else {
 3084                dirty_items
 3085            };
 3086
 3087            for (pane, item) in dirty_items {
 3088                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3089                    (
 3090                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3091                        item.project_entry_ids(cx),
 3092                    )
 3093                })?;
 3094                if (singleton || !project_entry_ids.is_empty())
 3095                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3096                {
 3097                    return Ok(false);
 3098                }
 3099            }
 3100            Ok(true)
 3101        })
 3102    }
 3103
 3104    pub fn open_workspace_for_paths(
 3105        &mut self,
 3106        replace_current_window: bool,
 3107        paths: Vec<PathBuf>,
 3108        window: &mut Window,
 3109        cx: &mut Context<Self>,
 3110    ) -> Task<Result<Entity<Workspace>>> {
 3111        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3112        let is_remote = self.project.read(cx).is_via_collab();
 3113        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3114        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3115
 3116        let window_to_replace = if replace_current_window {
 3117            window_handle
 3118        } else if is_remote || has_worktree || has_dirty_items {
 3119            None
 3120        } else {
 3121            window_handle
 3122        };
 3123        let app_state = self.app_state.clone();
 3124
 3125        cx.spawn(async move |_, cx| {
 3126            let OpenResult { workspace, .. } = cx
 3127                .update(|cx| {
 3128                    open_paths(
 3129                        &paths,
 3130                        app_state,
 3131                        OpenOptions {
 3132                            replace_window: window_to_replace,
 3133                            ..Default::default()
 3134                        },
 3135                        cx,
 3136                    )
 3137                })
 3138                .await?;
 3139            Ok(workspace)
 3140        })
 3141    }
 3142
 3143    #[allow(clippy::type_complexity)]
 3144    pub fn open_paths(
 3145        &mut self,
 3146        mut abs_paths: Vec<PathBuf>,
 3147        options: OpenOptions,
 3148        pane: Option<WeakEntity<Pane>>,
 3149        window: &mut Window,
 3150        cx: &mut Context<Self>,
 3151    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3152        let fs = self.app_state.fs.clone();
 3153
 3154        let caller_ordered_abs_paths = abs_paths.clone();
 3155
 3156        // Sort the paths to ensure we add worktrees for parents before their children.
 3157        abs_paths.sort_unstable();
 3158        cx.spawn_in(window, async move |this, cx| {
 3159            let mut tasks = Vec::with_capacity(abs_paths.len());
 3160
 3161            for abs_path in &abs_paths {
 3162                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3163                    OpenVisible::All => Some(true),
 3164                    OpenVisible::None => Some(false),
 3165                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3166                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3167                        Some(None) => Some(true),
 3168                        None => None,
 3169                    },
 3170                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3171                        Some(Some(metadata)) => Some(metadata.is_dir),
 3172                        Some(None) => Some(false),
 3173                        None => None,
 3174                    },
 3175                };
 3176                let project_path = match visible {
 3177                    Some(visible) => match this
 3178                        .update(cx, |this, cx| {
 3179                            Workspace::project_path_for_path(
 3180                                this.project.clone(),
 3181                                abs_path,
 3182                                visible,
 3183                                cx,
 3184                            )
 3185                        })
 3186                        .log_err()
 3187                    {
 3188                        Some(project_path) => project_path.await.log_err(),
 3189                        None => None,
 3190                    },
 3191                    None => None,
 3192                };
 3193
 3194                let this = this.clone();
 3195                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3196                let fs = fs.clone();
 3197                let pane = pane.clone();
 3198                let task = cx.spawn(async move |cx| {
 3199                    let (_worktree, project_path) = project_path?;
 3200                    if fs.is_dir(&abs_path).await {
 3201                        // Opening a directory should not race to update the active entry.
 3202                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3203                        None
 3204                    } else {
 3205                        Some(
 3206                            this.update_in(cx, |this, window, cx| {
 3207                                this.open_path(
 3208                                    project_path,
 3209                                    pane,
 3210                                    options.focus.unwrap_or(true),
 3211                                    window,
 3212                                    cx,
 3213                                )
 3214                            })
 3215                            .ok()?
 3216                            .await,
 3217                        )
 3218                    }
 3219                });
 3220                tasks.push(task);
 3221            }
 3222
 3223            let results = futures::future::join_all(tasks).await;
 3224
 3225            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3226            let mut winner: Option<(PathBuf, bool)> = None;
 3227            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3228                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3229                    if !metadata.is_dir {
 3230                        winner = Some((abs_path, false));
 3231                        break;
 3232                    }
 3233                    if winner.is_none() {
 3234                        winner = Some((abs_path, true));
 3235                    }
 3236                } else if winner.is_none() {
 3237                    winner = Some((abs_path, false));
 3238                }
 3239            }
 3240
 3241            // Compute the winner entry id on the foreground thread and emit once, after all
 3242            // paths finish opening. This avoids races between concurrently-opening paths
 3243            // (directories in particular) and makes the resulting project panel selection
 3244            // deterministic.
 3245            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3246                'emit_winner: {
 3247                    let winner_abs_path: Arc<Path> =
 3248                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3249
 3250                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3251                        OpenVisible::All => true,
 3252                        OpenVisible::None => false,
 3253                        OpenVisible::OnlyFiles => !winner_is_dir,
 3254                        OpenVisible::OnlyDirectories => winner_is_dir,
 3255                    };
 3256
 3257                    let Some(worktree_task) = this
 3258                        .update(cx, |workspace, cx| {
 3259                            workspace.project.update(cx, |project, cx| {
 3260                                project.find_or_create_worktree(
 3261                                    winner_abs_path.as_ref(),
 3262                                    visible,
 3263                                    cx,
 3264                                )
 3265                            })
 3266                        })
 3267                        .ok()
 3268                    else {
 3269                        break 'emit_winner;
 3270                    };
 3271
 3272                    let Ok((worktree, _)) = worktree_task.await else {
 3273                        break 'emit_winner;
 3274                    };
 3275
 3276                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3277                        let worktree = worktree.read(cx);
 3278                        let worktree_abs_path = worktree.abs_path();
 3279                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3280                            worktree.root_entry()
 3281                        } else {
 3282                            winner_abs_path
 3283                                .strip_prefix(worktree_abs_path.as_ref())
 3284                                .ok()
 3285                                .and_then(|relative_path| {
 3286                                    let relative_path =
 3287                                        RelPath::new(relative_path, PathStyle::local())
 3288                                            .log_err()?;
 3289                                    worktree.entry_for_path(&relative_path)
 3290                                })
 3291                        }?;
 3292                        Some(entry.id)
 3293                    }) else {
 3294                        break 'emit_winner;
 3295                    };
 3296
 3297                    this.update(cx, |workspace, cx| {
 3298                        workspace.project.update(cx, |_, cx| {
 3299                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3300                        });
 3301                    })
 3302                    .ok();
 3303                }
 3304            }
 3305
 3306            results
 3307        })
 3308    }
 3309
 3310    pub fn open_resolved_path(
 3311        &mut self,
 3312        path: ResolvedPath,
 3313        window: &mut Window,
 3314        cx: &mut Context<Self>,
 3315    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3316        match path {
 3317            ResolvedPath::ProjectPath { project_path, .. } => {
 3318                self.open_path(project_path, None, true, window, cx)
 3319            }
 3320            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3321                PathBuf::from(path),
 3322                OpenOptions {
 3323                    visible: Some(OpenVisible::None),
 3324                    ..Default::default()
 3325                },
 3326                window,
 3327                cx,
 3328            ),
 3329        }
 3330    }
 3331
 3332    pub fn absolute_path_of_worktree(
 3333        &self,
 3334        worktree_id: WorktreeId,
 3335        cx: &mut Context<Self>,
 3336    ) -> Option<PathBuf> {
 3337        self.project
 3338            .read(cx)
 3339            .worktree_for_id(worktree_id, cx)
 3340            // TODO: use `abs_path` or `root_dir`
 3341            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3342    }
 3343
 3344    fn add_folder_to_project(
 3345        &mut self,
 3346        _: &AddFolderToProject,
 3347        window: &mut Window,
 3348        cx: &mut Context<Self>,
 3349    ) {
 3350        let project = self.project.read(cx);
 3351        if project.is_via_collab() {
 3352            self.show_error(
 3353                &anyhow!("You cannot add folders to someone else's project"),
 3354                cx,
 3355            );
 3356            return;
 3357        }
 3358        let paths = self.prompt_for_open_path(
 3359            PathPromptOptions {
 3360                files: false,
 3361                directories: true,
 3362                multiple: true,
 3363                prompt: None,
 3364            },
 3365            DirectoryLister::Project(self.project.clone()),
 3366            window,
 3367            cx,
 3368        );
 3369        cx.spawn_in(window, async move |this, cx| {
 3370            if let Some(paths) = paths.await.log_err().flatten() {
 3371                let results = this
 3372                    .update_in(cx, |this, window, cx| {
 3373                        this.open_paths(
 3374                            paths,
 3375                            OpenOptions {
 3376                                visible: Some(OpenVisible::All),
 3377                                ..Default::default()
 3378                            },
 3379                            None,
 3380                            window,
 3381                            cx,
 3382                        )
 3383                    })?
 3384                    .await;
 3385                for result in results.into_iter().flatten() {
 3386                    result.log_err();
 3387                }
 3388            }
 3389            anyhow::Ok(())
 3390        })
 3391        .detach_and_log_err(cx);
 3392    }
 3393
 3394    pub fn project_path_for_path(
 3395        project: Entity<Project>,
 3396        abs_path: &Path,
 3397        visible: bool,
 3398        cx: &mut App,
 3399    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3400        let entry = project.update(cx, |project, cx| {
 3401            project.find_or_create_worktree(abs_path, visible, cx)
 3402        });
 3403        cx.spawn(async move |cx| {
 3404            let (worktree, path) = entry.await?;
 3405            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3406            Ok((worktree, ProjectPath { worktree_id, path }))
 3407        })
 3408    }
 3409
 3410    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3411        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3412    }
 3413
 3414    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3415        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3416    }
 3417
 3418    pub fn items_of_type<'a, T: Item>(
 3419        &'a self,
 3420        cx: &'a App,
 3421    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3422        self.panes
 3423            .iter()
 3424            .flat_map(|pane| pane.read(cx).items_of_type())
 3425    }
 3426
 3427    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3428        self.active_pane().read(cx).active_item()
 3429    }
 3430
 3431    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3432        let item = self.active_item(cx)?;
 3433        item.to_any_view().downcast::<I>().ok()
 3434    }
 3435
 3436    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3437        self.active_item(cx).and_then(|item| item.project_path(cx))
 3438    }
 3439
 3440    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3441        self.recent_navigation_history_iter(cx)
 3442            .filter_map(|(path, abs_path)| {
 3443                let worktree = self
 3444                    .project
 3445                    .read(cx)
 3446                    .worktree_for_id(path.worktree_id, cx)?;
 3447                if worktree.read(cx).is_visible() {
 3448                    abs_path
 3449                } else {
 3450                    None
 3451                }
 3452            })
 3453            .next()
 3454    }
 3455
 3456    pub fn save_active_item(
 3457        &mut self,
 3458        save_intent: SaveIntent,
 3459        window: &mut Window,
 3460        cx: &mut App,
 3461    ) -> Task<Result<()>> {
 3462        let project = self.project.clone();
 3463        let pane = self.active_pane();
 3464        let item = pane.read(cx).active_item();
 3465        let pane = pane.downgrade();
 3466
 3467        window.spawn(cx, async move |cx| {
 3468            if let Some(item) = item {
 3469                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3470                    .await
 3471                    .map(|_| ())
 3472            } else {
 3473                Ok(())
 3474            }
 3475        })
 3476    }
 3477
 3478    pub fn close_inactive_items_and_panes(
 3479        &mut self,
 3480        action: &CloseInactiveTabsAndPanes,
 3481        window: &mut Window,
 3482        cx: &mut Context<Self>,
 3483    ) {
 3484        if let Some(task) = self.close_all_internal(
 3485            true,
 3486            action.save_intent.unwrap_or(SaveIntent::Close),
 3487            window,
 3488            cx,
 3489        ) {
 3490            task.detach_and_log_err(cx)
 3491        }
 3492    }
 3493
 3494    pub fn close_all_items_and_panes(
 3495        &mut self,
 3496        action: &CloseAllItemsAndPanes,
 3497        window: &mut Window,
 3498        cx: &mut Context<Self>,
 3499    ) {
 3500        if let Some(task) = self.close_all_internal(
 3501            false,
 3502            action.save_intent.unwrap_or(SaveIntent::Close),
 3503            window,
 3504            cx,
 3505        ) {
 3506            task.detach_and_log_err(cx)
 3507        }
 3508    }
 3509
 3510    /// Closes the active item across all panes.
 3511    pub fn close_item_in_all_panes(
 3512        &mut self,
 3513        action: &CloseItemInAllPanes,
 3514        window: &mut Window,
 3515        cx: &mut Context<Self>,
 3516    ) {
 3517        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3518            return;
 3519        };
 3520
 3521        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3522        let close_pinned = action.close_pinned;
 3523
 3524        if let Some(project_path) = active_item.project_path(cx) {
 3525            self.close_items_with_project_path(
 3526                &project_path,
 3527                save_intent,
 3528                close_pinned,
 3529                window,
 3530                cx,
 3531            );
 3532        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3533            let item_id = active_item.item_id();
 3534            self.active_pane().update(cx, |pane, cx| {
 3535                pane.close_item_by_id(item_id, save_intent, window, cx)
 3536                    .detach_and_log_err(cx);
 3537            });
 3538        }
 3539    }
 3540
 3541    /// Closes all items with the given project path across all panes.
 3542    pub fn close_items_with_project_path(
 3543        &mut self,
 3544        project_path: &ProjectPath,
 3545        save_intent: SaveIntent,
 3546        close_pinned: bool,
 3547        window: &mut Window,
 3548        cx: &mut Context<Self>,
 3549    ) {
 3550        let panes = self.panes().to_vec();
 3551        for pane in panes {
 3552            pane.update(cx, |pane, cx| {
 3553                pane.close_items_for_project_path(
 3554                    project_path,
 3555                    save_intent,
 3556                    close_pinned,
 3557                    window,
 3558                    cx,
 3559                )
 3560                .detach_and_log_err(cx);
 3561            });
 3562        }
 3563    }
 3564
 3565    fn close_all_internal(
 3566        &mut self,
 3567        retain_active_pane: bool,
 3568        save_intent: SaveIntent,
 3569        window: &mut Window,
 3570        cx: &mut Context<Self>,
 3571    ) -> Option<Task<Result<()>>> {
 3572        let current_pane = self.active_pane();
 3573
 3574        let mut tasks = Vec::new();
 3575
 3576        if retain_active_pane {
 3577            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3578                pane.close_other_items(
 3579                    &CloseOtherItems {
 3580                        save_intent: None,
 3581                        close_pinned: false,
 3582                    },
 3583                    None,
 3584                    window,
 3585                    cx,
 3586                )
 3587            });
 3588
 3589            tasks.push(current_pane_close);
 3590        }
 3591
 3592        for pane in self.panes() {
 3593            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3594                continue;
 3595            }
 3596
 3597            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3598                pane.close_all_items(
 3599                    &CloseAllItems {
 3600                        save_intent: Some(save_intent),
 3601                        close_pinned: false,
 3602                    },
 3603                    window,
 3604                    cx,
 3605                )
 3606            });
 3607
 3608            tasks.push(close_pane_items)
 3609        }
 3610
 3611        if tasks.is_empty() {
 3612            None
 3613        } else {
 3614            Some(cx.spawn_in(window, async move |_, _| {
 3615                for task in tasks {
 3616                    task.await?
 3617                }
 3618                Ok(())
 3619            }))
 3620        }
 3621    }
 3622
 3623    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3624        self.dock_at_position(position).read(cx).is_open()
 3625    }
 3626
 3627    pub fn toggle_dock(
 3628        &mut self,
 3629        dock_side: DockPosition,
 3630        window: &mut Window,
 3631        cx: &mut Context<Self>,
 3632    ) {
 3633        let mut focus_center = false;
 3634        let mut reveal_dock = false;
 3635
 3636        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3637        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3638
 3639        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3640            telemetry::event!(
 3641                "Panel Button Clicked",
 3642                name = panel.persistent_name(),
 3643                toggle_state = !was_visible
 3644            );
 3645        }
 3646        if was_visible {
 3647            self.save_open_dock_positions(cx);
 3648        }
 3649
 3650        let dock = self.dock_at_position(dock_side);
 3651        dock.update(cx, |dock, cx| {
 3652            dock.set_open(!was_visible, window, cx);
 3653
 3654            if dock.active_panel().is_none() {
 3655                let Some(panel_ix) = dock
 3656                    .first_enabled_panel_idx(cx)
 3657                    .log_with_level(log::Level::Info)
 3658                else {
 3659                    return;
 3660                };
 3661                dock.activate_panel(panel_ix, window, cx);
 3662            }
 3663
 3664            if let Some(active_panel) = dock.active_panel() {
 3665                if was_visible {
 3666                    if active_panel
 3667                        .panel_focus_handle(cx)
 3668                        .contains_focused(window, cx)
 3669                    {
 3670                        focus_center = true;
 3671                    }
 3672                } else {
 3673                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3674                    window.focus(focus_handle, cx);
 3675                    reveal_dock = true;
 3676                }
 3677            }
 3678        });
 3679
 3680        if reveal_dock {
 3681            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3682        }
 3683
 3684        if focus_center {
 3685            self.active_pane
 3686                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3687        }
 3688
 3689        cx.notify();
 3690        self.serialize_workspace(window, cx);
 3691    }
 3692
 3693    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3694        self.all_docks().into_iter().find(|&dock| {
 3695            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3696        })
 3697    }
 3698
 3699    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3700        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3701            self.save_open_dock_positions(cx);
 3702            dock.update(cx, |dock, cx| {
 3703                dock.set_open(false, window, cx);
 3704            });
 3705            return true;
 3706        }
 3707        false
 3708    }
 3709
 3710    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3711        self.save_open_dock_positions(cx);
 3712        for dock in self.all_docks() {
 3713            dock.update(cx, |dock, cx| {
 3714                dock.set_open(false, window, cx);
 3715            });
 3716        }
 3717
 3718        cx.focus_self(window);
 3719        cx.notify();
 3720        self.serialize_workspace(window, cx);
 3721    }
 3722
 3723    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3724        self.all_docks()
 3725            .into_iter()
 3726            .filter_map(|dock| {
 3727                let dock_ref = dock.read(cx);
 3728                if dock_ref.is_open() {
 3729                    Some(dock_ref.position())
 3730                } else {
 3731                    None
 3732                }
 3733            })
 3734            .collect()
 3735    }
 3736
 3737    /// Saves the positions of currently open docks.
 3738    ///
 3739    /// Updates `last_open_dock_positions` with positions of all currently open
 3740    /// docks, to later be restored by the 'Toggle All Docks' action.
 3741    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3742        let open_dock_positions = self.get_open_dock_positions(cx);
 3743        if !open_dock_positions.is_empty() {
 3744            self.last_open_dock_positions = open_dock_positions;
 3745        }
 3746    }
 3747
 3748    /// Toggles all docks between open and closed states.
 3749    ///
 3750    /// If any docks are open, closes all and remembers their positions. If all
 3751    /// docks are closed, restores the last remembered dock configuration.
 3752    fn toggle_all_docks(
 3753        &mut self,
 3754        _: &ToggleAllDocks,
 3755        window: &mut Window,
 3756        cx: &mut Context<Self>,
 3757    ) {
 3758        let open_dock_positions = self.get_open_dock_positions(cx);
 3759
 3760        if !open_dock_positions.is_empty() {
 3761            self.close_all_docks(window, cx);
 3762        } else if !self.last_open_dock_positions.is_empty() {
 3763            self.restore_last_open_docks(window, cx);
 3764        }
 3765    }
 3766
 3767    /// Reopens docks from the most recently remembered configuration.
 3768    ///
 3769    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3770    /// and clears the stored positions.
 3771    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3772        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3773
 3774        for position in positions_to_open {
 3775            let dock = self.dock_at_position(position);
 3776            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3777        }
 3778
 3779        cx.focus_self(window);
 3780        cx.notify();
 3781        self.serialize_workspace(window, cx);
 3782    }
 3783
 3784    /// Transfer focus to the panel of the given type.
 3785    pub fn focus_panel<T: Panel>(
 3786        &mut self,
 3787        window: &mut Window,
 3788        cx: &mut Context<Self>,
 3789    ) -> Option<Entity<T>> {
 3790        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3791        panel.to_any().downcast().ok()
 3792    }
 3793
 3794    /// Focus the panel of the given type if it isn't already focused. If it is
 3795    /// already focused, then transfer focus back to the workspace center.
 3796    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3797    /// panel when transferring focus back to the center.
 3798    pub fn toggle_panel_focus<T: Panel>(
 3799        &mut self,
 3800        window: &mut Window,
 3801        cx: &mut Context<Self>,
 3802    ) -> bool {
 3803        let mut did_focus_panel = false;
 3804        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3805            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3806            did_focus_panel
 3807        });
 3808
 3809        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3810            self.close_panel::<T>(window, cx);
 3811        }
 3812
 3813        telemetry::event!(
 3814            "Panel Button Clicked",
 3815            name = T::persistent_name(),
 3816            toggle_state = did_focus_panel
 3817        );
 3818
 3819        did_focus_panel
 3820    }
 3821
 3822    pub fn activate_panel_for_proto_id(
 3823        &mut self,
 3824        panel_id: PanelId,
 3825        window: &mut Window,
 3826        cx: &mut Context<Self>,
 3827    ) -> Option<Arc<dyn PanelHandle>> {
 3828        let mut panel = None;
 3829        for dock in self.all_docks() {
 3830            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3831                panel = dock.update(cx, |dock, cx| {
 3832                    dock.activate_panel(panel_index, window, cx);
 3833                    dock.set_open(true, window, cx);
 3834                    dock.active_panel().cloned()
 3835                });
 3836                break;
 3837            }
 3838        }
 3839
 3840        if panel.is_some() {
 3841            cx.notify();
 3842            self.serialize_workspace(window, cx);
 3843        }
 3844
 3845        panel
 3846    }
 3847
 3848    /// Focus or unfocus the given panel type, depending on the given callback.
 3849    fn focus_or_unfocus_panel<T: Panel>(
 3850        &mut self,
 3851        window: &mut Window,
 3852        cx: &mut Context<Self>,
 3853        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3854    ) -> Option<Arc<dyn PanelHandle>> {
 3855        let mut result_panel = None;
 3856        let mut serialize = false;
 3857        for dock in self.all_docks() {
 3858            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3859                let mut focus_center = false;
 3860                let panel = dock.update(cx, |dock, cx| {
 3861                    dock.activate_panel(panel_index, window, cx);
 3862
 3863                    let panel = dock.active_panel().cloned();
 3864                    if let Some(panel) = panel.as_ref() {
 3865                        if should_focus(&**panel, window, cx) {
 3866                            dock.set_open(true, window, cx);
 3867                            panel.panel_focus_handle(cx).focus(window, cx);
 3868                        } else {
 3869                            focus_center = true;
 3870                        }
 3871                    }
 3872                    panel
 3873                });
 3874
 3875                if focus_center {
 3876                    self.active_pane
 3877                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3878                }
 3879
 3880                result_panel = panel;
 3881                serialize = true;
 3882                break;
 3883            }
 3884        }
 3885
 3886        if serialize {
 3887            self.serialize_workspace(window, cx);
 3888        }
 3889
 3890        cx.notify();
 3891        result_panel
 3892    }
 3893
 3894    /// Open the panel of the given type
 3895    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3896        for dock in self.all_docks() {
 3897            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3898                dock.update(cx, |dock, cx| {
 3899                    dock.activate_panel(panel_index, window, cx);
 3900                    dock.set_open(true, window, cx);
 3901                });
 3902            }
 3903        }
 3904    }
 3905
 3906    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3907        for dock in self.all_docks().iter() {
 3908            dock.update(cx, |dock, cx| {
 3909                if dock.panel::<T>().is_some() {
 3910                    dock.set_open(false, window, cx)
 3911                }
 3912            })
 3913        }
 3914    }
 3915
 3916    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3917        self.all_docks()
 3918            .iter()
 3919            .find_map(|dock| dock.read(cx).panel::<T>())
 3920    }
 3921
 3922    fn dismiss_zoomed_items_to_reveal(
 3923        &mut self,
 3924        dock_to_reveal: Option<DockPosition>,
 3925        window: &mut Window,
 3926        cx: &mut Context<Self>,
 3927    ) {
 3928        // If a center pane is zoomed, unzoom it.
 3929        for pane in &self.panes {
 3930            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3931                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3932            }
 3933        }
 3934
 3935        // If another dock is zoomed, hide it.
 3936        let mut focus_center = false;
 3937        for dock in self.all_docks() {
 3938            dock.update(cx, |dock, cx| {
 3939                if Some(dock.position()) != dock_to_reveal
 3940                    && let Some(panel) = dock.active_panel()
 3941                    && panel.is_zoomed(window, cx)
 3942                {
 3943                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3944                    dock.set_open(false, window, cx);
 3945                }
 3946            });
 3947        }
 3948
 3949        if focus_center {
 3950            self.active_pane
 3951                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3952        }
 3953
 3954        if self.zoomed_position != dock_to_reveal {
 3955            self.zoomed = None;
 3956            self.zoomed_position = None;
 3957            cx.emit(Event::ZoomChanged);
 3958        }
 3959
 3960        cx.notify();
 3961    }
 3962
 3963    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3964        let pane = cx.new(|cx| {
 3965            let mut pane = Pane::new(
 3966                self.weak_handle(),
 3967                self.project.clone(),
 3968                self.pane_history_timestamp.clone(),
 3969                None,
 3970                NewFile.boxed_clone(),
 3971                true,
 3972                window,
 3973                cx,
 3974            );
 3975            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3976            pane
 3977        });
 3978        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3979            .detach();
 3980        self.panes.push(pane.clone());
 3981
 3982        window.focus(&pane.focus_handle(cx), cx);
 3983
 3984        cx.emit(Event::PaneAdded(pane.clone()));
 3985        pane
 3986    }
 3987
 3988    pub fn add_item_to_center(
 3989        &mut self,
 3990        item: Box<dyn ItemHandle>,
 3991        window: &mut Window,
 3992        cx: &mut Context<Self>,
 3993    ) -> bool {
 3994        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3995            if let Some(center_pane) = center_pane.upgrade() {
 3996                center_pane.update(cx, |pane, cx| {
 3997                    pane.add_item(item, true, true, None, window, cx)
 3998                });
 3999                true
 4000            } else {
 4001                false
 4002            }
 4003        } else {
 4004            false
 4005        }
 4006    }
 4007
 4008    pub fn add_item_to_active_pane(
 4009        &mut self,
 4010        item: Box<dyn ItemHandle>,
 4011        destination_index: Option<usize>,
 4012        focus_item: bool,
 4013        window: &mut Window,
 4014        cx: &mut App,
 4015    ) {
 4016        self.add_item(
 4017            self.active_pane.clone(),
 4018            item,
 4019            destination_index,
 4020            false,
 4021            focus_item,
 4022            window,
 4023            cx,
 4024        )
 4025    }
 4026
 4027    pub fn add_item(
 4028        &mut self,
 4029        pane: Entity<Pane>,
 4030        item: Box<dyn ItemHandle>,
 4031        destination_index: Option<usize>,
 4032        activate_pane: bool,
 4033        focus_item: bool,
 4034        window: &mut Window,
 4035        cx: &mut App,
 4036    ) {
 4037        pane.update(cx, |pane, cx| {
 4038            pane.add_item(
 4039                item,
 4040                activate_pane,
 4041                focus_item,
 4042                destination_index,
 4043                window,
 4044                cx,
 4045            )
 4046        });
 4047    }
 4048
 4049    pub fn split_item(
 4050        &mut self,
 4051        split_direction: SplitDirection,
 4052        item: Box<dyn ItemHandle>,
 4053        window: &mut Window,
 4054        cx: &mut Context<Self>,
 4055    ) {
 4056        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4057        self.add_item(new_pane, item, None, true, true, window, cx);
 4058    }
 4059
 4060    pub fn open_abs_path(
 4061        &mut self,
 4062        abs_path: PathBuf,
 4063        options: OpenOptions,
 4064        window: &mut Window,
 4065        cx: &mut Context<Self>,
 4066    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4067        cx.spawn_in(window, async move |workspace, cx| {
 4068            let open_paths_task_result = workspace
 4069                .update_in(cx, |workspace, window, cx| {
 4070                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4071                })
 4072                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4073                .await;
 4074            anyhow::ensure!(
 4075                open_paths_task_result.len() == 1,
 4076                "open abs path {abs_path:?} task returned incorrect number of results"
 4077            );
 4078            match open_paths_task_result
 4079                .into_iter()
 4080                .next()
 4081                .expect("ensured single task result")
 4082            {
 4083                Some(open_result) => {
 4084                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4085                }
 4086                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4087            }
 4088        })
 4089    }
 4090
 4091    pub fn split_abs_path(
 4092        &mut self,
 4093        abs_path: PathBuf,
 4094        visible: bool,
 4095        window: &mut Window,
 4096        cx: &mut Context<Self>,
 4097    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4098        let project_path_task =
 4099            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4100        cx.spawn_in(window, async move |this, cx| {
 4101            let (_, path) = project_path_task.await?;
 4102            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4103                .await
 4104        })
 4105    }
 4106
 4107    pub fn open_path(
 4108        &mut self,
 4109        path: impl Into<ProjectPath>,
 4110        pane: Option<WeakEntity<Pane>>,
 4111        focus_item: bool,
 4112        window: &mut Window,
 4113        cx: &mut App,
 4114    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4115        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4116    }
 4117
 4118    pub fn open_path_preview(
 4119        &mut self,
 4120        path: impl Into<ProjectPath>,
 4121        pane: Option<WeakEntity<Pane>>,
 4122        focus_item: bool,
 4123        allow_preview: bool,
 4124        activate: bool,
 4125        window: &mut Window,
 4126        cx: &mut App,
 4127    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4128        let pane = pane.unwrap_or_else(|| {
 4129            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4130                self.panes
 4131                    .first()
 4132                    .expect("There must be an active pane")
 4133                    .downgrade()
 4134            })
 4135        });
 4136
 4137        let project_path = path.into();
 4138        let task = self.load_path(project_path.clone(), window, cx);
 4139        window.spawn(cx, async move |cx| {
 4140            let (project_entry_id, build_item) = task.await?;
 4141
 4142            pane.update_in(cx, |pane, window, cx| {
 4143                pane.open_item(
 4144                    project_entry_id,
 4145                    project_path,
 4146                    focus_item,
 4147                    allow_preview,
 4148                    activate,
 4149                    None,
 4150                    window,
 4151                    cx,
 4152                    build_item,
 4153                )
 4154            })
 4155        })
 4156    }
 4157
 4158    pub fn split_path(
 4159        &mut self,
 4160        path: impl Into<ProjectPath>,
 4161        window: &mut Window,
 4162        cx: &mut Context<Self>,
 4163    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4164        self.split_path_preview(path, false, None, window, cx)
 4165    }
 4166
 4167    pub fn split_path_preview(
 4168        &mut self,
 4169        path: impl Into<ProjectPath>,
 4170        allow_preview: bool,
 4171        split_direction: Option<SplitDirection>,
 4172        window: &mut Window,
 4173        cx: &mut Context<Self>,
 4174    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4175        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4176            self.panes
 4177                .first()
 4178                .expect("There must be an active pane")
 4179                .downgrade()
 4180        });
 4181
 4182        if let Member::Pane(center_pane) = &self.center.root
 4183            && center_pane.read(cx).items_len() == 0
 4184        {
 4185            return self.open_path(path, Some(pane), true, window, cx);
 4186        }
 4187
 4188        let project_path = path.into();
 4189        let task = self.load_path(project_path.clone(), window, cx);
 4190        cx.spawn_in(window, async move |this, cx| {
 4191            let (project_entry_id, build_item) = task.await?;
 4192            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4193                let pane = pane.upgrade()?;
 4194                let new_pane = this.split_pane(
 4195                    pane,
 4196                    split_direction.unwrap_or(SplitDirection::Right),
 4197                    window,
 4198                    cx,
 4199                );
 4200                new_pane.update(cx, |new_pane, cx| {
 4201                    Some(new_pane.open_item(
 4202                        project_entry_id,
 4203                        project_path,
 4204                        true,
 4205                        allow_preview,
 4206                        true,
 4207                        None,
 4208                        window,
 4209                        cx,
 4210                        build_item,
 4211                    ))
 4212                })
 4213            })
 4214            .map(|option| option.context("pane was dropped"))?
 4215        })
 4216    }
 4217
 4218    fn load_path(
 4219        &mut self,
 4220        path: ProjectPath,
 4221        window: &mut Window,
 4222        cx: &mut App,
 4223    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4224        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4225        registry.open_path(self.project(), &path, window, cx)
 4226    }
 4227
 4228    pub fn find_project_item<T>(
 4229        &self,
 4230        pane: &Entity<Pane>,
 4231        project_item: &Entity<T::Item>,
 4232        cx: &App,
 4233    ) -> Option<Entity<T>>
 4234    where
 4235        T: ProjectItem,
 4236    {
 4237        use project::ProjectItem as _;
 4238        let project_item = project_item.read(cx);
 4239        let entry_id = project_item.entry_id(cx);
 4240        let project_path = project_item.project_path(cx);
 4241
 4242        let mut item = None;
 4243        if let Some(entry_id) = entry_id {
 4244            item = pane.read(cx).item_for_entry(entry_id, cx);
 4245        }
 4246        if item.is_none()
 4247            && let Some(project_path) = project_path
 4248        {
 4249            item = pane.read(cx).item_for_path(project_path, cx);
 4250        }
 4251
 4252        item.and_then(|item| item.downcast::<T>())
 4253    }
 4254
 4255    pub fn is_project_item_open<T>(
 4256        &self,
 4257        pane: &Entity<Pane>,
 4258        project_item: &Entity<T::Item>,
 4259        cx: &App,
 4260    ) -> bool
 4261    where
 4262        T: ProjectItem,
 4263    {
 4264        self.find_project_item::<T>(pane, project_item, cx)
 4265            .is_some()
 4266    }
 4267
 4268    pub fn open_project_item<T>(
 4269        &mut self,
 4270        pane: Entity<Pane>,
 4271        project_item: Entity<T::Item>,
 4272        activate_pane: bool,
 4273        focus_item: bool,
 4274        keep_old_preview: bool,
 4275        allow_new_preview: bool,
 4276        window: &mut Window,
 4277        cx: &mut Context<Self>,
 4278    ) -> Entity<T>
 4279    where
 4280        T: ProjectItem,
 4281    {
 4282        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4283
 4284        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4285            if !keep_old_preview
 4286                && let Some(old_id) = old_item_id
 4287                && old_id != item.item_id()
 4288            {
 4289                // switching to a different item, so unpreview old active item
 4290                pane.update(cx, |pane, _| {
 4291                    pane.unpreview_item_if_preview(old_id);
 4292                });
 4293            }
 4294
 4295            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4296            if !allow_new_preview {
 4297                pane.update(cx, |pane, _| {
 4298                    pane.unpreview_item_if_preview(item.item_id());
 4299                });
 4300            }
 4301            return item;
 4302        }
 4303
 4304        let item = pane.update(cx, |pane, cx| {
 4305            cx.new(|cx| {
 4306                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4307            })
 4308        });
 4309        let mut destination_index = None;
 4310        pane.update(cx, |pane, cx| {
 4311            if !keep_old_preview && let Some(old_id) = old_item_id {
 4312                pane.unpreview_item_if_preview(old_id);
 4313            }
 4314            if allow_new_preview {
 4315                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4316            }
 4317        });
 4318
 4319        self.add_item(
 4320            pane,
 4321            Box::new(item.clone()),
 4322            destination_index,
 4323            activate_pane,
 4324            focus_item,
 4325            window,
 4326            cx,
 4327        );
 4328        item
 4329    }
 4330
 4331    pub fn open_shared_screen(
 4332        &mut self,
 4333        peer_id: PeerId,
 4334        window: &mut Window,
 4335        cx: &mut Context<Self>,
 4336    ) {
 4337        if let Some(shared_screen) =
 4338            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4339        {
 4340            self.active_pane.update(cx, |pane, cx| {
 4341                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4342            });
 4343        }
 4344    }
 4345
 4346    pub fn activate_item(
 4347        &mut self,
 4348        item: &dyn ItemHandle,
 4349        activate_pane: bool,
 4350        focus_item: bool,
 4351        window: &mut Window,
 4352        cx: &mut App,
 4353    ) -> bool {
 4354        let result = self.panes.iter().find_map(|pane| {
 4355            pane.read(cx)
 4356                .index_for_item(item)
 4357                .map(|ix| (pane.clone(), ix))
 4358        });
 4359        if let Some((pane, ix)) = result {
 4360            pane.update(cx, |pane, cx| {
 4361                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4362            });
 4363            true
 4364        } else {
 4365            false
 4366        }
 4367    }
 4368
 4369    fn activate_pane_at_index(
 4370        &mut self,
 4371        action: &ActivatePane,
 4372        window: &mut Window,
 4373        cx: &mut Context<Self>,
 4374    ) {
 4375        let panes = self.center.panes();
 4376        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4377            window.focus(&pane.focus_handle(cx), cx);
 4378        } else {
 4379            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4380                .detach();
 4381        }
 4382    }
 4383
 4384    fn move_item_to_pane_at_index(
 4385        &mut self,
 4386        action: &MoveItemToPane,
 4387        window: &mut Window,
 4388        cx: &mut Context<Self>,
 4389    ) {
 4390        let panes = self.center.panes();
 4391        let destination = match panes.get(action.destination) {
 4392            Some(&destination) => destination.clone(),
 4393            None => {
 4394                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4395                    return;
 4396                }
 4397                let direction = SplitDirection::Right;
 4398                let split_off_pane = self
 4399                    .find_pane_in_direction(direction, cx)
 4400                    .unwrap_or_else(|| self.active_pane.clone());
 4401                let new_pane = self.add_pane(window, cx);
 4402                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4403                new_pane
 4404            }
 4405        };
 4406
 4407        if action.clone {
 4408            if self
 4409                .active_pane
 4410                .read(cx)
 4411                .active_item()
 4412                .is_some_and(|item| item.can_split(cx))
 4413            {
 4414                clone_active_item(
 4415                    self.database_id(),
 4416                    &self.active_pane,
 4417                    &destination,
 4418                    action.focus,
 4419                    window,
 4420                    cx,
 4421                );
 4422                return;
 4423            }
 4424        }
 4425        move_active_item(
 4426            &self.active_pane,
 4427            &destination,
 4428            action.focus,
 4429            true,
 4430            window,
 4431            cx,
 4432        )
 4433    }
 4434
 4435    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4436        let panes = self.center.panes();
 4437        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4438            let next_ix = (ix + 1) % panes.len();
 4439            let next_pane = panes[next_ix].clone();
 4440            window.focus(&next_pane.focus_handle(cx), cx);
 4441        }
 4442    }
 4443
 4444    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4445        let panes = self.center.panes();
 4446        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4447            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4448            let prev_pane = panes[prev_ix].clone();
 4449            window.focus(&prev_pane.focus_handle(cx), cx);
 4450        }
 4451    }
 4452
 4453    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4454        let last_pane = self.center.last_pane();
 4455        window.focus(&last_pane.focus_handle(cx), cx);
 4456    }
 4457
 4458    pub fn activate_pane_in_direction(
 4459        &mut self,
 4460        direction: SplitDirection,
 4461        window: &mut Window,
 4462        cx: &mut App,
 4463    ) {
 4464        use ActivateInDirectionTarget as Target;
 4465        enum Origin {
 4466            LeftDock,
 4467            RightDock,
 4468            BottomDock,
 4469            Center,
 4470        }
 4471
 4472        let origin: Origin = [
 4473            (&self.left_dock, Origin::LeftDock),
 4474            (&self.right_dock, Origin::RightDock),
 4475            (&self.bottom_dock, Origin::BottomDock),
 4476        ]
 4477        .into_iter()
 4478        .find_map(|(dock, origin)| {
 4479            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4480                Some(origin)
 4481            } else {
 4482                None
 4483            }
 4484        })
 4485        .unwrap_or(Origin::Center);
 4486
 4487        let get_last_active_pane = || {
 4488            let pane = self
 4489                .last_active_center_pane
 4490                .clone()
 4491                .unwrap_or_else(|| {
 4492                    self.panes
 4493                        .first()
 4494                        .expect("There must be an active pane")
 4495                        .downgrade()
 4496                })
 4497                .upgrade()?;
 4498            (pane.read(cx).items_len() != 0).then_some(pane)
 4499        };
 4500
 4501        let try_dock =
 4502            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4503
 4504        let target = match (origin, direction) {
 4505            // We're in the center, so we first try to go to a different pane,
 4506            // otherwise try to go to a dock.
 4507            (Origin::Center, direction) => {
 4508                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4509                    Some(Target::Pane(pane))
 4510                } else {
 4511                    match direction {
 4512                        SplitDirection::Up => None,
 4513                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4514                        SplitDirection::Left => try_dock(&self.left_dock),
 4515                        SplitDirection::Right => try_dock(&self.right_dock),
 4516                    }
 4517                }
 4518            }
 4519
 4520            (Origin::LeftDock, SplitDirection::Right) => {
 4521                if let Some(last_active_pane) = get_last_active_pane() {
 4522                    Some(Target::Pane(last_active_pane))
 4523                } else {
 4524                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4525                }
 4526            }
 4527
 4528            (Origin::LeftDock, SplitDirection::Down)
 4529            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4530
 4531            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4532            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4533            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4534
 4535            (Origin::RightDock, SplitDirection::Left) => {
 4536                if let Some(last_active_pane) = get_last_active_pane() {
 4537                    Some(Target::Pane(last_active_pane))
 4538                } else {
 4539                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4540                }
 4541            }
 4542
 4543            _ => None,
 4544        };
 4545
 4546        match target {
 4547            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4548                let pane = pane.read(cx);
 4549                if let Some(item) = pane.active_item() {
 4550                    item.item_focus_handle(cx).focus(window, cx);
 4551                } else {
 4552                    log::error!(
 4553                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4554                    );
 4555                }
 4556            }
 4557            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4558                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4559                window.defer(cx, move |window, cx| {
 4560                    let dock = dock.read(cx);
 4561                    if let Some(panel) = dock.active_panel() {
 4562                        panel.panel_focus_handle(cx).focus(window, cx);
 4563                    } else {
 4564                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4565                    }
 4566                })
 4567            }
 4568            None => {}
 4569        }
 4570    }
 4571
 4572    pub fn move_item_to_pane_in_direction(
 4573        &mut self,
 4574        action: &MoveItemToPaneInDirection,
 4575        window: &mut Window,
 4576        cx: &mut Context<Self>,
 4577    ) {
 4578        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4579            Some(destination) => destination,
 4580            None => {
 4581                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4582                    return;
 4583                }
 4584                let new_pane = self.add_pane(window, cx);
 4585                self.center
 4586                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4587                new_pane
 4588            }
 4589        };
 4590
 4591        if action.clone {
 4592            if self
 4593                .active_pane
 4594                .read(cx)
 4595                .active_item()
 4596                .is_some_and(|item| item.can_split(cx))
 4597            {
 4598                clone_active_item(
 4599                    self.database_id(),
 4600                    &self.active_pane,
 4601                    &destination,
 4602                    action.focus,
 4603                    window,
 4604                    cx,
 4605                );
 4606                return;
 4607            }
 4608        }
 4609        move_active_item(
 4610            &self.active_pane,
 4611            &destination,
 4612            action.focus,
 4613            true,
 4614            window,
 4615            cx,
 4616        );
 4617    }
 4618
 4619    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4620        self.center.bounding_box_for_pane(pane)
 4621    }
 4622
 4623    pub fn find_pane_in_direction(
 4624        &mut self,
 4625        direction: SplitDirection,
 4626        cx: &App,
 4627    ) -> Option<Entity<Pane>> {
 4628        self.center
 4629            .find_pane_in_direction(&self.active_pane, direction, cx)
 4630            .cloned()
 4631    }
 4632
 4633    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4634        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4635            self.center.swap(&self.active_pane, &to, cx);
 4636            cx.notify();
 4637        }
 4638    }
 4639
 4640    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4641        if self
 4642            .center
 4643            .move_to_border(&self.active_pane, direction, cx)
 4644            .unwrap()
 4645        {
 4646            cx.notify();
 4647        }
 4648    }
 4649
 4650    pub fn resize_pane(
 4651        &mut self,
 4652        axis: gpui::Axis,
 4653        amount: Pixels,
 4654        window: &mut Window,
 4655        cx: &mut Context<Self>,
 4656    ) {
 4657        let docks = self.all_docks();
 4658        let active_dock = docks
 4659            .into_iter()
 4660            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4661
 4662        if let Some(dock) = active_dock {
 4663            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4664                return;
 4665            };
 4666            match dock.read(cx).position() {
 4667                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4668                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4669                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4670            }
 4671        } else {
 4672            self.center
 4673                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4674        }
 4675        cx.notify();
 4676    }
 4677
 4678    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4679        self.center.reset_pane_sizes(cx);
 4680        cx.notify();
 4681    }
 4682
 4683    fn handle_pane_focused(
 4684        &mut self,
 4685        pane: Entity<Pane>,
 4686        window: &mut Window,
 4687        cx: &mut Context<Self>,
 4688    ) {
 4689        // This is explicitly hoisted out of the following check for pane identity as
 4690        // terminal panel panes are not registered as a center panes.
 4691        self.status_bar.update(cx, |status_bar, cx| {
 4692            status_bar.set_active_pane(&pane, window, cx);
 4693        });
 4694        if self.active_pane != pane {
 4695            self.set_active_pane(&pane, window, cx);
 4696        }
 4697
 4698        if self.last_active_center_pane.is_none() {
 4699            self.last_active_center_pane = Some(pane.downgrade());
 4700        }
 4701
 4702        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4703        // This prevents the dock from closing when focus events fire during window activation.
 4704        // We also preserve any dock whose active panel itself has focus — this covers
 4705        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4706        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4707            let dock_read = dock.read(cx);
 4708            if let Some(panel) = dock_read.active_panel() {
 4709                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4710                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4711                {
 4712                    return Some(dock_read.position());
 4713                }
 4714            }
 4715            None
 4716        });
 4717
 4718        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4719        if pane.read(cx).is_zoomed() {
 4720            self.zoomed = Some(pane.downgrade().into());
 4721        } else {
 4722            self.zoomed = None;
 4723        }
 4724        self.zoomed_position = None;
 4725        cx.emit(Event::ZoomChanged);
 4726        self.update_active_view_for_followers(window, cx);
 4727        pane.update(cx, |pane, _| {
 4728            pane.track_alternate_file_items();
 4729        });
 4730
 4731        cx.notify();
 4732    }
 4733
 4734    fn set_active_pane(
 4735        &mut self,
 4736        pane: &Entity<Pane>,
 4737        window: &mut Window,
 4738        cx: &mut Context<Self>,
 4739    ) {
 4740        self.active_pane = pane.clone();
 4741        self.active_item_path_changed(true, window, cx);
 4742        self.last_active_center_pane = Some(pane.downgrade());
 4743    }
 4744
 4745    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4746        self.update_active_view_for_followers(window, cx);
 4747    }
 4748
 4749    fn handle_pane_event(
 4750        &mut self,
 4751        pane: &Entity<Pane>,
 4752        event: &pane::Event,
 4753        window: &mut Window,
 4754        cx: &mut Context<Self>,
 4755    ) {
 4756        let mut serialize_workspace = true;
 4757        match event {
 4758            pane::Event::AddItem { item } => {
 4759                item.added_to_pane(self, pane.clone(), window, cx);
 4760                cx.emit(Event::ItemAdded {
 4761                    item: item.boxed_clone(),
 4762                });
 4763            }
 4764            pane::Event::Split { direction, mode } => {
 4765                match mode {
 4766                    SplitMode::ClonePane => {
 4767                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4768                            .detach();
 4769                    }
 4770                    SplitMode::EmptyPane => {
 4771                        self.split_pane(pane.clone(), *direction, window, cx);
 4772                    }
 4773                    SplitMode::MovePane => {
 4774                        self.split_and_move(pane.clone(), *direction, window, cx);
 4775                    }
 4776                };
 4777            }
 4778            pane::Event::JoinIntoNext => {
 4779                self.join_pane_into_next(pane.clone(), window, cx);
 4780            }
 4781            pane::Event::JoinAll => {
 4782                self.join_all_panes(window, cx);
 4783            }
 4784            pane::Event::Remove { focus_on_pane } => {
 4785                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4786            }
 4787            pane::Event::ActivateItem {
 4788                local,
 4789                focus_changed,
 4790            } => {
 4791                window.invalidate_character_coordinates();
 4792
 4793                pane.update(cx, |pane, _| {
 4794                    pane.track_alternate_file_items();
 4795                });
 4796                if *local {
 4797                    self.unfollow_in_pane(pane, window, cx);
 4798                }
 4799                serialize_workspace = *focus_changed || pane != self.active_pane();
 4800                if pane == self.active_pane() {
 4801                    self.active_item_path_changed(*focus_changed, window, cx);
 4802                    self.update_active_view_for_followers(window, cx);
 4803                } else if *local {
 4804                    self.set_active_pane(pane, window, cx);
 4805                }
 4806            }
 4807            pane::Event::UserSavedItem { item, save_intent } => {
 4808                cx.emit(Event::UserSavedItem {
 4809                    pane: pane.downgrade(),
 4810                    item: item.boxed_clone(),
 4811                    save_intent: *save_intent,
 4812                });
 4813                serialize_workspace = false;
 4814            }
 4815            pane::Event::ChangeItemTitle => {
 4816                if *pane == self.active_pane {
 4817                    self.active_item_path_changed(false, window, cx);
 4818                }
 4819                serialize_workspace = false;
 4820            }
 4821            pane::Event::RemovedItem { item } => {
 4822                cx.emit(Event::ActiveItemChanged);
 4823                self.update_window_edited(window, cx);
 4824                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4825                    && entry.get().entity_id() == pane.entity_id()
 4826                {
 4827                    entry.remove();
 4828                }
 4829                cx.emit(Event::ItemRemoved {
 4830                    item_id: item.item_id(),
 4831                });
 4832            }
 4833            pane::Event::Focus => {
 4834                window.invalidate_character_coordinates();
 4835                self.handle_pane_focused(pane.clone(), window, cx);
 4836            }
 4837            pane::Event::ZoomIn => {
 4838                if *pane == self.active_pane {
 4839                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4840                    if pane.read(cx).has_focus(window, cx) {
 4841                        self.zoomed = Some(pane.downgrade().into());
 4842                        self.zoomed_position = None;
 4843                        cx.emit(Event::ZoomChanged);
 4844                    }
 4845                    cx.notify();
 4846                }
 4847            }
 4848            pane::Event::ZoomOut => {
 4849                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4850                if self.zoomed_position.is_none() {
 4851                    self.zoomed = None;
 4852                    cx.emit(Event::ZoomChanged);
 4853                }
 4854                cx.notify();
 4855            }
 4856            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4857        }
 4858
 4859        if serialize_workspace {
 4860            self.serialize_workspace(window, cx);
 4861        }
 4862    }
 4863
 4864    pub fn unfollow_in_pane(
 4865        &mut self,
 4866        pane: &Entity<Pane>,
 4867        window: &mut Window,
 4868        cx: &mut Context<Workspace>,
 4869    ) -> Option<CollaboratorId> {
 4870        let leader_id = self.leader_for_pane(pane)?;
 4871        self.unfollow(leader_id, window, cx);
 4872        Some(leader_id)
 4873    }
 4874
 4875    pub fn split_pane(
 4876        &mut self,
 4877        pane_to_split: Entity<Pane>,
 4878        split_direction: SplitDirection,
 4879        window: &mut Window,
 4880        cx: &mut Context<Self>,
 4881    ) -> Entity<Pane> {
 4882        let new_pane = self.add_pane(window, cx);
 4883        self.center
 4884            .split(&pane_to_split, &new_pane, split_direction, cx);
 4885        cx.notify();
 4886        new_pane
 4887    }
 4888
 4889    pub fn split_and_move(
 4890        &mut self,
 4891        pane: Entity<Pane>,
 4892        direction: SplitDirection,
 4893        window: &mut Window,
 4894        cx: &mut Context<Self>,
 4895    ) {
 4896        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4897            return;
 4898        };
 4899        let new_pane = self.add_pane(window, cx);
 4900        new_pane.update(cx, |pane, cx| {
 4901            pane.add_item(item, true, true, None, window, cx)
 4902        });
 4903        self.center.split(&pane, &new_pane, direction, cx);
 4904        cx.notify();
 4905    }
 4906
 4907    pub fn split_and_clone(
 4908        &mut self,
 4909        pane: Entity<Pane>,
 4910        direction: SplitDirection,
 4911        window: &mut Window,
 4912        cx: &mut Context<Self>,
 4913    ) -> Task<Option<Entity<Pane>>> {
 4914        let Some(item) = pane.read(cx).active_item() else {
 4915            return Task::ready(None);
 4916        };
 4917        if !item.can_split(cx) {
 4918            return Task::ready(None);
 4919        }
 4920        let task = item.clone_on_split(self.database_id(), window, cx);
 4921        cx.spawn_in(window, async move |this, cx| {
 4922            if let Some(clone) = task.await {
 4923                this.update_in(cx, |this, window, cx| {
 4924                    let new_pane = this.add_pane(window, cx);
 4925                    let nav_history = pane.read(cx).fork_nav_history();
 4926                    new_pane.update(cx, |pane, cx| {
 4927                        pane.set_nav_history(nav_history, cx);
 4928                        pane.add_item(clone, true, true, None, window, cx)
 4929                    });
 4930                    this.center.split(&pane, &new_pane, direction, cx);
 4931                    cx.notify();
 4932                    new_pane
 4933                })
 4934                .ok()
 4935            } else {
 4936                None
 4937            }
 4938        })
 4939    }
 4940
 4941    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4942        let active_item = self.active_pane.read(cx).active_item();
 4943        for pane in &self.panes {
 4944            join_pane_into_active(&self.active_pane, pane, window, cx);
 4945        }
 4946        if let Some(active_item) = active_item {
 4947            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4948        }
 4949        cx.notify();
 4950    }
 4951
 4952    pub fn join_pane_into_next(
 4953        &mut self,
 4954        pane: Entity<Pane>,
 4955        window: &mut Window,
 4956        cx: &mut Context<Self>,
 4957    ) {
 4958        let next_pane = self
 4959            .find_pane_in_direction(SplitDirection::Right, cx)
 4960            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4961            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4962            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4963        let Some(next_pane) = next_pane else {
 4964            return;
 4965        };
 4966        move_all_items(&pane, &next_pane, window, cx);
 4967        cx.notify();
 4968    }
 4969
 4970    fn remove_pane(
 4971        &mut self,
 4972        pane: Entity<Pane>,
 4973        focus_on: Option<Entity<Pane>>,
 4974        window: &mut Window,
 4975        cx: &mut Context<Self>,
 4976    ) {
 4977        if self.center.remove(&pane, cx).unwrap() {
 4978            self.force_remove_pane(&pane, &focus_on, window, cx);
 4979            self.unfollow_in_pane(&pane, window, cx);
 4980            self.last_leaders_by_pane.remove(&pane.downgrade());
 4981            for removed_item in pane.read(cx).items() {
 4982                self.panes_by_item.remove(&removed_item.item_id());
 4983            }
 4984
 4985            cx.notify();
 4986        } else {
 4987            self.active_item_path_changed(true, window, cx);
 4988        }
 4989        cx.emit(Event::PaneRemoved);
 4990    }
 4991
 4992    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4993        &mut self.panes
 4994    }
 4995
 4996    pub fn panes(&self) -> &[Entity<Pane>] {
 4997        &self.panes
 4998    }
 4999
 5000    pub fn active_pane(&self) -> &Entity<Pane> {
 5001        &self.active_pane
 5002    }
 5003
 5004    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5005        for dock in self.all_docks() {
 5006            if dock.focus_handle(cx).contains_focused(window, cx)
 5007                && let Some(pane) = dock
 5008                    .read(cx)
 5009                    .active_panel()
 5010                    .and_then(|panel| panel.pane(cx))
 5011            {
 5012                return pane;
 5013            }
 5014        }
 5015        self.active_pane().clone()
 5016    }
 5017
 5018    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5019        self.find_pane_in_direction(SplitDirection::Right, cx)
 5020            .unwrap_or_else(|| {
 5021                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5022            })
 5023    }
 5024
 5025    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5026        self.pane_for_item_id(handle.item_id())
 5027    }
 5028
 5029    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5030        let weak_pane = self.panes_by_item.get(&item_id)?;
 5031        weak_pane.upgrade()
 5032    }
 5033
 5034    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5035        self.panes
 5036            .iter()
 5037            .find(|pane| pane.entity_id() == entity_id)
 5038            .cloned()
 5039    }
 5040
 5041    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5042        self.follower_states.retain(|leader_id, state| {
 5043            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5044                for item in state.items_by_leader_view_id.values() {
 5045                    item.view.set_leader_id(None, window, cx);
 5046                }
 5047                false
 5048            } else {
 5049                true
 5050            }
 5051        });
 5052        cx.notify();
 5053    }
 5054
 5055    pub fn start_following(
 5056        &mut self,
 5057        leader_id: impl Into<CollaboratorId>,
 5058        window: &mut Window,
 5059        cx: &mut Context<Self>,
 5060    ) -> Option<Task<Result<()>>> {
 5061        let leader_id = leader_id.into();
 5062        let pane = self.active_pane().clone();
 5063
 5064        self.last_leaders_by_pane
 5065            .insert(pane.downgrade(), leader_id);
 5066        self.unfollow(leader_id, window, cx);
 5067        self.unfollow_in_pane(&pane, window, cx);
 5068        self.follower_states.insert(
 5069            leader_id,
 5070            FollowerState {
 5071                center_pane: pane.clone(),
 5072                dock_pane: None,
 5073                active_view_id: None,
 5074                items_by_leader_view_id: Default::default(),
 5075            },
 5076        );
 5077        cx.notify();
 5078
 5079        match leader_id {
 5080            CollaboratorId::PeerId(leader_peer_id) => {
 5081                let room_id = self.active_call()?.room_id(cx)?;
 5082                let project_id = self.project.read(cx).remote_id();
 5083                let request = self.app_state.client.request(proto::Follow {
 5084                    room_id,
 5085                    project_id,
 5086                    leader_id: Some(leader_peer_id),
 5087                });
 5088
 5089                Some(cx.spawn_in(window, async move |this, cx| {
 5090                    let response = request.await?;
 5091                    this.update(cx, |this, _| {
 5092                        let state = this
 5093                            .follower_states
 5094                            .get_mut(&leader_id)
 5095                            .context("following interrupted")?;
 5096                        state.active_view_id = response
 5097                            .active_view
 5098                            .as_ref()
 5099                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5100                        anyhow::Ok(())
 5101                    })??;
 5102                    if let Some(view) = response.active_view {
 5103                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5104                    }
 5105                    this.update_in(cx, |this, window, cx| {
 5106                        this.leader_updated(leader_id, window, cx)
 5107                    })?;
 5108                    Ok(())
 5109                }))
 5110            }
 5111            CollaboratorId::Agent => {
 5112                self.leader_updated(leader_id, window, cx)?;
 5113                Some(Task::ready(Ok(())))
 5114            }
 5115        }
 5116    }
 5117
 5118    pub fn follow_next_collaborator(
 5119        &mut self,
 5120        _: &FollowNextCollaborator,
 5121        window: &mut Window,
 5122        cx: &mut Context<Self>,
 5123    ) {
 5124        let collaborators = self.project.read(cx).collaborators();
 5125        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5126            let mut collaborators = collaborators.keys().copied();
 5127            for peer_id in collaborators.by_ref() {
 5128                if CollaboratorId::PeerId(peer_id) == leader_id {
 5129                    break;
 5130                }
 5131            }
 5132            collaborators.next().map(CollaboratorId::PeerId)
 5133        } else if let Some(last_leader_id) =
 5134            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5135        {
 5136            match last_leader_id {
 5137                CollaboratorId::PeerId(peer_id) => {
 5138                    if collaborators.contains_key(peer_id) {
 5139                        Some(*last_leader_id)
 5140                    } else {
 5141                        None
 5142                    }
 5143                }
 5144                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5145            }
 5146        } else {
 5147            None
 5148        };
 5149
 5150        let pane = self.active_pane.clone();
 5151        let Some(leader_id) = next_leader_id.or_else(|| {
 5152            Some(CollaboratorId::PeerId(
 5153                collaborators.keys().copied().next()?,
 5154            ))
 5155        }) else {
 5156            return;
 5157        };
 5158        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5159            return;
 5160        }
 5161        if let Some(task) = self.start_following(leader_id, window, cx) {
 5162            task.detach_and_log_err(cx)
 5163        }
 5164    }
 5165
 5166    pub fn follow(
 5167        &mut self,
 5168        leader_id: impl Into<CollaboratorId>,
 5169        window: &mut Window,
 5170        cx: &mut Context<Self>,
 5171    ) {
 5172        let leader_id = leader_id.into();
 5173
 5174        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5175            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5176                return;
 5177            };
 5178            let Some(remote_participant) =
 5179                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5180            else {
 5181                return;
 5182            };
 5183
 5184            let project = self.project.read(cx);
 5185
 5186            let other_project_id = match remote_participant.location {
 5187                ParticipantLocation::External => None,
 5188                ParticipantLocation::UnsharedProject => None,
 5189                ParticipantLocation::SharedProject { project_id } => {
 5190                    if Some(project_id) == project.remote_id() {
 5191                        None
 5192                    } else {
 5193                        Some(project_id)
 5194                    }
 5195                }
 5196            };
 5197
 5198            // if they are active in another project, follow there.
 5199            if let Some(project_id) = other_project_id {
 5200                let app_state = self.app_state.clone();
 5201                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5202                    .detach_and_log_err(cx);
 5203            }
 5204        }
 5205
 5206        // if you're already following, find the right pane and focus it.
 5207        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5208            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5209
 5210            return;
 5211        }
 5212
 5213        // Otherwise, follow.
 5214        if let Some(task) = self.start_following(leader_id, window, cx) {
 5215            task.detach_and_log_err(cx)
 5216        }
 5217    }
 5218
 5219    pub fn unfollow(
 5220        &mut self,
 5221        leader_id: impl Into<CollaboratorId>,
 5222        window: &mut Window,
 5223        cx: &mut Context<Self>,
 5224    ) -> Option<()> {
 5225        cx.notify();
 5226
 5227        let leader_id = leader_id.into();
 5228        let state = self.follower_states.remove(&leader_id)?;
 5229        for (_, item) in state.items_by_leader_view_id {
 5230            item.view.set_leader_id(None, window, cx);
 5231        }
 5232
 5233        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5234            let project_id = self.project.read(cx).remote_id();
 5235            let room_id = self.active_call()?.room_id(cx)?;
 5236            self.app_state
 5237                .client
 5238                .send(proto::Unfollow {
 5239                    room_id,
 5240                    project_id,
 5241                    leader_id: Some(leader_peer_id),
 5242                })
 5243                .log_err();
 5244        }
 5245
 5246        Some(())
 5247    }
 5248
 5249    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5250        self.follower_states.contains_key(&id.into())
 5251    }
 5252
 5253    fn active_item_path_changed(
 5254        &mut self,
 5255        focus_changed: bool,
 5256        window: &mut Window,
 5257        cx: &mut Context<Self>,
 5258    ) {
 5259        cx.emit(Event::ActiveItemChanged);
 5260        let active_entry = self.active_project_path(cx);
 5261        self.project.update(cx, |project, cx| {
 5262            project.set_active_path(active_entry.clone(), cx)
 5263        });
 5264
 5265        if focus_changed && let Some(project_path) = &active_entry {
 5266            let git_store_entity = self.project.read(cx).git_store().clone();
 5267            git_store_entity.update(cx, |git_store, cx| {
 5268                git_store.set_active_repo_for_path(project_path, cx);
 5269            });
 5270        }
 5271
 5272        self.update_window_title(window, cx);
 5273    }
 5274
 5275    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5276        let project = self.project().read(cx);
 5277        let mut title = String::new();
 5278
 5279        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5280            let name = {
 5281                let settings_location = SettingsLocation {
 5282                    worktree_id: worktree.read(cx).id(),
 5283                    path: RelPath::empty(),
 5284                };
 5285
 5286                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5287                match &settings.project_name {
 5288                    Some(name) => name.as_str(),
 5289                    None => worktree.read(cx).root_name_str(),
 5290                }
 5291            };
 5292            if i > 0 {
 5293                title.push_str(", ");
 5294            }
 5295            title.push_str(name);
 5296        }
 5297
 5298        if title.is_empty() {
 5299            title = "empty project".to_string();
 5300        }
 5301
 5302        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5303            let filename = path.path.file_name().or_else(|| {
 5304                Some(
 5305                    project
 5306                        .worktree_for_id(path.worktree_id, cx)?
 5307                        .read(cx)
 5308                        .root_name_str(),
 5309                )
 5310            });
 5311
 5312            if let Some(filename) = filename {
 5313                title.push_str("");
 5314                title.push_str(filename.as_ref());
 5315            }
 5316        }
 5317
 5318        if project.is_via_collab() {
 5319            title.push_str("");
 5320        } else if project.is_shared() {
 5321            title.push_str("");
 5322        }
 5323
 5324        if let Some(last_title) = self.last_window_title.as_ref()
 5325            && &title == last_title
 5326        {
 5327            return;
 5328        }
 5329        window.set_window_title(&title);
 5330        SystemWindowTabController::update_tab_title(
 5331            cx,
 5332            window.window_handle().window_id(),
 5333            SharedString::from(&title),
 5334        );
 5335        self.last_window_title = Some(title);
 5336    }
 5337
 5338    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5339        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5340        if is_edited != self.window_edited {
 5341            self.window_edited = is_edited;
 5342            window.set_window_edited(self.window_edited)
 5343        }
 5344    }
 5345
 5346    fn update_item_dirty_state(
 5347        &mut self,
 5348        item: &dyn ItemHandle,
 5349        window: &mut Window,
 5350        cx: &mut App,
 5351    ) {
 5352        let is_dirty = item.is_dirty(cx);
 5353        let item_id = item.item_id();
 5354        let was_dirty = self.dirty_items.contains_key(&item_id);
 5355        if is_dirty == was_dirty {
 5356            return;
 5357        }
 5358        if was_dirty {
 5359            self.dirty_items.remove(&item_id);
 5360            self.update_window_edited(window, cx);
 5361            return;
 5362        }
 5363
 5364        let workspace = self.weak_handle();
 5365        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5366            return;
 5367        };
 5368        let on_release_callback = Box::new(move |cx: &mut App| {
 5369            window_handle
 5370                .update(cx, |_, window, cx| {
 5371                    workspace
 5372                        .update(cx, |workspace, cx| {
 5373                            workspace.dirty_items.remove(&item_id);
 5374                            workspace.update_window_edited(window, cx)
 5375                        })
 5376                        .ok();
 5377                })
 5378                .ok();
 5379        });
 5380
 5381        let s = item.on_release(cx, on_release_callback);
 5382        self.dirty_items.insert(item_id, s);
 5383        self.update_window_edited(window, cx);
 5384    }
 5385
 5386    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5387        if self.notifications.is_empty() {
 5388            None
 5389        } else {
 5390            Some(
 5391                div()
 5392                    .absolute()
 5393                    .right_3()
 5394                    .bottom_3()
 5395                    .w_112()
 5396                    .h_full()
 5397                    .flex()
 5398                    .flex_col()
 5399                    .justify_end()
 5400                    .gap_2()
 5401                    .children(
 5402                        self.notifications
 5403                            .iter()
 5404                            .map(|(_, notification)| notification.clone().into_any()),
 5405                    ),
 5406            )
 5407        }
 5408    }
 5409
 5410    // RPC handlers
 5411
 5412    fn active_view_for_follower(
 5413        &self,
 5414        follower_project_id: Option<u64>,
 5415        window: &mut Window,
 5416        cx: &mut Context<Self>,
 5417    ) -> Option<proto::View> {
 5418        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5419        let item = item?;
 5420        let leader_id = self
 5421            .pane_for(&*item)
 5422            .and_then(|pane| self.leader_for_pane(&pane));
 5423        let leader_peer_id = match leader_id {
 5424            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5425            Some(CollaboratorId::Agent) | None => None,
 5426        };
 5427
 5428        let item_handle = item.to_followable_item_handle(cx)?;
 5429        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5430        let variant = item_handle.to_state_proto(window, cx)?;
 5431
 5432        if item_handle.is_project_item(window, cx)
 5433            && (follower_project_id.is_none()
 5434                || follower_project_id != self.project.read(cx).remote_id())
 5435        {
 5436            return None;
 5437        }
 5438
 5439        Some(proto::View {
 5440            id: id.to_proto(),
 5441            leader_id: leader_peer_id,
 5442            variant: Some(variant),
 5443            panel_id: panel_id.map(|id| id as i32),
 5444        })
 5445    }
 5446
 5447    fn handle_follow(
 5448        &mut self,
 5449        follower_project_id: Option<u64>,
 5450        window: &mut Window,
 5451        cx: &mut Context<Self>,
 5452    ) -> proto::FollowResponse {
 5453        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5454
 5455        cx.notify();
 5456        proto::FollowResponse {
 5457            views: active_view.iter().cloned().collect(),
 5458            active_view,
 5459        }
 5460    }
 5461
 5462    fn handle_update_followers(
 5463        &mut self,
 5464        leader_id: PeerId,
 5465        message: proto::UpdateFollowers,
 5466        _window: &mut Window,
 5467        _cx: &mut Context<Self>,
 5468    ) {
 5469        self.leader_updates_tx
 5470            .unbounded_send((leader_id, message))
 5471            .ok();
 5472    }
 5473
 5474    async fn process_leader_update(
 5475        this: &WeakEntity<Self>,
 5476        leader_id: PeerId,
 5477        update: proto::UpdateFollowers,
 5478        cx: &mut AsyncWindowContext,
 5479    ) -> Result<()> {
 5480        match update.variant.context("invalid update")? {
 5481            proto::update_followers::Variant::CreateView(view) => {
 5482                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5483                let should_add_view = this.update(cx, |this, _| {
 5484                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5485                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5486                    } else {
 5487                        anyhow::Ok(false)
 5488                    }
 5489                })??;
 5490
 5491                if should_add_view {
 5492                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5493                }
 5494            }
 5495            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5496                let should_add_view = this.update(cx, |this, _| {
 5497                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5498                        state.active_view_id = update_active_view
 5499                            .view
 5500                            .as_ref()
 5501                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5502
 5503                        if state.active_view_id.is_some_and(|view_id| {
 5504                            !state.items_by_leader_view_id.contains_key(&view_id)
 5505                        }) {
 5506                            anyhow::Ok(true)
 5507                        } else {
 5508                            anyhow::Ok(false)
 5509                        }
 5510                    } else {
 5511                        anyhow::Ok(false)
 5512                    }
 5513                })??;
 5514
 5515                if should_add_view && let Some(view) = update_active_view.view {
 5516                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5517                }
 5518            }
 5519            proto::update_followers::Variant::UpdateView(update_view) => {
 5520                let variant = update_view.variant.context("missing update view variant")?;
 5521                let id = update_view.id.context("missing update view id")?;
 5522                let mut tasks = Vec::new();
 5523                this.update_in(cx, |this, window, cx| {
 5524                    let project = this.project.clone();
 5525                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5526                        let view_id = ViewId::from_proto(id.clone())?;
 5527                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5528                            tasks.push(item.view.apply_update_proto(
 5529                                &project,
 5530                                variant.clone(),
 5531                                window,
 5532                                cx,
 5533                            ));
 5534                        }
 5535                    }
 5536                    anyhow::Ok(())
 5537                })??;
 5538                try_join_all(tasks).await.log_err();
 5539            }
 5540        }
 5541        this.update_in(cx, |this, window, cx| {
 5542            this.leader_updated(leader_id, window, cx)
 5543        })?;
 5544        Ok(())
 5545    }
 5546
 5547    async fn add_view_from_leader(
 5548        this: WeakEntity<Self>,
 5549        leader_id: PeerId,
 5550        view: &proto::View,
 5551        cx: &mut AsyncWindowContext,
 5552    ) -> Result<()> {
 5553        let this = this.upgrade().context("workspace dropped")?;
 5554
 5555        let Some(id) = view.id.clone() else {
 5556            anyhow::bail!("no id for view");
 5557        };
 5558        let id = ViewId::from_proto(id)?;
 5559        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5560
 5561        let pane = this.update(cx, |this, _cx| {
 5562            let state = this
 5563                .follower_states
 5564                .get(&leader_id.into())
 5565                .context("stopped following")?;
 5566            anyhow::Ok(state.pane().clone())
 5567        })?;
 5568        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5569            let client = this.read(cx).client().clone();
 5570            pane.items().find_map(|item| {
 5571                let item = item.to_followable_item_handle(cx)?;
 5572                if item.remote_id(&client, window, cx) == Some(id) {
 5573                    Some(item)
 5574                } else {
 5575                    None
 5576                }
 5577            })
 5578        })?;
 5579        let item = if let Some(existing_item) = existing_item {
 5580            existing_item
 5581        } else {
 5582            let variant = view.variant.clone();
 5583            anyhow::ensure!(variant.is_some(), "missing view variant");
 5584
 5585            let task = cx.update(|window, cx| {
 5586                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5587            })?;
 5588
 5589            let Some(task) = task else {
 5590                anyhow::bail!(
 5591                    "failed to construct view from leader (maybe from a different version of zed?)"
 5592                );
 5593            };
 5594
 5595            let mut new_item = task.await?;
 5596            pane.update_in(cx, |pane, window, cx| {
 5597                let mut item_to_remove = None;
 5598                for (ix, item) in pane.items().enumerate() {
 5599                    if let Some(item) = item.to_followable_item_handle(cx) {
 5600                        match new_item.dedup(item.as_ref(), window, cx) {
 5601                            Some(item::Dedup::KeepExisting) => {
 5602                                new_item =
 5603                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5604                                break;
 5605                            }
 5606                            Some(item::Dedup::ReplaceExisting) => {
 5607                                item_to_remove = Some((ix, item.item_id()));
 5608                                break;
 5609                            }
 5610                            None => {}
 5611                        }
 5612                    }
 5613                }
 5614
 5615                if let Some((ix, id)) = item_to_remove {
 5616                    pane.remove_item(id, false, false, window, cx);
 5617                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5618                }
 5619            })?;
 5620
 5621            new_item
 5622        };
 5623
 5624        this.update_in(cx, |this, window, cx| {
 5625            let state = this.follower_states.get_mut(&leader_id.into())?;
 5626            item.set_leader_id(Some(leader_id.into()), window, cx);
 5627            state.items_by_leader_view_id.insert(
 5628                id,
 5629                FollowerView {
 5630                    view: item,
 5631                    location: panel_id,
 5632                },
 5633            );
 5634
 5635            Some(())
 5636        })
 5637        .context("no follower state")?;
 5638
 5639        Ok(())
 5640    }
 5641
 5642    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5643        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5644            return;
 5645        };
 5646
 5647        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5648            let buffer_entity_id = agent_location.buffer.entity_id();
 5649            let view_id = ViewId {
 5650                creator: CollaboratorId::Agent,
 5651                id: buffer_entity_id.as_u64(),
 5652            };
 5653            follower_state.active_view_id = Some(view_id);
 5654
 5655            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5656                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5657                hash_map::Entry::Vacant(entry) => {
 5658                    let existing_view =
 5659                        follower_state
 5660                            .center_pane
 5661                            .read(cx)
 5662                            .items()
 5663                            .find_map(|item| {
 5664                                let item = item.to_followable_item_handle(cx)?;
 5665                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5666                                    && item.project_item_model_ids(cx).as_slice()
 5667                                        == [buffer_entity_id]
 5668                                {
 5669                                    Some(item)
 5670                                } else {
 5671                                    None
 5672                                }
 5673                            });
 5674                    let view = existing_view.or_else(|| {
 5675                        agent_location.buffer.upgrade().and_then(|buffer| {
 5676                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5677                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5678                            })?
 5679                            .to_followable_item_handle(cx)
 5680                        })
 5681                    });
 5682
 5683                    view.map(|view| {
 5684                        entry.insert(FollowerView {
 5685                            view,
 5686                            location: None,
 5687                        })
 5688                    })
 5689                }
 5690            };
 5691
 5692            if let Some(item) = item {
 5693                item.view
 5694                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5695                item.view
 5696                    .update_agent_location(agent_location.position, window, cx);
 5697            }
 5698        } else {
 5699            follower_state.active_view_id = None;
 5700        }
 5701
 5702        self.leader_updated(CollaboratorId::Agent, window, cx);
 5703    }
 5704
 5705    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5706        let mut is_project_item = true;
 5707        let mut update = proto::UpdateActiveView::default();
 5708        if window.is_window_active() {
 5709            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5710
 5711            if let Some(item) = active_item
 5712                && item.item_focus_handle(cx).contains_focused(window, cx)
 5713            {
 5714                let leader_id = self
 5715                    .pane_for(&*item)
 5716                    .and_then(|pane| self.leader_for_pane(&pane));
 5717                let leader_peer_id = match leader_id {
 5718                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5719                    Some(CollaboratorId::Agent) | None => None,
 5720                };
 5721
 5722                if let Some(item) = item.to_followable_item_handle(cx) {
 5723                    let id = item
 5724                        .remote_id(&self.app_state.client, window, cx)
 5725                        .map(|id| id.to_proto());
 5726
 5727                    if let Some(id) = id
 5728                        && let Some(variant) = item.to_state_proto(window, cx)
 5729                    {
 5730                        let view = Some(proto::View {
 5731                            id,
 5732                            leader_id: leader_peer_id,
 5733                            variant: Some(variant),
 5734                            panel_id: panel_id.map(|id| id as i32),
 5735                        });
 5736
 5737                        is_project_item = item.is_project_item(window, cx);
 5738                        update = proto::UpdateActiveView { view };
 5739                    };
 5740                }
 5741            }
 5742        }
 5743
 5744        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5745        if active_view_id != self.last_active_view_id.as_ref() {
 5746            self.last_active_view_id = active_view_id.cloned();
 5747            self.update_followers(
 5748                is_project_item,
 5749                proto::update_followers::Variant::UpdateActiveView(update),
 5750                window,
 5751                cx,
 5752            );
 5753        }
 5754    }
 5755
 5756    fn active_item_for_followers(
 5757        &self,
 5758        window: &mut Window,
 5759        cx: &mut App,
 5760    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5761        let mut active_item = None;
 5762        let mut panel_id = None;
 5763        for dock in self.all_docks() {
 5764            if dock.focus_handle(cx).contains_focused(window, cx)
 5765                && let Some(panel) = dock.read(cx).active_panel()
 5766                && let Some(pane) = panel.pane(cx)
 5767                && let Some(item) = pane.read(cx).active_item()
 5768            {
 5769                active_item = Some(item);
 5770                panel_id = panel.remote_id();
 5771                break;
 5772            }
 5773        }
 5774
 5775        if active_item.is_none() {
 5776            active_item = self.active_pane().read(cx).active_item();
 5777        }
 5778        (active_item, panel_id)
 5779    }
 5780
 5781    fn update_followers(
 5782        &self,
 5783        project_only: bool,
 5784        update: proto::update_followers::Variant,
 5785        _: &mut Window,
 5786        cx: &mut App,
 5787    ) -> Option<()> {
 5788        // If this update only applies to for followers in the current project,
 5789        // then skip it unless this project is shared. If it applies to all
 5790        // followers, regardless of project, then set `project_id` to none,
 5791        // indicating that it goes to all followers.
 5792        let project_id = if project_only {
 5793            Some(self.project.read(cx).remote_id()?)
 5794        } else {
 5795            None
 5796        };
 5797        self.app_state().workspace_store.update(cx, |store, cx| {
 5798            store.update_followers(project_id, update, cx)
 5799        })
 5800    }
 5801
 5802    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5803        self.follower_states.iter().find_map(|(leader_id, state)| {
 5804            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5805                Some(*leader_id)
 5806            } else {
 5807                None
 5808            }
 5809        })
 5810    }
 5811
 5812    fn leader_updated(
 5813        &mut self,
 5814        leader_id: impl Into<CollaboratorId>,
 5815        window: &mut Window,
 5816        cx: &mut Context<Self>,
 5817    ) -> Option<Box<dyn ItemHandle>> {
 5818        cx.notify();
 5819
 5820        let leader_id = leader_id.into();
 5821        let (panel_id, item) = match leader_id {
 5822            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5823            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5824        };
 5825
 5826        let state = self.follower_states.get(&leader_id)?;
 5827        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5828        let pane;
 5829        if let Some(panel_id) = panel_id {
 5830            pane = self
 5831                .activate_panel_for_proto_id(panel_id, window, cx)?
 5832                .pane(cx)?;
 5833            let state = self.follower_states.get_mut(&leader_id)?;
 5834            state.dock_pane = Some(pane.clone());
 5835        } else {
 5836            pane = state.center_pane.clone();
 5837            let state = self.follower_states.get_mut(&leader_id)?;
 5838            if let Some(dock_pane) = state.dock_pane.take() {
 5839                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5840            }
 5841        }
 5842
 5843        pane.update(cx, |pane, cx| {
 5844            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5845            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5846                pane.activate_item(index, false, false, window, cx);
 5847            } else {
 5848                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5849            }
 5850
 5851            if focus_active_item {
 5852                pane.focus_active_item(window, cx)
 5853            }
 5854        });
 5855
 5856        Some(item)
 5857    }
 5858
 5859    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5860        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5861        let active_view_id = state.active_view_id?;
 5862        Some(
 5863            state
 5864                .items_by_leader_view_id
 5865                .get(&active_view_id)?
 5866                .view
 5867                .boxed_clone(),
 5868        )
 5869    }
 5870
 5871    fn active_item_for_peer(
 5872        &self,
 5873        peer_id: PeerId,
 5874        window: &mut Window,
 5875        cx: &mut Context<Self>,
 5876    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5877        let call = self.active_call()?;
 5878        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5879        let leader_in_this_app;
 5880        let leader_in_this_project;
 5881        match participant.location {
 5882            ParticipantLocation::SharedProject { project_id } => {
 5883                leader_in_this_app = true;
 5884                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5885            }
 5886            ParticipantLocation::UnsharedProject => {
 5887                leader_in_this_app = true;
 5888                leader_in_this_project = false;
 5889            }
 5890            ParticipantLocation::External => {
 5891                leader_in_this_app = false;
 5892                leader_in_this_project = false;
 5893            }
 5894        };
 5895        let state = self.follower_states.get(&peer_id.into())?;
 5896        let mut item_to_activate = None;
 5897        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5898            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5899                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5900            {
 5901                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5902            }
 5903        } else if let Some(shared_screen) =
 5904            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5905        {
 5906            item_to_activate = Some((None, Box::new(shared_screen)));
 5907        }
 5908        item_to_activate
 5909    }
 5910
 5911    fn shared_screen_for_peer(
 5912        &self,
 5913        peer_id: PeerId,
 5914        pane: &Entity<Pane>,
 5915        window: &mut Window,
 5916        cx: &mut App,
 5917    ) -> Option<Entity<SharedScreen>> {
 5918        self.active_call()?
 5919            .create_shared_screen(peer_id, pane, window, cx)
 5920    }
 5921
 5922    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5923        if window.is_window_active() {
 5924            self.update_active_view_for_followers(window, cx);
 5925
 5926            if let Some(database_id) = self.database_id {
 5927                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5928                    .detach();
 5929            }
 5930        } else {
 5931            for pane in &self.panes {
 5932                pane.update(cx, |pane, cx| {
 5933                    if let Some(item) = pane.active_item() {
 5934                        item.workspace_deactivated(window, cx);
 5935                    }
 5936                    for item in pane.items() {
 5937                        if matches!(
 5938                            item.workspace_settings(cx).autosave,
 5939                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5940                        ) {
 5941                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5942                                .detach_and_log_err(cx);
 5943                        }
 5944                    }
 5945                });
 5946            }
 5947        }
 5948    }
 5949
 5950    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5951        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5952    }
 5953
 5954    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5955        self.active_call.as_ref().map(|(call, _)| call.clone())
 5956    }
 5957
 5958    fn on_active_call_event(
 5959        &mut self,
 5960        event: &ActiveCallEvent,
 5961        window: &mut Window,
 5962        cx: &mut Context<Self>,
 5963    ) {
 5964        match event {
 5965            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 5966            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 5967                self.leader_updated(participant_id, window, cx);
 5968            }
 5969        }
 5970    }
 5971
 5972    pub fn database_id(&self) -> Option<WorkspaceId> {
 5973        self.database_id
 5974    }
 5975
 5976    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 5977        self.database_id = Some(id);
 5978    }
 5979
 5980    pub fn session_id(&self) -> Option<String> {
 5981        self.session_id.clone()
 5982    }
 5983
 5984    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5985        let Some(display) = window.display(cx) else {
 5986            return Task::ready(());
 5987        };
 5988        let Ok(display_uuid) = display.uuid() else {
 5989            return Task::ready(());
 5990        };
 5991
 5992        let window_bounds = window.inner_window_bounds();
 5993        let database_id = self.database_id;
 5994        let has_paths = !self.root_paths(cx).is_empty();
 5995
 5996        cx.background_executor().spawn(async move {
 5997            if !has_paths {
 5998                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5999                    .await
 6000                    .log_err();
 6001            }
 6002            if let Some(database_id) = database_id {
 6003                DB.set_window_open_status(
 6004                    database_id,
 6005                    SerializedWindowBounds(window_bounds),
 6006                    display_uuid,
 6007                )
 6008                .await
 6009                .log_err();
 6010            } else {
 6011                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6012                    .await
 6013                    .log_err();
 6014            }
 6015        })
 6016    }
 6017
 6018    /// Bypass the 200ms serialization throttle and write workspace state to
 6019    /// the DB immediately. Returns a task the caller can await to ensure the
 6020    /// write completes. Used by the quit handler so the most recent state
 6021    /// isn't lost to a pending throttle timer when the process exits.
 6022    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6023        self._schedule_serialize_workspace.take();
 6024        self._serialize_workspace_task.take();
 6025        self.bounds_save_task_queued.take();
 6026
 6027        let bounds_task = self.save_window_bounds(window, cx);
 6028        let serialize_task = self.serialize_workspace_internal(window, cx);
 6029        cx.spawn(async move |_| {
 6030            bounds_task.await;
 6031            serialize_task.await;
 6032        })
 6033    }
 6034
 6035    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6036        let project = self.project().read(cx);
 6037        project
 6038            .visible_worktrees(cx)
 6039            .map(|worktree| worktree.read(cx).abs_path())
 6040            .collect::<Vec<_>>()
 6041    }
 6042
 6043    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6044        match member {
 6045            Member::Axis(PaneAxis { members, .. }) => {
 6046                for child in members.iter() {
 6047                    self.remove_panes(child.clone(), window, cx)
 6048                }
 6049            }
 6050            Member::Pane(pane) => {
 6051                self.force_remove_pane(&pane, &None, window, cx);
 6052            }
 6053        }
 6054    }
 6055
 6056    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6057        self.session_id.take();
 6058        self.serialize_workspace_internal(window, cx)
 6059    }
 6060
 6061    fn force_remove_pane(
 6062        &mut self,
 6063        pane: &Entity<Pane>,
 6064        focus_on: &Option<Entity<Pane>>,
 6065        window: &mut Window,
 6066        cx: &mut Context<Workspace>,
 6067    ) {
 6068        self.panes.retain(|p| p != pane);
 6069        if let Some(focus_on) = focus_on {
 6070            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6071        } else if self.active_pane() == pane {
 6072            self.panes
 6073                .last()
 6074                .unwrap()
 6075                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6076        }
 6077        if self.last_active_center_pane == Some(pane.downgrade()) {
 6078            self.last_active_center_pane = None;
 6079        }
 6080        cx.notify();
 6081    }
 6082
 6083    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6084        if self._schedule_serialize_workspace.is_none() {
 6085            self._schedule_serialize_workspace =
 6086                Some(cx.spawn_in(window, async move |this, cx| {
 6087                    cx.background_executor()
 6088                        .timer(SERIALIZATION_THROTTLE_TIME)
 6089                        .await;
 6090                    this.update_in(cx, |this, window, cx| {
 6091                        this._serialize_workspace_task =
 6092                            Some(this.serialize_workspace_internal(window, cx));
 6093                        this._schedule_serialize_workspace.take();
 6094                    })
 6095                    .log_err();
 6096                }));
 6097        }
 6098    }
 6099
 6100    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6101        let Some(database_id) = self.database_id() else {
 6102            return Task::ready(());
 6103        };
 6104
 6105        fn serialize_pane_handle(
 6106            pane_handle: &Entity<Pane>,
 6107            window: &mut Window,
 6108            cx: &mut App,
 6109        ) -> SerializedPane {
 6110            let (items, active, pinned_count) = {
 6111                let pane = pane_handle.read(cx);
 6112                let active_item_id = pane.active_item().map(|item| item.item_id());
 6113                (
 6114                    pane.items()
 6115                        .filter_map(|handle| {
 6116                            let handle = handle.to_serializable_item_handle(cx)?;
 6117
 6118                            Some(SerializedItem {
 6119                                kind: Arc::from(handle.serialized_item_kind()),
 6120                                item_id: handle.item_id().as_u64(),
 6121                                active: Some(handle.item_id()) == active_item_id,
 6122                                preview: pane.is_active_preview_item(handle.item_id()),
 6123                            })
 6124                        })
 6125                        .collect::<Vec<_>>(),
 6126                    pane.has_focus(window, cx),
 6127                    pane.pinned_count(),
 6128                )
 6129            };
 6130
 6131            SerializedPane::new(items, active, pinned_count)
 6132        }
 6133
 6134        fn build_serialized_pane_group(
 6135            pane_group: &Member,
 6136            window: &mut Window,
 6137            cx: &mut App,
 6138        ) -> SerializedPaneGroup {
 6139            match pane_group {
 6140                Member::Axis(PaneAxis {
 6141                    axis,
 6142                    members,
 6143                    flexes,
 6144                    bounding_boxes: _,
 6145                }) => SerializedPaneGroup::Group {
 6146                    axis: SerializedAxis(*axis),
 6147                    children: members
 6148                        .iter()
 6149                        .map(|member| build_serialized_pane_group(member, window, cx))
 6150                        .collect::<Vec<_>>(),
 6151                    flexes: Some(flexes.lock().clone()),
 6152                },
 6153                Member::Pane(pane_handle) => {
 6154                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6155                }
 6156            }
 6157        }
 6158
 6159        fn build_serialized_docks(
 6160            this: &Workspace,
 6161            window: &mut Window,
 6162            cx: &mut App,
 6163        ) -> DockStructure {
 6164            this.capture_dock_state(window, cx)
 6165        }
 6166
 6167        match self.workspace_location(cx) {
 6168            WorkspaceLocation::Location(location, paths) => {
 6169                let breakpoints = self.project.update(cx, |project, cx| {
 6170                    project
 6171                        .breakpoint_store()
 6172                        .read(cx)
 6173                        .all_source_breakpoints(cx)
 6174                });
 6175                let user_toolchains = self
 6176                    .project
 6177                    .read(cx)
 6178                    .user_toolchains(cx)
 6179                    .unwrap_or_default();
 6180
 6181                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6182                let docks = build_serialized_docks(self, window, cx);
 6183                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6184
 6185                let serialized_workspace = SerializedWorkspace {
 6186                    id: database_id,
 6187                    location,
 6188                    paths,
 6189                    center_group,
 6190                    window_bounds,
 6191                    display: Default::default(),
 6192                    docks,
 6193                    centered_layout: self.centered_layout,
 6194                    session_id: self.session_id.clone(),
 6195                    breakpoints,
 6196                    window_id: Some(window.window_handle().window_id().as_u64()),
 6197                    user_toolchains,
 6198                };
 6199
 6200                window.spawn(cx, async move |_| {
 6201                    persistence::DB.save_workspace(serialized_workspace).await;
 6202                })
 6203            }
 6204            WorkspaceLocation::DetachFromSession => {
 6205                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6206                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6207                // Save dock state for empty local workspaces
 6208                let docks = build_serialized_docks(self, window, cx);
 6209                window.spawn(cx, async move |_| {
 6210                    persistence::DB
 6211                        .set_window_open_status(
 6212                            database_id,
 6213                            window_bounds,
 6214                            display.unwrap_or_default(),
 6215                        )
 6216                        .await
 6217                        .log_err();
 6218                    persistence::DB
 6219                        .set_session_id(database_id, None)
 6220                        .await
 6221                        .log_err();
 6222                    persistence::write_default_dock_state(docks).await.log_err();
 6223                })
 6224            }
 6225            WorkspaceLocation::None => {
 6226                // Save dock state for empty non-local workspaces
 6227                let docks = build_serialized_docks(self, window, cx);
 6228                window.spawn(cx, async move |_| {
 6229                    persistence::write_default_dock_state(docks).await.log_err();
 6230                })
 6231            }
 6232        }
 6233    }
 6234
 6235    fn has_any_items_open(&self, cx: &App) -> bool {
 6236        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6237    }
 6238
 6239    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6240        let paths = PathList::new(&self.root_paths(cx));
 6241        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6242            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6243        } else if self.project.read(cx).is_local() {
 6244            if !paths.is_empty() || self.has_any_items_open(cx) {
 6245                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6246            } else {
 6247                WorkspaceLocation::DetachFromSession
 6248            }
 6249        } else {
 6250            WorkspaceLocation::None
 6251        }
 6252    }
 6253
 6254    fn update_history(&self, cx: &mut App) {
 6255        let Some(id) = self.database_id() else {
 6256            return;
 6257        };
 6258        if !self.project.read(cx).is_local() {
 6259            return;
 6260        }
 6261        if let Some(manager) = HistoryManager::global(cx) {
 6262            let paths = PathList::new(&self.root_paths(cx));
 6263            manager.update(cx, |this, cx| {
 6264                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6265            });
 6266        }
 6267    }
 6268
 6269    async fn serialize_items(
 6270        this: &WeakEntity<Self>,
 6271        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6272        cx: &mut AsyncWindowContext,
 6273    ) -> Result<()> {
 6274        const CHUNK_SIZE: usize = 200;
 6275
 6276        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6277
 6278        while let Some(items_received) = serializable_items.next().await {
 6279            let unique_items =
 6280                items_received
 6281                    .into_iter()
 6282                    .fold(HashMap::default(), |mut acc, item| {
 6283                        acc.entry(item.item_id()).or_insert(item);
 6284                        acc
 6285                    });
 6286
 6287            // We use into_iter() here so that the references to the items are moved into
 6288            // the tasks and not kept alive while we're sleeping.
 6289            for (_, item) in unique_items.into_iter() {
 6290                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6291                    item.serialize(workspace, false, window, cx)
 6292                }) {
 6293                    cx.background_spawn(async move { task.await.log_err() })
 6294                        .detach();
 6295                }
 6296            }
 6297
 6298            cx.background_executor()
 6299                .timer(SERIALIZATION_THROTTLE_TIME)
 6300                .await;
 6301        }
 6302
 6303        Ok(())
 6304    }
 6305
 6306    pub(crate) fn enqueue_item_serialization(
 6307        &mut self,
 6308        item: Box<dyn SerializableItemHandle>,
 6309    ) -> Result<()> {
 6310        self.serializable_items_tx
 6311            .unbounded_send(item)
 6312            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6313    }
 6314
 6315    pub(crate) fn load_workspace(
 6316        serialized_workspace: SerializedWorkspace,
 6317        paths_to_open: Vec<Option<ProjectPath>>,
 6318        window: &mut Window,
 6319        cx: &mut Context<Workspace>,
 6320    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6321        cx.spawn_in(window, async move |workspace, cx| {
 6322            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6323
 6324            let mut center_group = None;
 6325            let mut center_items = None;
 6326
 6327            // Traverse the splits tree and add to things
 6328            if let Some((group, active_pane, items)) = serialized_workspace
 6329                .center_group
 6330                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6331                .await
 6332            {
 6333                center_items = Some(items);
 6334                center_group = Some((group, active_pane))
 6335            }
 6336
 6337            let mut items_by_project_path = HashMap::default();
 6338            let mut item_ids_by_kind = HashMap::default();
 6339            let mut all_deserialized_items = Vec::default();
 6340            cx.update(|_, cx| {
 6341                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6342                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6343                        item_ids_by_kind
 6344                            .entry(serializable_item_handle.serialized_item_kind())
 6345                            .or_insert(Vec::new())
 6346                            .push(item.item_id().as_u64() as ItemId);
 6347                    }
 6348
 6349                    if let Some(project_path) = item.project_path(cx) {
 6350                        items_by_project_path.insert(project_path, item.clone());
 6351                    }
 6352                    all_deserialized_items.push(item);
 6353                }
 6354            })?;
 6355
 6356            let opened_items = paths_to_open
 6357                .into_iter()
 6358                .map(|path_to_open| {
 6359                    path_to_open
 6360                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6361                })
 6362                .collect::<Vec<_>>();
 6363
 6364            // Remove old panes from workspace panes list
 6365            workspace.update_in(cx, |workspace, window, cx| {
 6366                if let Some((center_group, active_pane)) = center_group {
 6367                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6368
 6369                    // Swap workspace center group
 6370                    workspace.center = PaneGroup::with_root(center_group);
 6371                    workspace.center.set_is_center(true);
 6372                    workspace.center.mark_positions(cx);
 6373
 6374                    if let Some(active_pane) = active_pane {
 6375                        workspace.set_active_pane(&active_pane, window, cx);
 6376                        cx.focus_self(window);
 6377                    } else {
 6378                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6379                    }
 6380                }
 6381
 6382                let docks = serialized_workspace.docks;
 6383
 6384                for (dock, serialized_dock) in [
 6385                    (&mut workspace.right_dock, docks.right),
 6386                    (&mut workspace.left_dock, docks.left),
 6387                    (&mut workspace.bottom_dock, docks.bottom),
 6388                ]
 6389                .iter_mut()
 6390                {
 6391                    dock.update(cx, |dock, cx| {
 6392                        dock.serialized_dock = Some(serialized_dock.clone());
 6393                        dock.restore_state(window, cx);
 6394                    });
 6395                }
 6396
 6397                cx.notify();
 6398            })?;
 6399
 6400            let _ = project
 6401                .update(cx, |project, cx| {
 6402                    project
 6403                        .breakpoint_store()
 6404                        .update(cx, |breakpoint_store, cx| {
 6405                            breakpoint_store
 6406                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6407                        })
 6408                })
 6409                .await;
 6410
 6411            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6412            // after loading the items, we might have different items and in order to avoid
 6413            // the database filling up, we delete items that haven't been loaded now.
 6414            //
 6415            // The items that have been loaded, have been saved after they've been added to the workspace.
 6416            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6417                item_ids_by_kind
 6418                    .into_iter()
 6419                    .map(|(item_kind, loaded_items)| {
 6420                        SerializableItemRegistry::cleanup(
 6421                            item_kind,
 6422                            serialized_workspace.id,
 6423                            loaded_items,
 6424                            window,
 6425                            cx,
 6426                        )
 6427                        .log_err()
 6428                    })
 6429                    .collect::<Vec<_>>()
 6430            })?;
 6431
 6432            futures::future::join_all(clean_up_tasks).await;
 6433
 6434            workspace
 6435                .update_in(cx, |workspace, window, cx| {
 6436                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6437                    workspace.serialize_workspace_internal(window, cx).detach();
 6438
 6439                    // Ensure that we mark the window as edited if we did load dirty items
 6440                    workspace.update_window_edited(window, cx);
 6441                })
 6442                .ok();
 6443
 6444            Ok(opened_items)
 6445        })
 6446    }
 6447
 6448    pub fn key_context(&self, cx: &App) -> KeyContext {
 6449        let mut context = KeyContext::new_with_defaults();
 6450        context.add("Workspace");
 6451        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6452        if let Some(status) = self
 6453            .debugger_provider
 6454            .as_ref()
 6455            .and_then(|provider| provider.active_thread_state(cx))
 6456        {
 6457            match status {
 6458                ThreadStatus::Running | ThreadStatus::Stepping => {
 6459                    context.add("debugger_running");
 6460                }
 6461                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6462                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6463            }
 6464        }
 6465
 6466        if self.left_dock.read(cx).is_open() {
 6467            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6468                context.set("left_dock", active_panel.panel_key());
 6469            }
 6470        }
 6471
 6472        if self.right_dock.read(cx).is_open() {
 6473            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6474                context.set("right_dock", active_panel.panel_key());
 6475            }
 6476        }
 6477
 6478        if self.bottom_dock.read(cx).is_open() {
 6479            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6480                context.set("bottom_dock", active_panel.panel_key());
 6481            }
 6482        }
 6483
 6484        context
 6485    }
 6486
 6487    /// Multiworkspace uses this to add workspace action handling to itself
 6488    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6489        self.add_workspace_actions_listeners(div, window, cx)
 6490            .on_action(cx.listener(
 6491                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6492                    for action in &action_sequence.0 {
 6493                        window.dispatch_action(action.boxed_clone(), cx);
 6494                    }
 6495                },
 6496            ))
 6497            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6498            .on_action(cx.listener(Self::close_all_items_and_panes))
 6499            .on_action(cx.listener(Self::close_item_in_all_panes))
 6500            .on_action(cx.listener(Self::save_all))
 6501            .on_action(cx.listener(Self::send_keystrokes))
 6502            .on_action(cx.listener(Self::add_folder_to_project))
 6503            .on_action(cx.listener(Self::follow_next_collaborator))
 6504            .on_action(cx.listener(Self::activate_pane_at_index))
 6505            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6506            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6507            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6508            .on_action(cx.listener(Self::toggle_theme_mode))
 6509            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6510                let pane = workspace.active_pane().clone();
 6511                workspace.unfollow_in_pane(&pane, window, cx);
 6512            }))
 6513            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6514                workspace
 6515                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6516                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6517            }))
 6518            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6519                workspace
 6520                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6521                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6522            }))
 6523            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6524                workspace
 6525                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6526                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6527            }))
 6528            .on_action(
 6529                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6530                    workspace.activate_previous_pane(window, cx)
 6531                }),
 6532            )
 6533            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6534                workspace.activate_next_pane(window, cx)
 6535            }))
 6536            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6537                workspace.activate_last_pane(window, cx)
 6538            }))
 6539            .on_action(
 6540                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6541                    workspace.activate_next_window(cx)
 6542                }),
 6543            )
 6544            .on_action(
 6545                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6546                    workspace.activate_previous_window(cx)
 6547                }),
 6548            )
 6549            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6550                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6551            }))
 6552            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6553                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6554            }))
 6555            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6556                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6557            }))
 6558            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6559                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6560            }))
 6561            .on_action(cx.listener(
 6562                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6563                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6564                },
 6565            ))
 6566            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6567                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6568            }))
 6569            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6570                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6571            }))
 6572            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6573                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6574            }))
 6575            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6576                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6577            }))
 6578            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6579                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6580                    SplitDirection::Down,
 6581                    SplitDirection::Up,
 6582                    SplitDirection::Right,
 6583                    SplitDirection::Left,
 6584                ];
 6585                for dir in DIRECTION_PRIORITY {
 6586                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6587                        workspace.swap_pane_in_direction(dir, cx);
 6588                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6589                        break;
 6590                    }
 6591                }
 6592            }))
 6593            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6594                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6595            }))
 6596            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6597                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6598            }))
 6599            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6600                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6601            }))
 6602            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6603                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6604            }))
 6605            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6606                this.toggle_dock(DockPosition::Left, window, cx);
 6607            }))
 6608            .on_action(cx.listener(
 6609                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6610                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6611                },
 6612            ))
 6613            .on_action(cx.listener(
 6614                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6615                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6616                },
 6617            ))
 6618            .on_action(cx.listener(
 6619                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6620                    if !workspace.close_active_dock(window, cx) {
 6621                        cx.propagate();
 6622                    }
 6623                },
 6624            ))
 6625            .on_action(
 6626                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6627                    workspace.close_all_docks(window, cx);
 6628                }),
 6629            )
 6630            .on_action(cx.listener(Self::toggle_all_docks))
 6631            .on_action(cx.listener(
 6632                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6633                    workspace.clear_all_notifications(cx);
 6634                },
 6635            ))
 6636            .on_action(cx.listener(
 6637                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6638                    workspace.clear_navigation_history(window, cx);
 6639                },
 6640            ))
 6641            .on_action(cx.listener(
 6642                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6643                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6644                        workspace.suppress_notification(&notification_id, cx);
 6645                    }
 6646                },
 6647            ))
 6648            .on_action(cx.listener(
 6649                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6650                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6651                },
 6652            ))
 6653            .on_action(
 6654                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6655                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6656                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6657                            trusted_worktrees.clear_trusted_paths()
 6658                        });
 6659                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6660                        cx.spawn(async move |_, cx| {
 6661                            if clear_task.await.log_err().is_some() {
 6662                                cx.update(|cx| reload(cx));
 6663                            }
 6664                        })
 6665                        .detach();
 6666                    }
 6667                }),
 6668            )
 6669            .on_action(cx.listener(
 6670                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6671                    workspace.reopen_closed_item(window, cx).detach();
 6672                },
 6673            ))
 6674            .on_action(cx.listener(
 6675                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6676                    for dock in workspace.all_docks() {
 6677                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6678                            let Some(panel) = dock.read(cx).active_panel() else {
 6679                                return;
 6680                            };
 6681
 6682                            // Set to `None`, then the size will fall back to the default.
 6683                            panel.clone().set_size(None, window, cx);
 6684
 6685                            return;
 6686                        }
 6687                    }
 6688                },
 6689            ))
 6690            .on_action(cx.listener(
 6691                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6692                    for dock in workspace.all_docks() {
 6693                        if let Some(panel) = dock.read(cx).visible_panel() {
 6694                            // Set to `None`, then the size will fall back to the default.
 6695                            panel.clone().set_size(None, window, cx);
 6696                        }
 6697                    }
 6698                },
 6699            ))
 6700            .on_action(cx.listener(
 6701                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6702                    adjust_active_dock_size_by_px(
 6703                        px_with_ui_font_fallback(act.px, cx),
 6704                        workspace,
 6705                        window,
 6706                        cx,
 6707                    );
 6708                },
 6709            ))
 6710            .on_action(cx.listener(
 6711                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6712                    adjust_active_dock_size_by_px(
 6713                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6714                        workspace,
 6715                        window,
 6716                        cx,
 6717                    );
 6718                },
 6719            ))
 6720            .on_action(cx.listener(
 6721                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6722                    adjust_open_docks_size_by_px(
 6723                        px_with_ui_font_fallback(act.px, cx),
 6724                        workspace,
 6725                        window,
 6726                        cx,
 6727                    );
 6728                },
 6729            ))
 6730            .on_action(cx.listener(
 6731                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6732                    adjust_open_docks_size_by_px(
 6733                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6734                        workspace,
 6735                        window,
 6736                        cx,
 6737                    );
 6738                },
 6739            ))
 6740            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6741            .on_action(cx.listener(
 6742                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6743                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6744                        let dock = active_dock.read(cx);
 6745                        if let Some(active_panel) = dock.active_panel() {
 6746                            if active_panel.pane(cx).is_none() {
 6747                                let mut recent_pane: Option<Entity<Pane>> = None;
 6748                                let mut recent_timestamp = 0;
 6749                                for pane_handle in workspace.panes() {
 6750                                    let pane = pane_handle.read(cx);
 6751                                    for entry in pane.activation_history() {
 6752                                        if entry.timestamp > recent_timestamp {
 6753                                            recent_timestamp = entry.timestamp;
 6754                                            recent_pane = Some(pane_handle.clone());
 6755                                        }
 6756                                    }
 6757                                }
 6758
 6759                                if let Some(pane) = recent_pane {
 6760                                    pane.update(cx, |pane, cx| {
 6761                                        let current_index = pane.active_item_index();
 6762                                        let items_len = pane.items_len();
 6763                                        if items_len > 0 {
 6764                                            let next_index = if current_index + 1 < items_len {
 6765                                                current_index + 1
 6766                                            } else {
 6767                                                0
 6768                                            };
 6769                                            pane.activate_item(
 6770                                                next_index, false, false, window, cx,
 6771                                            );
 6772                                        }
 6773                                    });
 6774                                    return;
 6775                                }
 6776                            }
 6777                        }
 6778                    }
 6779                    cx.propagate();
 6780                },
 6781            ))
 6782            .on_action(cx.listener(
 6783                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6784                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6785                        let dock = active_dock.read(cx);
 6786                        if let Some(active_panel) = dock.active_panel() {
 6787                            if active_panel.pane(cx).is_none() {
 6788                                let mut recent_pane: Option<Entity<Pane>> = None;
 6789                                let mut recent_timestamp = 0;
 6790                                for pane_handle in workspace.panes() {
 6791                                    let pane = pane_handle.read(cx);
 6792                                    for entry in pane.activation_history() {
 6793                                        if entry.timestamp > recent_timestamp {
 6794                                            recent_timestamp = entry.timestamp;
 6795                                            recent_pane = Some(pane_handle.clone());
 6796                                        }
 6797                                    }
 6798                                }
 6799
 6800                                if let Some(pane) = recent_pane {
 6801                                    pane.update(cx, |pane, cx| {
 6802                                        let current_index = pane.active_item_index();
 6803                                        let items_len = pane.items_len();
 6804                                        if items_len > 0 {
 6805                                            let prev_index = if current_index > 0 {
 6806                                                current_index - 1
 6807                                            } else {
 6808                                                items_len.saturating_sub(1)
 6809                                            };
 6810                                            pane.activate_item(
 6811                                                prev_index, false, false, window, cx,
 6812                                            );
 6813                                        }
 6814                                    });
 6815                                    return;
 6816                                }
 6817                            }
 6818                        }
 6819                    }
 6820                    cx.propagate();
 6821                },
 6822            ))
 6823            .on_action(cx.listener(
 6824                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6825                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6826                        let dock = active_dock.read(cx);
 6827                        if let Some(active_panel) = dock.active_panel() {
 6828                            if active_panel.pane(cx).is_none() {
 6829                                let active_pane = workspace.active_pane().clone();
 6830                                active_pane.update(cx, |pane, cx| {
 6831                                    pane.close_active_item(action, window, cx)
 6832                                        .detach_and_log_err(cx);
 6833                                });
 6834                                return;
 6835                            }
 6836                        }
 6837                    }
 6838                    cx.propagate();
 6839                },
 6840            ))
 6841            .on_action(
 6842                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6843                    let pane = workspace.active_pane().clone();
 6844                    if let Some(item) = pane.read(cx).active_item() {
 6845                        item.toggle_read_only(window, cx);
 6846                    }
 6847                }),
 6848            )
 6849            .on_action(cx.listener(Workspace::cancel))
 6850    }
 6851
 6852    #[cfg(any(test, feature = "test-support"))]
 6853    pub fn set_random_database_id(&mut self) {
 6854        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6855    }
 6856
 6857    #[cfg(any(test, feature = "test-support"))]
 6858    pub(crate) fn test_new(
 6859        project: Entity<Project>,
 6860        window: &mut Window,
 6861        cx: &mut Context<Self>,
 6862    ) -> Self {
 6863        use node_runtime::NodeRuntime;
 6864        use session::Session;
 6865
 6866        let client = project.read(cx).client();
 6867        let user_store = project.read(cx).user_store();
 6868        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6869        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6870        window.activate_window();
 6871        let app_state = Arc::new(AppState {
 6872            languages: project.read(cx).languages().clone(),
 6873            workspace_store,
 6874            client,
 6875            user_store,
 6876            fs: project.read(cx).fs().clone(),
 6877            build_window_options: |_, _| Default::default(),
 6878            node_runtime: NodeRuntime::unavailable(),
 6879            session,
 6880        });
 6881        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6882        workspace
 6883            .active_pane
 6884            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6885        workspace
 6886    }
 6887
 6888    pub fn register_action<A: Action>(
 6889        &mut self,
 6890        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6891    ) -> &mut Self {
 6892        let callback = Arc::new(callback);
 6893
 6894        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6895            let callback = callback.clone();
 6896            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6897                (callback)(workspace, event, window, cx)
 6898            }))
 6899        }));
 6900        self
 6901    }
 6902    pub fn register_action_renderer(
 6903        &mut self,
 6904        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6905    ) -> &mut Self {
 6906        self.workspace_actions.push(Box::new(callback));
 6907        self
 6908    }
 6909
 6910    fn add_workspace_actions_listeners(
 6911        &self,
 6912        mut div: Div,
 6913        window: &mut Window,
 6914        cx: &mut Context<Self>,
 6915    ) -> Div {
 6916        for action in self.workspace_actions.iter() {
 6917            div = (action)(div, self, window, cx)
 6918        }
 6919        div
 6920    }
 6921
 6922    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6923        self.modal_layer.read(cx).has_active_modal()
 6924    }
 6925
 6926    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6927        self.modal_layer.read(cx).active_modal()
 6928    }
 6929
 6930    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6931    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6932    /// If no modal is active, the new modal will be shown.
 6933    ///
 6934    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6935    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6936    /// will not be shown.
 6937    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6938    where
 6939        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6940    {
 6941        self.modal_layer.update(cx, |modal_layer, cx| {
 6942            modal_layer.toggle_modal(window, cx, build)
 6943        })
 6944    }
 6945
 6946    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6947        self.modal_layer
 6948            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6949    }
 6950
 6951    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6952        self.toast_layer
 6953            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6954    }
 6955
 6956    pub fn toggle_centered_layout(
 6957        &mut self,
 6958        _: &ToggleCenteredLayout,
 6959        _: &mut Window,
 6960        cx: &mut Context<Self>,
 6961    ) {
 6962        self.centered_layout = !self.centered_layout;
 6963        if let Some(database_id) = self.database_id() {
 6964            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6965                .detach_and_log_err(cx);
 6966        }
 6967        cx.notify();
 6968    }
 6969
 6970    fn adjust_padding(padding: Option<f32>) -> f32 {
 6971        padding
 6972            .unwrap_or(CenteredPaddingSettings::default().0)
 6973            .clamp(
 6974                CenteredPaddingSettings::MIN_PADDING,
 6975                CenteredPaddingSettings::MAX_PADDING,
 6976            )
 6977    }
 6978
 6979    fn render_dock(
 6980        &self,
 6981        position: DockPosition,
 6982        dock: &Entity<Dock>,
 6983        window: &mut Window,
 6984        cx: &mut App,
 6985    ) -> Option<Div> {
 6986        if self.zoomed_position == Some(position) {
 6987            return None;
 6988        }
 6989
 6990        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6991            let pane = panel.pane(cx)?;
 6992            let follower_states = &self.follower_states;
 6993            leader_border_for_pane(follower_states, &pane, window, cx)
 6994        });
 6995
 6996        Some(
 6997            div()
 6998                .flex()
 6999                .flex_none()
 7000                .overflow_hidden()
 7001                .child(dock.clone())
 7002                .children(leader_border),
 7003        )
 7004    }
 7005
 7006    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7007        window
 7008            .root::<MultiWorkspace>()
 7009            .flatten()
 7010            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7011    }
 7012
 7013    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7014        self.zoomed.as_ref()
 7015    }
 7016
 7017    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7018        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7019            return;
 7020        };
 7021        let windows = cx.windows();
 7022        let next_window =
 7023            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7024                || {
 7025                    windows
 7026                        .iter()
 7027                        .cycle()
 7028                        .skip_while(|window| window.window_id() != current_window_id)
 7029                        .nth(1)
 7030                },
 7031            );
 7032
 7033        if let Some(window) = next_window {
 7034            window
 7035                .update(cx, |_, window, _| window.activate_window())
 7036                .ok();
 7037        }
 7038    }
 7039
 7040    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7041        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7042            return;
 7043        };
 7044        let windows = cx.windows();
 7045        let prev_window =
 7046            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7047                || {
 7048                    windows
 7049                        .iter()
 7050                        .rev()
 7051                        .cycle()
 7052                        .skip_while(|window| window.window_id() != current_window_id)
 7053                        .nth(1)
 7054                },
 7055            );
 7056
 7057        if let Some(window) = prev_window {
 7058            window
 7059                .update(cx, |_, window, _| window.activate_window())
 7060                .ok();
 7061        }
 7062    }
 7063
 7064    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7065        if cx.stop_active_drag(window) {
 7066        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7067            dismiss_app_notification(&notification_id, cx);
 7068        } else {
 7069            cx.propagate();
 7070        }
 7071    }
 7072
 7073    fn adjust_dock_size_by_px(
 7074        &mut self,
 7075        panel_size: Pixels,
 7076        dock_pos: DockPosition,
 7077        px: Pixels,
 7078        window: &mut Window,
 7079        cx: &mut Context<Self>,
 7080    ) {
 7081        match dock_pos {
 7082            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7083            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7084            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7085        }
 7086    }
 7087
 7088    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7089        let workspace_width = self.bounds.size.width;
 7090        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7091
 7092        self.right_dock.read_with(cx, |right_dock, cx| {
 7093            let right_dock_size = right_dock
 7094                .active_panel_size(window, cx)
 7095                .unwrap_or(Pixels::ZERO);
 7096            if right_dock_size + size > workspace_width {
 7097                size = workspace_width - right_dock_size
 7098            }
 7099        });
 7100
 7101        self.left_dock.update(cx, |left_dock, cx| {
 7102            if WorkspaceSettings::get_global(cx)
 7103                .resize_all_panels_in_dock
 7104                .contains(&DockPosition::Left)
 7105            {
 7106                left_dock.resize_all_panels(Some(size), window, cx);
 7107            } else {
 7108                left_dock.resize_active_panel(Some(size), window, cx);
 7109            }
 7110        });
 7111    }
 7112
 7113    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7114        let workspace_width = self.bounds.size.width;
 7115        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7116        self.left_dock.read_with(cx, |left_dock, cx| {
 7117            let left_dock_size = left_dock
 7118                .active_panel_size(window, cx)
 7119                .unwrap_or(Pixels::ZERO);
 7120            if left_dock_size + size > workspace_width {
 7121                size = workspace_width - left_dock_size
 7122            }
 7123        });
 7124        self.right_dock.update(cx, |right_dock, cx| {
 7125            if WorkspaceSettings::get_global(cx)
 7126                .resize_all_panels_in_dock
 7127                .contains(&DockPosition::Right)
 7128            {
 7129                right_dock.resize_all_panels(Some(size), window, cx);
 7130            } else {
 7131                right_dock.resize_active_panel(Some(size), window, cx);
 7132            }
 7133        });
 7134    }
 7135
 7136    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7137        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7138        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7139            if WorkspaceSettings::get_global(cx)
 7140                .resize_all_panels_in_dock
 7141                .contains(&DockPosition::Bottom)
 7142            {
 7143                bottom_dock.resize_all_panels(Some(size), window, cx);
 7144            } else {
 7145                bottom_dock.resize_active_panel(Some(size), window, cx);
 7146            }
 7147        });
 7148    }
 7149
 7150    fn toggle_edit_predictions_all_files(
 7151        &mut self,
 7152        _: &ToggleEditPrediction,
 7153        _window: &mut Window,
 7154        cx: &mut Context<Self>,
 7155    ) {
 7156        let fs = self.project().read(cx).fs().clone();
 7157        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7158        update_settings_file(fs, cx, move |file, _| {
 7159            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7160        });
 7161    }
 7162
 7163    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7164        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7165        let next_mode = match current_mode {
 7166            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7167            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7168            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7169                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7170                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7171            },
 7172        };
 7173
 7174        let fs = self.project().read(cx).fs().clone();
 7175        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7176            theme::set_mode(settings, next_mode);
 7177        });
 7178    }
 7179
 7180    pub fn show_worktree_trust_security_modal(
 7181        &mut self,
 7182        toggle: bool,
 7183        window: &mut Window,
 7184        cx: &mut Context<Self>,
 7185    ) {
 7186        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7187            if toggle {
 7188                security_modal.update(cx, |security_modal, cx| {
 7189                    security_modal.dismiss(cx);
 7190                })
 7191            } else {
 7192                security_modal.update(cx, |security_modal, cx| {
 7193                    security_modal.refresh_restricted_paths(cx);
 7194                });
 7195            }
 7196        } else {
 7197            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7198                .map(|trusted_worktrees| {
 7199                    trusted_worktrees
 7200                        .read(cx)
 7201                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7202                })
 7203                .unwrap_or(false);
 7204            if has_restricted_worktrees {
 7205                let project = self.project().read(cx);
 7206                let remote_host = project
 7207                    .remote_connection_options(cx)
 7208                    .map(RemoteHostLocation::from);
 7209                let worktree_store = project.worktree_store().downgrade();
 7210                self.toggle_modal(window, cx, |_, cx| {
 7211                    SecurityModal::new(worktree_store, remote_host, cx)
 7212                });
 7213            }
 7214        }
 7215    }
 7216}
 7217
 7218pub trait AnyActiveCall {
 7219    fn entity(&self) -> AnyEntity;
 7220    fn is_in_room(&self, _: &App) -> bool;
 7221    fn room_id(&self, _: &App) -> Option<u64>;
 7222    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7223    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7224    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7225    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7226    fn is_sharing_project(&self, _: &App) -> bool;
 7227    fn has_remote_participants(&self, _: &App) -> bool;
 7228    fn local_participant_is_guest(&self, _: &App) -> bool;
 7229    fn client(&self, _: &App) -> Arc<Client>;
 7230    fn share_on_join(&self, _: &App) -> bool;
 7231    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7232    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7233    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7234    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7235    fn join_project(
 7236        &self,
 7237        _: u64,
 7238        _: Arc<LanguageRegistry>,
 7239        _: Arc<dyn Fs>,
 7240        _: &mut App,
 7241    ) -> Task<Result<Entity<Project>>>;
 7242    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7243    fn subscribe(
 7244        &self,
 7245        _: &mut Window,
 7246        _: &mut Context<Workspace>,
 7247        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7248    ) -> Subscription;
 7249    fn create_shared_screen(
 7250        &self,
 7251        _: PeerId,
 7252        _: &Entity<Pane>,
 7253        _: &mut Window,
 7254        _: &mut App,
 7255    ) -> Option<Entity<SharedScreen>>;
 7256}
 7257
 7258#[derive(Clone)]
 7259pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7260impl Global for GlobalAnyActiveCall {}
 7261
 7262impl GlobalAnyActiveCall {
 7263    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7264        cx.try_global()
 7265    }
 7266
 7267    pub(crate) fn global(cx: &App) -> &Self {
 7268        cx.global()
 7269    }
 7270}
 7271/// Workspace-local view of a remote participant's location.
 7272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7273pub enum ParticipantLocation {
 7274    SharedProject { project_id: u64 },
 7275    UnsharedProject,
 7276    External,
 7277}
 7278
 7279impl ParticipantLocation {
 7280    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7281        match location
 7282            .and_then(|l| l.variant)
 7283            .context("participant location was not provided")?
 7284        {
 7285            proto::participant_location::Variant::SharedProject(project) => {
 7286                Ok(Self::SharedProject {
 7287                    project_id: project.id,
 7288                })
 7289            }
 7290            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7291            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7292        }
 7293    }
 7294}
 7295/// Workspace-local view of a remote collaborator's state.
 7296/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7297#[derive(Clone)]
 7298pub struct RemoteCollaborator {
 7299    pub user: Arc<User>,
 7300    pub peer_id: PeerId,
 7301    pub location: ParticipantLocation,
 7302    pub participant_index: ParticipantIndex,
 7303}
 7304
 7305pub enum ActiveCallEvent {
 7306    ParticipantLocationChanged { participant_id: PeerId },
 7307    RemoteVideoTracksChanged { participant_id: PeerId },
 7308}
 7309
 7310fn leader_border_for_pane(
 7311    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7312    pane: &Entity<Pane>,
 7313    _: &Window,
 7314    cx: &App,
 7315) -> Option<Div> {
 7316    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7317        if state.pane() == pane {
 7318            Some((*leader_id, state))
 7319        } else {
 7320            None
 7321        }
 7322    })?;
 7323
 7324    let mut leader_color = match leader_id {
 7325        CollaboratorId::PeerId(leader_peer_id) => {
 7326            let leader = GlobalAnyActiveCall::try_global(cx)?
 7327                .0
 7328                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7329
 7330            cx.theme()
 7331                .players()
 7332                .color_for_participant(leader.participant_index.0)
 7333                .cursor
 7334        }
 7335        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7336    };
 7337    leader_color.fade_out(0.3);
 7338    Some(
 7339        div()
 7340            .absolute()
 7341            .size_full()
 7342            .left_0()
 7343            .top_0()
 7344            .border_2()
 7345            .border_color(leader_color),
 7346    )
 7347}
 7348
 7349fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7350    ZED_WINDOW_POSITION
 7351        .zip(*ZED_WINDOW_SIZE)
 7352        .map(|(position, size)| Bounds {
 7353            origin: position,
 7354            size,
 7355        })
 7356}
 7357
 7358fn open_items(
 7359    serialized_workspace: Option<SerializedWorkspace>,
 7360    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7361    window: &mut Window,
 7362    cx: &mut Context<Workspace>,
 7363) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7364    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7365        Workspace::load_workspace(
 7366            serialized_workspace,
 7367            project_paths_to_open
 7368                .iter()
 7369                .map(|(_, project_path)| project_path)
 7370                .cloned()
 7371                .collect(),
 7372            window,
 7373            cx,
 7374        )
 7375    });
 7376
 7377    cx.spawn_in(window, async move |workspace, cx| {
 7378        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7379
 7380        if let Some(restored_items) = restored_items {
 7381            let restored_items = restored_items.await?;
 7382
 7383            let restored_project_paths = restored_items
 7384                .iter()
 7385                .filter_map(|item| {
 7386                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7387                        .ok()
 7388                        .flatten()
 7389                })
 7390                .collect::<HashSet<_>>();
 7391
 7392            for restored_item in restored_items {
 7393                opened_items.push(restored_item.map(Ok));
 7394            }
 7395
 7396            project_paths_to_open
 7397                .iter_mut()
 7398                .for_each(|(_, project_path)| {
 7399                    if let Some(project_path_to_open) = project_path
 7400                        && restored_project_paths.contains(project_path_to_open)
 7401                    {
 7402                        *project_path = None;
 7403                    }
 7404                });
 7405        } else {
 7406            for _ in 0..project_paths_to_open.len() {
 7407                opened_items.push(None);
 7408            }
 7409        }
 7410        assert!(opened_items.len() == project_paths_to_open.len());
 7411
 7412        let tasks =
 7413            project_paths_to_open
 7414                .into_iter()
 7415                .enumerate()
 7416                .map(|(ix, (abs_path, project_path))| {
 7417                    let workspace = workspace.clone();
 7418                    cx.spawn(async move |cx| {
 7419                        let file_project_path = project_path?;
 7420                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7421                            workspace.project().update(cx, |project, cx| {
 7422                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7423                            })
 7424                        });
 7425
 7426                        // We only want to open file paths here. If one of the items
 7427                        // here is a directory, it was already opened further above
 7428                        // with a `find_or_create_worktree`.
 7429                        if let Ok(task) = abs_path_task
 7430                            && task.await.is_none_or(|p| p.is_file())
 7431                        {
 7432                            return Some((
 7433                                ix,
 7434                                workspace
 7435                                    .update_in(cx, |workspace, window, cx| {
 7436                                        workspace.open_path(
 7437                                            file_project_path,
 7438                                            None,
 7439                                            true,
 7440                                            window,
 7441                                            cx,
 7442                                        )
 7443                                    })
 7444                                    .log_err()?
 7445                                    .await,
 7446                            ));
 7447                        }
 7448                        None
 7449                    })
 7450                });
 7451
 7452        let tasks = tasks.collect::<Vec<_>>();
 7453
 7454        let tasks = futures::future::join_all(tasks);
 7455        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7456            opened_items[ix] = Some(path_open_result);
 7457        }
 7458
 7459        Ok(opened_items)
 7460    })
 7461}
 7462
 7463enum ActivateInDirectionTarget {
 7464    Pane(Entity<Pane>),
 7465    Dock(Entity<Dock>),
 7466}
 7467
 7468fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7469    window
 7470        .update(cx, |multi_workspace, _, cx| {
 7471            let workspace = multi_workspace.workspace().clone();
 7472            workspace.update(cx, |workspace, cx| {
 7473                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7474                    struct DatabaseFailedNotification;
 7475
 7476                    workspace.show_notification(
 7477                        NotificationId::unique::<DatabaseFailedNotification>(),
 7478                        cx,
 7479                        |cx| {
 7480                            cx.new(|cx| {
 7481                                MessageNotification::new("Failed to load the database file.", cx)
 7482                                    .primary_message("File an Issue")
 7483                                    .primary_icon(IconName::Plus)
 7484                                    .primary_on_click(|window, cx| {
 7485                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7486                                    })
 7487                            })
 7488                        },
 7489                    );
 7490                }
 7491            });
 7492        })
 7493        .log_err();
 7494}
 7495
 7496fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7497    if val == 0 {
 7498        ThemeSettings::get_global(cx).ui_font_size(cx)
 7499    } else {
 7500        px(val as f32)
 7501    }
 7502}
 7503
 7504fn adjust_active_dock_size_by_px(
 7505    px: Pixels,
 7506    workspace: &mut Workspace,
 7507    window: &mut Window,
 7508    cx: &mut Context<Workspace>,
 7509) {
 7510    let Some(active_dock) = workspace
 7511        .all_docks()
 7512        .into_iter()
 7513        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7514    else {
 7515        return;
 7516    };
 7517    let dock = active_dock.read(cx);
 7518    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7519        return;
 7520    };
 7521    let dock_pos = dock.position();
 7522    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7523}
 7524
 7525fn adjust_open_docks_size_by_px(
 7526    px: Pixels,
 7527    workspace: &mut Workspace,
 7528    window: &mut Window,
 7529    cx: &mut Context<Workspace>,
 7530) {
 7531    let docks = workspace
 7532        .all_docks()
 7533        .into_iter()
 7534        .filter_map(|dock| {
 7535            if dock.read(cx).is_open() {
 7536                let dock = dock.read(cx);
 7537                let panel_size = dock.active_panel_size(window, cx)?;
 7538                let dock_pos = dock.position();
 7539                Some((panel_size, dock_pos, px))
 7540            } else {
 7541                None
 7542            }
 7543        })
 7544        .collect::<Vec<_>>();
 7545
 7546    docks
 7547        .into_iter()
 7548        .for_each(|(panel_size, dock_pos, offset)| {
 7549            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7550        });
 7551}
 7552
 7553impl Focusable for Workspace {
 7554    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7555        self.active_pane.focus_handle(cx)
 7556    }
 7557}
 7558
 7559#[derive(Clone)]
 7560struct DraggedDock(DockPosition);
 7561
 7562impl Render for DraggedDock {
 7563    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7564        gpui::Empty
 7565    }
 7566}
 7567
 7568impl Render for Workspace {
 7569    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7570        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7571        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7572            log::info!("Rendered first frame");
 7573        }
 7574
 7575        let centered_layout = self.centered_layout
 7576            && self.center.panes().len() == 1
 7577            && self.active_item(cx).is_some();
 7578        let render_padding = |size| {
 7579            (size > 0.0).then(|| {
 7580                div()
 7581                    .h_full()
 7582                    .w(relative(size))
 7583                    .bg(cx.theme().colors().editor_background)
 7584                    .border_color(cx.theme().colors().pane_group_border)
 7585            })
 7586        };
 7587        let paddings = if centered_layout {
 7588            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7589            (
 7590                render_padding(Self::adjust_padding(
 7591                    settings.left_padding.map(|padding| padding.0),
 7592                )),
 7593                render_padding(Self::adjust_padding(
 7594                    settings.right_padding.map(|padding| padding.0),
 7595                )),
 7596            )
 7597        } else {
 7598            (None, None)
 7599        };
 7600        let ui_font = theme::setup_ui_font(window, cx);
 7601
 7602        let theme = cx.theme().clone();
 7603        let colors = theme.colors();
 7604        let notification_entities = self
 7605            .notifications
 7606            .iter()
 7607            .map(|(_, notification)| notification.entity_id())
 7608            .collect::<Vec<_>>();
 7609        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7610
 7611        div()
 7612            .relative()
 7613            .size_full()
 7614            .flex()
 7615            .flex_col()
 7616            .font(ui_font)
 7617            .gap_0()
 7618                .justify_start()
 7619                .items_start()
 7620                .text_color(colors.text)
 7621                .overflow_hidden()
 7622                .children(self.titlebar_item.clone())
 7623                .on_modifiers_changed(move |_, _, cx| {
 7624                    for &id in &notification_entities {
 7625                        cx.notify(id);
 7626                    }
 7627                })
 7628                .child(
 7629                    div()
 7630                        .size_full()
 7631                        .relative()
 7632                        .flex_1()
 7633                        .flex()
 7634                        .flex_col()
 7635                        .child(
 7636                            div()
 7637                                .id("workspace")
 7638                                .bg(colors.background)
 7639                                .relative()
 7640                                .flex_1()
 7641                                .w_full()
 7642                                .flex()
 7643                                .flex_col()
 7644                                .overflow_hidden()
 7645                                .border_t_1()
 7646                                .border_b_1()
 7647                                .border_color(colors.border)
 7648                                .child({
 7649                                    let this = cx.entity();
 7650                                    canvas(
 7651                                        move |bounds, window, cx| {
 7652                                            this.update(cx, |this, cx| {
 7653                                                let bounds_changed = this.bounds != bounds;
 7654                                                this.bounds = bounds;
 7655
 7656                                                if bounds_changed {
 7657                                                    this.left_dock.update(cx, |dock, cx| {
 7658                                                        dock.clamp_panel_size(
 7659                                                            bounds.size.width,
 7660                                                            window,
 7661                                                            cx,
 7662                                                        )
 7663                                                    });
 7664
 7665                                                    this.right_dock.update(cx, |dock, cx| {
 7666                                                        dock.clamp_panel_size(
 7667                                                            bounds.size.width,
 7668                                                            window,
 7669                                                            cx,
 7670                                                        )
 7671                                                    });
 7672
 7673                                                    this.bottom_dock.update(cx, |dock, cx| {
 7674                                                        dock.clamp_panel_size(
 7675                                                            bounds.size.height,
 7676                                                            window,
 7677                                                            cx,
 7678                                                        )
 7679                                                    });
 7680                                                }
 7681                                            })
 7682                                        },
 7683                                        |_, _, _, _| {},
 7684                                    )
 7685                                    .absolute()
 7686                                    .size_full()
 7687                                })
 7688                                .when(self.zoomed.is_none(), |this| {
 7689                                    this.on_drag_move(cx.listener(
 7690                                        move |workspace,
 7691                                              e: &DragMoveEvent<DraggedDock>,
 7692                                              window,
 7693                                              cx| {
 7694                                            if workspace.previous_dock_drag_coordinates
 7695                                                != Some(e.event.position)
 7696                                            {
 7697                                                workspace.previous_dock_drag_coordinates =
 7698                                                    Some(e.event.position);
 7699
 7700                                                match e.drag(cx).0 {
 7701                                                    DockPosition::Left => {
 7702                                                        workspace.resize_left_dock(
 7703                                                            e.event.position.x
 7704                                                                - workspace.bounds.left(),
 7705                                                            window,
 7706                                                            cx,
 7707                                                        );
 7708                                                    }
 7709                                                    DockPosition::Right => {
 7710                                                        workspace.resize_right_dock(
 7711                                                            workspace.bounds.right()
 7712                                                                - e.event.position.x,
 7713                                                            window,
 7714                                                            cx,
 7715                                                        );
 7716                                                    }
 7717                                                    DockPosition::Bottom => {
 7718                                                        workspace.resize_bottom_dock(
 7719                                                            workspace.bounds.bottom()
 7720                                                                - e.event.position.y,
 7721                                                            window,
 7722                                                            cx,
 7723                                                        );
 7724                                                    }
 7725                                                };
 7726                                                workspace.serialize_workspace(window, cx);
 7727                                            }
 7728                                        },
 7729                                    ))
 7730
 7731                                })
 7732                                .child({
 7733                                    match bottom_dock_layout {
 7734                                        BottomDockLayout::Full => div()
 7735                                            .flex()
 7736                                            .flex_col()
 7737                                            .h_full()
 7738                                            .child(
 7739                                                div()
 7740                                                    .flex()
 7741                                                    .flex_row()
 7742                                                    .flex_1()
 7743                                                    .overflow_hidden()
 7744                                                    .children(self.render_dock(
 7745                                                        DockPosition::Left,
 7746                                                        &self.left_dock,
 7747                                                        window,
 7748                                                        cx,
 7749                                                    ))
 7750
 7751                                                    .child(
 7752                                                        div()
 7753                                                            .flex()
 7754                                                            .flex_col()
 7755                                                            .flex_1()
 7756                                                            .overflow_hidden()
 7757                                                            .child(
 7758                                                                h_flex()
 7759                                                                    .flex_1()
 7760                                                                    .when_some(
 7761                                                                        paddings.0,
 7762                                                                        |this, p| {
 7763                                                                            this.child(
 7764                                                                                p.border_r_1(),
 7765                                                                            )
 7766                                                                        },
 7767                                                                    )
 7768                                                                    .child(self.center.render(
 7769                                                                        self.zoomed.as_ref(),
 7770                                                                        &PaneRenderContext {
 7771                                                                            follower_states:
 7772                                                                                &self.follower_states,
 7773                                                                            active_call: self.active_call(),
 7774                                                                            active_pane: &self.active_pane,
 7775                                                                            app_state: &self.app_state,
 7776                                                                            project: &self.project,
 7777                                                                            workspace: &self.weak_self,
 7778                                                                        },
 7779                                                                        window,
 7780                                                                        cx,
 7781                                                                    ))
 7782                                                                    .when_some(
 7783                                                                        paddings.1,
 7784                                                                        |this, p| {
 7785                                                                            this.child(
 7786                                                                                p.border_l_1(),
 7787                                                                            )
 7788                                                                        },
 7789                                                                    ),
 7790                                                            ),
 7791                                                    )
 7792
 7793                                                    .children(self.render_dock(
 7794                                                        DockPosition::Right,
 7795                                                        &self.right_dock,
 7796                                                        window,
 7797                                                        cx,
 7798                                                    )),
 7799                                            )
 7800                                            .child(div().w_full().children(self.render_dock(
 7801                                                DockPosition::Bottom,
 7802                                                &self.bottom_dock,
 7803                                                window,
 7804                                                cx
 7805                                            ))),
 7806
 7807                                        BottomDockLayout::LeftAligned => div()
 7808                                            .flex()
 7809                                            .flex_row()
 7810                                            .h_full()
 7811                                            .child(
 7812                                                div()
 7813                                                    .flex()
 7814                                                    .flex_col()
 7815                                                    .flex_1()
 7816                                                    .h_full()
 7817                                                    .child(
 7818                                                        div()
 7819                                                            .flex()
 7820                                                            .flex_row()
 7821                                                            .flex_1()
 7822                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7823
 7824                                                            .child(
 7825                                                                div()
 7826                                                                    .flex()
 7827                                                                    .flex_col()
 7828                                                                    .flex_1()
 7829                                                                    .overflow_hidden()
 7830                                                                    .child(
 7831                                                                        h_flex()
 7832                                                                            .flex_1()
 7833                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7834                                                                            .child(self.center.render(
 7835                                                                                self.zoomed.as_ref(),
 7836                                                                                &PaneRenderContext {
 7837                                                                                    follower_states:
 7838                                                                                        &self.follower_states,
 7839                                                                                    active_call: self.active_call(),
 7840                                                                                    active_pane: &self.active_pane,
 7841                                                                                    app_state: &self.app_state,
 7842                                                                                    project: &self.project,
 7843                                                                                    workspace: &self.weak_self,
 7844                                                                                },
 7845                                                                                window,
 7846                                                                                cx,
 7847                                                                            ))
 7848                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7849                                                                    )
 7850                                                            )
 7851
 7852                                                    )
 7853                                                    .child(
 7854                                                        div()
 7855                                                            .w_full()
 7856                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7857                                                    ),
 7858                                            )
 7859                                            .children(self.render_dock(
 7860                                                DockPosition::Right,
 7861                                                &self.right_dock,
 7862                                                window,
 7863                                                cx,
 7864                                            )),
 7865
 7866                                        BottomDockLayout::RightAligned => div()
 7867                                            .flex()
 7868                                            .flex_row()
 7869                                            .h_full()
 7870                                            .children(self.render_dock(
 7871                                                DockPosition::Left,
 7872                                                &self.left_dock,
 7873                                                window,
 7874                                                cx,
 7875                                            ))
 7876
 7877                                            .child(
 7878                                                div()
 7879                                                    .flex()
 7880                                                    .flex_col()
 7881                                                    .flex_1()
 7882                                                    .h_full()
 7883                                                    .child(
 7884                                                        div()
 7885                                                            .flex()
 7886                                                            .flex_row()
 7887                                                            .flex_1()
 7888                                                            .child(
 7889                                                                div()
 7890                                                                    .flex()
 7891                                                                    .flex_col()
 7892                                                                    .flex_1()
 7893                                                                    .overflow_hidden()
 7894                                                                    .child(
 7895                                                                        h_flex()
 7896                                                                            .flex_1()
 7897                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7898                                                                            .child(self.center.render(
 7899                                                                                self.zoomed.as_ref(),
 7900                                                                                &PaneRenderContext {
 7901                                                                                    follower_states:
 7902                                                                                        &self.follower_states,
 7903                                                                                    active_call: self.active_call(),
 7904                                                                                    active_pane: &self.active_pane,
 7905                                                                                    app_state: &self.app_state,
 7906                                                                                    project: &self.project,
 7907                                                                                    workspace: &self.weak_self,
 7908                                                                                },
 7909                                                                                window,
 7910                                                                                cx,
 7911                                                                            ))
 7912                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7913                                                                    )
 7914                                                            )
 7915
 7916                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7917                                                    )
 7918                                                    .child(
 7919                                                        div()
 7920                                                            .w_full()
 7921                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7922                                                    ),
 7923                                            ),
 7924
 7925                                        BottomDockLayout::Contained => div()
 7926                                            .flex()
 7927                                            .flex_row()
 7928                                            .h_full()
 7929                                            .children(self.render_dock(
 7930                                                DockPosition::Left,
 7931                                                &self.left_dock,
 7932                                                window,
 7933                                                cx,
 7934                                            ))
 7935
 7936                                            .child(
 7937                                                div()
 7938                                                    .flex()
 7939                                                    .flex_col()
 7940                                                    .flex_1()
 7941                                                    .overflow_hidden()
 7942                                                    .child(
 7943                                                        h_flex()
 7944                                                            .flex_1()
 7945                                                            .when_some(paddings.0, |this, p| {
 7946                                                                this.child(p.border_r_1())
 7947                                                            })
 7948                                                            .child(self.center.render(
 7949                                                                self.zoomed.as_ref(),
 7950                                                                &PaneRenderContext {
 7951                                                                    follower_states:
 7952                                                                        &self.follower_states,
 7953                                                                    active_call: self.active_call(),
 7954                                                                    active_pane: &self.active_pane,
 7955                                                                    app_state: &self.app_state,
 7956                                                                    project: &self.project,
 7957                                                                    workspace: &self.weak_self,
 7958                                                                },
 7959                                                                window,
 7960                                                                cx,
 7961                                                            ))
 7962                                                            .when_some(paddings.1, |this, p| {
 7963                                                                this.child(p.border_l_1())
 7964                                                            }),
 7965                                                    )
 7966                                                    .children(self.render_dock(
 7967                                                        DockPosition::Bottom,
 7968                                                        &self.bottom_dock,
 7969                                                        window,
 7970                                                        cx,
 7971                                                    )),
 7972                                            )
 7973
 7974                                            .children(self.render_dock(
 7975                                                DockPosition::Right,
 7976                                                &self.right_dock,
 7977                                                window,
 7978                                                cx,
 7979                                            )),
 7980                                    }
 7981                                })
 7982                                .children(self.zoomed.as_ref().and_then(|view| {
 7983                                    let zoomed_view = view.upgrade()?;
 7984                                    let div = div()
 7985                                        .occlude()
 7986                                        .absolute()
 7987                                        .overflow_hidden()
 7988                                        .border_color(colors.border)
 7989                                        .bg(colors.background)
 7990                                        .child(zoomed_view)
 7991                                        .inset_0()
 7992                                        .shadow_lg();
 7993
 7994                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7995                                       return Some(div);
 7996                                    }
 7997
 7998                                    Some(match self.zoomed_position {
 7999                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8000                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8001                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8002                                        None => {
 8003                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8004                                        }
 8005                                    })
 8006                                }))
 8007                                .children(self.render_notifications(window, cx)),
 8008                        )
 8009                        .when(self.status_bar_visible(cx), |parent| {
 8010                            parent.child(self.status_bar.clone())
 8011                        })
 8012                        .child(self.toast_layer.clone()),
 8013                )
 8014    }
 8015}
 8016
 8017impl WorkspaceStore {
 8018    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8019        Self {
 8020            workspaces: Default::default(),
 8021            _subscriptions: vec![
 8022                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8023                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8024            ],
 8025            client,
 8026        }
 8027    }
 8028
 8029    pub fn update_followers(
 8030        &self,
 8031        project_id: Option<u64>,
 8032        update: proto::update_followers::Variant,
 8033        cx: &App,
 8034    ) -> Option<()> {
 8035        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8036        let room_id = active_call.0.room_id(cx)?;
 8037        self.client
 8038            .send(proto::UpdateFollowers {
 8039                room_id,
 8040                project_id,
 8041                variant: Some(update),
 8042            })
 8043            .log_err()
 8044    }
 8045
 8046    pub async fn handle_follow(
 8047        this: Entity<Self>,
 8048        envelope: TypedEnvelope<proto::Follow>,
 8049        mut cx: AsyncApp,
 8050    ) -> Result<proto::FollowResponse> {
 8051        this.update(&mut cx, |this, cx| {
 8052            let follower = Follower {
 8053                project_id: envelope.payload.project_id,
 8054                peer_id: envelope.original_sender_id()?,
 8055            };
 8056
 8057            let mut response = proto::FollowResponse::default();
 8058
 8059            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8060                let Some(workspace) = weak_workspace.upgrade() else {
 8061                    return false;
 8062                };
 8063                window_handle
 8064                    .update(cx, |_, window, cx| {
 8065                        workspace.update(cx, |workspace, cx| {
 8066                            let handler_response =
 8067                                workspace.handle_follow(follower.project_id, window, cx);
 8068                            if let Some(active_view) = handler_response.active_view
 8069                                && workspace.project.read(cx).remote_id() == follower.project_id
 8070                            {
 8071                                response.active_view = Some(active_view)
 8072                            }
 8073                        });
 8074                    })
 8075                    .is_ok()
 8076            });
 8077
 8078            Ok(response)
 8079        })
 8080    }
 8081
 8082    async fn handle_update_followers(
 8083        this: Entity<Self>,
 8084        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8085        mut cx: AsyncApp,
 8086    ) -> Result<()> {
 8087        let leader_id = envelope.original_sender_id()?;
 8088        let update = envelope.payload;
 8089
 8090        this.update(&mut cx, |this, cx| {
 8091            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8092                let Some(workspace) = weak_workspace.upgrade() else {
 8093                    return false;
 8094                };
 8095                window_handle
 8096                    .update(cx, |_, window, cx| {
 8097                        workspace.update(cx, |workspace, cx| {
 8098                            let project_id = workspace.project.read(cx).remote_id();
 8099                            if update.project_id != project_id && update.project_id.is_some() {
 8100                                return;
 8101                            }
 8102                            workspace.handle_update_followers(
 8103                                leader_id,
 8104                                update.clone(),
 8105                                window,
 8106                                cx,
 8107                            );
 8108                        });
 8109                    })
 8110                    .is_ok()
 8111            });
 8112            Ok(())
 8113        })
 8114    }
 8115
 8116    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8117        self.workspaces.iter().map(|(_, weak)| weak)
 8118    }
 8119
 8120    pub fn workspaces_with_windows(
 8121        &self,
 8122    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8123        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8124    }
 8125}
 8126
 8127impl ViewId {
 8128    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8129        Ok(Self {
 8130            creator: message
 8131                .creator
 8132                .map(CollaboratorId::PeerId)
 8133                .context("creator is missing")?,
 8134            id: message.id,
 8135        })
 8136    }
 8137
 8138    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8139        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8140            Some(proto::ViewId {
 8141                creator: Some(peer_id),
 8142                id: self.id,
 8143            })
 8144        } else {
 8145            None
 8146        }
 8147    }
 8148}
 8149
 8150impl FollowerState {
 8151    fn pane(&self) -> &Entity<Pane> {
 8152        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8153    }
 8154}
 8155
 8156pub trait WorkspaceHandle {
 8157    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8158}
 8159
 8160impl WorkspaceHandle for Entity<Workspace> {
 8161    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8162        self.read(cx)
 8163            .worktrees(cx)
 8164            .flat_map(|worktree| {
 8165                let worktree_id = worktree.read(cx).id();
 8166                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8167                    worktree_id,
 8168                    path: f.path.clone(),
 8169                })
 8170            })
 8171            .collect::<Vec<_>>()
 8172    }
 8173}
 8174
 8175pub async fn last_opened_workspace_location(
 8176    fs: &dyn fs::Fs,
 8177) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8178    DB.last_workspace(fs)
 8179        .await
 8180        .log_err()
 8181        .flatten()
 8182        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8183}
 8184
 8185pub async fn last_session_workspace_locations(
 8186    last_session_id: &str,
 8187    last_session_window_stack: Option<Vec<WindowId>>,
 8188    fs: &dyn fs::Fs,
 8189) -> Option<Vec<SessionWorkspace>> {
 8190    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8191        .await
 8192        .log_err()
 8193}
 8194
 8195pub struct MultiWorkspaceRestoreResult {
 8196    pub window_handle: WindowHandle<MultiWorkspace>,
 8197    pub errors: Vec<anyhow::Error>,
 8198}
 8199
 8200pub async fn restore_multiworkspace(
 8201    multi_workspace: SerializedMultiWorkspace,
 8202    app_state: Arc<AppState>,
 8203    cx: &mut AsyncApp,
 8204) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8205    let SerializedMultiWorkspace {
 8206        workspaces,
 8207        state,
 8208        id: window_id,
 8209    } = multi_workspace;
 8210    let mut group_iter = workspaces.into_iter();
 8211    let first = group_iter
 8212        .next()
 8213        .context("window group must not be empty")?;
 8214
 8215    let window_handle = if first.paths.is_empty() {
 8216        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8217            .await?
 8218    } else {
 8219        let OpenResult { window, .. } = cx
 8220            .update(|cx| {
 8221                Workspace::new_local(
 8222                    first.paths.paths().to_vec(),
 8223                    app_state.clone(),
 8224                    None,
 8225                    None,
 8226                    None,
 8227                    true,
 8228                    cx,
 8229                )
 8230            })
 8231            .await?;
 8232        window
 8233    };
 8234
 8235    let mut errors = Vec::new();
 8236
 8237    for session_workspace in group_iter {
 8238        let error = if session_workspace.paths.is_empty() {
 8239            cx.update(|cx| {
 8240                open_workspace_by_id(
 8241                    session_workspace.workspace_id,
 8242                    app_state.clone(),
 8243                    Some(window_handle),
 8244                    cx,
 8245                )
 8246            })
 8247            .await
 8248            .err()
 8249        } else {
 8250            cx.update(|cx| {
 8251                Workspace::new_local(
 8252                    session_workspace.paths.paths().to_vec(),
 8253                    app_state.clone(),
 8254                    Some(window_handle),
 8255                    None,
 8256                    None,
 8257                    true,
 8258                    cx,
 8259                )
 8260            })
 8261            .await
 8262            .err()
 8263        };
 8264
 8265        if let Some(error) = error {
 8266            errors.push(error);
 8267        }
 8268    }
 8269
 8270    if let Some(target_id) = state.active_workspace_id {
 8271        window_handle
 8272            .update(cx, |multi_workspace, window, cx| {
 8273                multi_workspace.set_database_id(window_id);
 8274                let target_index = multi_workspace
 8275                    .workspaces()
 8276                    .iter()
 8277                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8278                if let Some(index) = target_index {
 8279                    multi_workspace.activate_index(index, window, cx);
 8280                } else if !multi_workspace.workspaces().is_empty() {
 8281                    multi_workspace.activate_index(0, window, cx);
 8282                }
 8283            })
 8284            .ok();
 8285    } else {
 8286        window_handle
 8287            .update(cx, |multi_workspace, window, cx| {
 8288                if !multi_workspace.workspaces().is_empty() {
 8289                    multi_workspace.activate_index(0, window, cx);
 8290                }
 8291            })
 8292            .ok();
 8293    }
 8294
 8295    window_handle
 8296        .update(cx, |_, window, _cx| {
 8297            window.activate_window();
 8298        })
 8299        .ok();
 8300
 8301    Ok(MultiWorkspaceRestoreResult {
 8302        window_handle,
 8303        errors,
 8304    })
 8305}
 8306
 8307actions!(
 8308    collab,
 8309    [
 8310        /// Opens the channel notes for the current call.
 8311        ///
 8312        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8313        /// channel in the collab panel.
 8314        ///
 8315        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8316        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8317        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8318        OpenChannelNotes,
 8319        /// Mutes your microphone.
 8320        Mute,
 8321        /// Deafens yourself (mute both microphone and speakers).
 8322        Deafen,
 8323        /// Leaves the current call.
 8324        LeaveCall,
 8325        /// Shares the current project with collaborators.
 8326        ShareProject,
 8327        /// Shares your screen with collaborators.
 8328        ScreenShare,
 8329        /// Copies the current room name and session id for debugging purposes.
 8330        CopyRoomId,
 8331    ]
 8332);
 8333
 8334/// Opens the channel notes for a specific channel by its ID.
 8335#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8336#[action(namespace = collab)]
 8337#[serde(deny_unknown_fields)]
 8338pub struct OpenChannelNotesById {
 8339    pub channel_id: u64,
 8340}
 8341
 8342actions!(
 8343    zed,
 8344    [
 8345        /// Opens the Zed log file.
 8346        OpenLog,
 8347        /// Reveals the Zed log file in the system file manager.
 8348        RevealLogInFileManager
 8349    ]
 8350);
 8351
 8352async fn join_channel_internal(
 8353    channel_id: ChannelId,
 8354    app_state: &Arc<AppState>,
 8355    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8356    requesting_workspace: Option<WeakEntity<Workspace>>,
 8357    active_call: &dyn AnyActiveCall,
 8358    cx: &mut AsyncApp,
 8359) -> Result<bool> {
 8360    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8361        if !active_call.is_in_room(cx) {
 8362            return (false, false);
 8363        }
 8364
 8365        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8366        let should_prompt = active_call.is_sharing_project(cx)
 8367            && active_call.has_remote_participants(cx)
 8368            && !already_in_channel;
 8369        (should_prompt, already_in_channel)
 8370    });
 8371
 8372    if already_in_channel {
 8373        let task = cx.update(|cx| {
 8374            if let Some((project, host)) = active_call.most_active_project(cx) {
 8375                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8376            } else {
 8377                None
 8378            }
 8379        });
 8380        if let Some(task) = task {
 8381            task.await?;
 8382        }
 8383        return anyhow::Ok(true);
 8384    }
 8385
 8386    if should_prompt {
 8387        if let Some(multi_workspace) = requesting_window {
 8388            let answer = multi_workspace
 8389                .update(cx, |_, window, cx| {
 8390                    window.prompt(
 8391                        PromptLevel::Warning,
 8392                        "Do you want to switch channels?",
 8393                        Some("Leaving this call will unshare your current project."),
 8394                        &["Yes, Join Channel", "Cancel"],
 8395                        cx,
 8396                    )
 8397                })?
 8398                .await;
 8399
 8400            if answer == Ok(1) {
 8401                return Ok(false);
 8402            }
 8403        } else {
 8404            return Ok(false);
 8405        }
 8406    }
 8407
 8408    let client = cx.update(|cx| active_call.client(cx));
 8409
 8410    let mut client_status = client.status();
 8411
 8412    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8413    'outer: loop {
 8414        let Some(status) = client_status.recv().await else {
 8415            anyhow::bail!("error connecting");
 8416        };
 8417
 8418        match status {
 8419            Status::Connecting
 8420            | Status::Authenticating
 8421            | Status::Authenticated
 8422            | Status::Reconnecting
 8423            | Status::Reauthenticating
 8424            | Status::Reauthenticated => continue,
 8425            Status::Connected { .. } => break 'outer,
 8426            Status::SignedOut | Status::AuthenticationError => {
 8427                return Err(ErrorCode::SignedOut.into());
 8428            }
 8429            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8430            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8431                return Err(ErrorCode::Disconnected.into());
 8432            }
 8433        }
 8434    }
 8435
 8436    let joined = cx
 8437        .update(|cx| active_call.join_channel(channel_id, cx))
 8438        .await?;
 8439
 8440    if !joined {
 8441        return anyhow::Ok(true);
 8442    }
 8443
 8444    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8445
 8446    let task = cx.update(|cx| {
 8447        if let Some((project, host)) = active_call.most_active_project(cx) {
 8448            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8449        }
 8450
 8451        // If you are the first to join a channel, see if you should share your project.
 8452        if !active_call.has_remote_participants(cx)
 8453            && !active_call.local_participant_is_guest(cx)
 8454            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8455        {
 8456            let project = workspace.update(cx, |workspace, cx| {
 8457                let project = workspace.project.read(cx);
 8458
 8459                if !active_call.share_on_join(cx) {
 8460                    return None;
 8461                }
 8462
 8463                if (project.is_local() || project.is_via_remote_server())
 8464                    && project.visible_worktrees(cx).any(|tree| {
 8465                        tree.read(cx)
 8466                            .root_entry()
 8467                            .is_some_and(|entry| entry.is_dir())
 8468                    })
 8469                {
 8470                    Some(workspace.project.clone())
 8471                } else {
 8472                    None
 8473                }
 8474            });
 8475            if let Some(project) = project {
 8476                let share_task = active_call.share_project(project, cx);
 8477                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8478                    share_task.await?;
 8479                    Ok(())
 8480                }));
 8481            }
 8482        }
 8483
 8484        None
 8485    });
 8486    if let Some(task) = task {
 8487        task.await?;
 8488        return anyhow::Ok(true);
 8489    }
 8490    anyhow::Ok(false)
 8491}
 8492
 8493pub fn join_channel(
 8494    channel_id: ChannelId,
 8495    app_state: Arc<AppState>,
 8496    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8497    requesting_workspace: Option<WeakEntity<Workspace>>,
 8498    cx: &mut App,
 8499) -> Task<Result<()>> {
 8500    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8501    cx.spawn(async move |cx| {
 8502        let result = join_channel_internal(
 8503            channel_id,
 8504            &app_state,
 8505            requesting_window,
 8506            requesting_workspace,
 8507            &*active_call.0,
 8508            cx,
 8509        )
 8510        .await;
 8511
 8512        // join channel succeeded, and opened a window
 8513        if matches!(result, Ok(true)) {
 8514            return anyhow::Ok(());
 8515        }
 8516
 8517        // find an existing workspace to focus and show call controls
 8518        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8519        if active_window.is_none() {
 8520            // no open workspaces, make one to show the error in (blergh)
 8521            let OpenResult {
 8522                window: window_handle,
 8523                ..
 8524            } = cx
 8525                .update(|cx| {
 8526                    Workspace::new_local(
 8527                        vec![],
 8528                        app_state.clone(),
 8529                        requesting_window,
 8530                        None,
 8531                        None,
 8532                        true,
 8533                        cx,
 8534                    )
 8535                })
 8536                .await?;
 8537
 8538            window_handle
 8539                .update(cx, |_, window, _cx| {
 8540                    window.activate_window();
 8541                })
 8542                .ok();
 8543
 8544            if result.is_ok() {
 8545                cx.update(|cx| {
 8546                    cx.dispatch_action(&OpenChannelNotes);
 8547                });
 8548            }
 8549
 8550            active_window = Some(window_handle);
 8551        }
 8552
 8553        if let Err(err) = result {
 8554            log::error!("failed to join channel: {}", err);
 8555            if let Some(active_window) = active_window {
 8556                active_window
 8557                    .update(cx, |_, window, cx| {
 8558                        let detail: SharedString = match err.error_code() {
 8559                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8560                            ErrorCode::UpgradeRequired => concat!(
 8561                                "Your are running an unsupported version of Zed. ",
 8562                                "Please update to continue."
 8563                            )
 8564                            .into(),
 8565                            ErrorCode::NoSuchChannel => concat!(
 8566                                "No matching channel was found. ",
 8567                                "Please check the link and try again."
 8568                            )
 8569                            .into(),
 8570                            ErrorCode::Forbidden => concat!(
 8571                                "This channel is private, and you do not have access. ",
 8572                                "Please ask someone to add you and try again."
 8573                            )
 8574                            .into(),
 8575                            ErrorCode::Disconnected => {
 8576                                "Please check your internet connection and try again.".into()
 8577                            }
 8578                            _ => format!("{}\n\nPlease try again.", err).into(),
 8579                        };
 8580                        window.prompt(
 8581                            PromptLevel::Critical,
 8582                            "Failed to join channel",
 8583                            Some(&detail),
 8584                            &["Ok"],
 8585                            cx,
 8586                        )
 8587                    })?
 8588                    .await
 8589                    .ok();
 8590            }
 8591        }
 8592
 8593        // return ok, we showed the error to the user.
 8594        anyhow::Ok(())
 8595    })
 8596}
 8597
 8598pub async fn get_any_active_multi_workspace(
 8599    app_state: Arc<AppState>,
 8600    mut cx: AsyncApp,
 8601) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8602    // find an existing workspace to focus and show call controls
 8603    let active_window = activate_any_workspace_window(&mut cx);
 8604    if active_window.is_none() {
 8605        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8606            .await?;
 8607    }
 8608    activate_any_workspace_window(&mut cx).context("could not open zed")
 8609}
 8610
 8611fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8612    cx.update(|cx| {
 8613        if let Some(workspace_window) = cx
 8614            .active_window()
 8615            .and_then(|window| window.downcast::<MultiWorkspace>())
 8616        {
 8617            return Some(workspace_window);
 8618        }
 8619
 8620        for window in cx.windows() {
 8621            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8622                workspace_window
 8623                    .update(cx, |_, window, _| window.activate_window())
 8624                    .ok();
 8625                return Some(workspace_window);
 8626            }
 8627        }
 8628        None
 8629    })
 8630}
 8631
 8632pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8633    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8634}
 8635
 8636pub fn workspace_windows_for_location(
 8637    serialized_location: &SerializedWorkspaceLocation,
 8638    cx: &App,
 8639) -> Vec<WindowHandle<MultiWorkspace>> {
 8640    cx.windows()
 8641        .into_iter()
 8642        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8643        .filter(|multi_workspace| {
 8644            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8645                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8646                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8647                }
 8648                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8649                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8650                    a.distro_name == b.distro_name
 8651                }
 8652                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8653                    a.container_id == b.container_id
 8654                }
 8655                #[cfg(any(test, feature = "test-support"))]
 8656                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8657                    a.id == b.id
 8658                }
 8659                _ => false,
 8660            };
 8661
 8662            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8663                multi_workspace.workspaces().iter().any(|workspace| {
 8664                    match workspace.read(cx).workspace_location(cx) {
 8665                        WorkspaceLocation::Location(location, _) => {
 8666                            match (&location, serialized_location) {
 8667                                (
 8668                                    SerializedWorkspaceLocation::Local,
 8669                                    SerializedWorkspaceLocation::Local,
 8670                                ) => true,
 8671                                (
 8672                                    SerializedWorkspaceLocation::Remote(a),
 8673                                    SerializedWorkspaceLocation::Remote(b),
 8674                                ) => same_host(a, b),
 8675                                _ => false,
 8676                            }
 8677                        }
 8678                        _ => false,
 8679                    }
 8680                })
 8681            })
 8682        })
 8683        .collect()
 8684}
 8685
 8686pub async fn find_existing_workspace(
 8687    abs_paths: &[PathBuf],
 8688    open_options: &OpenOptions,
 8689    location: &SerializedWorkspaceLocation,
 8690    cx: &mut AsyncApp,
 8691) -> (
 8692    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8693    OpenVisible,
 8694) {
 8695    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8696    let mut open_visible = OpenVisible::All;
 8697    let mut best_match = None;
 8698
 8699    if open_options.open_new_workspace != Some(true) {
 8700        cx.update(|cx| {
 8701            for window in workspace_windows_for_location(location, cx) {
 8702                if let Ok(multi_workspace) = window.read(cx) {
 8703                    for workspace in multi_workspace.workspaces() {
 8704                        let project = workspace.read(cx).project.read(cx);
 8705                        let m = project.visibility_for_paths(
 8706                            abs_paths,
 8707                            open_options.open_new_workspace == None,
 8708                            cx,
 8709                        );
 8710                        if m > best_match {
 8711                            existing = Some((window, workspace.clone()));
 8712                            best_match = m;
 8713                        } else if best_match.is_none()
 8714                            && open_options.open_new_workspace == Some(false)
 8715                        {
 8716                            existing = Some((window, workspace.clone()))
 8717                        }
 8718                    }
 8719                }
 8720            }
 8721        });
 8722
 8723        let all_paths_are_files = existing
 8724            .as_ref()
 8725            .and_then(|(_, target_workspace)| {
 8726                cx.update(|cx| {
 8727                    let workspace = target_workspace.read(cx);
 8728                    let project = workspace.project.read(cx);
 8729                    let path_style = workspace.path_style(cx);
 8730                    Some(!abs_paths.iter().any(|path| {
 8731                        let path = util::paths::SanitizedPath::new(path);
 8732                        project.worktrees(cx).any(|worktree| {
 8733                            let worktree = worktree.read(cx);
 8734                            let abs_path = worktree.abs_path();
 8735                            path_style
 8736                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8737                                .and_then(|rel| worktree.entry_for_path(&rel))
 8738                                .is_some_and(|e| e.is_dir())
 8739                        })
 8740                    }))
 8741                })
 8742            })
 8743            .unwrap_or(false);
 8744
 8745        if open_options.open_new_workspace.is_none()
 8746            && existing.is_some()
 8747            && open_options.wait
 8748            && all_paths_are_files
 8749        {
 8750            cx.update(|cx| {
 8751                let windows = workspace_windows_for_location(location, cx);
 8752                let window = cx
 8753                    .active_window()
 8754                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8755                    .filter(|window| windows.contains(window))
 8756                    .or_else(|| windows.into_iter().next());
 8757                if let Some(window) = window {
 8758                    if let Ok(multi_workspace) = window.read(cx) {
 8759                        let active_workspace = multi_workspace.workspace().clone();
 8760                        existing = Some((window, active_workspace));
 8761                        open_visible = OpenVisible::None;
 8762                    }
 8763                }
 8764            });
 8765        }
 8766    }
 8767    (existing, open_visible)
 8768}
 8769
 8770#[derive(Default, Clone)]
 8771pub struct OpenOptions {
 8772    pub visible: Option<OpenVisible>,
 8773    pub focus: Option<bool>,
 8774    pub open_new_workspace: Option<bool>,
 8775    pub wait: bool,
 8776    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8777    pub env: Option<HashMap<String, String>>,
 8778}
 8779
 8780/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 8781/// or [`Workspace::open_workspace_for_paths`].
 8782pub struct OpenResult {
 8783    pub window: WindowHandle<MultiWorkspace>,
 8784    pub workspace: Entity<Workspace>,
 8785    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8786}
 8787
 8788/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8789pub fn open_workspace_by_id(
 8790    workspace_id: WorkspaceId,
 8791    app_state: Arc<AppState>,
 8792    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8793    cx: &mut App,
 8794) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8795    let project_handle = Project::local(
 8796        app_state.client.clone(),
 8797        app_state.node_runtime.clone(),
 8798        app_state.user_store.clone(),
 8799        app_state.languages.clone(),
 8800        app_state.fs.clone(),
 8801        None,
 8802        project::LocalProjectFlags {
 8803            init_worktree_trust: true,
 8804            ..project::LocalProjectFlags::default()
 8805        },
 8806        cx,
 8807    );
 8808
 8809    cx.spawn(async move |cx| {
 8810        let serialized_workspace = persistence::DB
 8811            .workspace_for_id(workspace_id)
 8812            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8813
 8814        let centered_layout = serialized_workspace.centered_layout;
 8815
 8816        let (window, workspace) = if let Some(window) = requesting_window {
 8817            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8818                let workspace = cx.new(|cx| {
 8819                    let mut workspace = Workspace::new(
 8820                        Some(workspace_id),
 8821                        project_handle.clone(),
 8822                        app_state.clone(),
 8823                        window,
 8824                        cx,
 8825                    );
 8826                    workspace.centered_layout = centered_layout;
 8827                    workspace
 8828                });
 8829                multi_workspace.add_workspace(workspace.clone(), cx);
 8830                workspace
 8831            })?;
 8832            (window, workspace)
 8833        } else {
 8834            let window_bounds_override = window_bounds_env_override();
 8835
 8836            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8837                (Some(WindowBounds::Windowed(bounds)), None)
 8838            } else if let Some(display) = serialized_workspace.display
 8839                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8840            {
 8841                (Some(bounds.0), Some(display))
 8842            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8843                (Some(bounds), Some(display))
 8844            } else {
 8845                (None, None)
 8846            };
 8847
 8848            let options = cx.update(|cx| {
 8849                let mut options = (app_state.build_window_options)(display, cx);
 8850                options.window_bounds = window_bounds;
 8851                options
 8852            });
 8853
 8854            let window = cx.open_window(options, {
 8855                let app_state = app_state.clone();
 8856                let project_handle = project_handle.clone();
 8857                move |window, cx| {
 8858                    let workspace = cx.new(|cx| {
 8859                        let mut workspace = Workspace::new(
 8860                            Some(workspace_id),
 8861                            project_handle,
 8862                            app_state,
 8863                            window,
 8864                            cx,
 8865                        );
 8866                        workspace.centered_layout = centered_layout;
 8867                        workspace
 8868                    });
 8869                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8870                }
 8871            })?;
 8872
 8873            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8874                multi_workspace.workspace().clone()
 8875            })?;
 8876
 8877            (window, workspace)
 8878        };
 8879
 8880        notify_if_database_failed(window, cx);
 8881
 8882        // Restore items from the serialized workspace
 8883        window
 8884            .update(cx, |_, window, cx| {
 8885                workspace.update(cx, |_workspace, cx| {
 8886                    open_items(Some(serialized_workspace), vec![], window, cx)
 8887                })
 8888            })?
 8889            .await?;
 8890
 8891        window.update(cx, |_, window, cx| {
 8892            workspace.update(cx, |workspace, cx| {
 8893                workspace.serialize_workspace(window, cx);
 8894            });
 8895        })?;
 8896
 8897        Ok(window)
 8898    })
 8899}
 8900
 8901#[allow(clippy::type_complexity)]
 8902pub fn open_paths(
 8903    abs_paths: &[PathBuf],
 8904    app_state: Arc<AppState>,
 8905    open_options: OpenOptions,
 8906    cx: &mut App,
 8907) -> Task<anyhow::Result<OpenResult>> {
 8908    let abs_paths = abs_paths.to_vec();
 8909    #[cfg(target_os = "windows")]
 8910    let wsl_path = abs_paths
 8911        .iter()
 8912        .find_map(|p| util::paths::WslPath::from_path(p));
 8913
 8914    cx.spawn(async move |cx| {
 8915        let (mut existing, mut open_visible) = find_existing_workspace(
 8916            &abs_paths,
 8917            &open_options,
 8918            &SerializedWorkspaceLocation::Local,
 8919            cx,
 8920        )
 8921        .await;
 8922
 8923        // Fallback: if no workspace contains the paths and all paths are files,
 8924        // prefer an existing local workspace window (active window first).
 8925        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8926            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8927            let all_metadatas = futures::future::join_all(all_paths)
 8928                .await
 8929                .into_iter()
 8930                .filter_map(|result| result.ok().flatten())
 8931                .collect::<Vec<_>>();
 8932
 8933            if all_metadatas.iter().all(|file| !file.is_dir) {
 8934                cx.update(|cx| {
 8935                    let windows = workspace_windows_for_location(
 8936                        &SerializedWorkspaceLocation::Local,
 8937                        cx,
 8938                    );
 8939                    let window = cx
 8940                        .active_window()
 8941                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8942                        .filter(|window| windows.contains(window))
 8943                        .or_else(|| windows.into_iter().next());
 8944                    if let Some(window) = window {
 8945                        if let Ok(multi_workspace) = window.read(cx) {
 8946                            let active_workspace = multi_workspace.workspace().clone();
 8947                            existing = Some((window, active_workspace));
 8948                            open_visible = OpenVisible::None;
 8949                        }
 8950                    }
 8951                });
 8952            }
 8953        }
 8954
 8955        let result = if let Some((existing, target_workspace)) = existing {
 8956            let open_task = existing
 8957                .update(cx, |multi_workspace, window, cx| {
 8958                    window.activate_window();
 8959                    multi_workspace.activate(target_workspace.clone(), cx);
 8960                    target_workspace.update(cx, |workspace, cx| {
 8961                        workspace.open_paths(
 8962                            abs_paths,
 8963                            OpenOptions {
 8964                                visible: Some(open_visible),
 8965                                ..Default::default()
 8966                            },
 8967                            None,
 8968                            window,
 8969                            cx,
 8970                        )
 8971                    })
 8972                })?
 8973                .await;
 8974
 8975            _ = existing.update(cx, |multi_workspace, _, cx| {
 8976                let workspace = multi_workspace.workspace().clone();
 8977                workspace.update(cx, |workspace, cx| {
 8978                    for item in open_task.iter().flatten() {
 8979                        if let Err(e) = item {
 8980                            workspace.show_error(&e, cx);
 8981                        }
 8982                    }
 8983                });
 8984            });
 8985
 8986            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 8987        } else {
 8988            let result = cx
 8989                .update(move |cx| {
 8990                    Workspace::new_local(
 8991                        abs_paths,
 8992                        app_state.clone(),
 8993                        open_options.replace_window,
 8994                        open_options.env,
 8995                        None,
 8996                        true,
 8997                        cx,
 8998                    )
 8999                })
 9000                .await;
 9001
 9002            if let Ok(ref result) = result {
 9003                result.window
 9004                    .update(cx, |_, window, _cx| {
 9005                        window.activate_window();
 9006                    })
 9007                    .log_err();
 9008            }
 9009
 9010            result
 9011        };
 9012
 9013        #[cfg(target_os = "windows")]
 9014        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9015            && let Ok(ref result) = result
 9016        {
 9017            result.window
 9018                .update(cx, move |multi_workspace, _window, cx| {
 9019                    struct OpenInWsl;
 9020                    let workspace = multi_workspace.workspace().clone();
 9021                    workspace.update(cx, |workspace, cx| {
 9022                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9023                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9024                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9025                            cx.new(move |cx| {
 9026                                MessageNotification::new(msg, cx)
 9027                                    .primary_message("Open in WSL")
 9028                                    .primary_icon(IconName::FolderOpen)
 9029                                    .primary_on_click(move |window, cx| {
 9030                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9031                                                distro: remote::WslConnectionOptions {
 9032                                                        distro_name: distro.clone(),
 9033                                                    user: None,
 9034                                                },
 9035                                                paths: vec![path.clone().into()],
 9036                                            }), cx)
 9037                                    })
 9038                            })
 9039                        });
 9040                    });
 9041                })
 9042                .unwrap();
 9043        };
 9044        result
 9045    })
 9046}
 9047
 9048pub fn open_new(
 9049    open_options: OpenOptions,
 9050    app_state: Arc<AppState>,
 9051    cx: &mut App,
 9052    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9053) -> Task<anyhow::Result<()>> {
 9054    let task = Workspace::new_local(
 9055        Vec::new(),
 9056        app_state,
 9057        open_options.replace_window,
 9058        open_options.env,
 9059        Some(Box::new(init)),
 9060        true,
 9061        cx,
 9062    );
 9063    cx.spawn(async move |cx| {
 9064        let OpenResult { window, .. } = task.await?;
 9065        window
 9066            .update(cx, |_, window, _cx| {
 9067                window.activate_window();
 9068            })
 9069            .ok();
 9070        Ok(())
 9071    })
 9072}
 9073
 9074pub fn create_and_open_local_file(
 9075    path: &'static Path,
 9076    window: &mut Window,
 9077    cx: &mut Context<Workspace>,
 9078    default_content: impl 'static + Send + FnOnce() -> Rope,
 9079) -> Task<Result<Box<dyn ItemHandle>>> {
 9080    cx.spawn_in(window, async move |workspace, cx| {
 9081        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9082        if !fs.is_file(path).await {
 9083            fs.create_file(path, Default::default()).await?;
 9084            fs.save(path, &default_content(), Default::default())
 9085                .await?;
 9086        }
 9087
 9088        workspace
 9089            .update_in(cx, |workspace, window, cx| {
 9090                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9091                    let path = workspace
 9092                        .project
 9093                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9094                    cx.spawn_in(window, async move |workspace, cx| {
 9095                        let path = path.await?;
 9096                        let mut items = workspace
 9097                            .update_in(cx, |workspace, window, cx| {
 9098                                workspace.open_paths(
 9099                                    vec![path.to_path_buf()],
 9100                                    OpenOptions {
 9101                                        visible: Some(OpenVisible::None),
 9102                                        ..Default::default()
 9103                                    },
 9104                                    None,
 9105                                    window,
 9106                                    cx,
 9107                                )
 9108                            })?
 9109                            .await;
 9110                        let item = items.pop().flatten();
 9111                        item.with_context(|| format!("path {path:?} is not a file"))?
 9112                    })
 9113                })
 9114            })?
 9115            .await?
 9116            .await
 9117    })
 9118}
 9119
 9120pub fn open_remote_project_with_new_connection(
 9121    window: WindowHandle<MultiWorkspace>,
 9122    remote_connection: Arc<dyn RemoteConnection>,
 9123    cancel_rx: oneshot::Receiver<()>,
 9124    delegate: Arc<dyn RemoteClientDelegate>,
 9125    app_state: Arc<AppState>,
 9126    paths: Vec<PathBuf>,
 9127    cx: &mut App,
 9128) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9129    cx.spawn(async move |cx| {
 9130        let (workspace_id, serialized_workspace) =
 9131            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9132                .await?;
 9133
 9134        let session = match cx
 9135            .update(|cx| {
 9136                remote::RemoteClient::new(
 9137                    ConnectionIdentifier::Workspace(workspace_id.0),
 9138                    remote_connection,
 9139                    cancel_rx,
 9140                    delegate,
 9141                    cx,
 9142                )
 9143            })
 9144            .await?
 9145        {
 9146            Some(result) => result,
 9147            None => return Ok(Vec::new()),
 9148        };
 9149
 9150        let project = cx.update(|cx| {
 9151            project::Project::remote(
 9152                session,
 9153                app_state.client.clone(),
 9154                app_state.node_runtime.clone(),
 9155                app_state.user_store.clone(),
 9156                app_state.languages.clone(),
 9157                app_state.fs.clone(),
 9158                true,
 9159                cx,
 9160            )
 9161        });
 9162
 9163        open_remote_project_inner(
 9164            project,
 9165            paths,
 9166            workspace_id,
 9167            serialized_workspace,
 9168            app_state,
 9169            window,
 9170            cx,
 9171        )
 9172        .await
 9173    })
 9174}
 9175
 9176pub fn open_remote_project_with_existing_connection(
 9177    connection_options: RemoteConnectionOptions,
 9178    project: Entity<Project>,
 9179    paths: Vec<PathBuf>,
 9180    app_state: Arc<AppState>,
 9181    window: WindowHandle<MultiWorkspace>,
 9182    cx: &mut AsyncApp,
 9183) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9184    cx.spawn(async move |cx| {
 9185        let (workspace_id, serialized_workspace) =
 9186            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9187
 9188        open_remote_project_inner(
 9189            project,
 9190            paths,
 9191            workspace_id,
 9192            serialized_workspace,
 9193            app_state,
 9194            window,
 9195            cx,
 9196        )
 9197        .await
 9198    })
 9199}
 9200
 9201async fn open_remote_project_inner(
 9202    project: Entity<Project>,
 9203    paths: Vec<PathBuf>,
 9204    workspace_id: WorkspaceId,
 9205    serialized_workspace: Option<SerializedWorkspace>,
 9206    app_state: Arc<AppState>,
 9207    window: WindowHandle<MultiWorkspace>,
 9208    cx: &mut AsyncApp,
 9209) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9210    let toolchains = DB.toolchains(workspace_id).await?;
 9211    for (toolchain, worktree_path, path) in toolchains {
 9212        project
 9213            .update(cx, |this, cx| {
 9214                let Some(worktree_id) =
 9215                    this.find_worktree(&worktree_path, cx)
 9216                        .and_then(|(worktree, rel_path)| {
 9217                            if rel_path.is_empty() {
 9218                                Some(worktree.read(cx).id())
 9219                            } else {
 9220                                None
 9221                            }
 9222                        })
 9223                else {
 9224                    return Task::ready(None);
 9225                };
 9226
 9227                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9228            })
 9229            .await;
 9230    }
 9231    let mut project_paths_to_open = vec![];
 9232    let mut project_path_errors = vec![];
 9233
 9234    for path in paths {
 9235        let result = cx
 9236            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9237            .await;
 9238        match result {
 9239            Ok((_, project_path)) => {
 9240                project_paths_to_open.push((path.clone(), Some(project_path)));
 9241            }
 9242            Err(error) => {
 9243                project_path_errors.push(error);
 9244            }
 9245        };
 9246    }
 9247
 9248    if project_paths_to_open.is_empty() {
 9249        return Err(project_path_errors.pop().context("no paths given")?);
 9250    }
 9251
 9252    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9253        telemetry::event!("SSH Project Opened");
 9254
 9255        let new_workspace = cx.new(|cx| {
 9256            let mut workspace =
 9257                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9258            workspace.update_history(cx);
 9259
 9260            if let Some(ref serialized) = serialized_workspace {
 9261                workspace.centered_layout = serialized.centered_layout;
 9262            }
 9263
 9264            workspace
 9265        });
 9266
 9267        multi_workspace.activate(new_workspace.clone(), cx);
 9268        new_workspace
 9269    })?;
 9270
 9271    let items = window
 9272        .update(cx, |_, window, cx| {
 9273            window.activate_window();
 9274            workspace.update(cx, |_workspace, cx| {
 9275                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9276            })
 9277        })?
 9278        .await?;
 9279
 9280    workspace.update(cx, |workspace, cx| {
 9281        for error in project_path_errors {
 9282            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9283                if let Some(path) = error.error_tag("path") {
 9284                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9285                }
 9286            } else {
 9287                workspace.show_error(&error, cx)
 9288            }
 9289        }
 9290    });
 9291
 9292    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9293}
 9294
 9295fn deserialize_remote_project(
 9296    connection_options: RemoteConnectionOptions,
 9297    paths: Vec<PathBuf>,
 9298    cx: &AsyncApp,
 9299) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9300    cx.background_spawn(async move {
 9301        let remote_connection_id = persistence::DB
 9302            .get_or_create_remote_connection(connection_options)
 9303            .await?;
 9304
 9305        let serialized_workspace =
 9306            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9307
 9308        let workspace_id = if let Some(workspace_id) =
 9309            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9310        {
 9311            workspace_id
 9312        } else {
 9313            persistence::DB.next_id().await?
 9314        };
 9315
 9316        Ok((workspace_id, serialized_workspace))
 9317    })
 9318}
 9319
 9320pub fn join_in_room_project(
 9321    project_id: u64,
 9322    follow_user_id: u64,
 9323    app_state: Arc<AppState>,
 9324    cx: &mut App,
 9325) -> Task<Result<()>> {
 9326    let windows = cx.windows();
 9327    cx.spawn(async move |cx| {
 9328        let existing_window_and_workspace: Option<(
 9329            WindowHandle<MultiWorkspace>,
 9330            Entity<Workspace>,
 9331        )> = windows.into_iter().find_map(|window_handle| {
 9332            window_handle
 9333                .downcast::<MultiWorkspace>()
 9334                .and_then(|window_handle| {
 9335                    window_handle
 9336                        .update(cx, |multi_workspace, _window, cx| {
 9337                            for workspace in multi_workspace.workspaces() {
 9338                                if workspace.read(cx).project().read(cx).remote_id()
 9339                                    == Some(project_id)
 9340                                {
 9341                                    return Some((window_handle, workspace.clone()));
 9342                                }
 9343                            }
 9344                            None
 9345                        })
 9346                        .unwrap_or(None)
 9347                })
 9348        });
 9349
 9350        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9351            existing_window_and_workspace
 9352        {
 9353            existing_window
 9354                .update(cx, |multi_workspace, _, cx| {
 9355                    multi_workspace.activate(target_workspace, cx);
 9356                })
 9357                .ok();
 9358            existing_window
 9359        } else {
 9360            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9361            let project = cx
 9362                .update(|cx| {
 9363                    active_call.0.join_project(
 9364                        project_id,
 9365                        app_state.languages.clone(),
 9366                        app_state.fs.clone(),
 9367                        cx,
 9368                    )
 9369                })
 9370                .await?;
 9371
 9372            let window_bounds_override = window_bounds_env_override();
 9373            cx.update(|cx| {
 9374                let mut options = (app_state.build_window_options)(None, cx);
 9375                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9376                cx.open_window(options, |window, cx| {
 9377                    let workspace = cx.new(|cx| {
 9378                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9379                    });
 9380                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9381                })
 9382            })?
 9383        };
 9384
 9385        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9386            cx.activate(true);
 9387            window.activate_window();
 9388
 9389            // We set the active workspace above, so this is the correct workspace.
 9390            let workspace = multi_workspace.workspace().clone();
 9391            workspace.update(cx, |workspace, cx| {
 9392                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9393                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9394                    .or_else(|| {
 9395                        // If we couldn't follow the given user, follow the host instead.
 9396                        let collaborator = workspace
 9397                            .project()
 9398                            .read(cx)
 9399                            .collaborators()
 9400                            .values()
 9401                            .find(|collaborator| collaborator.is_host)?;
 9402                        Some(collaborator.peer_id)
 9403                    });
 9404
 9405                if let Some(follow_peer_id) = follow_peer_id {
 9406                    workspace.follow(follow_peer_id, window, cx);
 9407                }
 9408            });
 9409        })?;
 9410
 9411        anyhow::Ok(())
 9412    })
 9413}
 9414
 9415pub fn reload(cx: &mut App) {
 9416    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9417    let mut workspace_windows = cx
 9418        .windows()
 9419        .into_iter()
 9420        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9421        .collect::<Vec<_>>();
 9422
 9423    // If multiple windows have unsaved changes, and need a save prompt,
 9424    // prompt in the active window before switching to a different window.
 9425    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9426
 9427    let mut prompt = None;
 9428    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9429        prompt = window
 9430            .update(cx, |_, window, cx| {
 9431                window.prompt(
 9432                    PromptLevel::Info,
 9433                    "Are you sure you want to restart?",
 9434                    None,
 9435                    &["Restart", "Cancel"],
 9436                    cx,
 9437                )
 9438            })
 9439            .ok();
 9440    }
 9441
 9442    cx.spawn(async move |cx| {
 9443        if let Some(prompt) = prompt {
 9444            let answer = prompt.await?;
 9445            if answer != 0 {
 9446                return anyhow::Ok(());
 9447            }
 9448        }
 9449
 9450        // If the user cancels any save prompt, then keep the app open.
 9451        for window in workspace_windows {
 9452            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9453                let workspace = multi_workspace.workspace().clone();
 9454                workspace.update(cx, |workspace, cx| {
 9455                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9456                })
 9457            }) && !should_close.await?
 9458            {
 9459                return anyhow::Ok(());
 9460            }
 9461        }
 9462        cx.update(|cx| cx.restart());
 9463        anyhow::Ok(())
 9464    })
 9465    .detach_and_log_err(cx);
 9466}
 9467
 9468fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9469    let mut parts = value.split(',');
 9470    let x: usize = parts.next()?.parse().ok()?;
 9471    let y: usize = parts.next()?.parse().ok()?;
 9472    Some(point(px(x as f32), px(y as f32)))
 9473}
 9474
 9475fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9476    let mut parts = value.split(',');
 9477    let width: usize = parts.next()?.parse().ok()?;
 9478    let height: usize = parts.next()?.parse().ok()?;
 9479    Some(size(px(width as f32), px(height as f32)))
 9480}
 9481
 9482/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9483/// appropriate.
 9484///
 9485/// The `border_radius_tiling` parameter allows overriding which corners get
 9486/// rounded, independently of the actual window tiling state. This is used
 9487/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9488/// we want square corners on the left (so the sidebar appears flush with the
 9489/// window edge) but we still need the shadow padding for proper visual
 9490/// appearance. Unlike actual window tiling, this only affects border radius -
 9491/// not padding or shadows.
 9492pub fn client_side_decorations(
 9493    element: impl IntoElement,
 9494    window: &mut Window,
 9495    cx: &mut App,
 9496    border_radius_tiling: Tiling,
 9497) -> Stateful<Div> {
 9498    const BORDER_SIZE: Pixels = px(1.0);
 9499    let decorations = window.window_decorations();
 9500    let tiling = match decorations {
 9501        Decorations::Server => Tiling::default(),
 9502        Decorations::Client { tiling } => tiling,
 9503    };
 9504
 9505    match decorations {
 9506        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9507        Decorations::Server => window.set_client_inset(px(0.0)),
 9508    }
 9509
 9510    struct GlobalResizeEdge(ResizeEdge);
 9511    impl Global for GlobalResizeEdge {}
 9512
 9513    div()
 9514        .id("window-backdrop")
 9515        .bg(transparent_black())
 9516        .map(|div| match decorations {
 9517            Decorations::Server => div,
 9518            Decorations::Client { .. } => div
 9519                .when(
 9520                    !(tiling.top
 9521                        || tiling.right
 9522                        || border_radius_tiling.top
 9523                        || border_radius_tiling.right),
 9524                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9525                )
 9526                .when(
 9527                    !(tiling.top
 9528                        || tiling.left
 9529                        || border_radius_tiling.top
 9530                        || border_radius_tiling.left),
 9531                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9532                )
 9533                .when(
 9534                    !(tiling.bottom
 9535                        || tiling.right
 9536                        || border_radius_tiling.bottom
 9537                        || border_radius_tiling.right),
 9538                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9539                )
 9540                .when(
 9541                    !(tiling.bottom
 9542                        || tiling.left
 9543                        || border_radius_tiling.bottom
 9544                        || border_radius_tiling.left),
 9545                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9546                )
 9547                .when(!tiling.top, |div| {
 9548                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9549                })
 9550                .when(!tiling.bottom, |div| {
 9551                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9552                })
 9553                .when(!tiling.left, |div| {
 9554                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9555                })
 9556                .when(!tiling.right, |div| {
 9557                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9558                })
 9559                .on_mouse_move(move |e, window, cx| {
 9560                    let size = window.window_bounds().get_bounds().size;
 9561                    let pos = e.position;
 9562
 9563                    let new_edge =
 9564                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9565
 9566                    let edge = cx.try_global::<GlobalResizeEdge>();
 9567                    if new_edge != edge.map(|edge| edge.0) {
 9568                        window
 9569                            .window_handle()
 9570                            .update(cx, |workspace, _, cx| {
 9571                                cx.notify(workspace.entity_id());
 9572                            })
 9573                            .ok();
 9574                    }
 9575                })
 9576                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9577                    let size = window.window_bounds().get_bounds().size;
 9578                    let pos = e.position;
 9579
 9580                    let edge = match resize_edge(
 9581                        pos,
 9582                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9583                        size,
 9584                        tiling,
 9585                    ) {
 9586                        Some(value) => value,
 9587                        None => return,
 9588                    };
 9589
 9590                    window.start_window_resize(edge);
 9591                }),
 9592        })
 9593        .size_full()
 9594        .child(
 9595            div()
 9596                .cursor(CursorStyle::Arrow)
 9597                .map(|div| match decorations {
 9598                    Decorations::Server => div,
 9599                    Decorations::Client { .. } => div
 9600                        .border_color(cx.theme().colors().border)
 9601                        .when(
 9602                            !(tiling.top
 9603                                || tiling.right
 9604                                || border_radius_tiling.top
 9605                                || border_radius_tiling.right),
 9606                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9607                        )
 9608                        .when(
 9609                            !(tiling.top
 9610                                || tiling.left
 9611                                || border_radius_tiling.top
 9612                                || border_radius_tiling.left),
 9613                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9614                        )
 9615                        .when(
 9616                            !(tiling.bottom
 9617                                || tiling.right
 9618                                || border_radius_tiling.bottom
 9619                                || border_radius_tiling.right),
 9620                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9621                        )
 9622                        .when(
 9623                            !(tiling.bottom
 9624                                || tiling.left
 9625                                || border_radius_tiling.bottom
 9626                                || border_radius_tiling.left),
 9627                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9628                        )
 9629                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9630                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9631                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9632                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9633                        .when(!tiling.is_tiled(), |div| {
 9634                            div.shadow(vec![gpui::BoxShadow {
 9635                                color: Hsla {
 9636                                    h: 0.,
 9637                                    s: 0.,
 9638                                    l: 0.,
 9639                                    a: 0.4,
 9640                                },
 9641                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9642                                spread_radius: px(0.),
 9643                                offset: point(px(0.0), px(0.0)),
 9644                            }])
 9645                        }),
 9646                })
 9647                .on_mouse_move(|_e, _, cx| {
 9648                    cx.stop_propagation();
 9649                })
 9650                .size_full()
 9651                .child(element),
 9652        )
 9653        .map(|div| match decorations {
 9654            Decorations::Server => div,
 9655            Decorations::Client { tiling, .. } => div.child(
 9656                canvas(
 9657                    |_bounds, window, _| {
 9658                        window.insert_hitbox(
 9659                            Bounds::new(
 9660                                point(px(0.0), px(0.0)),
 9661                                window.window_bounds().get_bounds().size,
 9662                            ),
 9663                            HitboxBehavior::Normal,
 9664                        )
 9665                    },
 9666                    move |_bounds, hitbox, window, cx| {
 9667                        let mouse = window.mouse_position();
 9668                        let size = window.window_bounds().get_bounds().size;
 9669                        let Some(edge) =
 9670                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9671                        else {
 9672                            return;
 9673                        };
 9674                        cx.set_global(GlobalResizeEdge(edge));
 9675                        window.set_cursor_style(
 9676                            match edge {
 9677                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9678                                ResizeEdge::Left | ResizeEdge::Right => {
 9679                                    CursorStyle::ResizeLeftRight
 9680                                }
 9681                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9682                                    CursorStyle::ResizeUpLeftDownRight
 9683                                }
 9684                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9685                                    CursorStyle::ResizeUpRightDownLeft
 9686                                }
 9687                            },
 9688                            &hitbox,
 9689                        );
 9690                    },
 9691                )
 9692                .size_full()
 9693                .absolute(),
 9694            ),
 9695        })
 9696}
 9697
 9698fn resize_edge(
 9699    pos: Point<Pixels>,
 9700    shadow_size: Pixels,
 9701    window_size: Size<Pixels>,
 9702    tiling: Tiling,
 9703) -> Option<ResizeEdge> {
 9704    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9705    if bounds.contains(&pos) {
 9706        return None;
 9707    }
 9708
 9709    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9710    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9711    if !tiling.top && top_left_bounds.contains(&pos) {
 9712        return Some(ResizeEdge::TopLeft);
 9713    }
 9714
 9715    let top_right_bounds = Bounds::new(
 9716        Point::new(window_size.width - corner_size.width, px(0.)),
 9717        corner_size,
 9718    );
 9719    if !tiling.top && top_right_bounds.contains(&pos) {
 9720        return Some(ResizeEdge::TopRight);
 9721    }
 9722
 9723    let bottom_left_bounds = Bounds::new(
 9724        Point::new(px(0.), window_size.height - corner_size.height),
 9725        corner_size,
 9726    );
 9727    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9728        return Some(ResizeEdge::BottomLeft);
 9729    }
 9730
 9731    let bottom_right_bounds = Bounds::new(
 9732        Point::new(
 9733            window_size.width - corner_size.width,
 9734            window_size.height - corner_size.height,
 9735        ),
 9736        corner_size,
 9737    );
 9738    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9739        return Some(ResizeEdge::BottomRight);
 9740    }
 9741
 9742    if !tiling.top && pos.y < shadow_size {
 9743        Some(ResizeEdge::Top)
 9744    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9745        Some(ResizeEdge::Bottom)
 9746    } else if !tiling.left && pos.x < shadow_size {
 9747        Some(ResizeEdge::Left)
 9748    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9749        Some(ResizeEdge::Right)
 9750    } else {
 9751        None
 9752    }
 9753}
 9754
 9755fn join_pane_into_active(
 9756    active_pane: &Entity<Pane>,
 9757    pane: &Entity<Pane>,
 9758    window: &mut Window,
 9759    cx: &mut App,
 9760) {
 9761    if pane == active_pane {
 9762    } else if pane.read(cx).items_len() == 0 {
 9763        pane.update(cx, |_, cx| {
 9764            cx.emit(pane::Event::Remove {
 9765                focus_on_pane: None,
 9766            });
 9767        })
 9768    } else {
 9769        move_all_items(pane, active_pane, window, cx);
 9770    }
 9771}
 9772
 9773fn move_all_items(
 9774    from_pane: &Entity<Pane>,
 9775    to_pane: &Entity<Pane>,
 9776    window: &mut Window,
 9777    cx: &mut App,
 9778) {
 9779    let destination_is_different = from_pane != to_pane;
 9780    let mut moved_items = 0;
 9781    for (item_ix, item_handle) in from_pane
 9782        .read(cx)
 9783        .items()
 9784        .enumerate()
 9785        .map(|(ix, item)| (ix, item.clone()))
 9786        .collect::<Vec<_>>()
 9787    {
 9788        let ix = item_ix - moved_items;
 9789        if destination_is_different {
 9790            // Close item from previous pane
 9791            from_pane.update(cx, |source, cx| {
 9792                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9793            });
 9794            moved_items += 1;
 9795        }
 9796
 9797        // This automatically removes duplicate items in the pane
 9798        to_pane.update(cx, |destination, cx| {
 9799            destination.add_item(item_handle, true, true, None, window, cx);
 9800            window.focus(&destination.focus_handle(cx), cx)
 9801        });
 9802    }
 9803}
 9804
 9805pub fn move_item(
 9806    source: &Entity<Pane>,
 9807    destination: &Entity<Pane>,
 9808    item_id_to_move: EntityId,
 9809    destination_index: usize,
 9810    activate: bool,
 9811    window: &mut Window,
 9812    cx: &mut App,
 9813) {
 9814    let Some((item_ix, item_handle)) = source
 9815        .read(cx)
 9816        .items()
 9817        .enumerate()
 9818        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9819        .map(|(ix, item)| (ix, item.clone()))
 9820    else {
 9821        // Tab was closed during drag
 9822        return;
 9823    };
 9824
 9825    if source != destination {
 9826        // Close item from previous pane
 9827        source.update(cx, |source, cx| {
 9828            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9829        });
 9830    }
 9831
 9832    // This automatically removes duplicate items in the pane
 9833    destination.update(cx, |destination, cx| {
 9834        destination.add_item_inner(
 9835            item_handle,
 9836            activate,
 9837            activate,
 9838            activate,
 9839            Some(destination_index),
 9840            window,
 9841            cx,
 9842        );
 9843        if activate {
 9844            window.focus(&destination.focus_handle(cx), cx)
 9845        }
 9846    });
 9847}
 9848
 9849pub fn move_active_item(
 9850    source: &Entity<Pane>,
 9851    destination: &Entity<Pane>,
 9852    focus_destination: bool,
 9853    close_if_empty: bool,
 9854    window: &mut Window,
 9855    cx: &mut App,
 9856) {
 9857    if source == destination {
 9858        return;
 9859    }
 9860    let Some(active_item) = source.read(cx).active_item() else {
 9861        return;
 9862    };
 9863    source.update(cx, |source_pane, cx| {
 9864        let item_id = active_item.item_id();
 9865        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9866        destination.update(cx, |target_pane, cx| {
 9867            target_pane.add_item(
 9868                active_item,
 9869                focus_destination,
 9870                focus_destination,
 9871                Some(target_pane.items_len()),
 9872                window,
 9873                cx,
 9874            );
 9875        });
 9876    });
 9877}
 9878
 9879pub fn clone_active_item(
 9880    workspace_id: Option<WorkspaceId>,
 9881    source: &Entity<Pane>,
 9882    destination: &Entity<Pane>,
 9883    focus_destination: bool,
 9884    window: &mut Window,
 9885    cx: &mut App,
 9886) {
 9887    if source == destination {
 9888        return;
 9889    }
 9890    let Some(active_item) = source.read(cx).active_item() else {
 9891        return;
 9892    };
 9893    if !active_item.can_split(cx) {
 9894        return;
 9895    }
 9896    let destination = destination.downgrade();
 9897    let task = active_item.clone_on_split(workspace_id, window, cx);
 9898    window
 9899        .spawn(cx, async move |cx| {
 9900            let Some(clone) = task.await else {
 9901                return;
 9902            };
 9903            destination
 9904                .update_in(cx, |target_pane, window, cx| {
 9905                    target_pane.add_item(
 9906                        clone,
 9907                        focus_destination,
 9908                        focus_destination,
 9909                        Some(target_pane.items_len()),
 9910                        window,
 9911                        cx,
 9912                    );
 9913                })
 9914                .log_err();
 9915        })
 9916        .detach();
 9917}
 9918
 9919#[derive(Debug)]
 9920pub struct WorkspacePosition {
 9921    pub window_bounds: Option<WindowBounds>,
 9922    pub display: Option<Uuid>,
 9923    pub centered_layout: bool,
 9924}
 9925
 9926pub fn remote_workspace_position_from_db(
 9927    connection_options: RemoteConnectionOptions,
 9928    paths_to_open: &[PathBuf],
 9929    cx: &App,
 9930) -> Task<Result<WorkspacePosition>> {
 9931    let paths = paths_to_open.to_vec();
 9932
 9933    cx.background_spawn(async move {
 9934        let remote_connection_id = persistence::DB
 9935            .get_or_create_remote_connection(connection_options)
 9936            .await
 9937            .context("fetching serialized ssh project")?;
 9938        let serialized_workspace =
 9939            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9940
 9941        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9942            (Some(WindowBounds::Windowed(bounds)), None)
 9943        } else {
 9944            let restorable_bounds = serialized_workspace
 9945                .as_ref()
 9946                .and_then(|workspace| {
 9947                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9948                })
 9949                .or_else(|| persistence::read_default_window_bounds());
 9950
 9951            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9952                (Some(serialized_bounds), Some(serialized_display))
 9953            } else {
 9954                (None, None)
 9955            }
 9956        };
 9957
 9958        let centered_layout = serialized_workspace
 9959            .as_ref()
 9960            .map(|w| w.centered_layout)
 9961            .unwrap_or(false);
 9962
 9963        Ok(WorkspacePosition {
 9964            window_bounds,
 9965            display,
 9966            centered_layout,
 9967        })
 9968    })
 9969}
 9970
 9971pub fn with_active_or_new_workspace(
 9972    cx: &mut App,
 9973    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9974) {
 9975    match cx
 9976        .active_window()
 9977        .and_then(|w| w.downcast::<MultiWorkspace>())
 9978    {
 9979        Some(multi_workspace) => {
 9980            cx.defer(move |cx| {
 9981                multi_workspace
 9982                    .update(cx, |multi_workspace, window, cx| {
 9983                        let workspace = multi_workspace.workspace().clone();
 9984                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9985                    })
 9986                    .log_err();
 9987            });
 9988        }
 9989        None => {
 9990            let app_state = AppState::global(cx);
 9991            if let Some(app_state) = app_state.upgrade() {
 9992                open_new(
 9993                    OpenOptions::default(),
 9994                    app_state,
 9995                    cx,
 9996                    move |workspace, window, cx| f(workspace, window, cx),
 9997                )
 9998                .detach_and_log_err(cx);
 9999            }
10000        }
10001    }
10002}
10003
10004#[cfg(test)]
10005mod tests {
10006    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10007
10008    use super::*;
10009    use crate::{
10010        dock::{PanelEvent, test::TestPanel},
10011        item::{
10012            ItemBufferKind, ItemEvent,
10013            test::{TestItem, TestProjectItem},
10014        },
10015    };
10016    use fs::FakeFs;
10017    use gpui::{
10018        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10019        UpdateGlobal, VisualTestContext, px,
10020    };
10021    use project::{Project, ProjectEntryId};
10022    use serde_json::json;
10023    use settings::SettingsStore;
10024    use util::path;
10025    use util::rel_path::rel_path;
10026
10027    #[gpui::test]
10028    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10029        init_test(cx);
10030
10031        let fs = FakeFs::new(cx.executor());
10032        let project = Project::test(fs, [], cx).await;
10033        let (workspace, cx) =
10034            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10035
10036        // Adding an item with no ambiguity renders the tab without detail.
10037        let item1 = cx.new(|cx| {
10038            let mut item = TestItem::new(cx);
10039            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10040            item
10041        });
10042        workspace.update_in(cx, |workspace, window, cx| {
10043            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10044        });
10045        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10046
10047        // Adding an item that creates ambiguity increases the level of detail on
10048        // both tabs.
10049        let item2 = cx.new_window_entity(|_window, cx| {
10050            let mut item = TestItem::new(cx);
10051            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10052            item
10053        });
10054        workspace.update_in(cx, |workspace, window, cx| {
10055            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10056        });
10057        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10058        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10059
10060        // Adding an item that creates ambiguity increases the level of detail only
10061        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10062        // we stop at the highest detail available.
10063        let item3 = cx.new(|cx| {
10064            let mut item = TestItem::new(cx);
10065            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10066            item
10067        });
10068        workspace.update_in(cx, |workspace, window, cx| {
10069            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10070        });
10071        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10072        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10073        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10074    }
10075
10076    #[gpui::test]
10077    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10078        init_test(cx);
10079
10080        let fs = FakeFs::new(cx.executor());
10081        fs.insert_tree(
10082            "/root1",
10083            json!({
10084                "one.txt": "",
10085                "two.txt": "",
10086            }),
10087        )
10088        .await;
10089        fs.insert_tree(
10090            "/root2",
10091            json!({
10092                "three.txt": "",
10093            }),
10094        )
10095        .await;
10096
10097        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10098        let (workspace, cx) =
10099            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10100        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10101        let worktree_id = project.update(cx, |project, cx| {
10102            project.worktrees(cx).next().unwrap().read(cx).id()
10103        });
10104
10105        let item1 = cx.new(|cx| {
10106            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10107        });
10108        let item2 = cx.new(|cx| {
10109            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10110        });
10111
10112        // Add an item to an empty pane
10113        workspace.update_in(cx, |workspace, window, cx| {
10114            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10115        });
10116        project.update(cx, |project, cx| {
10117            assert_eq!(
10118                project.active_entry(),
10119                project
10120                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10121                    .map(|e| e.id)
10122            );
10123        });
10124        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10125
10126        // Add a second item to a non-empty pane
10127        workspace.update_in(cx, |workspace, window, cx| {
10128            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10129        });
10130        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10131        project.update(cx, |project, cx| {
10132            assert_eq!(
10133                project.active_entry(),
10134                project
10135                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10136                    .map(|e| e.id)
10137            );
10138        });
10139
10140        // Close the active item
10141        pane.update_in(cx, |pane, window, cx| {
10142            pane.close_active_item(&Default::default(), window, cx)
10143        })
10144        .await
10145        .unwrap();
10146        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10147        project.update(cx, |project, cx| {
10148            assert_eq!(
10149                project.active_entry(),
10150                project
10151                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10152                    .map(|e| e.id)
10153            );
10154        });
10155
10156        // Add a project folder
10157        project
10158            .update(cx, |project, cx| {
10159                project.find_or_create_worktree("root2", true, cx)
10160            })
10161            .await
10162            .unwrap();
10163        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10164
10165        // Remove a project folder
10166        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10167        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10168    }
10169
10170    #[gpui::test]
10171    async fn test_close_window(cx: &mut TestAppContext) {
10172        init_test(cx);
10173
10174        let fs = FakeFs::new(cx.executor());
10175        fs.insert_tree("/root", json!({ "one": "" })).await;
10176
10177        let project = Project::test(fs, ["root".as_ref()], cx).await;
10178        let (workspace, cx) =
10179            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10180
10181        // When there are no dirty items, there's nothing to do.
10182        let item1 = cx.new(TestItem::new);
10183        workspace.update_in(cx, |w, window, cx| {
10184            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10185        });
10186        let task = workspace.update_in(cx, |w, window, cx| {
10187            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10188        });
10189        assert!(task.await.unwrap());
10190
10191        // When there are dirty untitled items, prompt to save each one. If the user
10192        // cancels any prompt, then abort.
10193        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10194        let item3 = cx.new(|cx| {
10195            TestItem::new(cx)
10196                .with_dirty(true)
10197                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10198        });
10199        workspace.update_in(cx, |w, window, cx| {
10200            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10201            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10202        });
10203        let task = workspace.update_in(cx, |w, window, cx| {
10204            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10205        });
10206        cx.executor().run_until_parked();
10207        cx.simulate_prompt_answer("Cancel"); // cancel save all
10208        cx.executor().run_until_parked();
10209        assert!(!cx.has_pending_prompt());
10210        assert!(!task.await.unwrap());
10211    }
10212
10213    #[gpui::test]
10214    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10215        init_test(cx);
10216
10217        let fs = FakeFs::new(cx.executor());
10218        fs.insert_tree("/root", json!({ "one": "" })).await;
10219
10220        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10221        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10222        let multi_workspace_handle =
10223            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10224        cx.run_until_parked();
10225
10226        let workspace_a = multi_workspace_handle
10227            .read_with(cx, |mw, _| mw.workspace().clone())
10228            .unwrap();
10229
10230        let workspace_b = multi_workspace_handle
10231            .update(cx, |mw, window, cx| {
10232                mw.test_add_workspace(project_b, window, cx)
10233            })
10234            .unwrap();
10235
10236        // Activate workspace A
10237        multi_workspace_handle
10238            .update(cx, |mw, window, cx| {
10239                mw.activate_index(0, window, cx);
10240            })
10241            .unwrap();
10242
10243        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10244
10245        // Workspace A has a clean item
10246        let item_a = cx.new(TestItem::new);
10247        workspace_a.update_in(cx, |w, window, cx| {
10248            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10249        });
10250
10251        // Workspace B has a dirty item
10252        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10253        workspace_b.update_in(cx, |w, window, cx| {
10254            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10255        });
10256
10257        // Verify workspace A is active
10258        multi_workspace_handle
10259            .read_with(cx, |mw, _| {
10260                assert_eq!(mw.active_workspace_index(), 0);
10261            })
10262            .unwrap();
10263
10264        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10265        multi_workspace_handle
10266            .update(cx, |mw, window, cx| {
10267                mw.close_window(&CloseWindow, window, cx);
10268            })
10269            .unwrap();
10270        cx.run_until_parked();
10271
10272        // Workspace B should now be active since it has dirty items that need attention
10273        multi_workspace_handle
10274            .read_with(cx, |mw, _| {
10275                assert_eq!(
10276                    mw.active_workspace_index(),
10277                    1,
10278                    "workspace B should be activated when it prompts"
10279                );
10280            })
10281            .unwrap();
10282
10283        // User cancels the save prompt from workspace B
10284        cx.simulate_prompt_answer("Cancel");
10285        cx.run_until_parked();
10286
10287        // Window should still exist because workspace B's close was cancelled
10288        assert!(
10289            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10290            "window should still exist after cancelling one workspace's close"
10291        );
10292    }
10293
10294    #[gpui::test]
10295    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10296        init_test(cx);
10297
10298        // Register TestItem as a serializable item
10299        cx.update(|cx| {
10300            register_serializable_item::<TestItem>(cx);
10301        });
10302
10303        let fs = FakeFs::new(cx.executor());
10304        fs.insert_tree("/root", json!({ "one": "" })).await;
10305
10306        let project = Project::test(fs, ["root".as_ref()], cx).await;
10307        let (workspace, cx) =
10308            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10309
10310        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10311        let item1 = cx.new(|cx| {
10312            TestItem::new(cx)
10313                .with_dirty(true)
10314                .with_serialize(|| Some(Task::ready(Ok(()))))
10315        });
10316        let item2 = cx.new(|cx| {
10317            TestItem::new(cx)
10318                .with_dirty(true)
10319                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10320                .with_serialize(|| Some(Task::ready(Ok(()))))
10321        });
10322        workspace.update_in(cx, |w, window, cx| {
10323            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10324            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10325        });
10326        let task = workspace.update_in(cx, |w, window, cx| {
10327            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10328        });
10329        assert!(task.await.unwrap());
10330    }
10331
10332    #[gpui::test]
10333    async fn test_close_pane_items(cx: &mut TestAppContext) {
10334        init_test(cx);
10335
10336        let fs = FakeFs::new(cx.executor());
10337
10338        let project = Project::test(fs, None, cx).await;
10339        let (workspace, cx) =
10340            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10341
10342        let item1 = cx.new(|cx| {
10343            TestItem::new(cx)
10344                .with_dirty(true)
10345                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10346        });
10347        let item2 = cx.new(|cx| {
10348            TestItem::new(cx)
10349                .with_dirty(true)
10350                .with_conflict(true)
10351                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10352        });
10353        let item3 = cx.new(|cx| {
10354            TestItem::new(cx)
10355                .with_dirty(true)
10356                .with_conflict(true)
10357                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10358        });
10359        let item4 = cx.new(|cx| {
10360            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10361                let project_item = TestProjectItem::new_untitled(cx);
10362                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10363                project_item
10364            }])
10365        });
10366        let pane = workspace.update_in(cx, |workspace, window, cx| {
10367            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10368            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10369            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10370            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10371            workspace.active_pane().clone()
10372        });
10373
10374        let close_items = pane.update_in(cx, |pane, window, cx| {
10375            pane.activate_item(1, true, true, window, cx);
10376            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10377            let item1_id = item1.item_id();
10378            let item3_id = item3.item_id();
10379            let item4_id = item4.item_id();
10380            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10381                [item1_id, item3_id, item4_id].contains(&id)
10382            })
10383        });
10384        cx.executor().run_until_parked();
10385
10386        assert!(cx.has_pending_prompt());
10387        cx.simulate_prompt_answer("Save all");
10388
10389        cx.executor().run_until_parked();
10390
10391        // Item 1 is saved. There's a prompt to save item 3.
10392        pane.update(cx, |pane, cx| {
10393            assert_eq!(item1.read(cx).save_count, 1);
10394            assert_eq!(item1.read(cx).save_as_count, 0);
10395            assert_eq!(item1.read(cx).reload_count, 0);
10396            assert_eq!(pane.items_len(), 3);
10397            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10398        });
10399        assert!(cx.has_pending_prompt());
10400
10401        // Cancel saving item 3.
10402        cx.simulate_prompt_answer("Discard");
10403        cx.executor().run_until_parked();
10404
10405        // Item 3 is reloaded. There's a prompt to save item 4.
10406        pane.update(cx, |pane, cx| {
10407            assert_eq!(item3.read(cx).save_count, 0);
10408            assert_eq!(item3.read(cx).save_as_count, 0);
10409            assert_eq!(item3.read(cx).reload_count, 1);
10410            assert_eq!(pane.items_len(), 2);
10411            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10412        });
10413
10414        // There's a prompt for a path for item 4.
10415        cx.simulate_new_path_selection(|_| Some(Default::default()));
10416        close_items.await.unwrap();
10417
10418        // The requested items are closed.
10419        pane.update(cx, |pane, cx| {
10420            assert_eq!(item4.read(cx).save_count, 0);
10421            assert_eq!(item4.read(cx).save_as_count, 1);
10422            assert_eq!(item4.read(cx).reload_count, 0);
10423            assert_eq!(pane.items_len(), 1);
10424            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10425        });
10426    }
10427
10428    #[gpui::test]
10429    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10430        init_test(cx);
10431
10432        let fs = FakeFs::new(cx.executor());
10433        let project = Project::test(fs, [], cx).await;
10434        let (workspace, cx) =
10435            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10436
10437        // Create several workspace items with single project entries, and two
10438        // workspace items with multiple project entries.
10439        let single_entry_items = (0..=4)
10440            .map(|project_entry_id| {
10441                cx.new(|cx| {
10442                    TestItem::new(cx)
10443                        .with_dirty(true)
10444                        .with_project_items(&[dirty_project_item(
10445                            project_entry_id,
10446                            &format!("{project_entry_id}.txt"),
10447                            cx,
10448                        )])
10449                })
10450            })
10451            .collect::<Vec<_>>();
10452        let item_2_3 = cx.new(|cx| {
10453            TestItem::new(cx)
10454                .with_dirty(true)
10455                .with_buffer_kind(ItemBufferKind::Multibuffer)
10456                .with_project_items(&[
10457                    single_entry_items[2].read(cx).project_items[0].clone(),
10458                    single_entry_items[3].read(cx).project_items[0].clone(),
10459                ])
10460        });
10461        let item_3_4 = cx.new(|cx| {
10462            TestItem::new(cx)
10463                .with_dirty(true)
10464                .with_buffer_kind(ItemBufferKind::Multibuffer)
10465                .with_project_items(&[
10466                    single_entry_items[3].read(cx).project_items[0].clone(),
10467                    single_entry_items[4].read(cx).project_items[0].clone(),
10468                ])
10469        });
10470
10471        // Create two panes that contain the following project entries:
10472        //   left pane:
10473        //     multi-entry items:   (2, 3)
10474        //     single-entry items:  0, 2, 3, 4
10475        //   right pane:
10476        //     single-entry items:  4, 1
10477        //     multi-entry items:   (3, 4)
10478        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10479            let left_pane = workspace.active_pane().clone();
10480            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10481            workspace.add_item_to_active_pane(
10482                single_entry_items[0].boxed_clone(),
10483                None,
10484                true,
10485                window,
10486                cx,
10487            );
10488            workspace.add_item_to_active_pane(
10489                single_entry_items[2].boxed_clone(),
10490                None,
10491                true,
10492                window,
10493                cx,
10494            );
10495            workspace.add_item_to_active_pane(
10496                single_entry_items[3].boxed_clone(),
10497                None,
10498                true,
10499                window,
10500                cx,
10501            );
10502            workspace.add_item_to_active_pane(
10503                single_entry_items[4].boxed_clone(),
10504                None,
10505                true,
10506                window,
10507                cx,
10508            );
10509
10510            let right_pane =
10511                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10512
10513            let boxed_clone = single_entry_items[1].boxed_clone();
10514            let right_pane = window.spawn(cx, async move |cx| {
10515                right_pane.await.inspect(|right_pane| {
10516                    right_pane
10517                        .update_in(cx, |pane, window, cx| {
10518                            pane.add_item(boxed_clone, true, true, None, window, cx);
10519                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10520                        })
10521                        .unwrap();
10522                })
10523            });
10524
10525            (left_pane, right_pane)
10526        });
10527        let right_pane = right_pane.await.unwrap();
10528        cx.focus(&right_pane);
10529
10530        let close = right_pane.update_in(cx, |pane, window, cx| {
10531            pane.close_all_items(&CloseAllItems::default(), window, cx)
10532                .unwrap()
10533        });
10534        cx.executor().run_until_parked();
10535
10536        let msg = cx.pending_prompt().unwrap().0;
10537        assert!(msg.contains("1.txt"));
10538        assert!(!msg.contains("2.txt"));
10539        assert!(!msg.contains("3.txt"));
10540        assert!(!msg.contains("4.txt"));
10541
10542        // With best-effort close, cancelling item 1 keeps it open but items 4
10543        // and (3,4) still close since their entries exist in left pane.
10544        cx.simulate_prompt_answer("Cancel");
10545        close.await;
10546
10547        right_pane.read_with(cx, |pane, _| {
10548            assert_eq!(pane.items_len(), 1);
10549        });
10550
10551        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10552        left_pane
10553            .update_in(cx, |left_pane, window, cx| {
10554                left_pane.close_item_by_id(
10555                    single_entry_items[3].entity_id(),
10556                    SaveIntent::Skip,
10557                    window,
10558                    cx,
10559                )
10560            })
10561            .await
10562            .unwrap();
10563
10564        let close = left_pane.update_in(cx, |pane, window, cx| {
10565            pane.close_all_items(&CloseAllItems::default(), window, cx)
10566                .unwrap()
10567        });
10568        cx.executor().run_until_parked();
10569
10570        let details = cx.pending_prompt().unwrap().1;
10571        assert!(details.contains("0.txt"));
10572        assert!(details.contains("3.txt"));
10573        assert!(details.contains("4.txt"));
10574        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10575        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10576        // assert!(!details.contains("2.txt"));
10577
10578        cx.simulate_prompt_answer("Save all");
10579        cx.executor().run_until_parked();
10580        close.await;
10581
10582        left_pane.read_with(cx, |pane, _| {
10583            assert_eq!(pane.items_len(), 0);
10584        });
10585    }
10586
10587    #[gpui::test]
10588    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10589        init_test(cx);
10590
10591        let fs = FakeFs::new(cx.executor());
10592        let project = Project::test(fs, [], cx).await;
10593        let (workspace, cx) =
10594            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10595        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10596
10597        let item = cx.new(|cx| {
10598            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10599        });
10600        let item_id = item.entity_id();
10601        workspace.update_in(cx, |workspace, window, cx| {
10602            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10603        });
10604
10605        // Autosave on window change.
10606        item.update(cx, |item, cx| {
10607            SettingsStore::update_global(cx, |settings, cx| {
10608                settings.update_user_settings(cx, |settings| {
10609                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10610                })
10611            });
10612            item.is_dirty = true;
10613        });
10614
10615        // Deactivating the window saves the file.
10616        cx.deactivate_window();
10617        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10618
10619        // Re-activating the window doesn't save the file.
10620        cx.update(|window, _| window.activate_window());
10621        cx.executor().run_until_parked();
10622        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10623
10624        // Autosave on focus change.
10625        item.update_in(cx, |item, window, cx| {
10626            cx.focus_self(window);
10627            SettingsStore::update_global(cx, |settings, cx| {
10628                settings.update_user_settings(cx, |settings| {
10629                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10630                })
10631            });
10632            item.is_dirty = true;
10633        });
10634        // Blurring the item saves the file.
10635        item.update_in(cx, |_, window, _| window.blur());
10636        cx.executor().run_until_parked();
10637        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10638
10639        // Deactivating the window still saves the file.
10640        item.update_in(cx, |item, window, cx| {
10641            cx.focus_self(window);
10642            item.is_dirty = true;
10643        });
10644        cx.deactivate_window();
10645        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10646
10647        // Autosave after delay.
10648        item.update(cx, |item, cx| {
10649            SettingsStore::update_global(cx, |settings, cx| {
10650                settings.update_user_settings(cx, |settings| {
10651                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10652                        milliseconds: 500.into(),
10653                    });
10654                })
10655            });
10656            item.is_dirty = true;
10657            cx.emit(ItemEvent::Edit);
10658        });
10659
10660        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10661        cx.executor().advance_clock(Duration::from_millis(250));
10662        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10663
10664        // After delay expires, the file is saved.
10665        cx.executor().advance_clock(Duration::from_millis(250));
10666        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10667
10668        // Autosave after delay, should save earlier than delay if tab is closed
10669        item.update(cx, |item, cx| {
10670            item.is_dirty = true;
10671            cx.emit(ItemEvent::Edit);
10672        });
10673        cx.executor().advance_clock(Duration::from_millis(250));
10674        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10675
10676        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10677        pane.update_in(cx, |pane, window, cx| {
10678            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10679        })
10680        .await
10681        .unwrap();
10682        assert!(!cx.has_pending_prompt());
10683        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10684
10685        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10686        workspace.update_in(cx, |workspace, window, cx| {
10687            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10688        });
10689        item.update_in(cx, |item, _window, cx| {
10690            item.is_dirty = true;
10691            for project_item in &mut item.project_items {
10692                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10693            }
10694        });
10695        cx.run_until_parked();
10696        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10697
10698        // Autosave on focus change, ensuring closing the tab counts as such.
10699        item.update(cx, |item, cx| {
10700            SettingsStore::update_global(cx, |settings, cx| {
10701                settings.update_user_settings(cx, |settings| {
10702                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10703                })
10704            });
10705            item.is_dirty = true;
10706            for project_item in &mut item.project_items {
10707                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10708            }
10709        });
10710
10711        pane.update_in(cx, |pane, window, cx| {
10712            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10713        })
10714        .await
10715        .unwrap();
10716        assert!(!cx.has_pending_prompt());
10717        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10718
10719        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10720        workspace.update_in(cx, |workspace, window, cx| {
10721            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10722        });
10723        item.update_in(cx, |item, window, cx| {
10724            item.project_items[0].update(cx, |item, _| {
10725                item.entry_id = None;
10726            });
10727            item.is_dirty = true;
10728            window.blur();
10729        });
10730        cx.run_until_parked();
10731        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10732
10733        // Ensure autosave is prevented for deleted files also when closing the buffer.
10734        let _close_items = pane.update_in(cx, |pane, window, cx| {
10735            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10736        });
10737        cx.run_until_parked();
10738        assert!(cx.has_pending_prompt());
10739        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10740    }
10741
10742    #[gpui::test]
10743    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10744        init_test(cx);
10745
10746        let fs = FakeFs::new(cx.executor());
10747        let project = Project::test(fs, [], cx).await;
10748        let (workspace, cx) =
10749            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10750
10751        // Create a multibuffer-like item with two child focus handles,
10752        // simulating individual buffer editors within a multibuffer.
10753        let item = cx.new(|cx| {
10754            TestItem::new(cx)
10755                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10756                .with_child_focus_handles(2, cx)
10757        });
10758        workspace.update_in(cx, |workspace, window, cx| {
10759            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10760        });
10761
10762        // Set autosave to OnFocusChange and focus the first child handle,
10763        // simulating the user's cursor being inside one of the multibuffer's excerpts.
10764        item.update_in(cx, |item, window, cx| {
10765            SettingsStore::update_global(cx, |settings, cx| {
10766                settings.update_user_settings(cx, |settings| {
10767                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10768                })
10769            });
10770            item.is_dirty = true;
10771            window.focus(&item.child_focus_handles[0], cx);
10772        });
10773        cx.executor().run_until_parked();
10774        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10775
10776        // Moving focus from one child to another within the same item should
10777        // NOT trigger autosave — focus is still within the item's focus hierarchy.
10778        item.update_in(cx, |item, window, cx| {
10779            window.focus(&item.child_focus_handles[1], cx);
10780        });
10781        cx.executor().run_until_parked();
10782        item.read_with(cx, |item, _| {
10783            assert_eq!(
10784                item.save_count, 0,
10785                "Switching focus between children within the same item should not autosave"
10786            );
10787        });
10788
10789        // Blurring the item saves the file. This is the core regression scenario:
10790        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10791        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10792        // the leaf is always a child focus handle, so `on_blur` never detected
10793        // focus leaving the item.
10794        item.update_in(cx, |_, window, _| window.blur());
10795        cx.executor().run_until_parked();
10796        item.read_with(cx, |item, _| {
10797            assert_eq!(
10798                item.save_count, 1,
10799                "Blurring should trigger autosave when focus was on a child of the item"
10800            );
10801        });
10802
10803        // Deactivating the window should also trigger autosave when a child of
10804        // the multibuffer item currently owns focus.
10805        item.update_in(cx, |item, window, cx| {
10806            item.is_dirty = true;
10807            window.focus(&item.child_focus_handles[0], cx);
10808        });
10809        cx.executor().run_until_parked();
10810        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10811
10812        cx.deactivate_window();
10813        item.read_with(cx, |item, _| {
10814            assert_eq!(
10815                item.save_count, 2,
10816                "Deactivating window should trigger autosave when focus was on a child"
10817            );
10818        });
10819    }
10820
10821    #[gpui::test]
10822    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10823        init_test(cx);
10824
10825        let fs = FakeFs::new(cx.executor());
10826
10827        let project = Project::test(fs, [], cx).await;
10828        let (workspace, cx) =
10829            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10830
10831        let item = cx.new(|cx| {
10832            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10833        });
10834        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10835        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10836        let toolbar_notify_count = Rc::new(RefCell::new(0));
10837
10838        workspace.update_in(cx, |workspace, window, cx| {
10839            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10840            let toolbar_notification_count = toolbar_notify_count.clone();
10841            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10842                *toolbar_notification_count.borrow_mut() += 1
10843            })
10844            .detach();
10845        });
10846
10847        pane.read_with(cx, |pane, _| {
10848            assert!(!pane.can_navigate_backward());
10849            assert!(!pane.can_navigate_forward());
10850        });
10851
10852        item.update_in(cx, |item, _, cx| {
10853            item.set_state("one".to_string(), cx);
10854        });
10855
10856        // Toolbar must be notified to re-render the navigation buttons
10857        assert_eq!(*toolbar_notify_count.borrow(), 1);
10858
10859        pane.read_with(cx, |pane, _| {
10860            assert!(pane.can_navigate_backward());
10861            assert!(!pane.can_navigate_forward());
10862        });
10863
10864        workspace
10865            .update_in(cx, |workspace, window, cx| {
10866                workspace.go_back(pane.downgrade(), window, cx)
10867            })
10868            .await
10869            .unwrap();
10870
10871        assert_eq!(*toolbar_notify_count.borrow(), 2);
10872        pane.read_with(cx, |pane, _| {
10873            assert!(!pane.can_navigate_backward());
10874            assert!(pane.can_navigate_forward());
10875        });
10876    }
10877
10878    #[gpui::test]
10879    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10880        init_test(cx);
10881        let fs = FakeFs::new(cx.executor());
10882        let project = Project::test(fs, [], cx).await;
10883        let (multi_workspace, cx) =
10884            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10885        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10886
10887        workspace.update_in(cx, |workspace, window, cx| {
10888            let first_item = cx.new(|cx| {
10889                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10890            });
10891            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10892            workspace.split_pane(
10893                workspace.active_pane().clone(),
10894                SplitDirection::Right,
10895                window,
10896                cx,
10897            );
10898            workspace.split_pane(
10899                workspace.active_pane().clone(),
10900                SplitDirection::Right,
10901                window,
10902                cx,
10903            );
10904        });
10905
10906        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10907            let panes = workspace.center.panes();
10908            assert!(panes.len() >= 2);
10909            (
10910                panes.first().expect("at least one pane").entity_id(),
10911                panes.last().expect("at least one pane").entity_id(),
10912            )
10913        });
10914
10915        workspace.update_in(cx, |workspace, window, cx| {
10916            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10917        });
10918        workspace.update(cx, |workspace, _| {
10919            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10920            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10921        });
10922
10923        cx.dispatch_action(ActivateLastPane);
10924
10925        workspace.update(cx, |workspace, _| {
10926            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10927        });
10928    }
10929
10930    #[gpui::test]
10931    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10932        init_test(cx);
10933        let fs = FakeFs::new(cx.executor());
10934
10935        let project = Project::test(fs, [], cx).await;
10936        let (workspace, cx) =
10937            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10938
10939        let panel = workspace.update_in(cx, |workspace, window, cx| {
10940            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10941            workspace.add_panel(panel.clone(), window, cx);
10942
10943            workspace
10944                .right_dock()
10945                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10946
10947            panel
10948        });
10949
10950        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10951        pane.update_in(cx, |pane, window, cx| {
10952            let item = cx.new(TestItem::new);
10953            pane.add_item(Box::new(item), true, true, None, window, cx);
10954        });
10955
10956        // Transfer focus from center to panel
10957        workspace.update_in(cx, |workspace, window, cx| {
10958            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10959        });
10960
10961        workspace.update_in(cx, |workspace, window, cx| {
10962            assert!(workspace.right_dock().read(cx).is_open());
10963            assert!(!panel.is_zoomed(window, cx));
10964            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10965        });
10966
10967        // Transfer focus from panel to center
10968        workspace.update_in(cx, |workspace, window, cx| {
10969            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10970        });
10971
10972        workspace.update_in(cx, |workspace, window, cx| {
10973            assert!(workspace.right_dock().read(cx).is_open());
10974            assert!(!panel.is_zoomed(window, cx));
10975            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10976        });
10977
10978        // Close the dock
10979        workspace.update_in(cx, |workspace, window, cx| {
10980            workspace.toggle_dock(DockPosition::Right, window, cx);
10981        });
10982
10983        workspace.update_in(cx, |workspace, window, cx| {
10984            assert!(!workspace.right_dock().read(cx).is_open());
10985            assert!(!panel.is_zoomed(window, cx));
10986            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10987        });
10988
10989        // Open the dock
10990        workspace.update_in(cx, |workspace, window, cx| {
10991            workspace.toggle_dock(DockPosition::Right, window, cx);
10992        });
10993
10994        workspace.update_in(cx, |workspace, window, cx| {
10995            assert!(workspace.right_dock().read(cx).is_open());
10996            assert!(!panel.is_zoomed(window, cx));
10997            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10998        });
10999
11000        // Focus and zoom panel
11001        panel.update_in(cx, |panel, window, cx| {
11002            cx.focus_self(window);
11003            panel.set_zoomed(true, window, cx)
11004        });
11005
11006        workspace.update_in(cx, |workspace, window, cx| {
11007            assert!(workspace.right_dock().read(cx).is_open());
11008            assert!(panel.is_zoomed(window, cx));
11009            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11010        });
11011
11012        // Transfer focus to the center closes the dock
11013        workspace.update_in(cx, |workspace, window, cx| {
11014            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11015        });
11016
11017        workspace.update_in(cx, |workspace, window, cx| {
11018            assert!(!workspace.right_dock().read(cx).is_open());
11019            assert!(panel.is_zoomed(window, cx));
11020            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11021        });
11022
11023        // Transferring focus back to the panel keeps it zoomed
11024        workspace.update_in(cx, |workspace, window, cx| {
11025            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11026        });
11027
11028        workspace.update_in(cx, |workspace, window, cx| {
11029            assert!(workspace.right_dock().read(cx).is_open());
11030            assert!(panel.is_zoomed(window, cx));
11031            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11032        });
11033
11034        // Close the dock while it is zoomed
11035        workspace.update_in(cx, |workspace, window, cx| {
11036            workspace.toggle_dock(DockPosition::Right, window, cx)
11037        });
11038
11039        workspace.update_in(cx, |workspace, window, cx| {
11040            assert!(!workspace.right_dock().read(cx).is_open());
11041            assert!(panel.is_zoomed(window, cx));
11042            assert!(workspace.zoomed.is_none());
11043            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11044        });
11045
11046        // Opening the dock, when it's zoomed, retains focus
11047        workspace.update_in(cx, |workspace, window, cx| {
11048            workspace.toggle_dock(DockPosition::Right, window, cx)
11049        });
11050
11051        workspace.update_in(cx, |workspace, window, cx| {
11052            assert!(workspace.right_dock().read(cx).is_open());
11053            assert!(panel.is_zoomed(window, cx));
11054            assert!(workspace.zoomed.is_some());
11055            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11056        });
11057
11058        // Unzoom and close the panel, zoom the active pane.
11059        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11060        workspace.update_in(cx, |workspace, window, cx| {
11061            workspace.toggle_dock(DockPosition::Right, window, cx)
11062        });
11063        pane.update_in(cx, |pane, window, cx| {
11064            pane.toggle_zoom(&Default::default(), window, cx)
11065        });
11066
11067        // Opening a dock unzooms the pane.
11068        workspace.update_in(cx, |workspace, window, cx| {
11069            workspace.toggle_dock(DockPosition::Right, window, cx)
11070        });
11071        workspace.update_in(cx, |workspace, window, cx| {
11072            let pane = pane.read(cx);
11073            assert!(!pane.is_zoomed());
11074            assert!(!pane.focus_handle(cx).is_focused(window));
11075            assert!(workspace.right_dock().read(cx).is_open());
11076            assert!(workspace.zoomed.is_none());
11077        });
11078    }
11079
11080    #[gpui::test]
11081    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11082        init_test(cx);
11083        let fs = FakeFs::new(cx.executor());
11084
11085        let project = Project::test(fs, [], cx).await;
11086        let (workspace, cx) =
11087            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11088
11089        let panel = workspace.update_in(cx, |workspace, window, cx| {
11090            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11091            workspace.add_panel(panel.clone(), window, cx);
11092            panel
11093        });
11094
11095        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11096        pane.update_in(cx, |pane, window, cx| {
11097            let item = cx.new(TestItem::new);
11098            pane.add_item(Box::new(item), true, true, None, window, cx);
11099        });
11100
11101        // Enable close_panel_on_toggle
11102        cx.update_global(|store: &mut SettingsStore, cx| {
11103            store.update_user_settings(cx, |settings| {
11104                settings.workspace.close_panel_on_toggle = Some(true);
11105            });
11106        });
11107
11108        // Panel starts closed. Toggling should open and focus it.
11109        workspace.update_in(cx, |workspace, window, cx| {
11110            assert!(!workspace.right_dock().read(cx).is_open());
11111            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11112        });
11113
11114        workspace.update_in(cx, |workspace, window, cx| {
11115            assert!(
11116                workspace.right_dock().read(cx).is_open(),
11117                "Dock should be open after toggling from center"
11118            );
11119            assert!(
11120                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11121                "Panel should be focused after toggling from center"
11122            );
11123        });
11124
11125        // Panel is open and focused. Toggling should close the panel and
11126        // return focus to the center.
11127        workspace.update_in(cx, |workspace, window, cx| {
11128            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11129        });
11130
11131        workspace.update_in(cx, |workspace, window, cx| {
11132            assert!(
11133                !workspace.right_dock().read(cx).is_open(),
11134                "Dock should be closed after toggling from focused panel"
11135            );
11136            assert!(
11137                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11138                "Panel should not be focused after toggling from focused panel"
11139            );
11140        });
11141
11142        // Open the dock and focus something else so the panel is open but not
11143        // focused. Toggling should focus the panel (not close it).
11144        workspace.update_in(cx, |workspace, window, cx| {
11145            workspace
11146                .right_dock()
11147                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11148            window.focus(&pane.read(cx).focus_handle(cx), cx);
11149        });
11150
11151        workspace.update_in(cx, |workspace, window, cx| {
11152            assert!(workspace.right_dock().read(cx).is_open());
11153            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11154            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11155        });
11156
11157        workspace.update_in(cx, |workspace, window, cx| {
11158            assert!(
11159                workspace.right_dock().read(cx).is_open(),
11160                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11161            );
11162            assert!(
11163                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11164                "Panel should be focused after toggling an open-but-unfocused panel"
11165            );
11166        });
11167
11168        // Now disable the setting and verify the original behavior: toggling
11169        // from a focused panel moves focus to center but leaves the dock open.
11170        cx.update_global(|store: &mut SettingsStore, cx| {
11171            store.update_user_settings(cx, |settings| {
11172                settings.workspace.close_panel_on_toggle = Some(false);
11173            });
11174        });
11175
11176        workspace.update_in(cx, |workspace, window, cx| {
11177            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11178        });
11179
11180        workspace.update_in(cx, |workspace, window, cx| {
11181            assert!(
11182                workspace.right_dock().read(cx).is_open(),
11183                "Dock should remain open when setting is disabled"
11184            );
11185            assert!(
11186                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11187                "Panel should not be focused after toggling with setting disabled"
11188            );
11189        });
11190    }
11191
11192    #[gpui::test]
11193    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11194        init_test(cx);
11195        let fs = FakeFs::new(cx.executor());
11196
11197        let project = Project::test(fs, [], cx).await;
11198        let (workspace, cx) =
11199            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11200
11201        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11202            workspace.active_pane().clone()
11203        });
11204
11205        // Add an item to the pane so it can be zoomed
11206        workspace.update_in(cx, |workspace, window, cx| {
11207            let item = cx.new(TestItem::new);
11208            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11209        });
11210
11211        // Initially not zoomed
11212        workspace.update_in(cx, |workspace, _window, cx| {
11213            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11214            assert!(
11215                workspace.zoomed.is_none(),
11216                "Workspace should track no zoomed pane"
11217            );
11218            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11219        });
11220
11221        // Zoom In
11222        pane.update_in(cx, |pane, window, cx| {
11223            pane.zoom_in(&crate::ZoomIn, window, cx);
11224        });
11225
11226        workspace.update_in(cx, |workspace, window, cx| {
11227            assert!(
11228                pane.read(cx).is_zoomed(),
11229                "Pane should be zoomed after ZoomIn"
11230            );
11231            assert!(
11232                workspace.zoomed.is_some(),
11233                "Workspace should track the zoomed pane"
11234            );
11235            assert!(
11236                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11237                "ZoomIn should focus the pane"
11238            );
11239        });
11240
11241        // Zoom In again is a no-op
11242        pane.update_in(cx, |pane, window, cx| {
11243            pane.zoom_in(&crate::ZoomIn, window, cx);
11244        });
11245
11246        workspace.update_in(cx, |workspace, window, cx| {
11247            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11248            assert!(
11249                workspace.zoomed.is_some(),
11250                "Workspace still tracks zoomed pane"
11251            );
11252            assert!(
11253                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11254                "Pane remains focused after repeated ZoomIn"
11255            );
11256        });
11257
11258        // Zoom Out
11259        pane.update_in(cx, |pane, window, cx| {
11260            pane.zoom_out(&crate::ZoomOut, window, cx);
11261        });
11262
11263        workspace.update_in(cx, |workspace, _window, cx| {
11264            assert!(
11265                !pane.read(cx).is_zoomed(),
11266                "Pane should unzoom after ZoomOut"
11267            );
11268            assert!(
11269                workspace.zoomed.is_none(),
11270                "Workspace clears zoom tracking after ZoomOut"
11271            );
11272        });
11273
11274        // Zoom Out again is a no-op
11275        pane.update_in(cx, |pane, window, cx| {
11276            pane.zoom_out(&crate::ZoomOut, window, cx);
11277        });
11278
11279        workspace.update_in(cx, |workspace, _window, cx| {
11280            assert!(
11281                !pane.read(cx).is_zoomed(),
11282                "Second ZoomOut keeps pane unzoomed"
11283            );
11284            assert!(
11285                workspace.zoomed.is_none(),
11286                "Workspace remains without zoomed pane"
11287            );
11288        });
11289    }
11290
11291    #[gpui::test]
11292    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11293        init_test(cx);
11294        let fs = FakeFs::new(cx.executor());
11295
11296        let project = Project::test(fs, [], cx).await;
11297        let (workspace, cx) =
11298            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11299        workspace.update_in(cx, |workspace, window, cx| {
11300            // Open two docks
11301            let left_dock = workspace.dock_at_position(DockPosition::Left);
11302            let right_dock = workspace.dock_at_position(DockPosition::Right);
11303
11304            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11305            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11306
11307            assert!(left_dock.read(cx).is_open());
11308            assert!(right_dock.read(cx).is_open());
11309        });
11310
11311        workspace.update_in(cx, |workspace, window, cx| {
11312            // Toggle all docks - should close both
11313            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11314
11315            let left_dock = workspace.dock_at_position(DockPosition::Left);
11316            let right_dock = workspace.dock_at_position(DockPosition::Right);
11317            assert!(!left_dock.read(cx).is_open());
11318            assert!(!right_dock.read(cx).is_open());
11319        });
11320
11321        workspace.update_in(cx, |workspace, window, cx| {
11322            // Toggle again - should reopen both
11323            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11324
11325            let left_dock = workspace.dock_at_position(DockPosition::Left);
11326            let right_dock = workspace.dock_at_position(DockPosition::Right);
11327            assert!(left_dock.read(cx).is_open());
11328            assert!(right_dock.read(cx).is_open());
11329        });
11330    }
11331
11332    #[gpui::test]
11333    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11334        init_test(cx);
11335        let fs = FakeFs::new(cx.executor());
11336
11337        let project = Project::test(fs, [], cx).await;
11338        let (workspace, cx) =
11339            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11340        workspace.update_in(cx, |workspace, window, cx| {
11341            // Open two docks
11342            let left_dock = workspace.dock_at_position(DockPosition::Left);
11343            let right_dock = workspace.dock_at_position(DockPosition::Right);
11344
11345            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11346            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11347
11348            assert!(left_dock.read(cx).is_open());
11349            assert!(right_dock.read(cx).is_open());
11350        });
11351
11352        workspace.update_in(cx, |workspace, window, cx| {
11353            // Close them manually
11354            workspace.toggle_dock(DockPosition::Left, window, cx);
11355            workspace.toggle_dock(DockPosition::Right, window, cx);
11356
11357            let left_dock = workspace.dock_at_position(DockPosition::Left);
11358            let right_dock = workspace.dock_at_position(DockPosition::Right);
11359            assert!(!left_dock.read(cx).is_open());
11360            assert!(!right_dock.read(cx).is_open());
11361        });
11362
11363        workspace.update_in(cx, |workspace, window, cx| {
11364            // Toggle all docks - only last closed (right dock) should reopen
11365            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11366
11367            let left_dock = workspace.dock_at_position(DockPosition::Left);
11368            let right_dock = workspace.dock_at_position(DockPosition::Right);
11369            assert!(!left_dock.read(cx).is_open());
11370            assert!(right_dock.read(cx).is_open());
11371        });
11372    }
11373
11374    #[gpui::test]
11375    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11376        init_test(cx);
11377        let fs = FakeFs::new(cx.executor());
11378        let project = Project::test(fs, [], cx).await;
11379        let (multi_workspace, cx) =
11380            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11381        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11382
11383        // Open two docks (left and right) with one panel each
11384        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11385            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11386            workspace.add_panel(left_panel.clone(), window, cx);
11387
11388            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11389            workspace.add_panel(right_panel.clone(), window, cx);
11390
11391            workspace.toggle_dock(DockPosition::Left, window, cx);
11392            workspace.toggle_dock(DockPosition::Right, window, cx);
11393
11394            // Verify initial state
11395            assert!(
11396                workspace.left_dock().read(cx).is_open(),
11397                "Left dock should be open"
11398            );
11399            assert_eq!(
11400                workspace
11401                    .left_dock()
11402                    .read(cx)
11403                    .visible_panel()
11404                    .unwrap()
11405                    .panel_id(),
11406                left_panel.panel_id(),
11407                "Left panel should be visible in left dock"
11408            );
11409            assert!(
11410                workspace.right_dock().read(cx).is_open(),
11411                "Right dock should be open"
11412            );
11413            assert_eq!(
11414                workspace
11415                    .right_dock()
11416                    .read(cx)
11417                    .visible_panel()
11418                    .unwrap()
11419                    .panel_id(),
11420                right_panel.panel_id(),
11421                "Right panel should be visible in right dock"
11422            );
11423            assert!(
11424                !workspace.bottom_dock().read(cx).is_open(),
11425                "Bottom dock should be closed"
11426            );
11427
11428            (left_panel, right_panel)
11429        });
11430
11431        // Focus the left panel and move it to the next position (bottom dock)
11432        workspace.update_in(cx, |workspace, window, cx| {
11433            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11434            assert!(
11435                left_panel.read(cx).focus_handle(cx).is_focused(window),
11436                "Left panel should be focused"
11437            );
11438        });
11439
11440        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11441
11442        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11443        workspace.update(cx, |workspace, cx| {
11444            assert!(
11445                !workspace.left_dock().read(cx).is_open(),
11446                "Left dock should be closed"
11447            );
11448            assert!(
11449                workspace.bottom_dock().read(cx).is_open(),
11450                "Bottom dock should now be open"
11451            );
11452            assert_eq!(
11453                left_panel.read(cx).position,
11454                DockPosition::Bottom,
11455                "Left panel should now be in the bottom dock"
11456            );
11457            assert_eq!(
11458                workspace
11459                    .bottom_dock()
11460                    .read(cx)
11461                    .visible_panel()
11462                    .unwrap()
11463                    .panel_id(),
11464                left_panel.panel_id(),
11465                "Left panel should be the visible panel in the bottom dock"
11466            );
11467        });
11468
11469        // Toggle all docks off
11470        workspace.update_in(cx, |workspace, window, cx| {
11471            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11472            assert!(
11473                !workspace.left_dock().read(cx).is_open(),
11474                "Left dock should be closed"
11475            );
11476            assert!(
11477                !workspace.right_dock().read(cx).is_open(),
11478                "Right dock should be closed"
11479            );
11480            assert!(
11481                !workspace.bottom_dock().read(cx).is_open(),
11482                "Bottom dock should be closed"
11483            );
11484        });
11485
11486        // Toggle all docks back on and verify positions are restored
11487        workspace.update_in(cx, |workspace, window, cx| {
11488            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11489            assert!(
11490                !workspace.left_dock().read(cx).is_open(),
11491                "Left dock should remain closed"
11492            );
11493            assert!(
11494                workspace.right_dock().read(cx).is_open(),
11495                "Right dock should remain open"
11496            );
11497            assert!(
11498                workspace.bottom_dock().read(cx).is_open(),
11499                "Bottom dock should remain open"
11500            );
11501            assert_eq!(
11502                left_panel.read(cx).position,
11503                DockPosition::Bottom,
11504                "Left panel should remain in the bottom dock"
11505            );
11506            assert_eq!(
11507                right_panel.read(cx).position,
11508                DockPosition::Right,
11509                "Right panel should remain in the right dock"
11510            );
11511            assert_eq!(
11512                workspace
11513                    .bottom_dock()
11514                    .read(cx)
11515                    .visible_panel()
11516                    .unwrap()
11517                    .panel_id(),
11518                left_panel.panel_id(),
11519                "Left panel should be the visible panel in the right dock"
11520            );
11521        });
11522    }
11523
11524    #[gpui::test]
11525    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11526        init_test(cx);
11527
11528        let fs = FakeFs::new(cx.executor());
11529
11530        let project = Project::test(fs, None, cx).await;
11531        let (workspace, cx) =
11532            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11533
11534        // Let's arrange the panes like this:
11535        //
11536        // +-----------------------+
11537        // |         top           |
11538        // +------+--------+-------+
11539        // | left | center | right |
11540        // +------+--------+-------+
11541        // |        bottom         |
11542        // +-----------------------+
11543
11544        let top_item = cx.new(|cx| {
11545            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11546        });
11547        let bottom_item = cx.new(|cx| {
11548            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11549        });
11550        let left_item = cx.new(|cx| {
11551            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11552        });
11553        let right_item = cx.new(|cx| {
11554            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11555        });
11556        let center_item = cx.new(|cx| {
11557            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11558        });
11559
11560        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11561            let top_pane_id = workspace.active_pane().entity_id();
11562            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11563            workspace.split_pane(
11564                workspace.active_pane().clone(),
11565                SplitDirection::Down,
11566                window,
11567                cx,
11568            );
11569            top_pane_id
11570        });
11571        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11572            let bottom_pane_id = workspace.active_pane().entity_id();
11573            workspace.add_item_to_active_pane(
11574                Box::new(bottom_item.clone()),
11575                None,
11576                false,
11577                window,
11578                cx,
11579            );
11580            workspace.split_pane(
11581                workspace.active_pane().clone(),
11582                SplitDirection::Up,
11583                window,
11584                cx,
11585            );
11586            bottom_pane_id
11587        });
11588        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11589            let left_pane_id = workspace.active_pane().entity_id();
11590            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11591            workspace.split_pane(
11592                workspace.active_pane().clone(),
11593                SplitDirection::Right,
11594                window,
11595                cx,
11596            );
11597            left_pane_id
11598        });
11599        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11600            let right_pane_id = workspace.active_pane().entity_id();
11601            workspace.add_item_to_active_pane(
11602                Box::new(right_item.clone()),
11603                None,
11604                false,
11605                window,
11606                cx,
11607            );
11608            workspace.split_pane(
11609                workspace.active_pane().clone(),
11610                SplitDirection::Left,
11611                window,
11612                cx,
11613            );
11614            right_pane_id
11615        });
11616        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11617            let center_pane_id = workspace.active_pane().entity_id();
11618            workspace.add_item_to_active_pane(
11619                Box::new(center_item.clone()),
11620                None,
11621                false,
11622                window,
11623                cx,
11624            );
11625            center_pane_id
11626        });
11627        cx.executor().run_until_parked();
11628
11629        workspace.update_in(cx, |workspace, window, cx| {
11630            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11631
11632            // Join into next from center pane into right
11633            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11634        });
11635
11636        workspace.update_in(cx, |workspace, window, cx| {
11637            let active_pane = workspace.active_pane();
11638            assert_eq!(right_pane_id, active_pane.entity_id());
11639            assert_eq!(2, active_pane.read(cx).items_len());
11640            let item_ids_in_pane =
11641                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11642            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11643            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11644
11645            // Join into next from right pane into bottom
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!(bottom_pane_id, active_pane.entity_id());
11652            assert_eq!(3, 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            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11658
11659            // Join into next from bottom pane into left
11660            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11661        });
11662
11663        workspace.update_in(cx, |workspace, window, cx| {
11664            let active_pane = workspace.active_pane();
11665            assert_eq!(left_pane_id, active_pane.entity_id());
11666            assert_eq!(4, active_pane.read(cx).items_len());
11667            let item_ids_in_pane =
11668                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11669            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11670            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11671            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11672            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11673
11674            // Join into next from left pane into top
11675            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11676        });
11677
11678        workspace.update_in(cx, |workspace, window, cx| {
11679            let active_pane = workspace.active_pane();
11680            assert_eq!(top_pane_id, active_pane.entity_id());
11681            assert_eq!(5, active_pane.read(cx).items_len());
11682            let item_ids_in_pane =
11683                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11684            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11685            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11686            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11687            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11688            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11689
11690            // Single pane left: no-op
11691            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11692        });
11693
11694        workspace.update(cx, |workspace, _cx| {
11695            let active_pane = workspace.active_pane();
11696            assert_eq!(top_pane_id, active_pane.entity_id());
11697        });
11698    }
11699
11700    fn add_an_item_to_active_pane(
11701        cx: &mut VisualTestContext,
11702        workspace: &Entity<Workspace>,
11703        item_id: u64,
11704    ) -> Entity<TestItem> {
11705        let item = cx.new(|cx| {
11706            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11707                item_id,
11708                "item{item_id}.txt",
11709                cx,
11710            )])
11711        });
11712        workspace.update_in(cx, |workspace, window, cx| {
11713            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11714        });
11715        item
11716    }
11717
11718    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11719        workspace.update_in(cx, |workspace, window, cx| {
11720            workspace.split_pane(
11721                workspace.active_pane().clone(),
11722                SplitDirection::Right,
11723                window,
11724                cx,
11725            )
11726        })
11727    }
11728
11729    #[gpui::test]
11730    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11731        init_test(cx);
11732        let fs = FakeFs::new(cx.executor());
11733        let project = Project::test(fs, None, cx).await;
11734        let (workspace, cx) =
11735            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11736
11737        add_an_item_to_active_pane(cx, &workspace, 1);
11738        split_pane(cx, &workspace);
11739        add_an_item_to_active_pane(cx, &workspace, 2);
11740        split_pane(cx, &workspace); // empty pane
11741        split_pane(cx, &workspace);
11742        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11743
11744        cx.executor().run_until_parked();
11745
11746        workspace.update(cx, |workspace, cx| {
11747            let num_panes = workspace.panes().len();
11748            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11749            let active_item = workspace
11750                .active_pane()
11751                .read(cx)
11752                .active_item()
11753                .expect("item is in focus");
11754
11755            assert_eq!(num_panes, 4);
11756            assert_eq!(num_items_in_current_pane, 1);
11757            assert_eq!(active_item.item_id(), last_item.item_id());
11758        });
11759
11760        workspace.update_in(cx, |workspace, window, cx| {
11761            workspace.join_all_panes(window, cx);
11762        });
11763
11764        workspace.update(cx, |workspace, cx| {
11765            let num_panes = workspace.panes().len();
11766            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11767            let active_item = workspace
11768                .active_pane()
11769                .read(cx)
11770                .active_item()
11771                .expect("item is in focus");
11772
11773            assert_eq!(num_panes, 1);
11774            assert_eq!(num_items_in_current_pane, 3);
11775            assert_eq!(active_item.item_id(), last_item.item_id());
11776        });
11777    }
11778    struct TestModal(FocusHandle);
11779
11780    impl TestModal {
11781        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11782            Self(cx.focus_handle())
11783        }
11784    }
11785
11786    impl EventEmitter<DismissEvent> for TestModal {}
11787
11788    impl Focusable for TestModal {
11789        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11790            self.0.clone()
11791        }
11792    }
11793
11794    impl ModalView for TestModal {}
11795
11796    impl Render for TestModal {
11797        fn render(
11798            &mut self,
11799            _window: &mut Window,
11800            _cx: &mut Context<TestModal>,
11801        ) -> impl IntoElement {
11802            div().track_focus(&self.0)
11803        }
11804    }
11805
11806    #[gpui::test]
11807    async fn test_panels(cx: &mut gpui::TestAppContext) {
11808        init_test(cx);
11809        let fs = FakeFs::new(cx.executor());
11810
11811        let project = Project::test(fs, [], cx).await;
11812        let (multi_workspace, cx) =
11813            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11814        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11815
11816        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11817            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11818            workspace.add_panel(panel_1.clone(), window, cx);
11819            workspace.toggle_dock(DockPosition::Left, window, cx);
11820            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11821            workspace.add_panel(panel_2.clone(), window, cx);
11822            workspace.toggle_dock(DockPosition::Right, window, cx);
11823
11824            let left_dock = workspace.left_dock();
11825            assert_eq!(
11826                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11827                panel_1.panel_id()
11828            );
11829            assert_eq!(
11830                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11831                panel_1.size(window, cx)
11832            );
11833
11834            left_dock.update(cx, |left_dock, cx| {
11835                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11836            });
11837            assert_eq!(
11838                workspace
11839                    .right_dock()
11840                    .read(cx)
11841                    .visible_panel()
11842                    .unwrap()
11843                    .panel_id(),
11844                panel_2.panel_id(),
11845            );
11846
11847            (panel_1, panel_2)
11848        });
11849
11850        // Move panel_1 to the right
11851        panel_1.update_in(cx, |panel_1, window, cx| {
11852            panel_1.set_position(DockPosition::Right, window, cx)
11853        });
11854
11855        workspace.update_in(cx, |workspace, window, cx| {
11856            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11857            // Since it was the only panel on the left, the left dock should now be closed.
11858            assert!(!workspace.left_dock().read(cx).is_open());
11859            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11860            let right_dock = workspace.right_dock();
11861            assert_eq!(
11862                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11863                panel_1.panel_id()
11864            );
11865            assert_eq!(
11866                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11867                px(1337.)
11868            );
11869
11870            // Now we move panel_2 to the left
11871            panel_2.set_position(DockPosition::Left, window, cx);
11872        });
11873
11874        workspace.update(cx, |workspace, cx| {
11875            // Since panel_2 was not visible on the right, we don't open the left dock.
11876            assert!(!workspace.left_dock().read(cx).is_open());
11877            // And the right dock is unaffected in its displaying of panel_1
11878            assert!(workspace.right_dock().read(cx).is_open());
11879            assert_eq!(
11880                workspace
11881                    .right_dock()
11882                    .read(cx)
11883                    .visible_panel()
11884                    .unwrap()
11885                    .panel_id(),
11886                panel_1.panel_id(),
11887            );
11888        });
11889
11890        // Move panel_1 back to the left
11891        panel_1.update_in(cx, |panel_1, window, cx| {
11892            panel_1.set_position(DockPosition::Left, window, cx)
11893        });
11894
11895        workspace.update_in(cx, |workspace, window, cx| {
11896            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11897            let left_dock = workspace.left_dock();
11898            assert!(left_dock.read(cx).is_open());
11899            assert_eq!(
11900                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11901                panel_1.panel_id()
11902            );
11903            assert_eq!(
11904                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11905                px(1337.)
11906            );
11907            // And the right dock should be closed as it no longer has any panels.
11908            assert!(!workspace.right_dock().read(cx).is_open());
11909
11910            // Now we move panel_1 to the bottom
11911            panel_1.set_position(DockPosition::Bottom, window, cx);
11912        });
11913
11914        workspace.update_in(cx, |workspace, window, cx| {
11915            // Since panel_1 was visible on the left, we close the left dock.
11916            assert!(!workspace.left_dock().read(cx).is_open());
11917            // The bottom dock is sized based on the panel's default size,
11918            // since the panel orientation changed from vertical to horizontal.
11919            let bottom_dock = workspace.bottom_dock();
11920            assert_eq!(
11921                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11922                panel_1.size(window, cx),
11923            );
11924            // Close bottom dock and move panel_1 back to the left.
11925            bottom_dock.update(cx, |bottom_dock, cx| {
11926                bottom_dock.set_open(false, window, cx)
11927            });
11928            panel_1.set_position(DockPosition::Left, window, cx);
11929        });
11930
11931        // Emit activated event on panel 1
11932        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11933
11934        // Now the left dock is open and panel_1 is active and focused.
11935        workspace.update_in(cx, |workspace, window, cx| {
11936            let left_dock = workspace.left_dock();
11937            assert!(left_dock.read(cx).is_open());
11938            assert_eq!(
11939                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11940                panel_1.panel_id(),
11941            );
11942            assert!(panel_1.focus_handle(cx).is_focused(window));
11943        });
11944
11945        // Emit closed event on panel 2, which is not active
11946        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11947
11948        // Wo don't close the left dock, because panel_2 wasn't the active panel
11949        workspace.update(cx, |workspace, cx| {
11950            let left_dock = workspace.left_dock();
11951            assert!(left_dock.read(cx).is_open());
11952            assert_eq!(
11953                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11954                panel_1.panel_id(),
11955            );
11956        });
11957
11958        // Emitting a ZoomIn event shows the panel as zoomed.
11959        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11960        workspace.read_with(cx, |workspace, _| {
11961            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11962            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11963        });
11964
11965        // Move panel to another dock while it is zoomed
11966        panel_1.update_in(cx, |panel, window, cx| {
11967            panel.set_position(DockPosition::Right, window, cx)
11968        });
11969        workspace.read_with(cx, |workspace, _| {
11970            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11971
11972            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11973        });
11974
11975        // This is a helper for getting a:
11976        // - valid focus on an element,
11977        // - that isn't a part of the panes and panels system of the Workspace,
11978        // - and doesn't trigger the 'on_focus_lost' API.
11979        let focus_other_view = {
11980            let workspace = workspace.clone();
11981            move |cx: &mut VisualTestContext| {
11982                workspace.update_in(cx, |workspace, window, cx| {
11983                    if workspace.active_modal::<TestModal>(cx).is_some() {
11984                        workspace.toggle_modal(window, cx, TestModal::new);
11985                        workspace.toggle_modal(window, cx, TestModal::new);
11986                    } else {
11987                        workspace.toggle_modal(window, cx, TestModal::new);
11988                    }
11989                })
11990            }
11991        };
11992
11993        // If focus is transferred to another view that's not a panel or another pane, we still show
11994        // the panel as zoomed.
11995        focus_other_view(cx);
11996        workspace.read_with(cx, |workspace, _| {
11997            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11998            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11999        });
12000
12001        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12002        workspace.update_in(cx, |_workspace, window, cx| {
12003            cx.focus_self(window);
12004        });
12005        workspace.read_with(cx, |workspace, _| {
12006            assert_eq!(workspace.zoomed, None);
12007            assert_eq!(workspace.zoomed_position, None);
12008        });
12009
12010        // If focus is transferred again to another view that's not a panel or a pane, we won't
12011        // show the panel as zoomed because it wasn't zoomed before.
12012        focus_other_view(cx);
12013        workspace.read_with(cx, |workspace, _| {
12014            assert_eq!(workspace.zoomed, None);
12015            assert_eq!(workspace.zoomed_position, None);
12016        });
12017
12018        // When the panel is activated, it is zoomed again.
12019        cx.dispatch_action(ToggleRightDock);
12020        workspace.read_with(cx, |workspace, _| {
12021            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12022            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12023        });
12024
12025        // Emitting a ZoomOut event unzooms the panel.
12026        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12027        workspace.read_with(cx, |workspace, _| {
12028            assert_eq!(workspace.zoomed, None);
12029            assert_eq!(workspace.zoomed_position, None);
12030        });
12031
12032        // Emit closed event on panel 1, which is active
12033        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12034
12035        // Now the left dock is closed, because panel_1 was the active panel
12036        workspace.update(cx, |workspace, cx| {
12037            let right_dock = workspace.right_dock();
12038            assert!(!right_dock.read(cx).is_open());
12039        });
12040    }
12041
12042    #[gpui::test]
12043    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12044        init_test(cx);
12045
12046        let fs = FakeFs::new(cx.background_executor.clone());
12047        let project = Project::test(fs, [], cx).await;
12048        let (workspace, cx) =
12049            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12050        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12051
12052        let dirty_regular_buffer = cx.new(|cx| {
12053            TestItem::new(cx)
12054                .with_dirty(true)
12055                .with_label("1.txt")
12056                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12057        });
12058        let dirty_regular_buffer_2 = cx.new(|cx| {
12059            TestItem::new(cx)
12060                .with_dirty(true)
12061                .with_label("2.txt")
12062                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12063        });
12064        let dirty_multi_buffer_with_both = cx.new(|cx| {
12065            TestItem::new(cx)
12066                .with_dirty(true)
12067                .with_buffer_kind(ItemBufferKind::Multibuffer)
12068                .with_label("Fake Project Search")
12069                .with_project_items(&[
12070                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12071                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12072                ])
12073        });
12074        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12075        workspace.update_in(cx, |workspace, window, cx| {
12076            workspace.add_item(
12077                pane.clone(),
12078                Box::new(dirty_regular_buffer.clone()),
12079                None,
12080                false,
12081                false,
12082                window,
12083                cx,
12084            );
12085            workspace.add_item(
12086                pane.clone(),
12087                Box::new(dirty_regular_buffer_2.clone()),
12088                None,
12089                false,
12090                false,
12091                window,
12092                cx,
12093            );
12094            workspace.add_item(
12095                pane.clone(),
12096                Box::new(dirty_multi_buffer_with_both.clone()),
12097                None,
12098                false,
12099                false,
12100                window,
12101                cx,
12102            );
12103        });
12104
12105        pane.update_in(cx, |pane, window, cx| {
12106            pane.activate_item(2, true, true, window, cx);
12107            assert_eq!(
12108                pane.active_item().unwrap().item_id(),
12109                multi_buffer_with_both_files_id,
12110                "Should select the multi buffer in the pane"
12111            );
12112        });
12113        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12114            pane.close_other_items(
12115                &CloseOtherItems {
12116                    save_intent: Some(SaveIntent::Save),
12117                    close_pinned: true,
12118                },
12119                None,
12120                window,
12121                cx,
12122            )
12123        });
12124        cx.background_executor.run_until_parked();
12125        assert!(!cx.has_pending_prompt());
12126        close_all_but_multi_buffer_task
12127            .await
12128            .expect("Closing all buffers but the multi buffer failed");
12129        pane.update(cx, |pane, cx| {
12130            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12131            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12132            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12133            assert_eq!(pane.items_len(), 1);
12134            assert_eq!(
12135                pane.active_item().unwrap().item_id(),
12136                multi_buffer_with_both_files_id,
12137                "Should have only the multi buffer left in the pane"
12138            );
12139            assert!(
12140                dirty_multi_buffer_with_both.read(cx).is_dirty,
12141                "The multi buffer containing the unsaved buffer should still be dirty"
12142            );
12143        });
12144
12145        dirty_regular_buffer.update(cx, |buffer, cx| {
12146            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12147        });
12148
12149        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12150            pane.close_active_item(
12151                &CloseActiveItem {
12152                    save_intent: Some(SaveIntent::Close),
12153                    close_pinned: false,
12154                },
12155                window,
12156                cx,
12157            )
12158        });
12159        cx.background_executor.run_until_parked();
12160        assert!(
12161            cx.has_pending_prompt(),
12162            "Dirty multi buffer should prompt a save dialog"
12163        );
12164        cx.simulate_prompt_answer("Save");
12165        cx.background_executor.run_until_parked();
12166        close_multi_buffer_task
12167            .await
12168            .expect("Closing the multi buffer failed");
12169        pane.update(cx, |pane, cx| {
12170            assert_eq!(
12171                dirty_multi_buffer_with_both.read(cx).save_count,
12172                1,
12173                "Multi buffer item should get be saved"
12174            );
12175            // Test impl does not save inner items, so we do not assert them
12176            assert_eq!(
12177                pane.items_len(),
12178                0,
12179                "No more items should be left in the pane"
12180            );
12181            assert!(pane.active_item().is_none());
12182        });
12183    }
12184
12185    #[gpui::test]
12186    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12187        cx: &mut TestAppContext,
12188    ) {
12189        init_test(cx);
12190
12191        let fs = FakeFs::new(cx.background_executor.clone());
12192        let project = Project::test(fs, [], cx).await;
12193        let (workspace, cx) =
12194            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12195        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12196
12197        let dirty_regular_buffer = cx.new(|cx| {
12198            TestItem::new(cx)
12199                .with_dirty(true)
12200                .with_label("1.txt")
12201                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12202        });
12203        let dirty_regular_buffer_2 = cx.new(|cx| {
12204            TestItem::new(cx)
12205                .with_dirty(true)
12206                .with_label("2.txt")
12207                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12208        });
12209        let clear_regular_buffer = cx.new(|cx| {
12210            TestItem::new(cx)
12211                .with_label("3.txt")
12212                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12213        });
12214
12215        let dirty_multi_buffer_with_both = cx.new(|cx| {
12216            TestItem::new(cx)
12217                .with_dirty(true)
12218                .with_buffer_kind(ItemBufferKind::Multibuffer)
12219                .with_label("Fake Project Search")
12220                .with_project_items(&[
12221                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12222                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12223                    clear_regular_buffer.read(cx).project_items[0].clone(),
12224                ])
12225        });
12226        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12227        workspace.update_in(cx, |workspace, window, cx| {
12228            workspace.add_item(
12229                pane.clone(),
12230                Box::new(dirty_regular_buffer.clone()),
12231                None,
12232                false,
12233                false,
12234                window,
12235                cx,
12236            );
12237            workspace.add_item(
12238                pane.clone(),
12239                Box::new(dirty_multi_buffer_with_both.clone()),
12240                None,
12241                false,
12242                false,
12243                window,
12244                cx,
12245            );
12246        });
12247
12248        pane.update_in(cx, |pane, window, cx| {
12249            pane.activate_item(1, true, true, window, cx);
12250            assert_eq!(
12251                pane.active_item().unwrap().item_id(),
12252                multi_buffer_with_both_files_id,
12253                "Should select the multi buffer in the pane"
12254            );
12255        });
12256        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12257            pane.close_active_item(
12258                &CloseActiveItem {
12259                    save_intent: None,
12260                    close_pinned: false,
12261                },
12262                window,
12263                cx,
12264            )
12265        });
12266        cx.background_executor.run_until_parked();
12267        assert!(
12268            cx.has_pending_prompt(),
12269            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12270        );
12271    }
12272
12273    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12274    /// closed when they are deleted from disk.
12275    #[gpui::test]
12276    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12277        init_test(cx);
12278
12279        // Enable the close_on_disk_deletion setting
12280        cx.update_global(|store: &mut SettingsStore, cx| {
12281            store.update_user_settings(cx, |settings| {
12282                settings.workspace.close_on_file_delete = Some(true);
12283            });
12284        });
12285
12286        let fs = FakeFs::new(cx.background_executor.clone());
12287        let project = Project::test(fs, [], cx).await;
12288        let (workspace, cx) =
12289            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12290        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12291
12292        // Create a test item that simulates a file
12293        let item = cx.new(|cx| {
12294            TestItem::new(cx)
12295                .with_label("test.txt")
12296                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12297        });
12298
12299        // Add item to workspace
12300        workspace.update_in(cx, |workspace, window, cx| {
12301            workspace.add_item(
12302                pane.clone(),
12303                Box::new(item.clone()),
12304                None,
12305                false,
12306                false,
12307                window,
12308                cx,
12309            );
12310        });
12311
12312        // Verify the item is in the pane
12313        pane.read_with(cx, |pane, _| {
12314            assert_eq!(pane.items().count(), 1);
12315        });
12316
12317        // Simulate file deletion by setting the item's deleted state
12318        item.update(cx, |item, _| {
12319            item.set_has_deleted_file(true);
12320        });
12321
12322        // Emit UpdateTab event to trigger the close behavior
12323        cx.run_until_parked();
12324        item.update(cx, |_, cx| {
12325            cx.emit(ItemEvent::UpdateTab);
12326        });
12327
12328        // Allow the close operation to complete
12329        cx.run_until_parked();
12330
12331        // Verify the item was automatically closed
12332        pane.read_with(cx, |pane, _| {
12333            assert_eq!(
12334                pane.items().count(),
12335                0,
12336                "Item should be automatically closed when file is deleted"
12337            );
12338        });
12339    }
12340
12341    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12342    /// open with a strikethrough when they are deleted from disk.
12343    #[gpui::test]
12344    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12345        init_test(cx);
12346
12347        // Ensure close_on_disk_deletion is disabled (default)
12348        cx.update_global(|store: &mut SettingsStore, cx| {
12349            store.update_user_settings(cx, |settings| {
12350                settings.workspace.close_on_file_delete = Some(false);
12351            });
12352        });
12353
12354        let fs = FakeFs::new(cx.background_executor.clone());
12355        let project = Project::test(fs, [], cx).await;
12356        let (workspace, cx) =
12357            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12358        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12359
12360        // Create a test item that simulates a file
12361        let item = cx.new(|cx| {
12362            TestItem::new(cx)
12363                .with_label("test.txt")
12364                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12365        });
12366
12367        // Add item to workspace
12368        workspace.update_in(cx, |workspace, window, cx| {
12369            workspace.add_item(
12370                pane.clone(),
12371                Box::new(item.clone()),
12372                None,
12373                false,
12374                false,
12375                window,
12376                cx,
12377            );
12378        });
12379
12380        // Verify the item is in the pane
12381        pane.read_with(cx, |pane, _| {
12382            assert_eq!(pane.items().count(), 1);
12383        });
12384
12385        // Simulate file deletion
12386        item.update(cx, |item, _| {
12387            item.set_has_deleted_file(true);
12388        });
12389
12390        // Emit UpdateTab event
12391        cx.run_until_parked();
12392        item.update(cx, |_, cx| {
12393            cx.emit(ItemEvent::UpdateTab);
12394        });
12395
12396        // Allow any potential close operation to complete
12397        cx.run_until_parked();
12398
12399        // Verify the item remains open (with strikethrough)
12400        pane.read_with(cx, |pane, _| {
12401            assert_eq!(
12402                pane.items().count(),
12403                1,
12404                "Item should remain open when close_on_disk_deletion is disabled"
12405            );
12406        });
12407
12408        // Verify the item shows as deleted
12409        item.read_with(cx, |item, _| {
12410            assert!(
12411                item.has_deleted_file,
12412                "Item should be marked as having deleted file"
12413            );
12414        });
12415    }
12416
12417    /// Tests that dirty files are not automatically closed when deleted from disk,
12418    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12419    /// unsaved changes without being prompted.
12420    #[gpui::test]
12421    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12422        init_test(cx);
12423
12424        // Enable the close_on_file_delete setting
12425        cx.update_global(|store: &mut SettingsStore, cx| {
12426            store.update_user_settings(cx, |settings| {
12427                settings.workspace.close_on_file_delete = Some(true);
12428            });
12429        });
12430
12431        let fs = FakeFs::new(cx.background_executor.clone());
12432        let project = Project::test(fs, [], cx).await;
12433        let (workspace, cx) =
12434            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12435        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12436
12437        // Create a dirty test item
12438        let item = cx.new(|cx| {
12439            TestItem::new(cx)
12440                .with_dirty(true)
12441                .with_label("test.txt")
12442                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12443        });
12444
12445        // Add item to workspace
12446        workspace.update_in(cx, |workspace, window, cx| {
12447            workspace.add_item(
12448                pane.clone(),
12449                Box::new(item.clone()),
12450                None,
12451                false,
12452                false,
12453                window,
12454                cx,
12455            );
12456        });
12457
12458        // Simulate file deletion
12459        item.update(cx, |item, _| {
12460            item.set_has_deleted_file(true);
12461        });
12462
12463        // Emit UpdateTab event to trigger the close behavior
12464        cx.run_until_parked();
12465        item.update(cx, |_, cx| {
12466            cx.emit(ItemEvent::UpdateTab);
12467        });
12468
12469        // Allow any potential close operation to complete
12470        cx.run_until_parked();
12471
12472        // Verify the item remains open (dirty files are not auto-closed)
12473        pane.read_with(cx, |pane, _| {
12474            assert_eq!(
12475                pane.items().count(),
12476                1,
12477                "Dirty items should not be automatically closed even when file is deleted"
12478            );
12479        });
12480
12481        // Verify the item is marked as deleted and still dirty
12482        item.read_with(cx, |item, _| {
12483            assert!(
12484                item.has_deleted_file,
12485                "Item should be marked as having deleted file"
12486            );
12487            assert!(item.is_dirty, "Item should still be dirty");
12488        });
12489    }
12490
12491    /// Tests that navigation history is cleaned up when files are auto-closed
12492    /// due to deletion from disk.
12493    #[gpui::test]
12494    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12495        init_test(cx);
12496
12497        // Enable the close_on_file_delete setting
12498        cx.update_global(|store: &mut SettingsStore, cx| {
12499            store.update_user_settings(cx, |settings| {
12500                settings.workspace.close_on_file_delete = Some(true);
12501            });
12502        });
12503
12504        let fs = FakeFs::new(cx.background_executor.clone());
12505        let project = Project::test(fs, [], cx).await;
12506        let (workspace, cx) =
12507            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12508        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12509
12510        // Create test items
12511        let item1 = cx.new(|cx| {
12512            TestItem::new(cx)
12513                .with_label("test1.txt")
12514                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12515        });
12516        let item1_id = item1.item_id();
12517
12518        let item2 = cx.new(|cx| {
12519            TestItem::new(cx)
12520                .with_label("test2.txt")
12521                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12522        });
12523
12524        // Add items to workspace
12525        workspace.update_in(cx, |workspace, window, cx| {
12526            workspace.add_item(
12527                pane.clone(),
12528                Box::new(item1.clone()),
12529                None,
12530                false,
12531                false,
12532                window,
12533                cx,
12534            );
12535            workspace.add_item(
12536                pane.clone(),
12537                Box::new(item2.clone()),
12538                None,
12539                false,
12540                false,
12541                window,
12542                cx,
12543            );
12544        });
12545
12546        // Activate item1 to ensure it gets navigation entries
12547        pane.update_in(cx, |pane, window, cx| {
12548            pane.activate_item(0, true, true, window, cx);
12549        });
12550
12551        // Switch to item2 and back to create navigation history
12552        pane.update_in(cx, |pane, window, cx| {
12553            pane.activate_item(1, true, true, window, cx);
12554        });
12555        cx.run_until_parked();
12556
12557        pane.update_in(cx, |pane, window, cx| {
12558            pane.activate_item(0, true, true, window, cx);
12559        });
12560        cx.run_until_parked();
12561
12562        // Simulate file deletion for item1
12563        item1.update(cx, |item, _| {
12564            item.set_has_deleted_file(true);
12565        });
12566
12567        // Emit UpdateTab event to trigger the close behavior
12568        item1.update(cx, |_, cx| {
12569            cx.emit(ItemEvent::UpdateTab);
12570        });
12571        cx.run_until_parked();
12572
12573        // Verify item1 was closed
12574        pane.read_with(cx, |pane, _| {
12575            assert_eq!(
12576                pane.items().count(),
12577                1,
12578                "Should have 1 item remaining after auto-close"
12579            );
12580        });
12581
12582        // Check navigation history after close
12583        let has_item = pane.read_with(cx, |pane, cx| {
12584            let mut has_item = false;
12585            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12586                if entry.item.id() == item1_id {
12587                    has_item = true;
12588                }
12589            });
12590            has_item
12591        });
12592
12593        assert!(
12594            !has_item,
12595            "Navigation history should not contain closed item entries"
12596        );
12597    }
12598
12599    #[gpui::test]
12600    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12601        cx: &mut TestAppContext,
12602    ) {
12603        init_test(cx);
12604
12605        let fs = FakeFs::new(cx.background_executor.clone());
12606        let project = Project::test(fs, [], cx).await;
12607        let (workspace, cx) =
12608            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12609        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12610
12611        let dirty_regular_buffer = cx.new(|cx| {
12612            TestItem::new(cx)
12613                .with_dirty(true)
12614                .with_label("1.txt")
12615                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12616        });
12617        let dirty_regular_buffer_2 = cx.new(|cx| {
12618            TestItem::new(cx)
12619                .with_dirty(true)
12620                .with_label("2.txt")
12621                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12622        });
12623        let clear_regular_buffer = cx.new(|cx| {
12624            TestItem::new(cx)
12625                .with_label("3.txt")
12626                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12627        });
12628
12629        let dirty_multi_buffer = cx.new(|cx| {
12630            TestItem::new(cx)
12631                .with_dirty(true)
12632                .with_buffer_kind(ItemBufferKind::Multibuffer)
12633                .with_label("Fake Project Search")
12634                .with_project_items(&[
12635                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12636                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12637                    clear_regular_buffer.read(cx).project_items[0].clone(),
12638                ])
12639        });
12640        workspace.update_in(cx, |workspace, window, cx| {
12641            workspace.add_item(
12642                pane.clone(),
12643                Box::new(dirty_regular_buffer.clone()),
12644                None,
12645                false,
12646                false,
12647                window,
12648                cx,
12649            );
12650            workspace.add_item(
12651                pane.clone(),
12652                Box::new(dirty_regular_buffer_2.clone()),
12653                None,
12654                false,
12655                false,
12656                window,
12657                cx,
12658            );
12659            workspace.add_item(
12660                pane.clone(),
12661                Box::new(dirty_multi_buffer.clone()),
12662                None,
12663                false,
12664                false,
12665                window,
12666                cx,
12667            );
12668        });
12669
12670        pane.update_in(cx, |pane, window, cx| {
12671            pane.activate_item(2, true, true, window, cx);
12672            assert_eq!(
12673                pane.active_item().unwrap().item_id(),
12674                dirty_multi_buffer.item_id(),
12675                "Should select the multi buffer in the pane"
12676            );
12677        });
12678        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12679            pane.close_active_item(
12680                &CloseActiveItem {
12681                    save_intent: None,
12682                    close_pinned: false,
12683                },
12684                window,
12685                cx,
12686            )
12687        });
12688        cx.background_executor.run_until_parked();
12689        assert!(
12690            !cx.has_pending_prompt(),
12691            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12692        );
12693        close_multi_buffer_task
12694            .await
12695            .expect("Closing multi buffer failed");
12696        pane.update(cx, |pane, cx| {
12697            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12698            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12699            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12700            assert_eq!(
12701                pane.items()
12702                    .map(|item| item.item_id())
12703                    .sorted()
12704                    .collect::<Vec<_>>(),
12705                vec![
12706                    dirty_regular_buffer.item_id(),
12707                    dirty_regular_buffer_2.item_id(),
12708                ],
12709                "Should have no multi buffer left in the pane"
12710            );
12711            assert!(dirty_regular_buffer.read(cx).is_dirty);
12712            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12713        });
12714    }
12715
12716    #[gpui::test]
12717    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12718        init_test(cx);
12719        let fs = FakeFs::new(cx.executor());
12720        let project = Project::test(fs, [], cx).await;
12721        let (multi_workspace, cx) =
12722            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12723        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12724
12725        // Add a new panel to the right dock, opening the dock and setting the
12726        // focus to the new panel.
12727        let panel = workspace.update_in(cx, |workspace, window, cx| {
12728            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12729            workspace.add_panel(panel.clone(), window, cx);
12730
12731            workspace
12732                .right_dock()
12733                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12734
12735            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12736
12737            panel
12738        });
12739
12740        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12741        // panel to the next valid position which, in this case, is the left
12742        // dock.
12743        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12744        workspace.update(cx, |workspace, cx| {
12745            assert!(workspace.left_dock().read(cx).is_open());
12746            assert_eq!(panel.read(cx).position, DockPosition::Left);
12747        });
12748
12749        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12750        // panel to the next valid position which, in this case, is the bottom
12751        // dock.
12752        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12753        workspace.update(cx, |workspace, cx| {
12754            assert!(workspace.bottom_dock().read(cx).is_open());
12755            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12756        });
12757
12758        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12759        // around moving the panel to its initial position, the right dock.
12760        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12761        workspace.update(cx, |workspace, cx| {
12762            assert!(workspace.right_dock().read(cx).is_open());
12763            assert_eq!(panel.read(cx).position, DockPosition::Right);
12764        });
12765
12766        // Remove focus from the panel, ensuring that, if the panel is not
12767        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12768        // the panel's position, so the panel is still in the right dock.
12769        workspace.update_in(cx, |workspace, window, cx| {
12770            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12771        });
12772
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
12780    #[gpui::test]
12781    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12782        init_test(cx);
12783
12784        let fs = FakeFs::new(cx.executor());
12785        let project = Project::test(fs, [], cx).await;
12786        let (workspace, cx) =
12787            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12788
12789        let item_1 = cx.new(|cx| {
12790            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12791        });
12792        workspace.update_in(cx, |workspace, window, cx| {
12793            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12794            workspace.move_item_to_pane_in_direction(
12795                &MoveItemToPaneInDirection {
12796                    direction: SplitDirection::Right,
12797                    focus: true,
12798                    clone: false,
12799                },
12800                window,
12801                cx,
12802            );
12803            workspace.move_item_to_pane_at_index(
12804                &MoveItemToPane {
12805                    destination: 3,
12806                    focus: true,
12807                    clone: false,
12808                },
12809                window,
12810                cx,
12811            );
12812
12813            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12814            assert_eq!(
12815                pane_items_paths(&workspace.active_pane, cx),
12816                vec!["first.txt".to_string()],
12817                "Single item was not moved anywhere"
12818            );
12819        });
12820
12821        let item_2 = cx.new(|cx| {
12822            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12823        });
12824        workspace.update_in(cx, |workspace, window, cx| {
12825            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12826            assert_eq!(
12827                pane_items_paths(&workspace.panes[0], cx),
12828                vec!["first.txt".to_string(), "second.txt".to_string()],
12829            );
12830            workspace.move_item_to_pane_in_direction(
12831                &MoveItemToPaneInDirection {
12832                    direction: SplitDirection::Right,
12833                    focus: true,
12834                    clone: false,
12835                },
12836                window,
12837                cx,
12838            );
12839
12840            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12841            assert_eq!(
12842                pane_items_paths(&workspace.panes[0], cx),
12843                vec!["first.txt".to_string()],
12844                "After moving, one item should be left in the original pane"
12845            );
12846            assert_eq!(
12847                pane_items_paths(&workspace.panes[1], cx),
12848                vec!["second.txt".to_string()],
12849                "New item should have been moved to the new pane"
12850            );
12851        });
12852
12853        let item_3 = cx.new(|cx| {
12854            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12855        });
12856        workspace.update_in(cx, |workspace, window, cx| {
12857            let original_pane = workspace.panes[0].clone();
12858            workspace.set_active_pane(&original_pane, window, cx);
12859            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12860            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12861            assert_eq!(
12862                pane_items_paths(&workspace.active_pane, cx),
12863                vec!["first.txt".to_string(), "third.txt".to_string()],
12864                "New pane should be ready to move one item out"
12865            );
12866
12867            workspace.move_item_to_pane_at_index(
12868                &MoveItemToPane {
12869                    destination: 3,
12870                    focus: true,
12871                    clone: false,
12872                },
12873                window,
12874                cx,
12875            );
12876            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12877            assert_eq!(
12878                pane_items_paths(&workspace.active_pane, cx),
12879                vec!["first.txt".to_string()],
12880                "After moving, one item should be left in the original pane"
12881            );
12882            assert_eq!(
12883                pane_items_paths(&workspace.panes[1], cx),
12884                vec!["second.txt".to_string()],
12885                "Previously created pane should be unchanged"
12886            );
12887            assert_eq!(
12888                pane_items_paths(&workspace.panes[2], cx),
12889                vec!["third.txt".to_string()],
12890                "New item should have been moved to the new pane"
12891            );
12892        });
12893    }
12894
12895    #[gpui::test]
12896    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12897        init_test(cx);
12898
12899        let fs = FakeFs::new(cx.executor());
12900        let project = Project::test(fs, [], cx).await;
12901        let (workspace, cx) =
12902            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12903
12904        let item_1 = cx.new(|cx| {
12905            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12906        });
12907        workspace.update_in(cx, |workspace, window, cx| {
12908            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12909            workspace.move_item_to_pane_in_direction(
12910                &MoveItemToPaneInDirection {
12911                    direction: SplitDirection::Right,
12912                    focus: true,
12913                    clone: true,
12914                },
12915                window,
12916                cx,
12917            );
12918        });
12919        cx.run_until_parked();
12920        workspace.update_in(cx, |workspace, window, cx| {
12921            workspace.move_item_to_pane_at_index(
12922                &MoveItemToPane {
12923                    destination: 3,
12924                    focus: true,
12925                    clone: true,
12926                },
12927                window,
12928                cx,
12929            );
12930        });
12931        cx.run_until_parked();
12932
12933        workspace.update(cx, |workspace, cx| {
12934            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12935            for pane in workspace.panes() {
12936                assert_eq!(
12937                    pane_items_paths(pane, cx),
12938                    vec!["first.txt".to_string()],
12939                    "Single item exists in all panes"
12940                );
12941            }
12942        });
12943
12944        // verify that the active pane has been updated after waiting for the
12945        // pane focus event to fire and resolve
12946        workspace.read_with(cx, |workspace, _app| {
12947            assert_eq!(
12948                workspace.active_pane(),
12949                &workspace.panes[2],
12950                "The third pane should be the active one: {:?}",
12951                workspace.panes
12952            );
12953        })
12954    }
12955
12956    #[gpui::test]
12957    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12958        init_test(cx);
12959
12960        let fs = FakeFs::new(cx.executor());
12961        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12962
12963        let project = Project::test(fs, ["root".as_ref()], cx).await;
12964        let (workspace, cx) =
12965            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12966
12967        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12968        // Add item to pane A with project path
12969        let item_a = cx.new(|cx| {
12970            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12971        });
12972        workspace.update_in(cx, |workspace, window, cx| {
12973            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12974        });
12975
12976        // Split to create pane B
12977        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12978            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12979        });
12980
12981        // Add item with SAME project path to pane B, and pin it
12982        let item_b = cx.new(|cx| {
12983            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12984        });
12985        pane_b.update_in(cx, |pane, window, cx| {
12986            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12987            pane.set_pinned_count(1);
12988        });
12989
12990        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12991        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12992
12993        // close_pinned: false should only close the unpinned copy
12994        workspace.update_in(cx, |workspace, window, cx| {
12995            workspace.close_item_in_all_panes(
12996                &CloseItemInAllPanes {
12997                    save_intent: Some(SaveIntent::Close),
12998                    close_pinned: false,
12999                },
13000                window,
13001                cx,
13002            )
13003        });
13004        cx.executor().run_until_parked();
13005
13006        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13007        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13008        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13009        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13010
13011        // Split again, seeing as closing the previous item also closed its
13012        // pane, so only pane remains, which does not allow us to properly test
13013        // that both items close when `close_pinned: true`.
13014        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13015            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13016        });
13017
13018        // Add an item with the same project path to pane C so that
13019        // close_item_in_all_panes can determine what to close across all panes
13020        // (it reads the active item from the active pane, and split_pane
13021        // creates an empty pane).
13022        let item_c = cx.new(|cx| {
13023            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13024        });
13025        pane_c.update_in(cx, |pane, window, cx| {
13026            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13027        });
13028
13029        // close_pinned: true should close the pinned copy too
13030        workspace.update_in(cx, |workspace, window, cx| {
13031            let panes_count = workspace.panes().len();
13032            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13033
13034            workspace.close_item_in_all_panes(
13035                &CloseItemInAllPanes {
13036                    save_intent: Some(SaveIntent::Close),
13037                    close_pinned: true,
13038                },
13039                window,
13040                cx,
13041            )
13042        });
13043        cx.executor().run_until_parked();
13044
13045        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13046        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13047        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13048        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13049    }
13050
13051    mod register_project_item_tests {
13052
13053        use super::*;
13054
13055        // View
13056        struct TestPngItemView {
13057            focus_handle: FocusHandle,
13058        }
13059        // Model
13060        struct TestPngItem {}
13061
13062        impl project::ProjectItem for TestPngItem {
13063            fn try_open(
13064                _project: &Entity<Project>,
13065                path: &ProjectPath,
13066                cx: &mut App,
13067            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13068                if path.path.extension().unwrap() == "png" {
13069                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13070                } else {
13071                    None
13072                }
13073            }
13074
13075            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13076                None
13077            }
13078
13079            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13080                None
13081            }
13082
13083            fn is_dirty(&self) -> bool {
13084                false
13085            }
13086        }
13087
13088        impl Item for TestPngItemView {
13089            type Event = ();
13090            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13091                "".into()
13092            }
13093        }
13094        impl EventEmitter<()> for TestPngItemView {}
13095        impl Focusable for TestPngItemView {
13096            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13097                self.focus_handle.clone()
13098            }
13099        }
13100
13101        impl Render for TestPngItemView {
13102            fn render(
13103                &mut self,
13104                _window: &mut Window,
13105                _cx: &mut Context<Self>,
13106            ) -> impl IntoElement {
13107                Empty
13108            }
13109        }
13110
13111        impl ProjectItem for TestPngItemView {
13112            type Item = TestPngItem;
13113
13114            fn for_project_item(
13115                _project: Entity<Project>,
13116                _pane: Option<&Pane>,
13117                _item: Entity<Self::Item>,
13118                _: &mut Window,
13119                cx: &mut Context<Self>,
13120            ) -> Self
13121            where
13122                Self: Sized,
13123            {
13124                Self {
13125                    focus_handle: cx.focus_handle(),
13126                }
13127            }
13128        }
13129
13130        // View
13131        struct TestIpynbItemView {
13132            focus_handle: FocusHandle,
13133        }
13134        // Model
13135        struct TestIpynbItem {}
13136
13137        impl project::ProjectItem for TestIpynbItem {
13138            fn try_open(
13139                _project: &Entity<Project>,
13140                path: &ProjectPath,
13141                cx: &mut App,
13142            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13143                if path.path.extension().unwrap() == "ipynb" {
13144                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13145                } else {
13146                    None
13147                }
13148            }
13149
13150            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13151                None
13152            }
13153
13154            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13155                None
13156            }
13157
13158            fn is_dirty(&self) -> bool {
13159                false
13160            }
13161        }
13162
13163        impl Item for TestIpynbItemView {
13164            type Event = ();
13165            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13166                "".into()
13167            }
13168        }
13169        impl EventEmitter<()> for TestIpynbItemView {}
13170        impl Focusable for TestIpynbItemView {
13171            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13172                self.focus_handle.clone()
13173            }
13174        }
13175
13176        impl Render for TestIpynbItemView {
13177            fn render(
13178                &mut self,
13179                _window: &mut Window,
13180                _cx: &mut Context<Self>,
13181            ) -> impl IntoElement {
13182                Empty
13183            }
13184        }
13185
13186        impl ProjectItem for TestIpynbItemView {
13187            type Item = TestIpynbItem;
13188
13189            fn for_project_item(
13190                _project: Entity<Project>,
13191                _pane: Option<&Pane>,
13192                _item: Entity<Self::Item>,
13193                _: &mut Window,
13194                cx: &mut Context<Self>,
13195            ) -> Self
13196            where
13197                Self: Sized,
13198            {
13199                Self {
13200                    focus_handle: cx.focus_handle(),
13201                }
13202            }
13203        }
13204
13205        struct TestAlternatePngItemView {
13206            focus_handle: FocusHandle,
13207        }
13208
13209        impl Item for TestAlternatePngItemView {
13210            type Event = ();
13211            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13212                "".into()
13213            }
13214        }
13215
13216        impl EventEmitter<()> for TestAlternatePngItemView {}
13217        impl Focusable for TestAlternatePngItemView {
13218            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13219                self.focus_handle.clone()
13220            }
13221        }
13222
13223        impl Render for TestAlternatePngItemView {
13224            fn render(
13225                &mut self,
13226                _window: &mut Window,
13227                _cx: &mut Context<Self>,
13228            ) -> impl IntoElement {
13229                Empty
13230            }
13231        }
13232
13233        impl ProjectItem for TestAlternatePngItemView {
13234            type Item = TestPngItem;
13235
13236            fn for_project_item(
13237                _project: Entity<Project>,
13238                _pane: Option<&Pane>,
13239                _item: Entity<Self::Item>,
13240                _: &mut Window,
13241                cx: &mut Context<Self>,
13242            ) -> Self
13243            where
13244                Self: Sized,
13245            {
13246                Self {
13247                    focus_handle: cx.focus_handle(),
13248                }
13249            }
13250        }
13251
13252        #[gpui::test]
13253        async fn test_register_project_item(cx: &mut TestAppContext) {
13254            init_test(cx);
13255
13256            cx.update(|cx| {
13257                register_project_item::<TestPngItemView>(cx);
13258                register_project_item::<TestIpynbItemView>(cx);
13259            });
13260
13261            let fs = FakeFs::new(cx.executor());
13262            fs.insert_tree(
13263                "/root1",
13264                json!({
13265                    "one.png": "BINARYDATAHERE",
13266                    "two.ipynb": "{ totally a notebook }",
13267                    "three.txt": "editing text, sure why not?"
13268                }),
13269            )
13270            .await;
13271
13272            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13273            let (workspace, cx) =
13274                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13275
13276            let worktree_id = project.update(cx, |project, cx| {
13277                project.worktrees(cx).next().unwrap().read(cx).id()
13278            });
13279
13280            let handle = workspace
13281                .update_in(cx, |workspace, window, cx| {
13282                    let project_path = (worktree_id, rel_path("one.png"));
13283                    workspace.open_path(project_path, None, true, window, cx)
13284                })
13285                .await
13286                .unwrap();
13287
13288            // Now we can check if the handle we got back errored or not
13289            assert_eq!(
13290                handle.to_any_view().entity_type(),
13291                TypeId::of::<TestPngItemView>()
13292            );
13293
13294            let handle = workspace
13295                .update_in(cx, |workspace, window, cx| {
13296                    let project_path = (worktree_id, rel_path("two.ipynb"));
13297                    workspace.open_path(project_path, None, true, window, cx)
13298                })
13299                .await
13300                .unwrap();
13301
13302            assert_eq!(
13303                handle.to_any_view().entity_type(),
13304                TypeId::of::<TestIpynbItemView>()
13305            );
13306
13307            let handle = workspace
13308                .update_in(cx, |workspace, window, cx| {
13309                    let project_path = (worktree_id, rel_path("three.txt"));
13310                    workspace.open_path(project_path, None, true, window, cx)
13311                })
13312                .await;
13313            assert!(handle.is_err());
13314        }
13315
13316        #[gpui::test]
13317        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13318            init_test(cx);
13319
13320            cx.update(|cx| {
13321                register_project_item::<TestPngItemView>(cx);
13322                register_project_item::<TestAlternatePngItemView>(cx);
13323            });
13324
13325            let fs = FakeFs::new(cx.executor());
13326            fs.insert_tree(
13327                "/root1",
13328                json!({
13329                    "one.png": "BINARYDATAHERE",
13330                    "two.ipynb": "{ totally a notebook }",
13331                    "three.txt": "editing text, sure why not?"
13332                }),
13333            )
13334            .await;
13335            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13336            let (workspace, cx) =
13337                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13338            let worktree_id = project.update(cx, |project, cx| {
13339                project.worktrees(cx).next().unwrap().read(cx).id()
13340            });
13341
13342            let handle = workspace
13343                .update_in(cx, |workspace, window, cx| {
13344                    let project_path = (worktree_id, rel_path("one.png"));
13345                    workspace.open_path(project_path, None, true, window, cx)
13346                })
13347                .await
13348                .unwrap();
13349
13350            // This _must_ be the second item registered
13351            assert_eq!(
13352                handle.to_any_view().entity_type(),
13353                TypeId::of::<TestAlternatePngItemView>()
13354            );
13355
13356            let handle = workspace
13357                .update_in(cx, |workspace, window, cx| {
13358                    let project_path = (worktree_id, rel_path("three.txt"));
13359                    workspace.open_path(project_path, None, true, window, cx)
13360                })
13361                .await;
13362            assert!(handle.is_err());
13363        }
13364    }
13365
13366    #[gpui::test]
13367    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13368        init_test(cx);
13369
13370        let fs = FakeFs::new(cx.executor());
13371        let project = Project::test(fs, [], cx).await;
13372        let (workspace, _cx) =
13373            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13374
13375        // Test with status bar shown (default)
13376        workspace.read_with(cx, |workspace, cx| {
13377            let visible = workspace.status_bar_visible(cx);
13378            assert!(visible, "Status bar should be visible by default");
13379        });
13380
13381        // Test with status bar hidden
13382        cx.update_global(|store: &mut SettingsStore, cx| {
13383            store.update_user_settings(cx, |settings| {
13384                settings.status_bar.get_or_insert_default().show = Some(false);
13385            });
13386        });
13387
13388        workspace.read_with(cx, |workspace, cx| {
13389            let visible = workspace.status_bar_visible(cx);
13390            assert!(!visible, "Status bar should be hidden when show is false");
13391        });
13392
13393        // Test with status bar shown explicitly
13394        cx.update_global(|store: &mut SettingsStore, cx| {
13395            store.update_user_settings(cx, |settings| {
13396                settings.status_bar.get_or_insert_default().show = Some(true);
13397            });
13398        });
13399
13400        workspace.read_with(cx, |workspace, cx| {
13401            let visible = workspace.status_bar_visible(cx);
13402            assert!(visible, "Status bar should be visible when show is true");
13403        });
13404    }
13405
13406    #[gpui::test]
13407    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13408        init_test(cx);
13409
13410        let fs = FakeFs::new(cx.executor());
13411        let project = Project::test(fs, [], cx).await;
13412        let (multi_workspace, cx) =
13413            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13414        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13415        let panel = workspace.update_in(cx, |workspace, window, cx| {
13416            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13417            workspace.add_panel(panel.clone(), window, cx);
13418
13419            workspace
13420                .right_dock()
13421                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13422
13423            panel
13424        });
13425
13426        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13427        let item_a = cx.new(TestItem::new);
13428        let item_b = cx.new(TestItem::new);
13429        let item_a_id = item_a.entity_id();
13430        let item_b_id = item_b.entity_id();
13431
13432        pane.update_in(cx, |pane, window, cx| {
13433            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13434            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13435        });
13436
13437        pane.read_with(cx, |pane, _| {
13438            assert_eq!(pane.items_len(), 2);
13439            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13440        });
13441
13442        workspace.update_in(cx, |workspace, window, cx| {
13443            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13444        });
13445
13446        workspace.update_in(cx, |_, window, cx| {
13447            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13448        });
13449
13450        // Assert that the `pane::CloseActiveItem` action is handled at the
13451        // workspace level when one of the dock panels is focused and, in that
13452        // case, the center pane's active item is closed but the focus is not
13453        // moved.
13454        cx.dispatch_action(pane::CloseActiveItem::default());
13455        cx.run_until_parked();
13456
13457        pane.read_with(cx, |pane, _| {
13458            assert_eq!(pane.items_len(), 1);
13459            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13460        });
13461
13462        workspace.update_in(cx, |workspace, window, cx| {
13463            assert!(workspace.right_dock().read(cx).is_open());
13464            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13465        });
13466    }
13467
13468    #[gpui::test]
13469    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13470        init_test(cx);
13471        let fs = FakeFs::new(cx.executor());
13472
13473        let project_a = Project::test(fs.clone(), [], cx).await;
13474        let project_b = Project::test(fs, [], cx).await;
13475
13476        let multi_workspace_handle =
13477            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13478        cx.run_until_parked();
13479
13480        let workspace_a = multi_workspace_handle
13481            .read_with(cx, |mw, _| mw.workspace().clone())
13482            .unwrap();
13483
13484        let _workspace_b = multi_workspace_handle
13485            .update(cx, |mw, window, cx| {
13486                mw.test_add_workspace(project_b, window, cx)
13487            })
13488            .unwrap();
13489
13490        // Switch to workspace A
13491        multi_workspace_handle
13492            .update(cx, |mw, window, cx| {
13493                mw.activate_index(0, window, cx);
13494            })
13495            .unwrap();
13496
13497        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13498
13499        // Add a panel to workspace A's right dock and open the dock
13500        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13501            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13502            workspace.add_panel(panel.clone(), window, cx);
13503            workspace
13504                .right_dock()
13505                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13506            panel
13507        });
13508
13509        // Focus the panel through the workspace (matching existing test pattern)
13510        workspace_a.update_in(cx, |workspace, window, cx| {
13511            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13512        });
13513
13514        // Zoom the panel
13515        panel.update_in(cx, |panel, window, cx| {
13516            panel.set_zoomed(true, window, cx);
13517        });
13518
13519        // Verify the panel is zoomed and the dock is open
13520        workspace_a.update_in(cx, |workspace, window, cx| {
13521            assert!(
13522                workspace.right_dock().read(cx).is_open(),
13523                "dock should be open before switch"
13524            );
13525            assert!(
13526                panel.is_zoomed(window, cx),
13527                "panel should be zoomed before switch"
13528            );
13529            assert!(
13530                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13531                "panel should be focused before switch"
13532            );
13533        });
13534
13535        // Switch to workspace B
13536        multi_workspace_handle
13537            .update(cx, |mw, window, cx| {
13538                mw.activate_index(1, window, cx);
13539            })
13540            .unwrap();
13541        cx.run_until_parked();
13542
13543        // Switch back to workspace A
13544        multi_workspace_handle
13545            .update(cx, |mw, window, cx| {
13546                mw.activate_index(0, window, cx);
13547            })
13548            .unwrap();
13549        cx.run_until_parked();
13550
13551        // Verify the panel is still zoomed and the dock is still open
13552        workspace_a.update_in(cx, |workspace, window, cx| {
13553            assert!(
13554                workspace.right_dock().read(cx).is_open(),
13555                "dock should still be open after switching back"
13556            );
13557            assert!(
13558                panel.is_zoomed(window, cx),
13559                "panel should still be zoomed after switching back"
13560            );
13561        });
13562    }
13563
13564    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13565        pane.read(cx)
13566            .items()
13567            .flat_map(|item| {
13568                item.project_paths(cx)
13569                    .into_iter()
13570                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13571            })
13572            .collect()
13573    }
13574
13575    pub fn init_test(cx: &mut TestAppContext) {
13576        cx.update(|cx| {
13577            let settings_store = SettingsStore::test(cx);
13578            cx.set_global(settings_store);
13579            theme::init(theme::LoadThemes::JustBase, cx);
13580        });
13581    }
13582
13583    #[gpui::test]
13584    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13585        use settings::{ThemeName, ThemeSelection};
13586        use theme::SystemAppearance;
13587        use zed_actions::theme::ToggleMode;
13588
13589        init_test(cx);
13590
13591        let fs = FakeFs::new(cx.executor());
13592        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13593
13594        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13595            .await;
13596
13597        // Build a test project and workspace view so the test can invoke
13598        // the workspace action handler the same way the UI would.
13599        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13600        let (workspace, cx) =
13601            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13602
13603        // Seed the settings file with a plain static light theme so the
13604        // first toggle always starts from a known persisted state.
13605        workspace.update_in(cx, |_workspace, _window, cx| {
13606            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13607            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13608                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13609            });
13610        });
13611        cx.executor().advance_clock(Duration::from_millis(200));
13612        cx.run_until_parked();
13613
13614        // Confirm the initial persisted settings contain the static theme
13615        // we just wrote before any toggling happens.
13616        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13617        assert!(settings_text.contains(r#""theme": "One Light""#));
13618
13619        // Toggle once. This should migrate the persisted theme settings
13620        // into light/dark slots and enable system mode.
13621        workspace.update_in(cx, |workspace, window, cx| {
13622            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13623        });
13624        cx.executor().advance_clock(Duration::from_millis(200));
13625        cx.run_until_parked();
13626
13627        // 1. Static -> Dynamic
13628        // this assertion checks theme changed from static to dynamic.
13629        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13630        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13631        assert_eq!(
13632            parsed["theme"],
13633            serde_json::json!({
13634                "mode": "system",
13635                "light": "One Light",
13636                "dark": "One Dark"
13637            })
13638        );
13639
13640        // 2. Toggle again, suppose it will change the mode to light
13641        workspace.update_in(cx, |workspace, window, cx| {
13642            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13643        });
13644        cx.executor().advance_clock(Duration::from_millis(200));
13645        cx.run_until_parked();
13646
13647        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13648        assert!(settings_text.contains(r#""mode": "light""#));
13649    }
13650
13651    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13652        let item = TestProjectItem::new(id, path, cx);
13653        item.update(cx, |item, _| {
13654            item.is_dirty = true;
13655        });
13656        item
13657    }
13658
13659    #[gpui::test]
13660    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13661        cx: &mut gpui::TestAppContext,
13662    ) {
13663        init_test(cx);
13664        let fs = FakeFs::new(cx.executor());
13665
13666        let project = Project::test(fs, [], cx).await;
13667        let (workspace, cx) =
13668            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13669
13670        let panel = workspace.update_in(cx, |workspace, window, cx| {
13671            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13672            workspace.add_panel(panel.clone(), window, cx);
13673            workspace
13674                .right_dock()
13675                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13676            panel
13677        });
13678
13679        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13680        pane.update_in(cx, |pane, window, cx| {
13681            let item = cx.new(TestItem::new);
13682            pane.add_item(Box::new(item), true, true, None, window, cx);
13683        });
13684
13685        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13686        // mirrors the real-world flow and avoids side effects from directly
13687        // focusing the panel while the center pane is active.
13688        workspace.update_in(cx, |workspace, window, cx| {
13689            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13690        });
13691
13692        panel.update_in(cx, |panel, window, cx| {
13693            panel.set_zoomed(true, window, cx);
13694        });
13695
13696        workspace.update_in(cx, |workspace, window, cx| {
13697            assert!(workspace.right_dock().read(cx).is_open());
13698            assert!(panel.is_zoomed(window, cx));
13699            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13700        });
13701
13702        // Simulate a spurious pane::Event::Focus on the center pane while the
13703        // panel still has focus. This mirrors what happens during macOS window
13704        // activation: the center pane fires a focus event even though actual
13705        // focus remains on the dock panel.
13706        pane.update_in(cx, |_, _, cx| {
13707            cx.emit(pane::Event::Focus);
13708        });
13709
13710        // The dock must remain open because the panel had focus at the time the
13711        // event was processed. Before the fix, dock_to_preserve was None for
13712        // panels that don't implement pane(), causing the dock to close.
13713        workspace.update_in(cx, |workspace, window, cx| {
13714            assert!(
13715                workspace.right_dock().read(cx).is_open(),
13716                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13717            );
13718            assert!(panel.is_zoomed(window, cx));
13719        });
13720    }
13721}