workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6mod multi_workspace;
    7pub mod notifications;
    8pub mod pane;
    9pub mod pane_group;
   10pub mod path_list {
   11    pub use util::path_list::{PathList, SerializedPathList};
   12}
   13mod persistence;
   14pub mod searchable;
   15mod security_modal;
   16pub mod shared_screen;
   17use db::smol::future::yield_now;
   18pub use shared_screen::SharedScreen;
   19mod status_bar;
   20pub mod tasks;
   21mod theme_preview;
   22mod toast_layer;
   23mod toolbar;
   24pub mod welcome;
   25mod workspace_settings;
   26
   27pub use crate::notifications::NotificationFrame;
   28pub use dock::Panel;
   29pub use multi_workspace::{
   30    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent,
   31    NewWorkspaceInWindow, NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent,
   32    SidebarHandle, ToggleWorkspaceSidebar,
   33};
   34pub use path_list::{PathList, SerializedPathList};
   35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   36
   37use anyhow::{Context as _, Result, anyhow};
   38use client::{
   39    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   40    proto::{self, ErrorCode, PanelId, PeerId},
   41};
   42use collections::{HashMap, HashSet, hash_map};
   43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   44use fs::Fs;
   45use futures::{
   46    Future, FutureExt, StreamExt,
   47    channel::{
   48        mpsc::{self, UnboundedReceiver, UnboundedSender},
   49        oneshot,
   50    },
   51    future::{Shared, try_join_all},
   52};
   53use gpui::{
   54    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   55    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   56    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   57    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   58    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   59    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   60};
   61pub use history_manager::*;
   62pub use item::{
   63    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   64    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   65};
   66use itertools::Itertools;
   67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   68pub use modal_layer::*;
   69use node_runtime::NodeRuntime;
   70use notifications::{
   71    DetachAndPromptErr, Notifications, dismiss_app_notification,
   72    simple_message_notification::MessageNotification,
   73};
   74pub use pane::*;
   75pub use pane_group::{
   76    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   77    SplitDirection,
   78};
   79use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   80pub use persistence::{
   81    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   82    model::{
   83        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   84        SessionWorkspace,
   85    },
   86    read_serialized_multi_workspaces,
   87};
   88use postage::stream::Stream;
   89use project::{
   90    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   91    WorktreeSettings,
   92    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   93    project_settings::ProjectSettings,
   94    toolchain_store::ToolchainStoreEvent,
   95    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   96};
   97use remote::{
   98    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   99    remote_client::ConnectionIdentifier,
  100};
  101use schemars::JsonSchema;
  102use serde::Deserialize;
  103use session::AppSession;
  104use settings::{
  105    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  106};
  107
  108use sqlez::{
  109    bindable::{Bind, Column, StaticColumnCount},
  110    statement::Statement,
  111};
  112use status_bar::StatusBar;
  113pub use status_bar::StatusItemView;
  114use std::{
  115    any::TypeId,
  116    borrow::Cow,
  117    cell::RefCell,
  118    cmp,
  119    collections::VecDeque,
  120    env,
  121    hash::Hash,
  122    path::{Path, PathBuf},
  123    process::ExitStatus,
  124    rc::Rc,
  125    sync::{
  126        Arc, LazyLock, Weak,
  127        atomic::{AtomicBool, AtomicUsize},
  128    },
  129    time::Duration,
  130};
  131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  133pub use toolbar::{
  134    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  135};
  136pub use ui;
  137use ui::{Window, prelude::*};
  138use util::{
  139    ResultExt, TryFutureExt,
  140    paths::{PathStyle, SanitizedPath},
  141    rel_path::RelPath,
  142    serde::default_true,
  143};
  144use uuid::Uuid;
  145pub use workspace_settings::{
  146    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  147    WorkspaceSettings,
  148};
  149use zed_actions::{Spawn, feedback::FileBugReport};
  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 (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    left_dock_expanded_mode: bool,
 1340}
 1341
 1342impl EventEmitter<Event> for Workspace {}
 1343
 1344#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1345pub struct ViewId {
 1346    pub creator: CollaboratorId,
 1347    pub id: u64,
 1348}
 1349
 1350pub struct FollowerState {
 1351    center_pane: Entity<Pane>,
 1352    dock_pane: Option<Entity<Pane>>,
 1353    active_view_id: Option<ViewId>,
 1354    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1355}
 1356
 1357struct FollowerView {
 1358    view: Box<dyn FollowableItemHandle>,
 1359    location: Option<proto::PanelId>,
 1360}
 1361
 1362impl Workspace {
 1363    pub fn new(
 1364        workspace_id: Option<WorkspaceId>,
 1365        project: Entity<Project>,
 1366        app_state: Arc<AppState>,
 1367        window: &mut Window,
 1368        cx: &mut Context<Self>,
 1369    ) -> Self {
 1370        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1371            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1372                if let TrustedWorktreesEvent::Trusted(..) = e {
 1373                    // Do not persist auto trusted worktrees
 1374                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1375                        worktrees_store.update(cx, |worktrees_store, cx| {
 1376                            worktrees_store.schedule_serialization(
 1377                                cx,
 1378                                |new_trusted_worktrees, cx| {
 1379                                    let timeout =
 1380                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1381                                    cx.background_spawn(async move {
 1382                                        timeout.await;
 1383                                        persistence::DB
 1384                                            .save_trusted_worktrees(new_trusted_worktrees)
 1385                                            .await
 1386                                            .log_err();
 1387                                    })
 1388                                },
 1389                            )
 1390                        });
 1391                    }
 1392                }
 1393            })
 1394            .detach();
 1395
 1396            cx.observe_global::<SettingsStore>(|_, cx| {
 1397                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1398                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1399                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1400                            trusted_worktrees.auto_trust_all(cx);
 1401                        })
 1402                    }
 1403                }
 1404            })
 1405            .detach();
 1406        }
 1407
 1408        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1409            match event {
 1410                project::Event::RemoteIdChanged(_) => {
 1411                    this.update_window_title(window, cx);
 1412                }
 1413
 1414                project::Event::CollaboratorLeft(peer_id) => {
 1415                    this.collaborator_left(*peer_id, window, cx);
 1416                }
 1417
 1418                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1419                    this.update_window_title(window, cx);
 1420                    if this
 1421                        .project()
 1422                        .read(cx)
 1423                        .worktree_for_id(id, cx)
 1424                        .is_some_and(|wt| wt.read(cx).is_visible())
 1425                    {
 1426                        this.serialize_workspace(window, cx);
 1427                        this.update_history(cx);
 1428                    }
 1429                }
 1430                project::Event::WorktreeUpdatedEntries(..) => {
 1431                    this.update_window_title(window, cx);
 1432                    this.serialize_workspace(window, cx);
 1433                }
 1434
 1435                project::Event::DisconnectedFromHost => {
 1436                    this.update_window_edited(window, cx);
 1437                    let leaders_to_unfollow =
 1438                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1439                    for leader_id in leaders_to_unfollow {
 1440                        this.unfollow(leader_id, window, cx);
 1441                    }
 1442                }
 1443
 1444                project::Event::DisconnectedFromRemote {
 1445                    server_not_running: _,
 1446                } => {
 1447                    this.update_window_edited(window, cx);
 1448                }
 1449
 1450                project::Event::Closed => {
 1451                    window.remove_window();
 1452                }
 1453
 1454                project::Event::DeletedEntry(_, entry_id) => {
 1455                    for pane in this.panes.iter() {
 1456                        pane.update(cx, |pane, cx| {
 1457                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1458                        });
 1459                    }
 1460                }
 1461
 1462                project::Event::Toast {
 1463                    notification_id,
 1464                    message,
 1465                    link,
 1466                } => this.show_notification(
 1467                    NotificationId::named(notification_id.clone()),
 1468                    cx,
 1469                    |cx| {
 1470                        let mut notification = MessageNotification::new(message.clone(), cx);
 1471                        if let Some(link) = link {
 1472                            notification = notification
 1473                                .more_info_message(link.label)
 1474                                .more_info_url(link.url);
 1475                        }
 1476
 1477                        cx.new(|_| notification)
 1478                    },
 1479                ),
 1480
 1481                project::Event::HideToast { notification_id } => {
 1482                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1483                }
 1484
 1485                project::Event::LanguageServerPrompt(request) => {
 1486                    struct LanguageServerPrompt;
 1487
 1488                    this.show_notification(
 1489                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1490                        cx,
 1491                        |cx| {
 1492                            cx.new(|cx| {
 1493                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1494                            })
 1495                        },
 1496                    );
 1497                }
 1498
 1499                project::Event::AgentLocationChanged => {
 1500                    this.handle_agent_location_changed(window, cx)
 1501                }
 1502
 1503                _ => {}
 1504            }
 1505            cx.notify()
 1506        })
 1507        .detach();
 1508
 1509        cx.subscribe_in(
 1510            &project.read(cx).breakpoint_store(),
 1511            window,
 1512            |workspace, _, event, window, cx| match event {
 1513                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1514                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1515                    workspace.serialize_workspace(window, cx);
 1516                }
 1517                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1518            },
 1519        )
 1520        .detach();
 1521        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1522            cx.subscribe_in(
 1523                &toolchain_store,
 1524                window,
 1525                |workspace, _, event, window, cx| match event {
 1526                    ToolchainStoreEvent::CustomToolchainsModified => {
 1527                        workspace.serialize_workspace(window, cx);
 1528                    }
 1529                    _ => {}
 1530                },
 1531            )
 1532            .detach();
 1533        }
 1534
 1535        cx.on_focus_lost(window, |this, window, cx| {
 1536            let focus_handle = this.focus_handle(cx);
 1537            window.focus(&focus_handle, cx);
 1538        })
 1539        .detach();
 1540
 1541        let weak_handle = cx.entity().downgrade();
 1542        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1543
 1544        let center_pane = cx.new(|cx| {
 1545            let mut center_pane = Pane::new(
 1546                weak_handle.clone(),
 1547                project.clone(),
 1548                pane_history_timestamp.clone(),
 1549                None,
 1550                NewFile.boxed_clone(),
 1551                true,
 1552                window,
 1553                cx,
 1554            );
 1555            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1556            center_pane.set_should_display_welcome_page(true);
 1557            center_pane
 1558        });
 1559        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1560            .detach();
 1561
 1562        window.focus(&center_pane.focus_handle(cx), cx);
 1563
 1564        cx.emit(Event::PaneAdded(center_pane.clone()));
 1565
 1566        let any_window_handle = window.window_handle();
 1567        app_state.workspace_store.update(cx, |store, _| {
 1568            store
 1569                .workspaces
 1570                .insert((any_window_handle, weak_handle.clone()));
 1571        });
 1572
 1573        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1574        let mut connection_status = app_state.client.status();
 1575        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1576            current_user.next().await;
 1577            connection_status.next().await;
 1578            let mut stream =
 1579                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1580
 1581            while stream.recv().await.is_some() {
 1582                this.update(cx, |_, cx| cx.notify())?;
 1583            }
 1584            anyhow::Ok(())
 1585        });
 1586
 1587        // All leader updates are enqueued and then processed in a single task, so
 1588        // that each asynchronous operation can be run in order.
 1589        let (leader_updates_tx, mut leader_updates_rx) =
 1590            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1591        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1592            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1593                Self::process_leader_update(&this, leader_id, update, cx)
 1594                    .await
 1595                    .log_err();
 1596            }
 1597
 1598            Ok(())
 1599        });
 1600
 1601        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1602        let modal_layer = cx.new(|_| ModalLayer::new());
 1603        let toast_layer = cx.new(|_| ToastLayer::new());
 1604        cx.subscribe(
 1605            &modal_layer,
 1606            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1607                cx.emit(Event::ModalOpened);
 1608            },
 1609        )
 1610        .detach();
 1611
 1612        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1613        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1614        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1615        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1616        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1617        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1618        let status_bar = cx.new(|cx| {
 1619            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1620            status_bar.add_left_item(left_dock_buttons, window, cx);
 1621            status_bar.add_right_item(right_dock_buttons, window, cx);
 1622            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1623            status_bar
 1624        });
 1625
 1626        let session_id = app_state.session.read(cx).id().to_owned();
 1627
 1628        let mut active_call = None;
 1629        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1630            let subscriptions =
 1631                vec![
 1632                    call.0
 1633                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1634                ];
 1635            active_call = Some((call, subscriptions));
 1636        }
 1637
 1638        let (serializable_items_tx, serializable_items_rx) =
 1639            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1640        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1641            Self::serialize_items(&this, serializable_items_rx, cx).await
 1642        });
 1643
 1644        let subscriptions = vec![
 1645            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1646            cx.observe_window_bounds(window, move |this, window, cx| {
 1647                if this.bounds_save_task_queued.is_some() {
 1648                    return;
 1649                }
 1650                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1651                    cx.background_executor()
 1652                        .timer(Duration::from_millis(100))
 1653                        .await;
 1654                    this.update_in(cx, |this, window, cx| {
 1655                        this.save_window_bounds(window, cx).detach();
 1656                        this.bounds_save_task_queued.take();
 1657                    })
 1658                    .ok();
 1659                }));
 1660                cx.notify();
 1661            }),
 1662            cx.observe_window_appearance(window, |_, window, cx| {
 1663                let window_appearance = window.appearance();
 1664
 1665                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1666
 1667                GlobalTheme::reload_theme(cx);
 1668                GlobalTheme::reload_icon_theme(cx);
 1669            }),
 1670            cx.on_release({
 1671                let weak_handle = weak_handle.clone();
 1672                move |this, cx| {
 1673                    this.app_state.workspace_store.update(cx, move |store, _| {
 1674                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1675                    })
 1676                }
 1677            }),
 1678        ];
 1679
 1680        cx.defer_in(window, move |this, window, cx| {
 1681            this.update_window_title(window, cx);
 1682            this.show_initial_notifications(cx);
 1683        });
 1684
 1685        let mut center = PaneGroup::new(center_pane.clone());
 1686        center.set_is_center(true);
 1687        center.mark_positions(cx);
 1688
 1689        Workspace {
 1690            weak_self: weak_handle.clone(),
 1691            zoomed: None,
 1692            zoomed_position: None,
 1693            previous_dock_drag_coordinates: None,
 1694            center,
 1695            panes: vec![center_pane.clone()],
 1696            panes_by_item: Default::default(),
 1697            active_pane: center_pane.clone(),
 1698            last_active_center_pane: Some(center_pane.downgrade()),
 1699            last_active_view_id: None,
 1700            status_bar,
 1701            modal_layer,
 1702            toast_layer,
 1703            titlebar_item: None,
 1704            active_worktree_override: None,
 1705            notifications: Notifications::default(),
 1706            suppressed_notifications: HashSet::default(),
 1707            left_dock,
 1708            bottom_dock,
 1709            right_dock,
 1710            _panels_task: None,
 1711            project: project.clone(),
 1712            follower_states: Default::default(),
 1713            last_leaders_by_pane: Default::default(),
 1714            dispatching_keystrokes: Default::default(),
 1715            window_edited: false,
 1716            last_window_title: None,
 1717            dirty_items: Default::default(),
 1718            active_call,
 1719            database_id: workspace_id,
 1720            app_state,
 1721            _observe_current_user,
 1722            _apply_leader_updates,
 1723            _schedule_serialize_workspace: None,
 1724            _serialize_workspace_task: None,
 1725            _schedule_serialize_ssh_paths: None,
 1726            leader_updates_tx,
 1727            _subscriptions: subscriptions,
 1728            pane_history_timestamp,
 1729            workspace_actions: Default::default(),
 1730            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1731            bounds: Default::default(),
 1732            centered_layout: false,
 1733            bounds_save_task_queued: None,
 1734            on_prompt_for_new_path: None,
 1735            on_prompt_for_open_path: None,
 1736            terminal_provider: None,
 1737            debugger_provider: None,
 1738            serializable_items_tx,
 1739            _items_serializer,
 1740            session_id: Some(session_id),
 1741
 1742            scheduled_tasks: Vec::new(),
 1743            last_open_dock_positions: Vec::new(),
 1744            removing: false,
 1745            left_dock_expanded_mode: false,
 1746        }
 1747    }
 1748
 1749    pub fn new_local(
 1750        abs_paths: Vec<PathBuf>,
 1751        app_state: Arc<AppState>,
 1752        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1753        env: Option<HashMap<String, String>>,
 1754        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1755        activate: bool,
 1756        cx: &mut App,
 1757    ) -> Task<
 1758        anyhow::Result<(
 1759            WindowHandle<MultiWorkspace>,
 1760            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1761        )>,
 1762    > {
 1763        let project_handle = Project::local(
 1764            app_state.client.clone(),
 1765            app_state.node_runtime.clone(),
 1766            app_state.user_store.clone(),
 1767            app_state.languages.clone(),
 1768            app_state.fs.clone(),
 1769            env,
 1770            Default::default(),
 1771            cx,
 1772        );
 1773
 1774        cx.spawn(async move |cx| {
 1775            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1776            for path in abs_paths.into_iter() {
 1777                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1778                    paths_to_open.push(canonical)
 1779                } else {
 1780                    paths_to_open.push(path)
 1781                }
 1782            }
 1783
 1784            let serialized_workspace =
 1785                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1786
 1787            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1788                paths_to_open = paths.ordered_paths().cloned().collect();
 1789                if !paths.is_lexicographically_ordered() {
 1790                    project_handle.update(cx, |project, cx| {
 1791                        project.set_worktrees_reordered(true, cx);
 1792                    });
 1793                }
 1794            }
 1795
 1796            // Get project paths for all of the abs_paths
 1797            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1798                Vec::with_capacity(paths_to_open.len());
 1799
 1800            for path in paths_to_open.into_iter() {
 1801                if let Some((_, project_entry)) = cx
 1802                    .update(|cx| {
 1803                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1804                    })
 1805                    .await
 1806                    .log_err()
 1807                {
 1808                    project_paths.push((path, Some(project_entry)));
 1809                } else {
 1810                    project_paths.push((path, None));
 1811                }
 1812            }
 1813
 1814            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1815                serialized_workspace.id
 1816            } else {
 1817                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1818            };
 1819
 1820            let toolchains = DB.toolchains(workspace_id).await?;
 1821
 1822            for (toolchain, worktree_path, path) in toolchains {
 1823                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1824                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1825                    this.find_worktree(&worktree_path, cx)
 1826                        .and_then(|(worktree, rel_path)| {
 1827                            if rel_path.is_empty() {
 1828                                Some(worktree.read(cx).id())
 1829                            } else {
 1830                                None
 1831                            }
 1832                        })
 1833                }) else {
 1834                    // We did not find a worktree with a given path, but that's whatever.
 1835                    continue;
 1836                };
 1837                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1838                    continue;
 1839                }
 1840
 1841                project_handle
 1842                    .update(cx, |this, cx| {
 1843                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1844                    })
 1845                    .await;
 1846            }
 1847            if let Some(workspace) = serialized_workspace.as_ref() {
 1848                project_handle.update(cx, |this, cx| {
 1849                    for (scope, toolchains) in &workspace.user_toolchains {
 1850                        for toolchain in toolchains {
 1851                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1852                        }
 1853                    }
 1854                });
 1855            }
 1856
 1857            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1858                if let Some(window) = requesting_window {
 1859                    let centered_layout = serialized_workspace
 1860                        .as_ref()
 1861                        .map(|w| w.centered_layout)
 1862                        .unwrap_or(false);
 1863
 1864                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1865                        let workspace = cx.new(|cx| {
 1866                            let mut workspace = Workspace::new(
 1867                                Some(workspace_id),
 1868                                project_handle.clone(),
 1869                                app_state.clone(),
 1870                                window,
 1871                                cx,
 1872                            );
 1873
 1874                            workspace.centered_layout = centered_layout;
 1875
 1876                            // Call init callback to add items before window renders
 1877                            if let Some(init) = init {
 1878                                init(&mut workspace, window, cx);
 1879                            }
 1880
 1881                            workspace
 1882                        });
 1883                        if activate {
 1884                            multi_workspace.activate(workspace.clone(), cx);
 1885                        } else {
 1886                            multi_workspace.add_workspace(workspace.clone(), cx);
 1887                        }
 1888                        workspace
 1889                    })?;
 1890                    (window, workspace)
 1891                } else {
 1892                    let window_bounds_override = window_bounds_env_override();
 1893
 1894                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1895                        (Some(WindowBounds::Windowed(bounds)), None)
 1896                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1897                        && let Some(display) = workspace.display
 1898                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1899                    {
 1900                        // Reopening an existing workspace - restore its saved bounds
 1901                        (Some(bounds.0), Some(display))
 1902                    } else if let Some((display, bounds)) =
 1903                        persistence::read_default_window_bounds()
 1904                    {
 1905                        // New or empty workspace - use the last known window bounds
 1906                        (Some(bounds), Some(display))
 1907                    } else {
 1908                        // New window - let GPUI's default_bounds() handle cascading
 1909                        (None, None)
 1910                    };
 1911
 1912                    // Use the serialized workspace to construct the new window
 1913                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1914                    options.window_bounds = window_bounds;
 1915                    let centered_layout = serialized_workspace
 1916                        .as_ref()
 1917                        .map(|w| w.centered_layout)
 1918                        .unwrap_or(false);
 1919                    let window = cx.open_window(options, {
 1920                        let app_state = app_state.clone();
 1921                        let project_handle = project_handle.clone();
 1922                        move |window, cx| {
 1923                            let workspace = cx.new(|cx| {
 1924                                let mut workspace = Workspace::new(
 1925                                    Some(workspace_id),
 1926                                    project_handle,
 1927                                    app_state,
 1928                                    window,
 1929                                    cx,
 1930                                );
 1931                                workspace.centered_layout = centered_layout;
 1932
 1933                                // Call init callback to add items before window renders
 1934                                if let Some(init) = init {
 1935                                    init(&mut workspace, window, cx);
 1936                                }
 1937
 1938                                workspace
 1939                            });
 1940                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1941                        }
 1942                    })?;
 1943                    let workspace =
 1944                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1945                            multi_workspace.workspace().clone()
 1946                        })?;
 1947                    (window, workspace)
 1948                };
 1949
 1950            notify_if_database_failed(window, cx);
 1951            // Check if this is an empty workspace (no paths to open)
 1952            // An empty workspace is one where project_paths is empty
 1953            let is_empty_workspace = project_paths.is_empty();
 1954            // Check if serialized workspace has paths before it's moved
 1955            let serialized_workspace_has_paths = serialized_workspace
 1956                .as_ref()
 1957                .map(|ws| !ws.paths.is_empty())
 1958                .unwrap_or(false);
 1959
 1960            let opened_items = window
 1961                .update(cx, |_, window, cx| {
 1962                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1963                        open_items(serialized_workspace, project_paths, window, cx)
 1964                    })
 1965                })?
 1966                .await
 1967                .unwrap_or_default();
 1968
 1969            // Restore default dock state for empty workspaces
 1970            // Only restore if:
 1971            // 1. This is an empty workspace (no paths), AND
 1972            // 2. The serialized workspace either doesn't exist or has no paths
 1973            if is_empty_workspace && !serialized_workspace_has_paths {
 1974                if let Some(default_docks) = persistence::read_default_dock_state() {
 1975                    window
 1976                        .update(cx, |_, window, cx| {
 1977                            workspace.update(cx, |workspace, cx| {
 1978                                for (dock, serialized_dock) in [
 1979                                    (&workspace.right_dock, &default_docks.right),
 1980                                    (&workspace.left_dock, &default_docks.left),
 1981                                    (&workspace.bottom_dock, &default_docks.bottom),
 1982                                ] {
 1983                                    dock.update(cx, |dock, cx| {
 1984                                        dock.serialized_dock = Some(serialized_dock.clone());
 1985                                        dock.restore_state(window, cx);
 1986                                    });
 1987                                }
 1988                                cx.notify();
 1989                            });
 1990                        })
 1991                        .log_err();
 1992                }
 1993            }
 1994
 1995            window
 1996                .update(cx, |_, _window, cx| {
 1997                    workspace.update(cx, |this: &mut Workspace, cx| {
 1998                        this.update_history(cx);
 1999                    });
 2000                })
 2001                .log_err();
 2002            Ok((window, opened_items))
 2003        })
 2004    }
 2005
 2006    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2007        self.weak_self.clone()
 2008    }
 2009
 2010    pub fn left_dock(&self) -> &Entity<Dock> {
 2011        &self.left_dock
 2012    }
 2013
 2014    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2015        &self.bottom_dock
 2016    }
 2017
 2018    pub fn set_left_dock_expanded_mode(&mut self, is_expanded_mode: bool, cx: &mut Context<Self>) {
 2019        self.left_dock_expanded_mode = is_expanded_mode;
 2020        cx.notify();
 2021    }
 2022
 2023    pub fn set_bottom_dock_layout(
 2024        &mut self,
 2025        layout: BottomDockLayout,
 2026        window: &mut Window,
 2027        cx: &mut Context<Self>,
 2028    ) {
 2029        let fs = self.project().read(cx).fs();
 2030        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2031            content.workspace.bottom_dock_layout = Some(layout);
 2032        });
 2033
 2034        cx.notify();
 2035        self.serialize_workspace(window, cx);
 2036    }
 2037
 2038    pub fn right_dock(&self) -> &Entity<Dock> {
 2039        &self.right_dock
 2040    }
 2041
 2042    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2043        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2044    }
 2045
 2046    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2047        let left_dock = self.left_dock.read(cx);
 2048        let left_visible = left_dock.is_open();
 2049        let left_active_panel = left_dock
 2050            .active_panel()
 2051            .map(|panel| panel.persistent_name().to_string());
 2052        // `zoomed_position` is kept in sync with individual panel zoom state
 2053        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2054        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2055
 2056        let right_dock = self.right_dock.read(cx);
 2057        let right_visible = right_dock.is_open();
 2058        let right_active_panel = right_dock
 2059            .active_panel()
 2060            .map(|panel| panel.persistent_name().to_string());
 2061        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2062
 2063        let bottom_dock = self.bottom_dock.read(cx);
 2064        let bottom_visible = bottom_dock.is_open();
 2065        let bottom_active_panel = bottom_dock
 2066            .active_panel()
 2067            .map(|panel| panel.persistent_name().to_string());
 2068        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2069
 2070        DockStructure {
 2071            left: DockData {
 2072                visible: left_visible,
 2073                active_panel: left_active_panel,
 2074                zoom: left_dock_zoom,
 2075            },
 2076            right: DockData {
 2077                visible: right_visible,
 2078                active_panel: right_active_panel,
 2079                zoom: right_dock_zoom,
 2080            },
 2081            bottom: DockData {
 2082                visible: bottom_visible,
 2083                active_panel: bottom_active_panel,
 2084                zoom: bottom_dock_zoom,
 2085            },
 2086        }
 2087    }
 2088
 2089    pub fn set_dock_structure(
 2090        &self,
 2091        docks: DockStructure,
 2092        window: &mut Window,
 2093        cx: &mut Context<Self>,
 2094    ) {
 2095        for (dock, data) in [
 2096            (&self.left_dock, docks.left),
 2097            (&self.bottom_dock, docks.bottom),
 2098            (&self.right_dock, docks.right),
 2099        ] {
 2100            dock.update(cx, |dock, cx| {
 2101                dock.serialized_dock = Some(data);
 2102                dock.restore_state(window, cx);
 2103            });
 2104        }
 2105    }
 2106
 2107    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2108        self.items(cx)
 2109            .filter_map(|item| {
 2110                let project_path = item.project_path(cx)?;
 2111                self.project.read(cx).absolute_path(&project_path, cx)
 2112            })
 2113            .collect()
 2114    }
 2115
 2116    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2117        match position {
 2118            DockPosition::Left => &self.left_dock,
 2119            DockPosition::Bottom => &self.bottom_dock,
 2120            DockPosition::Right => &self.right_dock,
 2121        }
 2122    }
 2123
 2124    pub fn is_edited(&self) -> bool {
 2125        self.window_edited
 2126    }
 2127
 2128    pub fn add_panel<T: Panel>(
 2129        &mut self,
 2130        panel: Entity<T>,
 2131        position: DockPosition,
 2132        window: &mut Window,
 2133        cx: &mut Context<Self>,
 2134    ) {
 2135        let focus_handle = panel.panel_focus_handle(cx);
 2136        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2137            .detach();
 2138
 2139        let dock = self.dock_at_position(position);
 2140        let any_panel = panel.to_any();
 2141
 2142        dock.update(cx, |dock, cx| {
 2143            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2144        });
 2145
 2146        cx.emit(Event::PanelAdded(any_panel));
 2147    }
 2148
 2149    pub fn move_panel_to_dock(
 2150        &mut self,
 2151        panel_id: EntityId,
 2152        new_position: DockPosition,
 2153        window: &mut Window,
 2154        cx: &mut Context<Self>,
 2155    ) {
 2156        let current_dock_position = self
 2157            .all_docks()
 2158            .iter()
 2159            .find(|dock| dock.read(cx).panel_for_id(panel_id).is_some())
 2160            .map(|dock| dock.read(cx).position());
 2161
 2162        let Some(current_dock_position) = current_dock_position else {
 2163            return;
 2164        };
 2165
 2166        if current_dock_position == new_position {
 2167            return;
 2168        }
 2169
 2170        let current_dock = self.dock_at_position(current_dock_position).clone();
 2171
 2172        let was_visible = current_dock.read(cx).is_open()
 2173            && current_dock
 2174                .read(cx)
 2175                .visible_panel()
 2176                .is_some_and(|active_panel| active_panel.panel_id() == panel_id);
 2177
 2178        let panel_handle = current_dock.read(cx).panel_for_id(panel_id).cloned();
 2179
 2180        let Some(panel_handle) = panel_handle else {
 2181            return;
 2182        };
 2183
 2184        if panel_handle.is_zoomed(window, cx) {
 2185            self.zoomed_position = Some(new_position);
 2186        }
 2187
 2188        current_dock.update(cx, |dock, cx| {
 2189            dock.remove_panel_by_id(panel_id, window, cx);
 2190        });
 2191
 2192        let new_dock = self.dock_at_position(new_position).clone();
 2193
 2194        new_dock.update(cx, |dock, cx| {
 2195            dock.remove_panel_by_id(panel_id, window, cx);
 2196        });
 2197
 2198        let weak_self = self.weak_self.clone();
 2199        new_dock.update(cx, |dock, cx| {
 2200            let index = panel_handle.add_to_dock(dock, weak_self, window, cx);
 2201            if was_visible {
 2202                dock.set_open(true, window, cx);
 2203                dock.activate_panel(index, window, cx);
 2204            }
 2205        });
 2206
 2207        self.serialize_workspace(window, cx);
 2208    }
 2209
 2210    pub fn all_panel_ids_and_positions(&self, cx: &App) -> Vec<(EntityId, DockPosition)> {
 2211        let mut result = Vec::new();
 2212        for dock in self.all_docks() {
 2213            let dock = dock.read(cx);
 2214            let position = dock.position();
 2215            for panel_id in dock.panel_ids() {
 2216                result.push((panel_id, position));
 2217            }
 2218        }
 2219        result
 2220    }
 2221
 2222    pub fn remove_panel<T: Panel>(
 2223        &mut self,
 2224        panel: &Entity<T>,
 2225        window: &mut Window,
 2226        cx: &mut Context<Self>,
 2227    ) {
 2228        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2229            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2230        }
 2231    }
 2232
 2233    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2234        &self.status_bar
 2235    }
 2236
 2237    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2238        self.status_bar.update(cx, |status_bar, cx| {
 2239            status_bar.set_workspace_sidebar_open(open, cx);
 2240        });
 2241    }
 2242
 2243    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2244        StatusBarSettings::get_global(cx).show
 2245    }
 2246
 2247    pub fn app_state(&self) -> &Arc<AppState> {
 2248        &self.app_state
 2249    }
 2250
 2251    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2252        self._panels_task = Some(task);
 2253    }
 2254
 2255    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2256        self._panels_task.take()
 2257    }
 2258
 2259    pub fn user_store(&self) -> &Entity<UserStore> {
 2260        &self.app_state.user_store
 2261    }
 2262
 2263    pub fn project(&self) -> &Entity<Project> {
 2264        &self.project
 2265    }
 2266
 2267    pub fn path_style(&self, cx: &App) -> PathStyle {
 2268        self.project.read(cx).path_style(cx)
 2269    }
 2270
 2271    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2272        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2273
 2274        for pane_handle in &self.panes {
 2275            let pane = pane_handle.read(cx);
 2276
 2277            for entry in pane.activation_history() {
 2278                history.insert(
 2279                    entry.entity_id,
 2280                    history
 2281                        .get(&entry.entity_id)
 2282                        .cloned()
 2283                        .unwrap_or(0)
 2284                        .max(entry.timestamp),
 2285                );
 2286            }
 2287        }
 2288
 2289        history
 2290    }
 2291
 2292    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2293        let mut recent_item: Option<Entity<T>> = None;
 2294        let mut recent_timestamp = 0;
 2295        for pane_handle in &self.panes {
 2296            let pane = pane_handle.read(cx);
 2297            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2298                pane.items().map(|item| (item.item_id(), item)).collect();
 2299            for entry in pane.activation_history() {
 2300                if entry.timestamp > recent_timestamp
 2301                    && let Some(&item) = item_map.get(&entry.entity_id)
 2302                    && let Some(typed_item) = item.act_as::<T>(cx)
 2303                {
 2304                    recent_timestamp = entry.timestamp;
 2305                    recent_item = Some(typed_item);
 2306                }
 2307            }
 2308        }
 2309        recent_item
 2310    }
 2311
 2312    pub fn recent_navigation_history_iter(
 2313        &self,
 2314        cx: &App,
 2315    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2316        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2317        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2318
 2319        for pane in &self.panes {
 2320            let pane = pane.read(cx);
 2321
 2322            pane.nav_history()
 2323                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2324                    if let Some(fs_path) = &fs_path {
 2325                        abs_paths_opened
 2326                            .entry(fs_path.clone())
 2327                            .or_default()
 2328                            .insert(project_path.clone());
 2329                    }
 2330                    let timestamp = entry.timestamp;
 2331                    match history.entry(project_path) {
 2332                        hash_map::Entry::Occupied(mut entry) => {
 2333                            let (_, old_timestamp) = entry.get();
 2334                            if &timestamp > old_timestamp {
 2335                                entry.insert((fs_path, timestamp));
 2336                            }
 2337                        }
 2338                        hash_map::Entry::Vacant(entry) => {
 2339                            entry.insert((fs_path, timestamp));
 2340                        }
 2341                    }
 2342                });
 2343
 2344            if let Some(item) = pane.active_item()
 2345                && let Some(project_path) = item.project_path(cx)
 2346            {
 2347                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2348
 2349                if let Some(fs_path) = &fs_path {
 2350                    abs_paths_opened
 2351                        .entry(fs_path.clone())
 2352                        .or_default()
 2353                        .insert(project_path.clone());
 2354                }
 2355
 2356                history.insert(project_path, (fs_path, std::usize::MAX));
 2357            }
 2358        }
 2359
 2360        history
 2361            .into_iter()
 2362            .sorted_by_key(|(_, (_, order))| *order)
 2363            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2364            .rev()
 2365            .filter(move |(history_path, abs_path)| {
 2366                let latest_project_path_opened = abs_path
 2367                    .as_ref()
 2368                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2369                    .and_then(|project_paths| {
 2370                        project_paths
 2371                            .iter()
 2372                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2373                    });
 2374
 2375                latest_project_path_opened.is_none_or(|path| path == history_path)
 2376            })
 2377    }
 2378
 2379    pub fn recent_navigation_history(
 2380        &self,
 2381        limit: Option<usize>,
 2382        cx: &App,
 2383    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2384        self.recent_navigation_history_iter(cx)
 2385            .take(limit.unwrap_or(usize::MAX))
 2386            .collect()
 2387    }
 2388
 2389    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2390        for pane in &self.panes {
 2391            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2392        }
 2393    }
 2394
 2395    fn navigate_history(
 2396        &mut self,
 2397        pane: WeakEntity<Pane>,
 2398        mode: NavigationMode,
 2399        window: &mut Window,
 2400        cx: &mut Context<Workspace>,
 2401    ) -> Task<Result<()>> {
 2402        self.navigate_history_impl(
 2403            pane,
 2404            mode,
 2405            window,
 2406            &mut |history, cx| history.pop(mode, cx),
 2407            cx,
 2408        )
 2409    }
 2410
 2411    fn navigate_tag_history(
 2412        &mut self,
 2413        pane: WeakEntity<Pane>,
 2414        mode: TagNavigationMode,
 2415        window: &mut Window,
 2416        cx: &mut Context<Workspace>,
 2417    ) -> Task<Result<()>> {
 2418        self.navigate_history_impl(
 2419            pane,
 2420            NavigationMode::Normal,
 2421            window,
 2422            &mut |history, _cx| history.pop_tag(mode),
 2423            cx,
 2424        )
 2425    }
 2426
 2427    fn navigate_history_impl(
 2428        &mut self,
 2429        pane: WeakEntity<Pane>,
 2430        mode: NavigationMode,
 2431        window: &mut Window,
 2432        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2433        cx: &mut Context<Workspace>,
 2434    ) -> Task<Result<()>> {
 2435        let to_load = if let Some(pane) = pane.upgrade() {
 2436            pane.update(cx, |pane, cx| {
 2437                window.focus(&pane.focus_handle(cx), cx);
 2438                loop {
 2439                    // Retrieve the weak item handle from the history.
 2440                    let entry = cb(pane.nav_history_mut(), cx)?;
 2441
 2442                    // If the item is still present in this pane, then activate it.
 2443                    if let Some(index) = entry
 2444                        .item
 2445                        .upgrade()
 2446                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2447                    {
 2448                        let prev_active_item_index = pane.active_item_index();
 2449                        pane.nav_history_mut().set_mode(mode);
 2450                        pane.activate_item(index, true, true, window, cx);
 2451                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2452
 2453                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2454                        if let Some(data) = entry.data {
 2455                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2456                        }
 2457
 2458                        if navigated {
 2459                            break None;
 2460                        }
 2461                    } else {
 2462                        // If the item is no longer present in this pane, then retrieve its
 2463                        // path info in order to reopen it.
 2464                        break pane
 2465                            .nav_history()
 2466                            .path_for_item(entry.item.id())
 2467                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2468                    }
 2469                }
 2470            })
 2471        } else {
 2472            None
 2473        };
 2474
 2475        if let Some((project_path, abs_path, entry)) = to_load {
 2476            // If the item was no longer present, then load it again from its previous path, first try the local path
 2477            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2478
 2479            cx.spawn_in(window, async move  |workspace, cx| {
 2480                let open_by_project_path = open_by_project_path.await;
 2481                let mut navigated = false;
 2482                match open_by_project_path
 2483                    .with_context(|| format!("Navigating to {project_path:?}"))
 2484                {
 2485                    Ok((project_entry_id, build_item)) => {
 2486                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2487                            pane.nav_history_mut().set_mode(mode);
 2488                            pane.active_item().map(|p| p.item_id())
 2489                        })?;
 2490
 2491                        pane.update_in(cx, |pane, window, cx| {
 2492                            let item = pane.open_item(
 2493                                project_entry_id,
 2494                                project_path,
 2495                                true,
 2496                                entry.is_preview,
 2497                                true,
 2498                                None,
 2499                                window, cx,
 2500                                build_item,
 2501                            );
 2502                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2503                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2504                            if let Some(data) = entry.data {
 2505                                navigated |= item.navigate(data, window, cx);
 2506                            }
 2507                        })?;
 2508                    }
 2509                    Err(open_by_project_path_e) => {
 2510                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2511                        // and its worktree is now dropped
 2512                        if let Some(abs_path) = abs_path {
 2513                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2514                                pane.nav_history_mut().set_mode(mode);
 2515                                pane.active_item().map(|p| p.item_id())
 2516                            })?;
 2517                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2518                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2519                            })?;
 2520                            match open_by_abs_path
 2521                                .await
 2522                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2523                            {
 2524                                Ok(item) => {
 2525                                    pane.update_in(cx, |pane, window, cx| {
 2526                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2527                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2528                                        if let Some(data) = entry.data {
 2529                                            navigated |= item.navigate(data, window, cx);
 2530                                        }
 2531                                    })?;
 2532                                }
 2533                                Err(open_by_abs_path_e) => {
 2534                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2535                                }
 2536                            }
 2537                        }
 2538                    }
 2539                }
 2540
 2541                if !navigated {
 2542                    workspace
 2543                        .update_in(cx, |workspace, window, cx| {
 2544                            Self::navigate_history(workspace, pane, mode, window, cx)
 2545                        })?
 2546                        .await?;
 2547                }
 2548
 2549                Ok(())
 2550            })
 2551        } else {
 2552            Task::ready(Ok(()))
 2553        }
 2554    }
 2555
 2556    pub fn go_back(
 2557        &mut self,
 2558        pane: WeakEntity<Pane>,
 2559        window: &mut Window,
 2560        cx: &mut Context<Workspace>,
 2561    ) -> Task<Result<()>> {
 2562        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2563    }
 2564
 2565    pub fn go_forward(
 2566        &mut self,
 2567        pane: WeakEntity<Pane>,
 2568        window: &mut Window,
 2569        cx: &mut Context<Workspace>,
 2570    ) -> Task<Result<()>> {
 2571        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2572    }
 2573
 2574    pub fn reopen_closed_item(
 2575        &mut self,
 2576        window: &mut Window,
 2577        cx: &mut Context<Workspace>,
 2578    ) -> Task<Result<()>> {
 2579        self.navigate_history(
 2580            self.active_pane().downgrade(),
 2581            NavigationMode::ReopeningClosedItem,
 2582            window,
 2583            cx,
 2584        )
 2585    }
 2586
 2587    pub fn client(&self) -> &Arc<Client> {
 2588        &self.app_state.client
 2589    }
 2590
 2591    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2592        self.titlebar_item = Some(item);
 2593        cx.notify();
 2594    }
 2595
 2596    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2597        self.on_prompt_for_new_path = Some(prompt)
 2598    }
 2599
 2600    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2601        self.on_prompt_for_open_path = Some(prompt)
 2602    }
 2603
 2604    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2605        self.terminal_provider = Some(Box::new(provider));
 2606    }
 2607
 2608    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2609        self.debugger_provider = Some(Arc::new(provider));
 2610    }
 2611
 2612    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2613        self.debugger_provider.clone()
 2614    }
 2615
 2616    pub fn prompt_for_open_path(
 2617        &mut self,
 2618        path_prompt_options: PathPromptOptions,
 2619        lister: DirectoryLister,
 2620        window: &mut Window,
 2621        cx: &mut Context<Self>,
 2622    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2623        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2624            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2625            let rx = prompt(self, lister, window, cx);
 2626            self.on_prompt_for_open_path = Some(prompt);
 2627            rx
 2628        } else {
 2629            let (tx, rx) = oneshot::channel();
 2630            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2631
 2632            cx.spawn_in(window, async move |workspace, cx| {
 2633                let Ok(result) = abs_path.await else {
 2634                    return Ok(());
 2635                };
 2636
 2637                match result {
 2638                    Ok(result) => {
 2639                        tx.send(result).ok();
 2640                    }
 2641                    Err(err) => {
 2642                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2643                            workspace.show_portal_error(err.to_string(), cx);
 2644                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2645                            let rx = prompt(workspace, lister, window, cx);
 2646                            workspace.on_prompt_for_open_path = Some(prompt);
 2647                            rx
 2648                        })?;
 2649                        if let Ok(path) = rx.await {
 2650                            tx.send(path).ok();
 2651                        }
 2652                    }
 2653                };
 2654                anyhow::Ok(())
 2655            })
 2656            .detach();
 2657
 2658            rx
 2659        }
 2660    }
 2661
 2662    pub fn prompt_for_new_path(
 2663        &mut self,
 2664        lister: DirectoryLister,
 2665        suggested_name: Option<String>,
 2666        window: &mut Window,
 2667        cx: &mut Context<Self>,
 2668    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2669        if self.project.read(cx).is_via_collab()
 2670            || self.project.read(cx).is_via_remote_server()
 2671            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2672        {
 2673            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2674            let rx = prompt(self, lister, suggested_name, window, cx);
 2675            self.on_prompt_for_new_path = Some(prompt);
 2676            return rx;
 2677        }
 2678
 2679        let (tx, rx) = oneshot::channel();
 2680        cx.spawn_in(window, async move |workspace, cx| {
 2681            let abs_path = workspace.update(cx, |workspace, cx| {
 2682                let relative_to = workspace
 2683                    .most_recent_active_path(cx)
 2684                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2685                    .or_else(|| {
 2686                        let project = workspace.project.read(cx);
 2687                        project.visible_worktrees(cx).find_map(|worktree| {
 2688                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2689                        })
 2690                    })
 2691                    .or_else(std::env::home_dir)
 2692                    .unwrap_or_else(|| PathBuf::from(""));
 2693                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2694            })?;
 2695            let abs_path = match abs_path.await? {
 2696                Ok(path) => path,
 2697                Err(err) => {
 2698                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2699                        workspace.show_portal_error(err.to_string(), cx);
 2700
 2701                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2702                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2703                        workspace.on_prompt_for_new_path = Some(prompt);
 2704                        rx
 2705                    })?;
 2706                    if let Ok(path) = rx.await {
 2707                        tx.send(path).ok();
 2708                    }
 2709                    return anyhow::Ok(());
 2710                }
 2711            };
 2712
 2713            tx.send(abs_path.map(|path| vec![path])).ok();
 2714            anyhow::Ok(())
 2715        })
 2716        .detach();
 2717
 2718        rx
 2719    }
 2720
 2721    pub fn titlebar_item(&self) -> Option<AnyView> {
 2722        self.titlebar_item.clone()
 2723    }
 2724
 2725    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2726    /// When set, git-related operations should use this worktree instead of deriving
 2727    /// the active worktree from the focused file.
 2728    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2729        self.active_worktree_override
 2730    }
 2731
 2732    pub fn set_active_worktree_override(
 2733        &mut self,
 2734        worktree_id: Option<WorktreeId>,
 2735        cx: &mut Context<Self>,
 2736    ) {
 2737        self.active_worktree_override = worktree_id;
 2738        cx.notify();
 2739    }
 2740
 2741    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2742        self.active_worktree_override = None;
 2743        cx.notify();
 2744    }
 2745
 2746    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2747    ///
 2748    /// If the given workspace has a local project, then it will be passed
 2749    /// to the callback. Otherwise, a new empty window will be created.
 2750    pub fn with_local_workspace<T, F>(
 2751        &mut self,
 2752        window: &mut Window,
 2753        cx: &mut Context<Self>,
 2754        callback: F,
 2755    ) -> Task<Result<T>>
 2756    where
 2757        T: 'static,
 2758        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2759    {
 2760        if self.project.read(cx).is_local() {
 2761            Task::ready(Ok(callback(self, window, cx)))
 2762        } else {
 2763            let env = self.project.read(cx).cli_environment(cx);
 2764            let task = Self::new_local(
 2765                Vec::new(),
 2766                self.app_state.clone(),
 2767                None,
 2768                env,
 2769                None,
 2770                true,
 2771                cx,
 2772            );
 2773            cx.spawn_in(window, async move |_vh, cx| {
 2774                let (multi_workspace_window, _) = task.await?;
 2775                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2776                    let workspace = multi_workspace.workspace().clone();
 2777                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2778                })
 2779            })
 2780        }
 2781    }
 2782
 2783    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2784    ///
 2785    /// If the given workspace has a local project, then it will be passed
 2786    /// to the callback. Otherwise, a new empty window will be created.
 2787    pub fn with_local_or_wsl_workspace<T, F>(
 2788        &mut self,
 2789        window: &mut Window,
 2790        cx: &mut Context<Self>,
 2791        callback: F,
 2792    ) -> Task<Result<T>>
 2793    where
 2794        T: 'static,
 2795        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2796    {
 2797        let project = self.project.read(cx);
 2798        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2799            Task::ready(Ok(callback(self, window, cx)))
 2800        } else {
 2801            let env = self.project.read(cx).cli_environment(cx);
 2802            let task = Self::new_local(
 2803                Vec::new(),
 2804                self.app_state.clone(),
 2805                None,
 2806                env,
 2807                None,
 2808                true,
 2809                cx,
 2810            );
 2811            cx.spawn_in(window, async move |_vh, cx| {
 2812                let (multi_workspace_window, _) = task.await?;
 2813                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2814                    let workspace = multi_workspace.workspace().clone();
 2815                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2816                })
 2817            })
 2818        }
 2819    }
 2820
 2821    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2822        self.project.read(cx).worktrees(cx)
 2823    }
 2824
 2825    pub fn visible_worktrees<'a>(
 2826        &self,
 2827        cx: &'a App,
 2828    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2829        self.project.read(cx).visible_worktrees(cx)
 2830    }
 2831
 2832    #[cfg(any(test, feature = "test-support"))]
 2833    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2834        let futures = self
 2835            .worktrees(cx)
 2836            .filter_map(|worktree| worktree.read(cx).as_local())
 2837            .map(|worktree| worktree.scan_complete())
 2838            .collect::<Vec<_>>();
 2839        async move {
 2840            for future in futures {
 2841                future.await;
 2842            }
 2843        }
 2844    }
 2845
 2846    pub fn close_global(cx: &mut App) {
 2847        cx.defer(|cx| {
 2848            cx.windows().iter().find(|window| {
 2849                window
 2850                    .update(cx, |_, window, _| {
 2851                        if window.is_window_active() {
 2852                            //This can only get called when the window's project connection has been lost
 2853                            //so we don't need to prompt the user for anything and instead just close the window
 2854                            window.remove_window();
 2855                            true
 2856                        } else {
 2857                            false
 2858                        }
 2859                    })
 2860                    .unwrap_or(false)
 2861            });
 2862        });
 2863    }
 2864
 2865    pub fn move_focused_panel_to_next_position(
 2866        &mut self,
 2867        _: &MoveFocusedPanelToNextPosition,
 2868        window: &mut Window,
 2869        cx: &mut Context<Self>,
 2870    ) {
 2871        let docks = self.all_docks();
 2872        let active_dock = docks
 2873            .into_iter()
 2874            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2875
 2876        if let Some(dock) = active_dock {
 2877            dock.update(cx, |dock, cx| {
 2878                let active_panel = dock
 2879                    .active_panel()
 2880                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2881
 2882                if let Some(panel) = active_panel {
 2883                    panel.move_to_next_position(window, cx);
 2884                }
 2885            })
 2886        }
 2887    }
 2888
 2889    pub fn prepare_to_close(
 2890        &mut self,
 2891        close_intent: CloseIntent,
 2892        window: &mut Window,
 2893        cx: &mut Context<Self>,
 2894    ) -> Task<Result<bool>> {
 2895        let active_call = self.active_global_call();
 2896
 2897        cx.spawn_in(window, async move |this, cx| {
 2898            this.update(cx, |this, _| {
 2899                if close_intent == CloseIntent::CloseWindow {
 2900                    this.removing = true;
 2901                }
 2902            })?;
 2903
 2904            let workspace_count = cx.update(|_window, cx| {
 2905                cx.windows()
 2906                    .iter()
 2907                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2908                    .count()
 2909            })?;
 2910
 2911            #[cfg(target_os = "macos")]
 2912            let save_last_workspace = false;
 2913
 2914            // On Linux and Windows, closing the last window should restore the last workspace.
 2915            #[cfg(not(target_os = "macos"))]
 2916            let save_last_workspace = {
 2917                let remaining_workspaces = cx.update(|_window, cx| {
 2918                    cx.windows()
 2919                        .iter()
 2920                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2921                        .filter_map(|multi_workspace| {
 2922                            multi_workspace
 2923                                .update(cx, |multi_workspace, _, cx| {
 2924                                    multi_workspace.workspace().read(cx).removing
 2925                                })
 2926                                .ok()
 2927                        })
 2928                        .filter(|removing| !removing)
 2929                        .count()
 2930                })?;
 2931
 2932                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2933            };
 2934
 2935            if let Some(active_call) = active_call
 2936                && workspace_count == 1
 2937                && cx
 2938                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2939                    .unwrap_or(false)
 2940            {
 2941                if close_intent == CloseIntent::CloseWindow {
 2942                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2943                    let answer = cx.update(|window, cx| {
 2944                        window.prompt(
 2945                            PromptLevel::Warning,
 2946                            "Do you want to leave the current call?",
 2947                            None,
 2948                            &["Close window and hang up", "Cancel"],
 2949                            cx,
 2950                        )
 2951                    })?;
 2952
 2953                    if answer.await.log_err() == Some(1) {
 2954                        return anyhow::Ok(false);
 2955                    } else {
 2956                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2957                            task.await.log_err();
 2958                        }
 2959                    }
 2960                }
 2961                if close_intent == CloseIntent::ReplaceWindow {
 2962                    _ = cx.update(|_window, cx| {
 2963                        let multi_workspace = cx
 2964                            .windows()
 2965                            .iter()
 2966                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2967                            .next()
 2968                            .unwrap();
 2969                        let project = multi_workspace
 2970                            .read(cx)?
 2971                            .workspace()
 2972                            .read(cx)
 2973                            .project
 2974                            .clone();
 2975                        if project.read(cx).is_shared() {
 2976                            active_call.0.unshare_project(project, cx)?;
 2977                        }
 2978                        Ok::<_, anyhow::Error>(())
 2979                    });
 2980                }
 2981            }
 2982
 2983            let save_result = this
 2984                .update_in(cx, |this, window, cx| {
 2985                    this.save_all_internal(SaveIntent::Close, window, cx)
 2986                })?
 2987                .await;
 2988
 2989            // If we're not quitting, but closing, we remove the workspace from
 2990            // the current session.
 2991            if close_intent != CloseIntent::Quit
 2992                && !save_last_workspace
 2993                && save_result.as_ref().is_ok_and(|&res| res)
 2994            {
 2995                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2996                    .await;
 2997            }
 2998
 2999            save_result
 3000        })
 3001    }
 3002
 3003    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3004        self.save_all_internal(
 3005            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3006            window,
 3007            cx,
 3008        )
 3009        .detach_and_log_err(cx);
 3010    }
 3011
 3012    fn send_keystrokes(
 3013        &mut self,
 3014        action: &SendKeystrokes,
 3015        window: &mut Window,
 3016        cx: &mut Context<Self>,
 3017    ) {
 3018        let keystrokes: Vec<Keystroke> = action
 3019            .0
 3020            .split(' ')
 3021            .flat_map(|k| Keystroke::parse(k).log_err())
 3022            .map(|k| {
 3023                cx.keyboard_mapper()
 3024                    .map_key_equivalent(k, false)
 3025                    .inner()
 3026                    .clone()
 3027            })
 3028            .collect();
 3029        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3030    }
 3031
 3032    pub fn send_keystrokes_impl(
 3033        &mut self,
 3034        keystrokes: Vec<Keystroke>,
 3035        window: &mut Window,
 3036        cx: &mut Context<Self>,
 3037    ) -> Shared<Task<()>> {
 3038        let mut state = self.dispatching_keystrokes.borrow_mut();
 3039        if !state.dispatched.insert(keystrokes.clone()) {
 3040            cx.propagate();
 3041            return state.task.clone().unwrap();
 3042        }
 3043
 3044        state.queue.extend(keystrokes);
 3045
 3046        let keystrokes = self.dispatching_keystrokes.clone();
 3047        if state.task.is_none() {
 3048            state.task = Some(
 3049                window
 3050                    .spawn(cx, async move |cx| {
 3051                        // limit to 100 keystrokes to avoid infinite recursion.
 3052                        for _ in 0..100 {
 3053                            let keystroke = {
 3054                                let mut state = keystrokes.borrow_mut();
 3055                                let Some(keystroke) = state.queue.pop_front() else {
 3056                                    state.dispatched.clear();
 3057                                    state.task.take();
 3058                                    return;
 3059                                };
 3060                                keystroke
 3061                            };
 3062                            cx.update(|window, cx| {
 3063                                let focused = window.focused(cx);
 3064                                window.dispatch_keystroke(keystroke.clone(), cx);
 3065                                if window.focused(cx) != focused {
 3066                                    // dispatch_keystroke may cause the focus to change.
 3067                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3068                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3069                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3070                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3071                                    // )
 3072                                    window.draw(cx).clear();
 3073                                }
 3074                            })
 3075                            .ok();
 3076
 3077                            // Yield between synthetic keystrokes so deferred focus and
 3078                            // other effects can settle before dispatching the next key.
 3079                            yield_now().await;
 3080                        }
 3081
 3082                        *keystrokes.borrow_mut() = Default::default();
 3083                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3084                    })
 3085                    .shared(),
 3086            );
 3087        }
 3088        state.task.clone().unwrap()
 3089    }
 3090
 3091    fn save_all_internal(
 3092        &mut self,
 3093        mut save_intent: SaveIntent,
 3094        window: &mut Window,
 3095        cx: &mut Context<Self>,
 3096    ) -> Task<Result<bool>> {
 3097        if self.project.read(cx).is_disconnected(cx) {
 3098            return Task::ready(Ok(true));
 3099        }
 3100        let dirty_items = self
 3101            .panes
 3102            .iter()
 3103            .flat_map(|pane| {
 3104                pane.read(cx).items().filter_map(|item| {
 3105                    if item.is_dirty(cx) {
 3106                        item.tab_content_text(0, cx);
 3107                        Some((pane.downgrade(), item.boxed_clone()))
 3108                    } else {
 3109                        None
 3110                    }
 3111                })
 3112            })
 3113            .collect::<Vec<_>>();
 3114
 3115        let project = self.project.clone();
 3116        cx.spawn_in(window, async move |workspace, cx| {
 3117            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3118                let (serialize_tasks, remaining_dirty_items) =
 3119                    workspace.update_in(cx, |workspace, window, cx| {
 3120                        let mut remaining_dirty_items = Vec::new();
 3121                        let mut serialize_tasks = Vec::new();
 3122                        for (pane, item) in dirty_items {
 3123                            if let Some(task) = item
 3124                                .to_serializable_item_handle(cx)
 3125                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3126                            {
 3127                                serialize_tasks.push(task);
 3128                            } else {
 3129                                remaining_dirty_items.push((pane, item));
 3130                            }
 3131                        }
 3132                        (serialize_tasks, remaining_dirty_items)
 3133                    })?;
 3134
 3135                futures::future::try_join_all(serialize_tasks).await?;
 3136
 3137                if !remaining_dirty_items.is_empty() {
 3138                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3139                }
 3140
 3141                if remaining_dirty_items.len() > 1 {
 3142                    let answer = workspace.update_in(cx, |_, window, cx| {
 3143                        let detail = Pane::file_names_for_prompt(
 3144                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3145                            cx,
 3146                        );
 3147                        window.prompt(
 3148                            PromptLevel::Warning,
 3149                            "Do you want to save all changes in the following files?",
 3150                            Some(&detail),
 3151                            &["Save all", "Discard all", "Cancel"],
 3152                            cx,
 3153                        )
 3154                    })?;
 3155                    match answer.await.log_err() {
 3156                        Some(0) => save_intent = SaveIntent::SaveAll,
 3157                        Some(1) => save_intent = SaveIntent::Skip,
 3158                        Some(2) => return Ok(false),
 3159                        _ => {}
 3160                    }
 3161                }
 3162
 3163                remaining_dirty_items
 3164            } else {
 3165                dirty_items
 3166            };
 3167
 3168            for (pane, item) in dirty_items {
 3169                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3170                    (
 3171                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3172                        item.project_entry_ids(cx),
 3173                    )
 3174                })?;
 3175                if (singleton || !project_entry_ids.is_empty())
 3176                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3177                {
 3178                    return Ok(false);
 3179                }
 3180            }
 3181            Ok(true)
 3182        })
 3183    }
 3184
 3185    pub fn open_workspace_for_paths(
 3186        &mut self,
 3187        replace_current_window: bool,
 3188        paths: Vec<PathBuf>,
 3189        window: &mut Window,
 3190        cx: &mut Context<Self>,
 3191    ) -> Task<Result<()>> {
 3192        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3193        let is_remote = self.project.read(cx).is_via_collab();
 3194        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3195        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3196
 3197        let window_to_replace = if replace_current_window {
 3198            window_handle
 3199        } else if is_remote || has_worktree || has_dirty_items {
 3200            None
 3201        } else {
 3202            window_handle
 3203        };
 3204        let app_state = self.app_state.clone();
 3205
 3206        cx.spawn(async move |_, cx| {
 3207            cx.update(|cx| {
 3208                open_paths(
 3209                    &paths,
 3210                    app_state,
 3211                    OpenOptions {
 3212                        replace_window: window_to_replace,
 3213                        ..Default::default()
 3214                    },
 3215                    cx,
 3216                )
 3217            })
 3218            .await?;
 3219            Ok(())
 3220        })
 3221    }
 3222
 3223    #[allow(clippy::type_complexity)]
 3224    pub fn open_paths(
 3225        &mut self,
 3226        mut abs_paths: Vec<PathBuf>,
 3227        options: OpenOptions,
 3228        pane: Option<WeakEntity<Pane>>,
 3229        window: &mut Window,
 3230        cx: &mut Context<Self>,
 3231    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3232        let fs = self.app_state.fs.clone();
 3233
 3234        let caller_ordered_abs_paths = abs_paths.clone();
 3235
 3236        // Sort the paths to ensure we add worktrees for parents before their children.
 3237        abs_paths.sort_unstable();
 3238        cx.spawn_in(window, async move |this, cx| {
 3239            let mut tasks = Vec::with_capacity(abs_paths.len());
 3240
 3241            for abs_path in &abs_paths {
 3242                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3243                    OpenVisible::All => Some(true),
 3244                    OpenVisible::None => Some(false),
 3245                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3246                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3247                        Some(None) => Some(true),
 3248                        None => None,
 3249                    },
 3250                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3251                        Some(Some(metadata)) => Some(metadata.is_dir),
 3252                        Some(None) => Some(false),
 3253                        None => None,
 3254                    },
 3255                };
 3256                let project_path = match visible {
 3257                    Some(visible) => match this
 3258                        .update(cx, |this, cx| {
 3259                            Workspace::project_path_for_path(
 3260                                this.project.clone(),
 3261                                abs_path,
 3262                                visible,
 3263                                cx,
 3264                            )
 3265                        })
 3266                        .log_err()
 3267                    {
 3268                        Some(project_path) => project_path.await.log_err(),
 3269                        None => None,
 3270                    },
 3271                    None => None,
 3272                };
 3273
 3274                let this = this.clone();
 3275                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3276                let fs = fs.clone();
 3277                let pane = pane.clone();
 3278                let task = cx.spawn(async move |cx| {
 3279                    let (_worktree, project_path) = project_path?;
 3280                    if fs.is_dir(&abs_path).await {
 3281                        // Opening a directory should not race to update the active entry.
 3282                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3283                        None
 3284                    } else {
 3285                        Some(
 3286                            this.update_in(cx, |this, window, cx| {
 3287                                this.open_path(
 3288                                    project_path,
 3289                                    pane,
 3290                                    options.focus.unwrap_or(true),
 3291                                    window,
 3292                                    cx,
 3293                                )
 3294                            })
 3295                            .ok()?
 3296                            .await,
 3297                        )
 3298                    }
 3299                });
 3300                tasks.push(task);
 3301            }
 3302
 3303            let results = futures::future::join_all(tasks).await;
 3304
 3305            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3306            let mut winner: Option<(PathBuf, bool)> = None;
 3307            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3308                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3309                    if !metadata.is_dir {
 3310                        winner = Some((abs_path, false));
 3311                        break;
 3312                    }
 3313                    if winner.is_none() {
 3314                        winner = Some((abs_path, true));
 3315                    }
 3316                } else if winner.is_none() {
 3317                    winner = Some((abs_path, false));
 3318                }
 3319            }
 3320
 3321            // Compute the winner entry id on the foreground thread and emit once, after all
 3322            // paths finish opening. This avoids races between concurrently-opening paths
 3323            // (directories in particular) and makes the resulting project panel selection
 3324            // deterministic.
 3325            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3326                'emit_winner: {
 3327                    let winner_abs_path: Arc<Path> =
 3328                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3329
 3330                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3331                        OpenVisible::All => true,
 3332                        OpenVisible::None => false,
 3333                        OpenVisible::OnlyFiles => !winner_is_dir,
 3334                        OpenVisible::OnlyDirectories => winner_is_dir,
 3335                    };
 3336
 3337                    let Some(worktree_task) = this
 3338                        .update(cx, |workspace, cx| {
 3339                            workspace.project.update(cx, |project, cx| {
 3340                                project.find_or_create_worktree(
 3341                                    winner_abs_path.as_ref(),
 3342                                    visible,
 3343                                    cx,
 3344                                )
 3345                            })
 3346                        })
 3347                        .ok()
 3348                    else {
 3349                        break 'emit_winner;
 3350                    };
 3351
 3352                    let Ok((worktree, _)) = worktree_task.await else {
 3353                        break 'emit_winner;
 3354                    };
 3355
 3356                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3357                        let worktree = worktree.read(cx);
 3358                        let worktree_abs_path = worktree.abs_path();
 3359                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3360                            worktree.root_entry()
 3361                        } else {
 3362                            winner_abs_path
 3363                                .strip_prefix(worktree_abs_path.as_ref())
 3364                                .ok()
 3365                                .and_then(|relative_path| {
 3366                                    let relative_path =
 3367                                        RelPath::new(relative_path, PathStyle::local())
 3368                                            .log_err()?;
 3369                                    worktree.entry_for_path(&relative_path)
 3370                                })
 3371                        }?;
 3372                        Some(entry.id)
 3373                    }) else {
 3374                        break 'emit_winner;
 3375                    };
 3376
 3377                    this.update(cx, |workspace, cx| {
 3378                        workspace.project.update(cx, |_, cx| {
 3379                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3380                        });
 3381                    })
 3382                    .ok();
 3383                }
 3384            }
 3385
 3386            results
 3387        })
 3388    }
 3389
 3390    pub fn open_resolved_path(
 3391        &mut self,
 3392        path: ResolvedPath,
 3393        window: &mut Window,
 3394        cx: &mut Context<Self>,
 3395    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3396        match path {
 3397            ResolvedPath::ProjectPath { project_path, .. } => {
 3398                self.open_path(project_path, None, true, window, cx)
 3399            }
 3400            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3401                PathBuf::from(path),
 3402                OpenOptions {
 3403                    visible: Some(OpenVisible::None),
 3404                    ..Default::default()
 3405                },
 3406                window,
 3407                cx,
 3408            ),
 3409        }
 3410    }
 3411
 3412    pub fn absolute_path_of_worktree(
 3413        &self,
 3414        worktree_id: WorktreeId,
 3415        cx: &mut Context<Self>,
 3416    ) -> Option<PathBuf> {
 3417        self.project
 3418            .read(cx)
 3419            .worktree_for_id(worktree_id, cx)
 3420            // TODO: use `abs_path` or `root_dir`
 3421            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3422    }
 3423
 3424    fn add_folder_to_project(
 3425        &mut self,
 3426        _: &AddFolderToProject,
 3427        window: &mut Window,
 3428        cx: &mut Context<Self>,
 3429    ) {
 3430        let project = self.project.read(cx);
 3431        if project.is_via_collab() {
 3432            self.show_error(
 3433                &anyhow!("You cannot add folders to someone else's project"),
 3434                cx,
 3435            );
 3436            return;
 3437        }
 3438        let paths = self.prompt_for_open_path(
 3439            PathPromptOptions {
 3440                files: false,
 3441                directories: true,
 3442                multiple: true,
 3443                prompt: None,
 3444            },
 3445            DirectoryLister::Project(self.project.clone()),
 3446            window,
 3447            cx,
 3448        );
 3449        cx.spawn_in(window, async move |this, cx| {
 3450            if let Some(paths) = paths.await.log_err().flatten() {
 3451                let results = this
 3452                    .update_in(cx, |this, window, cx| {
 3453                        this.open_paths(
 3454                            paths,
 3455                            OpenOptions {
 3456                                visible: Some(OpenVisible::All),
 3457                                ..Default::default()
 3458                            },
 3459                            None,
 3460                            window,
 3461                            cx,
 3462                        )
 3463                    })?
 3464                    .await;
 3465                for result in results.into_iter().flatten() {
 3466                    result.log_err();
 3467                }
 3468            }
 3469            anyhow::Ok(())
 3470        })
 3471        .detach_and_log_err(cx);
 3472    }
 3473
 3474    pub fn project_path_for_path(
 3475        project: Entity<Project>,
 3476        abs_path: &Path,
 3477        visible: bool,
 3478        cx: &mut App,
 3479    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3480        let entry = project.update(cx, |project, cx| {
 3481            project.find_or_create_worktree(abs_path, visible, cx)
 3482        });
 3483        cx.spawn(async move |cx| {
 3484            let (worktree, path) = entry.await?;
 3485            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3486            Ok((worktree, ProjectPath { worktree_id, path }))
 3487        })
 3488    }
 3489
 3490    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3491        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3492    }
 3493
 3494    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3495        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3496    }
 3497
 3498    pub fn items_of_type<'a, T: Item>(
 3499        &'a self,
 3500        cx: &'a App,
 3501    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3502        self.panes
 3503            .iter()
 3504            .flat_map(|pane| pane.read(cx).items_of_type())
 3505    }
 3506
 3507    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3508        self.active_pane().read(cx).active_item()
 3509    }
 3510
 3511    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3512        let item = self.active_item(cx)?;
 3513        item.to_any_view().downcast::<I>().ok()
 3514    }
 3515
 3516    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3517        self.active_item(cx).and_then(|item| item.project_path(cx))
 3518    }
 3519
 3520    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3521        self.recent_navigation_history_iter(cx)
 3522            .filter_map(|(path, abs_path)| {
 3523                let worktree = self
 3524                    .project
 3525                    .read(cx)
 3526                    .worktree_for_id(path.worktree_id, cx)?;
 3527                if worktree.read(cx).is_visible() {
 3528                    abs_path
 3529                } else {
 3530                    None
 3531                }
 3532            })
 3533            .next()
 3534    }
 3535
 3536    pub fn save_active_item(
 3537        &mut self,
 3538        save_intent: SaveIntent,
 3539        window: &mut Window,
 3540        cx: &mut App,
 3541    ) -> Task<Result<()>> {
 3542        let project = self.project.clone();
 3543        let pane = self.active_pane();
 3544        let item = pane.read(cx).active_item();
 3545        let pane = pane.downgrade();
 3546
 3547        window.spawn(cx, async move |cx| {
 3548            if let Some(item) = item {
 3549                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3550                    .await
 3551                    .map(|_| ())
 3552            } else {
 3553                Ok(())
 3554            }
 3555        })
 3556    }
 3557
 3558    pub fn close_inactive_items_and_panes(
 3559        &mut self,
 3560        action: &CloseInactiveTabsAndPanes,
 3561        window: &mut Window,
 3562        cx: &mut Context<Self>,
 3563    ) {
 3564        if let Some(task) = self.close_all_internal(
 3565            true,
 3566            action.save_intent.unwrap_or(SaveIntent::Close),
 3567            window,
 3568            cx,
 3569        ) {
 3570            task.detach_and_log_err(cx)
 3571        }
 3572    }
 3573
 3574    pub fn close_all_items_and_panes(
 3575        &mut self,
 3576        action: &CloseAllItemsAndPanes,
 3577        window: &mut Window,
 3578        cx: &mut Context<Self>,
 3579    ) {
 3580        if let Some(task) = self.close_all_internal(
 3581            false,
 3582            action.save_intent.unwrap_or(SaveIntent::Close),
 3583            window,
 3584            cx,
 3585        ) {
 3586            task.detach_and_log_err(cx)
 3587        }
 3588    }
 3589
 3590    /// Closes the active item across all panes.
 3591    pub fn close_item_in_all_panes(
 3592        &mut self,
 3593        action: &CloseItemInAllPanes,
 3594        window: &mut Window,
 3595        cx: &mut Context<Self>,
 3596    ) {
 3597        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3598            return;
 3599        };
 3600
 3601        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3602        let close_pinned = action.close_pinned;
 3603
 3604        if let Some(project_path) = active_item.project_path(cx) {
 3605            self.close_items_with_project_path(
 3606                &project_path,
 3607                save_intent,
 3608                close_pinned,
 3609                window,
 3610                cx,
 3611            );
 3612        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3613            let item_id = active_item.item_id();
 3614            self.active_pane().update(cx, |pane, cx| {
 3615                pane.close_item_by_id(item_id, save_intent, window, cx)
 3616                    .detach_and_log_err(cx);
 3617            });
 3618        }
 3619    }
 3620
 3621    /// Closes all items with the given project path across all panes.
 3622    pub fn close_items_with_project_path(
 3623        &mut self,
 3624        project_path: &ProjectPath,
 3625        save_intent: SaveIntent,
 3626        close_pinned: bool,
 3627        window: &mut Window,
 3628        cx: &mut Context<Self>,
 3629    ) {
 3630        let panes = self.panes().to_vec();
 3631        for pane in panes {
 3632            pane.update(cx, |pane, cx| {
 3633                pane.close_items_for_project_path(
 3634                    project_path,
 3635                    save_intent,
 3636                    close_pinned,
 3637                    window,
 3638                    cx,
 3639                )
 3640                .detach_and_log_err(cx);
 3641            });
 3642        }
 3643    }
 3644
 3645    fn close_all_internal(
 3646        &mut self,
 3647        retain_active_pane: bool,
 3648        save_intent: SaveIntent,
 3649        window: &mut Window,
 3650        cx: &mut Context<Self>,
 3651    ) -> Option<Task<Result<()>>> {
 3652        let current_pane = self.active_pane();
 3653
 3654        let mut tasks = Vec::new();
 3655
 3656        if retain_active_pane {
 3657            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3658                pane.close_other_items(
 3659                    &CloseOtherItems {
 3660                        save_intent: None,
 3661                        close_pinned: false,
 3662                    },
 3663                    None,
 3664                    window,
 3665                    cx,
 3666                )
 3667            });
 3668
 3669            tasks.push(current_pane_close);
 3670        }
 3671
 3672        for pane in self.panes() {
 3673            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3674                continue;
 3675            }
 3676
 3677            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3678                pane.close_all_items(
 3679                    &CloseAllItems {
 3680                        save_intent: Some(save_intent),
 3681                        close_pinned: false,
 3682                    },
 3683                    window,
 3684                    cx,
 3685                )
 3686            });
 3687
 3688            tasks.push(close_pane_items)
 3689        }
 3690
 3691        if tasks.is_empty() {
 3692            None
 3693        } else {
 3694            Some(cx.spawn_in(window, async move |_, _| {
 3695                for task in tasks {
 3696                    task.await?
 3697                }
 3698                Ok(())
 3699            }))
 3700        }
 3701    }
 3702
 3703    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3704        self.dock_at_position(position).read(cx).is_open()
 3705    }
 3706
 3707    pub fn toggle_dock(
 3708        &mut self,
 3709        dock_side: DockPosition,
 3710        window: &mut Window,
 3711        cx: &mut Context<Self>,
 3712    ) {
 3713        let mut focus_center = false;
 3714        let mut reveal_dock = false;
 3715
 3716        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3717        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3718
 3719        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3720            telemetry::event!(
 3721                "Panel Button Clicked",
 3722                name = panel.persistent_name(),
 3723                toggle_state = !was_visible
 3724            );
 3725        }
 3726        if was_visible {
 3727            self.save_open_dock_positions(cx);
 3728        }
 3729
 3730        let dock = self.dock_at_position(dock_side);
 3731        dock.update(cx, |dock, cx| {
 3732            dock.set_open(!was_visible, window, cx);
 3733
 3734            if dock.active_panel().is_none() {
 3735                let Some(panel_ix) = dock
 3736                    .first_enabled_panel_idx(cx)
 3737                    .log_with_level(log::Level::Info)
 3738                else {
 3739                    return;
 3740                };
 3741                dock.activate_panel(panel_ix, window, cx);
 3742            }
 3743
 3744            if let Some(active_panel) = dock.active_panel() {
 3745                if was_visible {
 3746                    if active_panel
 3747                        .panel_focus_handle(cx)
 3748                        .contains_focused(window, cx)
 3749                    {
 3750                        focus_center = true;
 3751                    }
 3752                } else {
 3753                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3754                    window.focus(focus_handle, cx);
 3755                    reveal_dock = true;
 3756                }
 3757            }
 3758        });
 3759
 3760        if reveal_dock {
 3761            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3762        }
 3763
 3764        if focus_center {
 3765            self.active_pane
 3766                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3767        }
 3768
 3769        cx.notify();
 3770        self.serialize_workspace(window, cx);
 3771    }
 3772
 3773    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3774        self.all_docks().into_iter().find(|&dock| {
 3775            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3776        })
 3777    }
 3778
 3779    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3780        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3781            self.save_open_dock_positions(cx);
 3782            dock.update(cx, |dock, cx| {
 3783                dock.set_open(false, window, cx);
 3784            });
 3785            return true;
 3786        }
 3787        false
 3788    }
 3789
 3790    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3791        self.save_open_dock_positions(cx);
 3792        for dock in self.all_docks() {
 3793            dock.update(cx, |dock, cx| {
 3794                dock.set_open(false, window, cx);
 3795            });
 3796        }
 3797
 3798        cx.focus_self(window);
 3799        cx.notify();
 3800        self.serialize_workspace(window, cx);
 3801    }
 3802
 3803    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3804        self.all_docks()
 3805            .into_iter()
 3806            .filter_map(|dock| {
 3807                let dock_ref = dock.read(cx);
 3808                if dock_ref.is_open() {
 3809                    Some(dock_ref.position())
 3810                } else {
 3811                    None
 3812                }
 3813            })
 3814            .collect()
 3815    }
 3816
 3817    /// Saves the positions of currently open docks.
 3818    ///
 3819    /// Updates `last_open_dock_positions` with positions of all currently open
 3820    /// docks, to later be restored by the 'Toggle All Docks' action.
 3821    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3822        let open_dock_positions = self.get_open_dock_positions(cx);
 3823        if !open_dock_positions.is_empty() {
 3824            self.last_open_dock_positions = open_dock_positions;
 3825        }
 3826    }
 3827
 3828    /// Toggles all docks between open and closed states.
 3829    ///
 3830    /// If any docks are open, closes all and remembers their positions. If all
 3831    /// docks are closed, restores the last remembered dock configuration.
 3832    fn toggle_all_docks(
 3833        &mut self,
 3834        _: &ToggleAllDocks,
 3835        window: &mut Window,
 3836        cx: &mut Context<Self>,
 3837    ) {
 3838        let open_dock_positions = self.get_open_dock_positions(cx);
 3839
 3840        if !open_dock_positions.is_empty() {
 3841            self.close_all_docks(window, cx);
 3842        } else if !self.last_open_dock_positions.is_empty() {
 3843            self.restore_last_open_docks(window, cx);
 3844        }
 3845    }
 3846
 3847    /// Reopens docks from the most recently remembered configuration.
 3848    ///
 3849    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3850    /// and clears the stored positions.
 3851    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3852        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3853
 3854        for position in positions_to_open {
 3855            let dock = self.dock_at_position(position);
 3856            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3857        }
 3858
 3859        cx.focus_self(window);
 3860        cx.notify();
 3861        self.serialize_workspace(window, cx);
 3862    }
 3863
 3864    /// Transfer focus to the panel of the given type.
 3865    pub fn focus_panel<T: Panel>(
 3866        &mut self,
 3867        window: &mut Window,
 3868        cx: &mut Context<Self>,
 3869    ) -> Option<Entity<T>> {
 3870        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3871        panel.to_any().downcast().ok()
 3872    }
 3873
 3874    /// Focus the panel of the given type if it isn't already focused. If it is
 3875    /// already focused, then transfer focus back to the workspace center.
 3876    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3877    /// panel when transferring focus back to the center.
 3878    pub fn toggle_panel_focus<T: Panel>(
 3879        &mut self,
 3880        window: &mut Window,
 3881        cx: &mut Context<Self>,
 3882    ) -> bool {
 3883        let mut did_focus_panel = false;
 3884        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3885            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3886            did_focus_panel
 3887        });
 3888
 3889        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3890            self.close_panel::<T>(window, cx);
 3891        }
 3892
 3893        telemetry::event!(
 3894            "Panel Button Clicked",
 3895            name = T::persistent_name(),
 3896            toggle_state = did_focus_panel
 3897        );
 3898
 3899        did_focus_panel
 3900    }
 3901
 3902    pub fn activate_panel_for_proto_id(
 3903        &mut self,
 3904        panel_id: PanelId,
 3905        window: &mut Window,
 3906        cx: &mut Context<Self>,
 3907    ) -> Option<Arc<dyn PanelHandle>> {
 3908        let mut panel = None;
 3909        for dock in self.all_docks() {
 3910            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3911                panel = dock.update(cx, |dock, cx| {
 3912                    dock.activate_panel(panel_index, window, cx);
 3913                    dock.set_open(true, window, cx);
 3914                    dock.active_panel().cloned()
 3915                });
 3916                break;
 3917            }
 3918        }
 3919
 3920        if panel.is_some() {
 3921            cx.notify();
 3922            self.serialize_workspace(window, cx);
 3923        }
 3924
 3925        panel
 3926    }
 3927
 3928    /// Focus or unfocus the given panel type, depending on the given callback.
 3929    fn focus_or_unfocus_panel<T: Panel>(
 3930        &mut self,
 3931        window: &mut Window,
 3932        cx: &mut Context<Self>,
 3933        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3934    ) -> Option<Arc<dyn PanelHandle>> {
 3935        let mut result_panel = None;
 3936        let mut serialize = false;
 3937        for dock in self.all_docks() {
 3938            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3939                let mut focus_center = false;
 3940                let panel = dock.update(cx, |dock, cx| {
 3941                    dock.activate_panel(panel_index, window, cx);
 3942
 3943                    let panel = dock.active_panel().cloned();
 3944                    if let Some(panel) = panel.as_ref() {
 3945                        if should_focus(&**panel, window, cx) {
 3946                            dock.set_open(true, window, cx);
 3947                            panel.panel_focus_handle(cx).focus(window, cx);
 3948                        } else {
 3949                            focus_center = true;
 3950                        }
 3951                    }
 3952                    panel
 3953                });
 3954
 3955                if focus_center {
 3956                    self.active_pane
 3957                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3958                }
 3959
 3960                result_panel = panel;
 3961                serialize = true;
 3962                break;
 3963            }
 3964        }
 3965
 3966        if serialize {
 3967            self.serialize_workspace(window, cx);
 3968        }
 3969
 3970        cx.notify();
 3971        result_panel
 3972    }
 3973
 3974    /// Open the panel of the given type
 3975    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3976        for dock in self.all_docks() {
 3977            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3978                dock.update(cx, |dock, cx| {
 3979                    dock.activate_panel(panel_index, window, cx);
 3980                    dock.set_open(true, window, cx);
 3981                });
 3982            }
 3983        }
 3984    }
 3985
 3986    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3987        for dock in self.all_docks().iter() {
 3988            dock.update(cx, |dock, cx| {
 3989                if dock.panel::<T>().is_some() {
 3990                    dock.set_open(false, window, cx)
 3991                }
 3992            })
 3993        }
 3994    }
 3995
 3996    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3997        self.all_docks()
 3998            .iter()
 3999            .find_map(|dock| dock.read(cx).panel::<T>())
 4000    }
 4001
 4002    fn dismiss_zoomed_items_to_reveal(
 4003        &mut self,
 4004        dock_to_reveal: Option<DockPosition>,
 4005        window: &mut Window,
 4006        cx: &mut Context<Self>,
 4007    ) {
 4008        // If a center pane is zoomed, unzoom it.
 4009        for pane in &self.panes {
 4010            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4011                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4012            }
 4013        }
 4014
 4015        // If another dock is zoomed, hide it.
 4016        let mut focus_center = false;
 4017        for dock in self.all_docks() {
 4018            dock.update(cx, |dock, cx| {
 4019                if Some(dock.position()) != dock_to_reveal
 4020                    && let Some(panel) = dock.active_panel()
 4021                    && panel.is_zoomed(window, cx)
 4022                {
 4023                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4024                    dock.set_open(false, window, cx);
 4025                }
 4026            });
 4027        }
 4028
 4029        if focus_center {
 4030            self.active_pane
 4031                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4032        }
 4033
 4034        if self.zoomed_position != dock_to_reveal {
 4035            self.zoomed = None;
 4036            self.zoomed_position = None;
 4037            cx.emit(Event::ZoomChanged);
 4038        }
 4039
 4040        cx.notify();
 4041    }
 4042
 4043    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4044        let pane = cx.new(|cx| {
 4045            let mut pane = Pane::new(
 4046                self.weak_handle(),
 4047                self.project.clone(),
 4048                self.pane_history_timestamp.clone(),
 4049                None,
 4050                NewFile.boxed_clone(),
 4051                true,
 4052                window,
 4053                cx,
 4054            );
 4055            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4056            pane
 4057        });
 4058        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4059            .detach();
 4060        self.panes.push(pane.clone());
 4061
 4062        window.focus(&pane.focus_handle(cx), cx);
 4063
 4064        cx.emit(Event::PaneAdded(pane.clone()));
 4065        pane
 4066    }
 4067
 4068    pub fn add_item_to_center(
 4069        &mut self,
 4070        item: Box<dyn ItemHandle>,
 4071        window: &mut Window,
 4072        cx: &mut Context<Self>,
 4073    ) -> bool {
 4074        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4075            if let Some(center_pane) = center_pane.upgrade() {
 4076                center_pane.update(cx, |pane, cx| {
 4077                    pane.add_item(item, true, true, None, window, cx)
 4078                });
 4079                true
 4080            } else {
 4081                false
 4082            }
 4083        } else {
 4084            false
 4085        }
 4086    }
 4087
 4088    pub fn add_item_to_active_pane(
 4089        &mut self,
 4090        item: Box<dyn ItemHandle>,
 4091        destination_index: Option<usize>,
 4092        focus_item: bool,
 4093        window: &mut Window,
 4094        cx: &mut App,
 4095    ) {
 4096        self.add_item(
 4097            self.active_pane.clone(),
 4098            item,
 4099            destination_index,
 4100            false,
 4101            focus_item,
 4102            window,
 4103            cx,
 4104        )
 4105    }
 4106
 4107    pub fn add_item(
 4108        &mut self,
 4109        pane: Entity<Pane>,
 4110        item: Box<dyn ItemHandle>,
 4111        destination_index: Option<usize>,
 4112        activate_pane: bool,
 4113        focus_item: bool,
 4114        window: &mut Window,
 4115        cx: &mut App,
 4116    ) {
 4117        pane.update(cx, |pane, cx| {
 4118            pane.add_item(
 4119                item,
 4120                activate_pane,
 4121                focus_item,
 4122                destination_index,
 4123                window,
 4124                cx,
 4125            )
 4126        });
 4127    }
 4128
 4129    pub fn split_item(
 4130        &mut self,
 4131        split_direction: SplitDirection,
 4132        item: Box<dyn ItemHandle>,
 4133        window: &mut Window,
 4134        cx: &mut Context<Self>,
 4135    ) {
 4136        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4137        self.add_item(new_pane, item, None, true, true, window, cx);
 4138    }
 4139
 4140    pub fn open_abs_path(
 4141        &mut self,
 4142        abs_path: PathBuf,
 4143        options: OpenOptions,
 4144        window: &mut Window,
 4145        cx: &mut Context<Self>,
 4146    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4147        cx.spawn_in(window, async move |workspace, cx| {
 4148            let open_paths_task_result = workspace
 4149                .update_in(cx, |workspace, window, cx| {
 4150                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4151                })
 4152                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4153                .await;
 4154            anyhow::ensure!(
 4155                open_paths_task_result.len() == 1,
 4156                "open abs path {abs_path:?} task returned incorrect number of results"
 4157            );
 4158            match open_paths_task_result
 4159                .into_iter()
 4160                .next()
 4161                .expect("ensured single task result")
 4162            {
 4163                Some(open_result) => {
 4164                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4165                }
 4166                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4167            }
 4168        })
 4169    }
 4170
 4171    pub fn split_abs_path(
 4172        &mut self,
 4173        abs_path: PathBuf,
 4174        visible: bool,
 4175        window: &mut Window,
 4176        cx: &mut Context<Self>,
 4177    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4178        let project_path_task =
 4179            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4180        cx.spawn_in(window, async move |this, cx| {
 4181            let (_, path) = project_path_task.await?;
 4182            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4183                .await
 4184        })
 4185    }
 4186
 4187    pub fn open_path(
 4188        &mut self,
 4189        path: impl Into<ProjectPath>,
 4190        pane: Option<WeakEntity<Pane>>,
 4191        focus_item: bool,
 4192        window: &mut Window,
 4193        cx: &mut App,
 4194    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4195        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4196    }
 4197
 4198    pub fn open_path_preview(
 4199        &mut self,
 4200        path: impl Into<ProjectPath>,
 4201        pane: Option<WeakEntity<Pane>>,
 4202        focus_item: bool,
 4203        allow_preview: bool,
 4204        activate: bool,
 4205        window: &mut Window,
 4206        cx: &mut App,
 4207    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4208        let pane = pane.unwrap_or_else(|| {
 4209            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4210                self.panes
 4211                    .first()
 4212                    .expect("There must be an active pane")
 4213                    .downgrade()
 4214            })
 4215        });
 4216
 4217        let project_path = path.into();
 4218        let task = self.load_path(project_path.clone(), window, cx);
 4219        window.spawn(cx, async move |cx| {
 4220            let (project_entry_id, build_item) = task.await?;
 4221
 4222            pane.update_in(cx, |pane, window, cx| {
 4223                pane.open_item(
 4224                    project_entry_id,
 4225                    project_path,
 4226                    focus_item,
 4227                    allow_preview,
 4228                    activate,
 4229                    None,
 4230                    window,
 4231                    cx,
 4232                    build_item,
 4233                )
 4234            })
 4235        })
 4236    }
 4237
 4238    pub fn split_path(
 4239        &mut self,
 4240        path: impl Into<ProjectPath>,
 4241        window: &mut Window,
 4242        cx: &mut Context<Self>,
 4243    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4244        self.split_path_preview(path, false, None, window, cx)
 4245    }
 4246
 4247    pub fn split_path_preview(
 4248        &mut self,
 4249        path: impl Into<ProjectPath>,
 4250        allow_preview: bool,
 4251        split_direction: Option<SplitDirection>,
 4252        window: &mut Window,
 4253        cx: &mut Context<Self>,
 4254    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4255        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4256            self.panes
 4257                .first()
 4258                .expect("There must be an active pane")
 4259                .downgrade()
 4260        });
 4261
 4262        if let Member::Pane(center_pane) = &self.center.root
 4263            && center_pane.read(cx).items_len() == 0
 4264        {
 4265            return self.open_path(path, Some(pane), true, window, cx);
 4266        }
 4267
 4268        let project_path = path.into();
 4269        let task = self.load_path(project_path.clone(), window, cx);
 4270        cx.spawn_in(window, async move |this, cx| {
 4271            let (project_entry_id, build_item) = task.await?;
 4272            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4273                let pane = pane.upgrade()?;
 4274                let new_pane = this.split_pane(
 4275                    pane,
 4276                    split_direction.unwrap_or(SplitDirection::Right),
 4277                    window,
 4278                    cx,
 4279                );
 4280                new_pane.update(cx, |new_pane, cx| {
 4281                    Some(new_pane.open_item(
 4282                        project_entry_id,
 4283                        project_path,
 4284                        true,
 4285                        allow_preview,
 4286                        true,
 4287                        None,
 4288                        window,
 4289                        cx,
 4290                        build_item,
 4291                    ))
 4292                })
 4293            })
 4294            .map(|option| option.context("pane was dropped"))?
 4295        })
 4296    }
 4297
 4298    fn load_path(
 4299        &mut self,
 4300        path: ProjectPath,
 4301        window: &mut Window,
 4302        cx: &mut App,
 4303    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4304        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4305        registry.open_path(self.project(), &path, window, cx)
 4306    }
 4307
 4308    pub fn find_project_item<T>(
 4309        &self,
 4310        pane: &Entity<Pane>,
 4311        project_item: &Entity<T::Item>,
 4312        cx: &App,
 4313    ) -> Option<Entity<T>>
 4314    where
 4315        T: ProjectItem,
 4316    {
 4317        use project::ProjectItem as _;
 4318        let project_item = project_item.read(cx);
 4319        let entry_id = project_item.entry_id(cx);
 4320        let project_path = project_item.project_path(cx);
 4321
 4322        let mut item = None;
 4323        if let Some(entry_id) = entry_id {
 4324            item = pane.read(cx).item_for_entry(entry_id, cx);
 4325        }
 4326        if item.is_none()
 4327            && let Some(project_path) = project_path
 4328        {
 4329            item = pane.read(cx).item_for_path(project_path, cx);
 4330        }
 4331
 4332        item.and_then(|item| item.downcast::<T>())
 4333    }
 4334
 4335    pub fn is_project_item_open<T>(
 4336        &self,
 4337        pane: &Entity<Pane>,
 4338        project_item: &Entity<T::Item>,
 4339        cx: &App,
 4340    ) -> bool
 4341    where
 4342        T: ProjectItem,
 4343    {
 4344        self.find_project_item::<T>(pane, project_item, cx)
 4345            .is_some()
 4346    }
 4347
 4348    pub fn open_project_item<T>(
 4349        &mut self,
 4350        pane: Entity<Pane>,
 4351        project_item: Entity<T::Item>,
 4352        activate_pane: bool,
 4353        focus_item: bool,
 4354        keep_old_preview: bool,
 4355        allow_new_preview: bool,
 4356        window: &mut Window,
 4357        cx: &mut Context<Self>,
 4358    ) -> Entity<T>
 4359    where
 4360        T: ProjectItem,
 4361    {
 4362        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4363
 4364        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4365            if !keep_old_preview
 4366                && let Some(old_id) = old_item_id
 4367                && old_id != item.item_id()
 4368            {
 4369                // switching to a different item, so unpreview old active item
 4370                pane.update(cx, |pane, _| {
 4371                    pane.unpreview_item_if_preview(old_id);
 4372                });
 4373            }
 4374
 4375            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4376            if !allow_new_preview {
 4377                pane.update(cx, |pane, _| {
 4378                    pane.unpreview_item_if_preview(item.item_id());
 4379                });
 4380            }
 4381            return item;
 4382        }
 4383
 4384        let item = pane.update(cx, |pane, cx| {
 4385            cx.new(|cx| {
 4386                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4387            })
 4388        });
 4389        let mut destination_index = None;
 4390        pane.update(cx, |pane, cx| {
 4391            if !keep_old_preview && let Some(old_id) = old_item_id {
 4392                pane.unpreview_item_if_preview(old_id);
 4393            }
 4394            if allow_new_preview {
 4395                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4396            }
 4397        });
 4398
 4399        self.add_item(
 4400            pane,
 4401            Box::new(item.clone()),
 4402            destination_index,
 4403            activate_pane,
 4404            focus_item,
 4405            window,
 4406            cx,
 4407        );
 4408        item
 4409    }
 4410
 4411    pub fn open_shared_screen(
 4412        &mut self,
 4413        peer_id: PeerId,
 4414        window: &mut Window,
 4415        cx: &mut Context<Self>,
 4416    ) {
 4417        if let Some(shared_screen) =
 4418            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4419        {
 4420            self.active_pane.update(cx, |pane, cx| {
 4421                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4422            });
 4423        }
 4424    }
 4425
 4426    pub fn activate_item(
 4427        &mut self,
 4428        item: &dyn ItemHandle,
 4429        activate_pane: bool,
 4430        focus_item: bool,
 4431        window: &mut Window,
 4432        cx: &mut App,
 4433    ) -> bool {
 4434        let result = self.panes.iter().find_map(|pane| {
 4435            pane.read(cx)
 4436                .index_for_item(item)
 4437                .map(|ix| (pane.clone(), ix))
 4438        });
 4439        if let Some((pane, ix)) = result {
 4440            pane.update(cx, |pane, cx| {
 4441                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4442            });
 4443            true
 4444        } else {
 4445            false
 4446        }
 4447    }
 4448
 4449    fn activate_pane_at_index(
 4450        &mut self,
 4451        action: &ActivatePane,
 4452        window: &mut Window,
 4453        cx: &mut Context<Self>,
 4454    ) {
 4455        let panes = self.center.panes();
 4456        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4457            window.focus(&pane.focus_handle(cx), cx);
 4458        } else {
 4459            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4460                .detach();
 4461        }
 4462    }
 4463
 4464    fn move_item_to_pane_at_index(
 4465        &mut self,
 4466        action: &MoveItemToPane,
 4467        window: &mut Window,
 4468        cx: &mut Context<Self>,
 4469    ) {
 4470        let panes = self.center.panes();
 4471        let destination = match panes.get(action.destination) {
 4472            Some(&destination) => destination.clone(),
 4473            None => {
 4474                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4475                    return;
 4476                }
 4477                let direction = SplitDirection::Right;
 4478                let split_off_pane = self
 4479                    .find_pane_in_direction(direction, cx)
 4480                    .unwrap_or_else(|| self.active_pane.clone());
 4481                let new_pane = self.add_pane(window, cx);
 4482                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4483                new_pane
 4484            }
 4485        };
 4486
 4487        if action.clone {
 4488            if self
 4489                .active_pane
 4490                .read(cx)
 4491                .active_item()
 4492                .is_some_and(|item| item.can_split(cx))
 4493            {
 4494                clone_active_item(
 4495                    self.database_id(),
 4496                    &self.active_pane,
 4497                    &destination,
 4498                    action.focus,
 4499                    window,
 4500                    cx,
 4501                );
 4502                return;
 4503            }
 4504        }
 4505        move_active_item(
 4506            &self.active_pane,
 4507            &destination,
 4508            action.focus,
 4509            true,
 4510            window,
 4511            cx,
 4512        )
 4513    }
 4514
 4515    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4516        let panes = self.center.panes();
 4517        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4518            let next_ix = (ix + 1) % panes.len();
 4519            let next_pane = panes[next_ix].clone();
 4520            window.focus(&next_pane.focus_handle(cx), cx);
 4521        }
 4522    }
 4523
 4524    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4525        let panes = self.center.panes();
 4526        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4527            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4528            let prev_pane = panes[prev_ix].clone();
 4529            window.focus(&prev_pane.focus_handle(cx), cx);
 4530        }
 4531    }
 4532
 4533    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4534        let last_pane = self.center.last_pane();
 4535        window.focus(&last_pane.focus_handle(cx), cx);
 4536    }
 4537
 4538    pub fn activate_pane_in_direction(
 4539        &mut self,
 4540        direction: SplitDirection,
 4541        window: &mut Window,
 4542        cx: &mut App,
 4543    ) {
 4544        use ActivateInDirectionTarget as Target;
 4545        enum Origin {
 4546            LeftDock,
 4547            RightDock,
 4548            BottomDock,
 4549            Center,
 4550        }
 4551
 4552        let origin: Origin = [
 4553            (&self.left_dock, Origin::LeftDock),
 4554            (&self.right_dock, Origin::RightDock),
 4555            (&self.bottom_dock, Origin::BottomDock),
 4556        ]
 4557        .into_iter()
 4558        .find_map(|(dock, origin)| {
 4559            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4560                Some(origin)
 4561            } else {
 4562                None
 4563            }
 4564        })
 4565        .unwrap_or(Origin::Center);
 4566
 4567        let get_last_active_pane = || {
 4568            let pane = self
 4569                .last_active_center_pane
 4570                .clone()
 4571                .unwrap_or_else(|| {
 4572                    self.panes
 4573                        .first()
 4574                        .expect("There must be an active pane")
 4575                        .downgrade()
 4576                })
 4577                .upgrade()?;
 4578            (pane.read(cx).items_len() != 0).then_some(pane)
 4579        };
 4580
 4581        let try_dock =
 4582            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4583
 4584        let target = match (origin, direction) {
 4585            // We're in the center, so we first try to go to a different pane,
 4586            // otherwise try to go to a dock.
 4587            (Origin::Center, direction) => {
 4588                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4589                    Some(Target::Pane(pane))
 4590                } else {
 4591                    match direction {
 4592                        SplitDirection::Up => None,
 4593                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4594                        SplitDirection::Left => try_dock(&self.left_dock),
 4595                        SplitDirection::Right => try_dock(&self.right_dock),
 4596                    }
 4597                }
 4598            }
 4599
 4600            (Origin::LeftDock, SplitDirection::Right) => {
 4601                if let Some(last_active_pane) = get_last_active_pane() {
 4602                    Some(Target::Pane(last_active_pane))
 4603                } else {
 4604                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4605                }
 4606            }
 4607
 4608            (Origin::LeftDock, SplitDirection::Down)
 4609            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4610
 4611            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4612            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4613            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4614
 4615            (Origin::RightDock, SplitDirection::Left) => {
 4616                if let Some(last_active_pane) = get_last_active_pane() {
 4617                    Some(Target::Pane(last_active_pane))
 4618                } else {
 4619                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4620                }
 4621            }
 4622
 4623            _ => None,
 4624        };
 4625
 4626        match target {
 4627            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4628                let pane = pane.read(cx);
 4629                if let Some(item) = pane.active_item() {
 4630                    item.item_focus_handle(cx).focus(window, cx);
 4631                } else {
 4632                    log::error!(
 4633                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4634                    );
 4635                }
 4636            }
 4637            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4638                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4639                window.defer(cx, move |window, cx| {
 4640                    let dock = dock.read(cx);
 4641                    if let Some(panel) = dock.active_panel() {
 4642                        panel.panel_focus_handle(cx).focus(window, cx);
 4643                    } else {
 4644                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4645                    }
 4646                })
 4647            }
 4648            None => {}
 4649        }
 4650    }
 4651
 4652    pub fn move_item_to_pane_in_direction(
 4653        &mut self,
 4654        action: &MoveItemToPaneInDirection,
 4655        window: &mut Window,
 4656        cx: &mut Context<Self>,
 4657    ) {
 4658        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4659            Some(destination) => destination,
 4660            None => {
 4661                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4662                    return;
 4663                }
 4664                let new_pane = self.add_pane(window, cx);
 4665                self.center
 4666                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4667                new_pane
 4668            }
 4669        };
 4670
 4671        if action.clone {
 4672            if self
 4673                .active_pane
 4674                .read(cx)
 4675                .active_item()
 4676                .is_some_and(|item| item.can_split(cx))
 4677            {
 4678                clone_active_item(
 4679                    self.database_id(),
 4680                    &self.active_pane,
 4681                    &destination,
 4682                    action.focus,
 4683                    window,
 4684                    cx,
 4685                );
 4686                return;
 4687            }
 4688        }
 4689        move_active_item(
 4690            &self.active_pane,
 4691            &destination,
 4692            action.focus,
 4693            true,
 4694            window,
 4695            cx,
 4696        );
 4697    }
 4698
 4699    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4700        self.center.bounding_box_for_pane(pane)
 4701    }
 4702
 4703    pub fn find_pane_in_direction(
 4704        &mut self,
 4705        direction: SplitDirection,
 4706        cx: &App,
 4707    ) -> Option<Entity<Pane>> {
 4708        self.center
 4709            .find_pane_in_direction(&self.active_pane, direction, cx)
 4710            .cloned()
 4711    }
 4712
 4713    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4714        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4715            self.center.swap(&self.active_pane, &to, cx);
 4716            cx.notify();
 4717        }
 4718    }
 4719
 4720    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4721        if self
 4722            .center
 4723            .move_to_border(&self.active_pane, direction, cx)
 4724            .unwrap()
 4725        {
 4726            cx.notify();
 4727        }
 4728    }
 4729
 4730    pub fn resize_pane(
 4731        &mut self,
 4732        axis: gpui::Axis,
 4733        amount: Pixels,
 4734        window: &mut Window,
 4735        cx: &mut Context<Self>,
 4736    ) {
 4737        let docks = self.all_docks();
 4738        let active_dock = docks
 4739            .into_iter()
 4740            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4741
 4742        if let Some(dock) = active_dock {
 4743            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4744                return;
 4745            };
 4746            match dock.read(cx).position() {
 4747                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4748                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4749                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4750            }
 4751        } else {
 4752            self.center
 4753                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4754        }
 4755        cx.notify();
 4756    }
 4757
 4758    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4759        self.center.reset_pane_sizes(cx);
 4760        cx.notify();
 4761    }
 4762
 4763    fn handle_pane_focused(
 4764        &mut self,
 4765        pane: Entity<Pane>,
 4766        window: &mut Window,
 4767        cx: &mut Context<Self>,
 4768    ) {
 4769        // This is explicitly hoisted out of the following check for pane identity as
 4770        // terminal panel panes are not registered as a center panes.
 4771        self.status_bar.update(cx, |status_bar, cx| {
 4772            status_bar.set_active_pane(&pane, window, cx);
 4773        });
 4774        if self.active_pane != pane {
 4775            self.set_active_pane(&pane, window, cx);
 4776        }
 4777
 4778        if self.last_active_center_pane.is_none() {
 4779            self.last_active_center_pane = Some(pane.downgrade());
 4780        }
 4781
 4782        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4783        // This prevents the dock from closing when focus events fire during window activation.
 4784        // We also preserve any dock whose active panel itself has focus — this covers
 4785        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4786        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4787            let dock_read = dock.read(cx);
 4788            if let Some(panel) = dock_read.active_panel() {
 4789                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4790                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4791                {
 4792                    return Some(dock_read.position());
 4793                }
 4794            }
 4795            None
 4796        });
 4797
 4798        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4799        if pane.read(cx).is_zoomed() {
 4800            self.zoomed = Some(pane.downgrade().into());
 4801        } else {
 4802            self.zoomed = None;
 4803        }
 4804        self.zoomed_position = None;
 4805        cx.emit(Event::ZoomChanged);
 4806        self.update_active_view_for_followers(window, cx);
 4807        pane.update(cx, |pane, _| {
 4808            pane.track_alternate_file_items();
 4809        });
 4810
 4811        cx.notify();
 4812    }
 4813
 4814    fn set_active_pane(
 4815        &mut self,
 4816        pane: &Entity<Pane>,
 4817        window: &mut Window,
 4818        cx: &mut Context<Self>,
 4819    ) {
 4820        self.active_pane = pane.clone();
 4821        self.active_item_path_changed(true, window, cx);
 4822        self.last_active_center_pane = Some(pane.downgrade());
 4823    }
 4824
 4825    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4826        self.update_active_view_for_followers(window, cx);
 4827    }
 4828
 4829    fn handle_pane_event(
 4830        &mut self,
 4831        pane: &Entity<Pane>,
 4832        event: &pane::Event,
 4833        window: &mut Window,
 4834        cx: &mut Context<Self>,
 4835    ) {
 4836        let mut serialize_workspace = true;
 4837        match event {
 4838            pane::Event::AddItem { item } => {
 4839                item.added_to_pane(self, pane.clone(), window, cx);
 4840                cx.emit(Event::ItemAdded {
 4841                    item: item.boxed_clone(),
 4842                });
 4843            }
 4844            pane::Event::Split { direction, mode } => {
 4845                match mode {
 4846                    SplitMode::ClonePane => {
 4847                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4848                            .detach();
 4849                    }
 4850                    SplitMode::EmptyPane => {
 4851                        self.split_pane(pane.clone(), *direction, window, cx);
 4852                    }
 4853                    SplitMode::MovePane => {
 4854                        self.split_and_move(pane.clone(), *direction, window, cx);
 4855                    }
 4856                };
 4857            }
 4858            pane::Event::JoinIntoNext => {
 4859                self.join_pane_into_next(pane.clone(), window, cx);
 4860            }
 4861            pane::Event::JoinAll => {
 4862                self.join_all_panes(window, cx);
 4863            }
 4864            pane::Event::Remove { focus_on_pane } => {
 4865                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4866            }
 4867            pane::Event::ActivateItem {
 4868                local,
 4869                focus_changed,
 4870            } => {
 4871                window.invalidate_character_coordinates();
 4872
 4873                pane.update(cx, |pane, _| {
 4874                    pane.track_alternate_file_items();
 4875                });
 4876                if *local {
 4877                    self.unfollow_in_pane(pane, window, cx);
 4878                }
 4879                serialize_workspace = *focus_changed || pane != self.active_pane();
 4880                if pane == self.active_pane() {
 4881                    self.active_item_path_changed(*focus_changed, window, cx);
 4882                    self.update_active_view_for_followers(window, cx);
 4883                } else if *local {
 4884                    self.set_active_pane(pane, window, cx);
 4885                }
 4886            }
 4887            pane::Event::UserSavedItem { item, save_intent } => {
 4888                cx.emit(Event::UserSavedItem {
 4889                    pane: pane.downgrade(),
 4890                    item: item.boxed_clone(),
 4891                    save_intent: *save_intent,
 4892                });
 4893                serialize_workspace = false;
 4894            }
 4895            pane::Event::ChangeItemTitle => {
 4896                if *pane == self.active_pane {
 4897                    self.active_item_path_changed(false, window, cx);
 4898                }
 4899                serialize_workspace = false;
 4900            }
 4901            pane::Event::RemovedItem { item } => {
 4902                cx.emit(Event::ActiveItemChanged);
 4903                self.update_window_edited(window, cx);
 4904                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4905                    && entry.get().entity_id() == pane.entity_id()
 4906                {
 4907                    entry.remove();
 4908                }
 4909                cx.emit(Event::ItemRemoved {
 4910                    item_id: item.item_id(),
 4911                });
 4912            }
 4913            pane::Event::Focus => {
 4914                window.invalidate_character_coordinates();
 4915                self.handle_pane_focused(pane.clone(), window, cx);
 4916            }
 4917            pane::Event::ZoomIn => {
 4918                if *pane == self.active_pane {
 4919                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4920                    if pane.read(cx).has_focus(window, cx) {
 4921                        self.zoomed = Some(pane.downgrade().into());
 4922                        self.zoomed_position = None;
 4923                        cx.emit(Event::ZoomChanged);
 4924                    }
 4925                    cx.notify();
 4926                }
 4927            }
 4928            pane::Event::ZoomOut => {
 4929                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4930                if self.zoomed_position.is_none() {
 4931                    self.zoomed = None;
 4932                    cx.emit(Event::ZoomChanged);
 4933                }
 4934                cx.notify();
 4935            }
 4936            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4937        }
 4938
 4939        if serialize_workspace {
 4940            self.serialize_workspace(window, cx);
 4941        }
 4942    }
 4943
 4944    pub fn unfollow_in_pane(
 4945        &mut self,
 4946        pane: &Entity<Pane>,
 4947        window: &mut Window,
 4948        cx: &mut Context<Workspace>,
 4949    ) -> Option<CollaboratorId> {
 4950        let leader_id = self.leader_for_pane(pane)?;
 4951        self.unfollow(leader_id, window, cx);
 4952        Some(leader_id)
 4953    }
 4954
 4955    pub fn split_pane(
 4956        &mut self,
 4957        pane_to_split: Entity<Pane>,
 4958        split_direction: SplitDirection,
 4959        window: &mut Window,
 4960        cx: &mut Context<Self>,
 4961    ) -> Entity<Pane> {
 4962        let new_pane = self.add_pane(window, cx);
 4963        self.center
 4964            .split(&pane_to_split, &new_pane, split_direction, cx);
 4965        cx.notify();
 4966        new_pane
 4967    }
 4968
 4969    pub fn split_and_move(
 4970        &mut self,
 4971        pane: Entity<Pane>,
 4972        direction: SplitDirection,
 4973        window: &mut Window,
 4974        cx: &mut Context<Self>,
 4975    ) {
 4976        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4977            return;
 4978        };
 4979        let new_pane = self.add_pane(window, cx);
 4980        new_pane.update(cx, |pane, cx| {
 4981            pane.add_item(item, true, true, None, window, cx)
 4982        });
 4983        self.center.split(&pane, &new_pane, direction, cx);
 4984        cx.notify();
 4985    }
 4986
 4987    pub fn split_and_clone(
 4988        &mut self,
 4989        pane: Entity<Pane>,
 4990        direction: SplitDirection,
 4991        window: &mut Window,
 4992        cx: &mut Context<Self>,
 4993    ) -> Task<Option<Entity<Pane>>> {
 4994        let Some(item) = pane.read(cx).active_item() else {
 4995            return Task::ready(None);
 4996        };
 4997        if !item.can_split(cx) {
 4998            return Task::ready(None);
 4999        }
 5000        let task = item.clone_on_split(self.database_id(), window, cx);
 5001        cx.spawn_in(window, async move |this, cx| {
 5002            if let Some(clone) = task.await {
 5003                this.update_in(cx, |this, window, cx| {
 5004                    let new_pane = this.add_pane(window, cx);
 5005                    let nav_history = pane.read(cx).fork_nav_history();
 5006                    new_pane.update(cx, |pane, cx| {
 5007                        pane.set_nav_history(nav_history, cx);
 5008                        pane.add_item(clone, true, true, None, window, cx)
 5009                    });
 5010                    this.center.split(&pane, &new_pane, direction, cx);
 5011                    cx.notify();
 5012                    new_pane
 5013                })
 5014                .ok()
 5015            } else {
 5016                None
 5017            }
 5018        })
 5019    }
 5020
 5021    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5022        let active_item = self.active_pane.read(cx).active_item();
 5023        for pane in &self.panes {
 5024            join_pane_into_active(&self.active_pane, pane, window, cx);
 5025        }
 5026        if let Some(active_item) = active_item {
 5027            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5028        }
 5029        cx.notify();
 5030    }
 5031
 5032    pub fn join_pane_into_next(
 5033        &mut self,
 5034        pane: Entity<Pane>,
 5035        window: &mut Window,
 5036        cx: &mut Context<Self>,
 5037    ) {
 5038        let next_pane = self
 5039            .find_pane_in_direction(SplitDirection::Right, cx)
 5040            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5041            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5042            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5043        let Some(next_pane) = next_pane else {
 5044            return;
 5045        };
 5046        move_all_items(&pane, &next_pane, window, cx);
 5047        cx.notify();
 5048    }
 5049
 5050    fn remove_pane(
 5051        &mut self,
 5052        pane: Entity<Pane>,
 5053        focus_on: Option<Entity<Pane>>,
 5054        window: &mut Window,
 5055        cx: &mut Context<Self>,
 5056    ) {
 5057        if self.center.remove(&pane, cx).unwrap() {
 5058            self.force_remove_pane(&pane, &focus_on, window, cx);
 5059            self.unfollow_in_pane(&pane, window, cx);
 5060            self.last_leaders_by_pane.remove(&pane.downgrade());
 5061            for removed_item in pane.read(cx).items() {
 5062                self.panes_by_item.remove(&removed_item.item_id());
 5063            }
 5064
 5065            cx.notify();
 5066        } else {
 5067            self.active_item_path_changed(true, window, cx);
 5068        }
 5069        cx.emit(Event::PaneRemoved);
 5070    }
 5071
 5072    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5073        &mut self.panes
 5074    }
 5075
 5076    pub fn panes(&self) -> &[Entity<Pane>] {
 5077        &self.panes
 5078    }
 5079
 5080    pub fn active_pane(&self) -> &Entity<Pane> {
 5081        &self.active_pane
 5082    }
 5083
 5084    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5085        for dock in self.all_docks() {
 5086            if dock.focus_handle(cx).contains_focused(window, cx)
 5087                && let Some(pane) = dock
 5088                    .read(cx)
 5089                    .active_panel()
 5090                    .and_then(|panel| panel.pane(cx))
 5091            {
 5092                return pane;
 5093            }
 5094        }
 5095        self.active_pane().clone()
 5096    }
 5097
 5098    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5099        self.find_pane_in_direction(SplitDirection::Right, cx)
 5100            .unwrap_or_else(|| {
 5101                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5102            })
 5103    }
 5104
 5105    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5106        self.pane_for_item_id(handle.item_id())
 5107    }
 5108
 5109    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5110        let weak_pane = self.panes_by_item.get(&item_id)?;
 5111        weak_pane.upgrade()
 5112    }
 5113
 5114    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5115        self.panes
 5116            .iter()
 5117            .find(|pane| pane.entity_id() == entity_id)
 5118            .cloned()
 5119    }
 5120
 5121    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5122        self.follower_states.retain(|leader_id, state| {
 5123            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5124                for item in state.items_by_leader_view_id.values() {
 5125                    item.view.set_leader_id(None, window, cx);
 5126                }
 5127                false
 5128            } else {
 5129                true
 5130            }
 5131        });
 5132        cx.notify();
 5133    }
 5134
 5135    pub fn start_following(
 5136        &mut self,
 5137        leader_id: impl Into<CollaboratorId>,
 5138        window: &mut Window,
 5139        cx: &mut Context<Self>,
 5140    ) -> Option<Task<Result<()>>> {
 5141        let leader_id = leader_id.into();
 5142        let pane = self.active_pane().clone();
 5143
 5144        self.last_leaders_by_pane
 5145            .insert(pane.downgrade(), leader_id);
 5146        self.unfollow(leader_id, window, cx);
 5147        self.unfollow_in_pane(&pane, window, cx);
 5148        self.follower_states.insert(
 5149            leader_id,
 5150            FollowerState {
 5151                center_pane: pane.clone(),
 5152                dock_pane: None,
 5153                active_view_id: None,
 5154                items_by_leader_view_id: Default::default(),
 5155            },
 5156        );
 5157        cx.notify();
 5158
 5159        match leader_id {
 5160            CollaboratorId::PeerId(leader_peer_id) => {
 5161                let room_id = self.active_call()?.room_id(cx)?;
 5162                let project_id = self.project.read(cx).remote_id();
 5163                let request = self.app_state.client.request(proto::Follow {
 5164                    room_id,
 5165                    project_id,
 5166                    leader_id: Some(leader_peer_id),
 5167                });
 5168
 5169                Some(cx.spawn_in(window, async move |this, cx| {
 5170                    let response = request.await?;
 5171                    this.update(cx, |this, _| {
 5172                        let state = this
 5173                            .follower_states
 5174                            .get_mut(&leader_id)
 5175                            .context("following interrupted")?;
 5176                        state.active_view_id = response
 5177                            .active_view
 5178                            .as_ref()
 5179                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5180                        anyhow::Ok(())
 5181                    })??;
 5182                    if let Some(view) = response.active_view {
 5183                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5184                    }
 5185                    this.update_in(cx, |this, window, cx| {
 5186                        this.leader_updated(leader_id, window, cx)
 5187                    })?;
 5188                    Ok(())
 5189                }))
 5190            }
 5191            CollaboratorId::Agent => {
 5192                self.leader_updated(leader_id, window, cx)?;
 5193                Some(Task::ready(Ok(())))
 5194            }
 5195        }
 5196    }
 5197
 5198    pub fn follow_next_collaborator(
 5199        &mut self,
 5200        _: &FollowNextCollaborator,
 5201        window: &mut Window,
 5202        cx: &mut Context<Self>,
 5203    ) {
 5204        let collaborators = self.project.read(cx).collaborators();
 5205        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5206            let mut collaborators = collaborators.keys().copied();
 5207            for peer_id in collaborators.by_ref() {
 5208                if CollaboratorId::PeerId(peer_id) == leader_id {
 5209                    break;
 5210                }
 5211            }
 5212            collaborators.next().map(CollaboratorId::PeerId)
 5213        } else if let Some(last_leader_id) =
 5214            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5215        {
 5216            match last_leader_id {
 5217                CollaboratorId::PeerId(peer_id) => {
 5218                    if collaborators.contains_key(peer_id) {
 5219                        Some(*last_leader_id)
 5220                    } else {
 5221                        None
 5222                    }
 5223                }
 5224                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5225            }
 5226        } else {
 5227            None
 5228        };
 5229
 5230        let pane = self.active_pane.clone();
 5231        let Some(leader_id) = next_leader_id.or_else(|| {
 5232            Some(CollaboratorId::PeerId(
 5233                collaborators.keys().copied().next()?,
 5234            ))
 5235        }) else {
 5236            return;
 5237        };
 5238        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5239            return;
 5240        }
 5241        if let Some(task) = self.start_following(leader_id, window, cx) {
 5242            task.detach_and_log_err(cx)
 5243        }
 5244    }
 5245
 5246    pub fn follow(
 5247        &mut self,
 5248        leader_id: impl Into<CollaboratorId>,
 5249        window: &mut Window,
 5250        cx: &mut Context<Self>,
 5251    ) {
 5252        let leader_id = leader_id.into();
 5253
 5254        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5255            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5256                return;
 5257            };
 5258            let Some(remote_participant) =
 5259                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5260            else {
 5261                return;
 5262            };
 5263
 5264            let project = self.project.read(cx);
 5265
 5266            let other_project_id = match remote_participant.location {
 5267                ParticipantLocation::External => None,
 5268                ParticipantLocation::UnsharedProject => None,
 5269                ParticipantLocation::SharedProject { project_id } => {
 5270                    if Some(project_id) == project.remote_id() {
 5271                        None
 5272                    } else {
 5273                        Some(project_id)
 5274                    }
 5275                }
 5276            };
 5277
 5278            // if they are active in another project, follow there.
 5279            if let Some(project_id) = other_project_id {
 5280                let app_state = self.app_state.clone();
 5281                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5282                    .detach_and_log_err(cx);
 5283            }
 5284        }
 5285
 5286        // if you're already following, find the right pane and focus it.
 5287        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5288            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5289
 5290            return;
 5291        }
 5292
 5293        // Otherwise, follow.
 5294        if let Some(task) = self.start_following(leader_id, window, cx) {
 5295            task.detach_and_log_err(cx)
 5296        }
 5297    }
 5298
 5299    pub fn unfollow(
 5300        &mut self,
 5301        leader_id: impl Into<CollaboratorId>,
 5302        window: &mut Window,
 5303        cx: &mut Context<Self>,
 5304    ) -> Option<()> {
 5305        cx.notify();
 5306
 5307        let leader_id = leader_id.into();
 5308        let state = self.follower_states.remove(&leader_id)?;
 5309        for (_, item) in state.items_by_leader_view_id {
 5310            item.view.set_leader_id(None, window, cx);
 5311        }
 5312
 5313        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5314            let project_id = self.project.read(cx).remote_id();
 5315            let room_id = self.active_call()?.room_id(cx)?;
 5316            self.app_state
 5317                .client
 5318                .send(proto::Unfollow {
 5319                    room_id,
 5320                    project_id,
 5321                    leader_id: Some(leader_peer_id),
 5322                })
 5323                .log_err();
 5324        }
 5325
 5326        Some(())
 5327    }
 5328
 5329    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5330        self.follower_states.contains_key(&id.into())
 5331    }
 5332
 5333    fn active_item_path_changed(
 5334        &mut self,
 5335        focus_changed: bool,
 5336        window: &mut Window,
 5337        cx: &mut Context<Self>,
 5338    ) {
 5339        cx.emit(Event::ActiveItemChanged);
 5340        let active_entry = self.active_project_path(cx);
 5341        self.project.update(cx, |project, cx| {
 5342            project.set_active_path(active_entry.clone(), cx)
 5343        });
 5344
 5345        if focus_changed && let Some(project_path) = &active_entry {
 5346            let git_store_entity = self.project.read(cx).git_store().clone();
 5347            git_store_entity.update(cx, |git_store, cx| {
 5348                git_store.set_active_repo_for_path(project_path, cx);
 5349            });
 5350        }
 5351
 5352        self.update_window_title(window, cx);
 5353    }
 5354
 5355    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5356        let project = self.project().read(cx);
 5357        let mut title = String::new();
 5358
 5359        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5360            let name = {
 5361                let settings_location = SettingsLocation {
 5362                    worktree_id: worktree.read(cx).id(),
 5363                    path: RelPath::empty(),
 5364                };
 5365
 5366                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5367                match &settings.project_name {
 5368                    Some(name) => name.as_str(),
 5369                    None => worktree.read(cx).root_name_str(),
 5370                }
 5371            };
 5372            if i > 0 {
 5373                title.push_str(", ");
 5374            }
 5375            title.push_str(name);
 5376        }
 5377
 5378        if title.is_empty() {
 5379            title = "empty project".to_string();
 5380        }
 5381
 5382        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5383            let filename = path.path.file_name().or_else(|| {
 5384                Some(
 5385                    project
 5386                        .worktree_for_id(path.worktree_id, cx)?
 5387                        .read(cx)
 5388                        .root_name_str(),
 5389                )
 5390            });
 5391
 5392            if let Some(filename) = filename {
 5393                title.push_str("");
 5394                title.push_str(filename.as_ref());
 5395            }
 5396        }
 5397
 5398        if project.is_via_collab() {
 5399            title.push_str("");
 5400        } else if project.is_shared() {
 5401            title.push_str("");
 5402        }
 5403
 5404        if let Some(last_title) = self.last_window_title.as_ref()
 5405            && &title == last_title
 5406        {
 5407            return;
 5408        }
 5409        window.set_window_title(&title);
 5410        SystemWindowTabController::update_tab_title(
 5411            cx,
 5412            window.window_handle().window_id(),
 5413            SharedString::from(&title),
 5414        );
 5415        self.last_window_title = Some(title);
 5416    }
 5417
 5418    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5419        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5420        if is_edited != self.window_edited {
 5421            self.window_edited = is_edited;
 5422            window.set_window_edited(self.window_edited)
 5423        }
 5424    }
 5425
 5426    fn update_item_dirty_state(
 5427        &mut self,
 5428        item: &dyn ItemHandle,
 5429        window: &mut Window,
 5430        cx: &mut App,
 5431    ) {
 5432        let is_dirty = item.is_dirty(cx);
 5433        let item_id = item.item_id();
 5434        let was_dirty = self.dirty_items.contains_key(&item_id);
 5435        if is_dirty == was_dirty {
 5436            return;
 5437        }
 5438        if was_dirty {
 5439            self.dirty_items.remove(&item_id);
 5440            self.update_window_edited(window, cx);
 5441            return;
 5442        }
 5443
 5444        let workspace = self.weak_handle();
 5445        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5446            return;
 5447        };
 5448        let on_release_callback = Box::new(move |cx: &mut App| {
 5449            window_handle
 5450                .update(cx, |_, window, cx| {
 5451                    workspace
 5452                        .update(cx, |workspace, cx| {
 5453                            workspace.dirty_items.remove(&item_id);
 5454                            workspace.update_window_edited(window, cx)
 5455                        })
 5456                        .ok();
 5457                })
 5458                .ok();
 5459        });
 5460
 5461        let s = item.on_release(cx, on_release_callback);
 5462        self.dirty_items.insert(item_id, s);
 5463        self.update_window_edited(window, cx);
 5464    }
 5465
 5466    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5467        if self.notifications.is_empty() {
 5468            None
 5469        } else {
 5470            Some(
 5471                div()
 5472                    .absolute()
 5473                    .right_3()
 5474                    .bottom_3()
 5475                    .w_112()
 5476                    .h_full()
 5477                    .flex()
 5478                    .flex_col()
 5479                    .justify_end()
 5480                    .gap_2()
 5481                    .children(
 5482                        self.notifications
 5483                            .iter()
 5484                            .map(|(_, notification)| notification.clone().into_any()),
 5485                    ),
 5486            )
 5487        }
 5488    }
 5489
 5490    // RPC handlers
 5491
 5492    fn active_view_for_follower(
 5493        &self,
 5494        follower_project_id: Option<u64>,
 5495        window: &mut Window,
 5496        cx: &mut Context<Self>,
 5497    ) -> Option<proto::View> {
 5498        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5499        let item = item?;
 5500        let leader_id = self
 5501            .pane_for(&*item)
 5502            .and_then(|pane| self.leader_for_pane(&pane));
 5503        let leader_peer_id = match leader_id {
 5504            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5505            Some(CollaboratorId::Agent) | None => None,
 5506        };
 5507
 5508        let item_handle = item.to_followable_item_handle(cx)?;
 5509        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5510        let variant = item_handle.to_state_proto(window, cx)?;
 5511
 5512        if item_handle.is_project_item(window, cx)
 5513            && (follower_project_id.is_none()
 5514                || follower_project_id != self.project.read(cx).remote_id())
 5515        {
 5516            return None;
 5517        }
 5518
 5519        Some(proto::View {
 5520            id: id.to_proto(),
 5521            leader_id: leader_peer_id,
 5522            variant: Some(variant),
 5523            panel_id: panel_id.map(|id| id as i32),
 5524        })
 5525    }
 5526
 5527    fn handle_follow(
 5528        &mut self,
 5529        follower_project_id: Option<u64>,
 5530        window: &mut Window,
 5531        cx: &mut Context<Self>,
 5532    ) -> proto::FollowResponse {
 5533        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5534
 5535        cx.notify();
 5536        proto::FollowResponse {
 5537            views: active_view.iter().cloned().collect(),
 5538            active_view,
 5539        }
 5540    }
 5541
 5542    fn handle_update_followers(
 5543        &mut self,
 5544        leader_id: PeerId,
 5545        message: proto::UpdateFollowers,
 5546        _window: &mut Window,
 5547        _cx: &mut Context<Self>,
 5548    ) {
 5549        self.leader_updates_tx
 5550            .unbounded_send((leader_id, message))
 5551            .ok();
 5552    }
 5553
 5554    async fn process_leader_update(
 5555        this: &WeakEntity<Self>,
 5556        leader_id: PeerId,
 5557        update: proto::UpdateFollowers,
 5558        cx: &mut AsyncWindowContext,
 5559    ) -> Result<()> {
 5560        match update.variant.context("invalid update")? {
 5561            proto::update_followers::Variant::CreateView(view) => {
 5562                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5563                let should_add_view = this.update(cx, |this, _| {
 5564                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5565                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5566                    } else {
 5567                        anyhow::Ok(false)
 5568                    }
 5569                })??;
 5570
 5571                if should_add_view {
 5572                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5573                }
 5574            }
 5575            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5576                let should_add_view = this.update(cx, |this, _| {
 5577                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5578                        state.active_view_id = update_active_view
 5579                            .view
 5580                            .as_ref()
 5581                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5582
 5583                        if state.active_view_id.is_some_and(|view_id| {
 5584                            !state.items_by_leader_view_id.contains_key(&view_id)
 5585                        }) {
 5586                            anyhow::Ok(true)
 5587                        } else {
 5588                            anyhow::Ok(false)
 5589                        }
 5590                    } else {
 5591                        anyhow::Ok(false)
 5592                    }
 5593                })??;
 5594
 5595                if should_add_view && let Some(view) = update_active_view.view {
 5596                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5597                }
 5598            }
 5599            proto::update_followers::Variant::UpdateView(update_view) => {
 5600                let variant = update_view.variant.context("missing update view variant")?;
 5601                let id = update_view.id.context("missing update view id")?;
 5602                let mut tasks = Vec::new();
 5603                this.update_in(cx, |this, window, cx| {
 5604                    let project = this.project.clone();
 5605                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5606                        let view_id = ViewId::from_proto(id.clone())?;
 5607                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5608                            tasks.push(item.view.apply_update_proto(
 5609                                &project,
 5610                                variant.clone(),
 5611                                window,
 5612                                cx,
 5613                            ));
 5614                        }
 5615                    }
 5616                    anyhow::Ok(())
 5617                })??;
 5618                try_join_all(tasks).await.log_err();
 5619            }
 5620        }
 5621        this.update_in(cx, |this, window, cx| {
 5622            this.leader_updated(leader_id, window, cx)
 5623        })?;
 5624        Ok(())
 5625    }
 5626
 5627    async fn add_view_from_leader(
 5628        this: WeakEntity<Self>,
 5629        leader_id: PeerId,
 5630        view: &proto::View,
 5631        cx: &mut AsyncWindowContext,
 5632    ) -> Result<()> {
 5633        let this = this.upgrade().context("workspace dropped")?;
 5634
 5635        let Some(id) = view.id.clone() else {
 5636            anyhow::bail!("no id for view");
 5637        };
 5638        let id = ViewId::from_proto(id)?;
 5639        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5640
 5641        let pane = this.update(cx, |this, _cx| {
 5642            let state = this
 5643                .follower_states
 5644                .get(&leader_id.into())
 5645                .context("stopped following")?;
 5646            anyhow::Ok(state.pane().clone())
 5647        })?;
 5648        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5649            let client = this.read(cx).client().clone();
 5650            pane.items().find_map(|item| {
 5651                let item = item.to_followable_item_handle(cx)?;
 5652                if item.remote_id(&client, window, cx) == Some(id) {
 5653                    Some(item)
 5654                } else {
 5655                    None
 5656                }
 5657            })
 5658        })?;
 5659        let item = if let Some(existing_item) = existing_item {
 5660            existing_item
 5661        } else {
 5662            let variant = view.variant.clone();
 5663            anyhow::ensure!(variant.is_some(), "missing view variant");
 5664
 5665            let task = cx.update(|window, cx| {
 5666                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5667            })?;
 5668
 5669            let Some(task) = task else {
 5670                anyhow::bail!(
 5671                    "failed to construct view from leader (maybe from a different version of zed?)"
 5672                );
 5673            };
 5674
 5675            let mut new_item = task.await?;
 5676            pane.update_in(cx, |pane, window, cx| {
 5677                let mut item_to_remove = None;
 5678                for (ix, item) in pane.items().enumerate() {
 5679                    if let Some(item) = item.to_followable_item_handle(cx) {
 5680                        match new_item.dedup(item.as_ref(), window, cx) {
 5681                            Some(item::Dedup::KeepExisting) => {
 5682                                new_item =
 5683                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5684                                break;
 5685                            }
 5686                            Some(item::Dedup::ReplaceExisting) => {
 5687                                item_to_remove = Some((ix, item.item_id()));
 5688                                break;
 5689                            }
 5690                            None => {}
 5691                        }
 5692                    }
 5693                }
 5694
 5695                if let Some((ix, id)) = item_to_remove {
 5696                    pane.remove_item(id, false, false, window, cx);
 5697                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5698                }
 5699            })?;
 5700
 5701            new_item
 5702        };
 5703
 5704        this.update_in(cx, |this, window, cx| {
 5705            let state = this.follower_states.get_mut(&leader_id.into())?;
 5706            item.set_leader_id(Some(leader_id.into()), window, cx);
 5707            state.items_by_leader_view_id.insert(
 5708                id,
 5709                FollowerView {
 5710                    view: item,
 5711                    location: panel_id,
 5712                },
 5713            );
 5714
 5715            Some(())
 5716        })
 5717        .context("no follower state")?;
 5718
 5719        Ok(())
 5720    }
 5721
 5722    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5723        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5724            return;
 5725        };
 5726
 5727        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5728            let buffer_entity_id = agent_location.buffer.entity_id();
 5729            let view_id = ViewId {
 5730                creator: CollaboratorId::Agent,
 5731                id: buffer_entity_id.as_u64(),
 5732            };
 5733            follower_state.active_view_id = Some(view_id);
 5734
 5735            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5736                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5737                hash_map::Entry::Vacant(entry) => {
 5738                    let existing_view =
 5739                        follower_state
 5740                            .center_pane
 5741                            .read(cx)
 5742                            .items()
 5743                            .find_map(|item| {
 5744                                let item = item.to_followable_item_handle(cx)?;
 5745                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5746                                    && item.project_item_model_ids(cx).as_slice()
 5747                                        == [buffer_entity_id]
 5748                                {
 5749                                    Some(item)
 5750                                } else {
 5751                                    None
 5752                                }
 5753                            });
 5754                    let view = existing_view.or_else(|| {
 5755                        agent_location.buffer.upgrade().and_then(|buffer| {
 5756                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5757                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5758                            })?
 5759                            .to_followable_item_handle(cx)
 5760                        })
 5761                    });
 5762
 5763                    view.map(|view| {
 5764                        entry.insert(FollowerView {
 5765                            view,
 5766                            location: None,
 5767                        })
 5768                    })
 5769                }
 5770            };
 5771
 5772            if let Some(item) = item {
 5773                item.view
 5774                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5775                item.view
 5776                    .update_agent_location(agent_location.position, window, cx);
 5777            }
 5778        } else {
 5779            follower_state.active_view_id = None;
 5780        }
 5781
 5782        self.leader_updated(CollaboratorId::Agent, window, cx);
 5783    }
 5784
 5785    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5786        let mut is_project_item = true;
 5787        let mut update = proto::UpdateActiveView::default();
 5788        if window.is_window_active() {
 5789            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5790
 5791            if let Some(item) = active_item
 5792                && item.item_focus_handle(cx).contains_focused(window, cx)
 5793            {
 5794                let leader_id = self
 5795                    .pane_for(&*item)
 5796                    .and_then(|pane| self.leader_for_pane(&pane));
 5797                let leader_peer_id = match leader_id {
 5798                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5799                    Some(CollaboratorId::Agent) | None => None,
 5800                };
 5801
 5802                if let Some(item) = item.to_followable_item_handle(cx) {
 5803                    let id = item
 5804                        .remote_id(&self.app_state.client, window, cx)
 5805                        .map(|id| id.to_proto());
 5806
 5807                    if let Some(id) = id
 5808                        && let Some(variant) = item.to_state_proto(window, cx)
 5809                    {
 5810                        let view = Some(proto::View {
 5811                            id,
 5812                            leader_id: leader_peer_id,
 5813                            variant: Some(variant),
 5814                            panel_id: panel_id.map(|id| id as i32),
 5815                        });
 5816
 5817                        is_project_item = item.is_project_item(window, cx);
 5818                        update = proto::UpdateActiveView { view };
 5819                    };
 5820                }
 5821            }
 5822        }
 5823
 5824        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5825        if active_view_id != self.last_active_view_id.as_ref() {
 5826            self.last_active_view_id = active_view_id.cloned();
 5827            self.update_followers(
 5828                is_project_item,
 5829                proto::update_followers::Variant::UpdateActiveView(update),
 5830                window,
 5831                cx,
 5832            );
 5833        }
 5834    }
 5835
 5836    fn active_item_for_followers(
 5837        &self,
 5838        window: &mut Window,
 5839        cx: &mut App,
 5840    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5841        let mut active_item = None;
 5842        let mut panel_id = None;
 5843        for dock in self.all_docks() {
 5844            if dock.focus_handle(cx).contains_focused(window, cx)
 5845                && let Some(panel) = dock.read(cx).active_panel()
 5846                && let Some(pane) = panel.pane(cx)
 5847                && let Some(item) = pane.read(cx).active_item()
 5848            {
 5849                active_item = Some(item);
 5850                panel_id = panel.remote_id();
 5851                break;
 5852            }
 5853        }
 5854
 5855        if active_item.is_none() {
 5856            active_item = self.active_pane().read(cx).active_item();
 5857        }
 5858        (active_item, panel_id)
 5859    }
 5860
 5861    fn update_followers(
 5862        &self,
 5863        project_only: bool,
 5864        update: proto::update_followers::Variant,
 5865        _: &mut Window,
 5866        cx: &mut App,
 5867    ) -> Option<()> {
 5868        // If this update only applies to for followers in the current project,
 5869        // then skip it unless this project is shared. If it applies to all
 5870        // followers, regardless of project, then set `project_id` to none,
 5871        // indicating that it goes to all followers.
 5872        let project_id = if project_only {
 5873            Some(self.project.read(cx).remote_id()?)
 5874        } else {
 5875            None
 5876        };
 5877        self.app_state().workspace_store.update(cx, |store, cx| {
 5878            store.update_followers(project_id, update, cx)
 5879        })
 5880    }
 5881
 5882    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5883        self.follower_states.iter().find_map(|(leader_id, state)| {
 5884            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5885                Some(*leader_id)
 5886            } else {
 5887                None
 5888            }
 5889        })
 5890    }
 5891
 5892    fn leader_updated(
 5893        &mut self,
 5894        leader_id: impl Into<CollaboratorId>,
 5895        window: &mut Window,
 5896        cx: &mut Context<Self>,
 5897    ) -> Option<Box<dyn ItemHandle>> {
 5898        cx.notify();
 5899
 5900        let leader_id = leader_id.into();
 5901        let (panel_id, item) = match leader_id {
 5902            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5903            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5904        };
 5905
 5906        let state = self.follower_states.get(&leader_id)?;
 5907        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5908        let pane;
 5909        if let Some(panel_id) = panel_id {
 5910            pane = self
 5911                .activate_panel_for_proto_id(panel_id, window, cx)?
 5912                .pane(cx)?;
 5913            let state = self.follower_states.get_mut(&leader_id)?;
 5914            state.dock_pane = Some(pane.clone());
 5915        } else {
 5916            pane = state.center_pane.clone();
 5917            let state = self.follower_states.get_mut(&leader_id)?;
 5918            if let Some(dock_pane) = state.dock_pane.take() {
 5919                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5920            }
 5921        }
 5922
 5923        pane.update(cx, |pane, cx| {
 5924            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5925            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5926                pane.activate_item(index, false, false, window, cx);
 5927            } else {
 5928                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5929            }
 5930
 5931            if focus_active_item {
 5932                pane.focus_active_item(window, cx)
 5933            }
 5934        });
 5935
 5936        Some(item)
 5937    }
 5938
 5939    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5940        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5941        let active_view_id = state.active_view_id?;
 5942        Some(
 5943            state
 5944                .items_by_leader_view_id
 5945                .get(&active_view_id)?
 5946                .view
 5947                .boxed_clone(),
 5948        )
 5949    }
 5950
 5951    fn active_item_for_peer(
 5952        &self,
 5953        peer_id: PeerId,
 5954        window: &mut Window,
 5955        cx: &mut Context<Self>,
 5956    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5957        let call = self.active_call()?;
 5958        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5959        let leader_in_this_app;
 5960        let leader_in_this_project;
 5961        match participant.location {
 5962            ParticipantLocation::SharedProject { project_id } => {
 5963                leader_in_this_app = true;
 5964                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5965            }
 5966            ParticipantLocation::UnsharedProject => {
 5967                leader_in_this_app = true;
 5968                leader_in_this_project = false;
 5969            }
 5970            ParticipantLocation::External => {
 5971                leader_in_this_app = false;
 5972                leader_in_this_project = false;
 5973            }
 5974        };
 5975        let state = self.follower_states.get(&peer_id.into())?;
 5976        let mut item_to_activate = None;
 5977        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5978            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5979                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5980            {
 5981                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5982            }
 5983        } else if let Some(shared_screen) =
 5984            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5985        {
 5986            item_to_activate = Some((None, Box::new(shared_screen)));
 5987        }
 5988        item_to_activate
 5989    }
 5990
 5991    fn shared_screen_for_peer(
 5992        &self,
 5993        peer_id: PeerId,
 5994        pane: &Entity<Pane>,
 5995        window: &mut Window,
 5996        cx: &mut App,
 5997    ) -> Option<Entity<SharedScreen>> {
 5998        self.active_call()?
 5999            .create_shared_screen(peer_id, pane, window, cx)
 6000    }
 6001
 6002    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6003        if window.is_window_active() {
 6004            self.update_active_view_for_followers(window, cx);
 6005
 6006            if let Some(database_id) = self.database_id {
 6007                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 6008                    .detach();
 6009            }
 6010        } else {
 6011            for pane in &self.panes {
 6012                pane.update(cx, |pane, cx| {
 6013                    if let Some(item) = pane.active_item() {
 6014                        item.workspace_deactivated(window, cx);
 6015                    }
 6016                    for item in pane.items() {
 6017                        if matches!(
 6018                            item.workspace_settings(cx).autosave,
 6019                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6020                        ) {
 6021                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6022                                .detach_and_log_err(cx);
 6023                        }
 6024                    }
 6025                });
 6026            }
 6027        }
 6028    }
 6029
 6030    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6031        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6032    }
 6033
 6034    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6035        self.active_call.as_ref().map(|(call, _)| call.clone())
 6036    }
 6037
 6038    fn on_active_call_event(
 6039        &mut self,
 6040        event: &ActiveCallEvent,
 6041        window: &mut Window,
 6042        cx: &mut Context<Self>,
 6043    ) {
 6044        match event {
 6045            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6046            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6047                self.leader_updated(participant_id, window, cx);
 6048            }
 6049        }
 6050    }
 6051
 6052    pub fn database_id(&self) -> Option<WorkspaceId> {
 6053        self.database_id
 6054    }
 6055
 6056    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6057        self.database_id = Some(id);
 6058    }
 6059
 6060    pub fn session_id(&self) -> Option<String> {
 6061        self.session_id.clone()
 6062    }
 6063
 6064    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6065        let Some(display) = window.display(cx) else {
 6066            return Task::ready(());
 6067        };
 6068        let Ok(display_uuid) = display.uuid() else {
 6069            return Task::ready(());
 6070        };
 6071
 6072        let window_bounds = window.inner_window_bounds();
 6073        let database_id = self.database_id;
 6074        let has_paths = !self.root_paths(cx).is_empty();
 6075
 6076        cx.background_executor().spawn(async move {
 6077            if !has_paths {
 6078                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6079                    .await
 6080                    .log_err();
 6081            }
 6082            if let Some(database_id) = database_id {
 6083                DB.set_window_open_status(
 6084                    database_id,
 6085                    SerializedWindowBounds(window_bounds),
 6086                    display_uuid,
 6087                )
 6088                .await
 6089                .log_err();
 6090            } else {
 6091                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6092                    .await
 6093                    .log_err();
 6094            }
 6095        })
 6096    }
 6097
 6098    /// Bypass the 200ms serialization throttle and write workspace state to
 6099    /// the DB immediately. Returns a task the caller can await to ensure the
 6100    /// write completes. Used by the quit handler so the most recent state
 6101    /// isn't lost to a pending throttle timer when the process exits.
 6102    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6103        self._schedule_serialize_workspace.take();
 6104        self._serialize_workspace_task.take();
 6105        self.bounds_save_task_queued.take();
 6106
 6107        let bounds_task = self.save_window_bounds(window, cx);
 6108        let serialize_task = self.serialize_workspace_internal(window, cx);
 6109        cx.spawn(async move |_| {
 6110            bounds_task.await;
 6111            serialize_task.await;
 6112        })
 6113    }
 6114
 6115    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6116        let project = self.project().read(cx);
 6117        project
 6118            .visible_worktrees(cx)
 6119            .map(|worktree| worktree.read(cx).abs_path())
 6120            .collect::<Vec<_>>()
 6121    }
 6122
 6123    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6124        match member {
 6125            Member::Axis(PaneAxis { members, .. }) => {
 6126                for child in members.iter() {
 6127                    self.remove_panes(child.clone(), window, cx)
 6128                }
 6129            }
 6130            Member::Pane(pane) => {
 6131                self.force_remove_pane(&pane, &None, window, cx);
 6132            }
 6133        }
 6134    }
 6135
 6136    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6137        self.session_id.take();
 6138        self.serialize_workspace_internal(window, cx)
 6139    }
 6140
 6141    fn force_remove_pane(
 6142        &mut self,
 6143        pane: &Entity<Pane>,
 6144        focus_on: &Option<Entity<Pane>>,
 6145        window: &mut Window,
 6146        cx: &mut Context<Workspace>,
 6147    ) {
 6148        self.panes.retain(|p| p != pane);
 6149        if let Some(focus_on) = focus_on {
 6150            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6151        } else if self.active_pane() == pane {
 6152            self.panes
 6153                .last()
 6154                .unwrap()
 6155                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6156        }
 6157        if self.last_active_center_pane == Some(pane.downgrade()) {
 6158            self.last_active_center_pane = None;
 6159        }
 6160        cx.notify();
 6161    }
 6162
 6163    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6164        if self._schedule_serialize_workspace.is_none() {
 6165            self._schedule_serialize_workspace =
 6166                Some(cx.spawn_in(window, async move |this, cx| {
 6167                    cx.background_executor()
 6168                        .timer(SERIALIZATION_THROTTLE_TIME)
 6169                        .await;
 6170                    this.update_in(cx, |this, window, cx| {
 6171                        this._serialize_workspace_task =
 6172                            Some(this.serialize_workspace_internal(window, cx));
 6173                        this._schedule_serialize_workspace.take();
 6174                    })
 6175                    .log_err();
 6176                }));
 6177        }
 6178    }
 6179
 6180    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6181        let Some(database_id) = self.database_id() else {
 6182            return Task::ready(());
 6183        };
 6184
 6185        fn serialize_pane_handle(
 6186            pane_handle: &Entity<Pane>,
 6187            window: &mut Window,
 6188            cx: &mut App,
 6189        ) -> SerializedPane {
 6190            let (items, active, pinned_count) = {
 6191                let pane = pane_handle.read(cx);
 6192                let active_item_id = pane.active_item().map(|item| item.item_id());
 6193                (
 6194                    pane.items()
 6195                        .filter_map(|handle| {
 6196                            let handle = handle.to_serializable_item_handle(cx)?;
 6197
 6198                            Some(SerializedItem {
 6199                                kind: Arc::from(handle.serialized_item_kind()),
 6200                                item_id: handle.item_id().as_u64(),
 6201                                active: Some(handle.item_id()) == active_item_id,
 6202                                preview: pane.is_active_preview_item(handle.item_id()),
 6203                            })
 6204                        })
 6205                        .collect::<Vec<_>>(),
 6206                    pane.has_focus(window, cx),
 6207                    pane.pinned_count(),
 6208                )
 6209            };
 6210
 6211            SerializedPane::new(items, active, pinned_count)
 6212        }
 6213
 6214        fn build_serialized_pane_group(
 6215            pane_group: &Member,
 6216            window: &mut Window,
 6217            cx: &mut App,
 6218        ) -> SerializedPaneGroup {
 6219            match pane_group {
 6220                Member::Axis(PaneAxis {
 6221                    axis,
 6222                    members,
 6223                    flexes,
 6224                    bounding_boxes: _,
 6225                }) => SerializedPaneGroup::Group {
 6226                    axis: SerializedAxis(*axis),
 6227                    children: members
 6228                        .iter()
 6229                        .map(|member| build_serialized_pane_group(member, window, cx))
 6230                        .collect::<Vec<_>>(),
 6231                    flexes: Some(flexes.lock().clone()),
 6232                },
 6233                Member::Pane(pane_handle) => {
 6234                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6235                }
 6236            }
 6237        }
 6238
 6239        fn build_serialized_docks(
 6240            this: &Workspace,
 6241            window: &mut Window,
 6242            cx: &mut App,
 6243        ) -> DockStructure {
 6244            this.capture_dock_state(window, cx)
 6245        }
 6246
 6247        match self.workspace_location(cx) {
 6248            WorkspaceLocation::Location(location, paths) => {
 6249                let breakpoints = self.project.update(cx, |project, cx| {
 6250                    project
 6251                        .breakpoint_store()
 6252                        .read(cx)
 6253                        .all_source_breakpoints(cx)
 6254                });
 6255                let user_toolchains = self
 6256                    .project
 6257                    .read(cx)
 6258                    .user_toolchains(cx)
 6259                    .unwrap_or_default();
 6260
 6261                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6262                let docks = build_serialized_docks(self, window, cx);
 6263                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6264
 6265                let serialized_workspace = SerializedWorkspace {
 6266                    id: database_id,
 6267                    location,
 6268                    paths,
 6269                    center_group,
 6270                    window_bounds,
 6271                    display: Default::default(),
 6272                    docks,
 6273                    centered_layout: self.centered_layout,
 6274                    session_id: self.session_id.clone(),
 6275                    breakpoints,
 6276                    window_id: Some(window.window_handle().window_id().as_u64()),
 6277                    user_toolchains,
 6278                };
 6279
 6280                window.spawn(cx, async move |_| {
 6281                    persistence::DB.save_workspace(serialized_workspace).await;
 6282                })
 6283            }
 6284            WorkspaceLocation::DetachFromSession => {
 6285                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6286                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6287                // Save dock state for empty local workspaces
 6288                let docks = build_serialized_docks(self, window, cx);
 6289                window.spawn(cx, async move |_| {
 6290                    persistence::DB
 6291                        .set_window_open_status(
 6292                            database_id,
 6293                            window_bounds,
 6294                            display.unwrap_or_default(),
 6295                        )
 6296                        .await
 6297                        .log_err();
 6298                    persistence::DB
 6299                        .set_session_id(database_id, None)
 6300                        .await
 6301                        .log_err();
 6302                    persistence::write_default_dock_state(docks).await.log_err();
 6303                })
 6304            }
 6305            WorkspaceLocation::None => {
 6306                // Save dock state for empty non-local workspaces
 6307                let docks = build_serialized_docks(self, window, cx);
 6308                window.spawn(cx, async move |_| {
 6309                    persistence::write_default_dock_state(docks).await.log_err();
 6310                })
 6311            }
 6312        }
 6313    }
 6314
 6315    fn has_any_items_open(&self, cx: &App) -> bool {
 6316        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6317    }
 6318
 6319    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6320        let paths = PathList::new(&self.root_paths(cx));
 6321        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6322            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6323        } else if self.project.read(cx).is_local() {
 6324            if !paths.is_empty() || self.has_any_items_open(cx) {
 6325                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6326            } else {
 6327                WorkspaceLocation::DetachFromSession
 6328            }
 6329        } else {
 6330            WorkspaceLocation::None
 6331        }
 6332    }
 6333
 6334    fn update_history(&self, cx: &mut App) {
 6335        let Some(id) = self.database_id() else {
 6336            return;
 6337        };
 6338        if !self.project.read(cx).is_local() {
 6339            return;
 6340        }
 6341        if let Some(manager) = HistoryManager::global(cx) {
 6342            let paths = PathList::new(&self.root_paths(cx));
 6343            manager.update(cx, |this, cx| {
 6344                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6345            });
 6346        }
 6347    }
 6348
 6349    async fn serialize_items(
 6350        this: &WeakEntity<Self>,
 6351        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6352        cx: &mut AsyncWindowContext,
 6353    ) -> Result<()> {
 6354        const CHUNK_SIZE: usize = 200;
 6355
 6356        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6357
 6358        while let Some(items_received) = serializable_items.next().await {
 6359            let unique_items =
 6360                items_received
 6361                    .into_iter()
 6362                    .fold(HashMap::default(), |mut acc, item| {
 6363                        acc.entry(item.item_id()).or_insert(item);
 6364                        acc
 6365                    });
 6366
 6367            // We use into_iter() here so that the references to the items are moved into
 6368            // the tasks and not kept alive while we're sleeping.
 6369            for (_, item) in unique_items.into_iter() {
 6370                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6371                    item.serialize(workspace, false, window, cx)
 6372                }) {
 6373                    cx.background_spawn(async move { task.await.log_err() })
 6374                        .detach();
 6375                }
 6376            }
 6377
 6378            cx.background_executor()
 6379                .timer(SERIALIZATION_THROTTLE_TIME)
 6380                .await;
 6381        }
 6382
 6383        Ok(())
 6384    }
 6385
 6386    pub(crate) fn enqueue_item_serialization(
 6387        &mut self,
 6388        item: Box<dyn SerializableItemHandle>,
 6389    ) -> Result<()> {
 6390        self.serializable_items_tx
 6391            .unbounded_send(item)
 6392            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6393    }
 6394
 6395    pub(crate) fn load_workspace(
 6396        serialized_workspace: SerializedWorkspace,
 6397        paths_to_open: Vec<Option<ProjectPath>>,
 6398        window: &mut Window,
 6399        cx: &mut Context<Workspace>,
 6400    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6401        cx.spawn_in(window, async move |workspace, cx| {
 6402            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6403
 6404            let mut center_group = None;
 6405            let mut center_items = None;
 6406
 6407            // Traverse the splits tree and add to things
 6408            if let Some((group, active_pane, items)) = serialized_workspace
 6409                .center_group
 6410                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6411                .await
 6412            {
 6413                center_items = Some(items);
 6414                center_group = Some((group, active_pane))
 6415            }
 6416
 6417            let mut items_by_project_path = HashMap::default();
 6418            let mut item_ids_by_kind = HashMap::default();
 6419            let mut all_deserialized_items = Vec::default();
 6420            cx.update(|_, cx| {
 6421                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6422                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6423                        item_ids_by_kind
 6424                            .entry(serializable_item_handle.serialized_item_kind())
 6425                            .or_insert(Vec::new())
 6426                            .push(item.item_id().as_u64() as ItemId);
 6427                    }
 6428
 6429                    if let Some(project_path) = item.project_path(cx) {
 6430                        items_by_project_path.insert(project_path, item.clone());
 6431                    }
 6432                    all_deserialized_items.push(item);
 6433                }
 6434            })?;
 6435
 6436            let opened_items = paths_to_open
 6437                .into_iter()
 6438                .map(|path_to_open| {
 6439                    path_to_open
 6440                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6441                })
 6442                .collect::<Vec<_>>();
 6443
 6444            // Remove old panes from workspace panes list
 6445            workspace.update_in(cx, |workspace, window, cx| {
 6446                if let Some((center_group, active_pane)) = center_group {
 6447                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6448
 6449                    // Swap workspace center group
 6450                    workspace.center = PaneGroup::with_root(center_group);
 6451                    workspace.center.set_is_center(true);
 6452                    workspace.center.mark_positions(cx);
 6453
 6454                    if let Some(active_pane) = active_pane {
 6455                        workspace.set_active_pane(&active_pane, window, cx);
 6456                        cx.focus_self(window);
 6457                    } else {
 6458                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6459                    }
 6460                }
 6461
 6462                let docks = serialized_workspace.docks;
 6463
 6464                for (dock, serialized_dock) in [
 6465                    (&mut workspace.right_dock, docks.right),
 6466                    (&mut workspace.left_dock, docks.left),
 6467                    (&mut workspace.bottom_dock, docks.bottom),
 6468                ]
 6469                .iter_mut()
 6470                {
 6471                    dock.update(cx, |dock, cx| {
 6472                        dock.serialized_dock = Some(serialized_dock.clone());
 6473                        dock.restore_state(window, cx);
 6474                    });
 6475                }
 6476
 6477                cx.notify();
 6478            })?;
 6479
 6480            let _ = project
 6481                .update(cx, |project, cx| {
 6482                    project
 6483                        .breakpoint_store()
 6484                        .update(cx, |breakpoint_store, cx| {
 6485                            breakpoint_store
 6486                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6487                        })
 6488                })
 6489                .await;
 6490
 6491            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6492            // after loading the items, we might have different items and in order to avoid
 6493            // the database filling up, we delete items that haven't been loaded now.
 6494            //
 6495            // The items that have been loaded, have been saved after they've been added to the workspace.
 6496            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6497                item_ids_by_kind
 6498                    .into_iter()
 6499                    .map(|(item_kind, loaded_items)| {
 6500                        SerializableItemRegistry::cleanup(
 6501                            item_kind,
 6502                            serialized_workspace.id,
 6503                            loaded_items,
 6504                            window,
 6505                            cx,
 6506                        )
 6507                        .log_err()
 6508                    })
 6509                    .collect::<Vec<_>>()
 6510            })?;
 6511
 6512            futures::future::join_all(clean_up_tasks).await;
 6513
 6514            workspace
 6515                .update_in(cx, |workspace, window, cx| {
 6516                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6517                    workspace.serialize_workspace_internal(window, cx).detach();
 6518
 6519                    // Ensure that we mark the window as edited if we did load dirty items
 6520                    workspace.update_window_edited(window, cx);
 6521                })
 6522                .ok();
 6523
 6524            Ok(opened_items)
 6525        })
 6526    }
 6527
 6528    pub fn key_context(&self, cx: &App) -> KeyContext {
 6529        let mut context = KeyContext::new_with_defaults();
 6530        context.add("Workspace");
 6531        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6532        if let Some(status) = self
 6533            .debugger_provider
 6534            .as_ref()
 6535            .and_then(|provider| provider.active_thread_state(cx))
 6536        {
 6537            match status {
 6538                ThreadStatus::Running | ThreadStatus::Stepping => {
 6539                    context.add("debugger_running");
 6540                }
 6541                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6542                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6543            }
 6544        }
 6545
 6546        if self.left_dock.read(cx).is_open() {
 6547            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6548                context.set("left_dock", active_panel.panel_key());
 6549            }
 6550        }
 6551
 6552        if self.right_dock.read(cx).is_open() {
 6553            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6554                context.set("right_dock", active_panel.panel_key());
 6555            }
 6556        }
 6557
 6558        if self.bottom_dock.read(cx).is_open() {
 6559            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6560                context.set("bottom_dock", active_panel.panel_key());
 6561            }
 6562        }
 6563
 6564        context
 6565    }
 6566
 6567    /// Multiworkspace uses this to add workspace action handling to itself
 6568    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6569        self.add_workspace_actions_listeners(div, window, cx)
 6570            .on_action(cx.listener(
 6571                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6572                    for action in &action_sequence.0 {
 6573                        window.dispatch_action(action.boxed_clone(), cx);
 6574                    }
 6575                },
 6576            ))
 6577            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6578            .on_action(cx.listener(Self::close_all_items_and_panes))
 6579            .on_action(cx.listener(Self::close_item_in_all_panes))
 6580            .on_action(cx.listener(Self::save_all))
 6581            .on_action(cx.listener(Self::send_keystrokes))
 6582            .on_action(cx.listener(Self::add_folder_to_project))
 6583            .on_action(cx.listener(Self::follow_next_collaborator))
 6584            .on_action(cx.listener(Self::activate_pane_at_index))
 6585            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6586            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6587            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6588            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6589                let pane = workspace.active_pane().clone();
 6590                workspace.unfollow_in_pane(&pane, window, cx);
 6591            }))
 6592            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6593                workspace
 6594                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6595                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6596            }))
 6597            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6598                workspace
 6599                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6600                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6601            }))
 6602            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6603                workspace
 6604                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6605                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6606            }))
 6607            .on_action(
 6608                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6609                    workspace.activate_previous_pane(window, cx)
 6610                }),
 6611            )
 6612            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6613                workspace.activate_next_pane(window, cx)
 6614            }))
 6615            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6616                workspace.activate_last_pane(window, cx)
 6617            }))
 6618            .on_action(
 6619                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6620                    workspace.activate_next_window(cx)
 6621                }),
 6622            )
 6623            .on_action(
 6624                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6625                    workspace.activate_previous_window(cx)
 6626                }),
 6627            )
 6628            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6629                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6630            }))
 6631            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6632                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6633            }))
 6634            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6635                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6636            }))
 6637            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6638                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6639            }))
 6640            .on_action(cx.listener(
 6641                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6642                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6643                },
 6644            ))
 6645            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6646                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6647            }))
 6648            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6649                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6650            }))
 6651            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6652                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6653            }))
 6654            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6655                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6656            }))
 6657            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6658                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6659                    SplitDirection::Down,
 6660                    SplitDirection::Up,
 6661                    SplitDirection::Right,
 6662                    SplitDirection::Left,
 6663                ];
 6664                for dir in DIRECTION_PRIORITY {
 6665                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6666                        workspace.swap_pane_in_direction(dir, cx);
 6667                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6668                        break;
 6669                    }
 6670                }
 6671            }))
 6672            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6673                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6674            }))
 6675            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6676                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6677            }))
 6678            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6679                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6680            }))
 6681            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6682                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6683            }))
 6684            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6685                this.toggle_dock(DockPosition::Left, window, cx);
 6686            }))
 6687            .on_action(cx.listener(
 6688                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6689                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6690                },
 6691            ))
 6692            .on_action(cx.listener(
 6693                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6694                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6695                },
 6696            ))
 6697            .on_action(cx.listener(
 6698                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6699                    if !workspace.close_active_dock(window, cx) {
 6700                        cx.propagate();
 6701                    }
 6702                },
 6703            ))
 6704            .on_action(
 6705                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6706                    workspace.close_all_docks(window, cx);
 6707                }),
 6708            )
 6709            .on_action(cx.listener(Self::toggle_all_docks))
 6710            .on_action(cx.listener(
 6711                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6712                    workspace.clear_all_notifications(cx);
 6713                },
 6714            ))
 6715            .on_action(cx.listener(
 6716                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6717                    workspace.clear_navigation_history(window, cx);
 6718                },
 6719            ))
 6720            .on_action(cx.listener(
 6721                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6722                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6723                        workspace.suppress_notification(&notification_id, cx);
 6724                    }
 6725                },
 6726            ))
 6727            .on_action(cx.listener(
 6728                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6729                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6730                },
 6731            ))
 6732            .on_action(
 6733                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6734                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6735                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6736                            trusted_worktrees.clear_trusted_paths()
 6737                        });
 6738                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6739                        cx.spawn(async move |_, cx| {
 6740                            if clear_task.await.log_err().is_some() {
 6741                                cx.update(|cx| reload(cx));
 6742                            }
 6743                        })
 6744                        .detach();
 6745                    }
 6746                }),
 6747            )
 6748            .on_action(cx.listener(
 6749                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6750                    workspace.reopen_closed_item(window, cx).detach();
 6751                },
 6752            ))
 6753            .on_action(cx.listener(
 6754                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6755                    for dock in workspace.all_docks() {
 6756                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6757                            let Some(panel) = dock.read(cx).active_panel() else {
 6758                                return;
 6759                            };
 6760
 6761                            // Set to `None`, then the size will fall back to the default.
 6762                            panel.clone().set_size(None, window, cx);
 6763
 6764                            return;
 6765                        }
 6766                    }
 6767                },
 6768            ))
 6769            .on_action(cx.listener(
 6770                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6771                    for dock in workspace.all_docks() {
 6772                        if let Some(panel) = dock.read(cx).visible_panel() {
 6773                            // Set to `None`, then the size will fall back to the default.
 6774                            panel.clone().set_size(None, window, cx);
 6775                        }
 6776                    }
 6777                },
 6778            ))
 6779            .on_action(cx.listener(
 6780                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6781                    adjust_active_dock_size_by_px(
 6782                        px_with_ui_font_fallback(act.px, cx),
 6783                        workspace,
 6784                        window,
 6785                        cx,
 6786                    );
 6787                },
 6788            ))
 6789            .on_action(cx.listener(
 6790                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6791                    adjust_active_dock_size_by_px(
 6792                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6793                        workspace,
 6794                        window,
 6795                        cx,
 6796                    );
 6797                },
 6798            ))
 6799            .on_action(cx.listener(
 6800                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6801                    adjust_open_docks_size_by_px(
 6802                        px_with_ui_font_fallback(act.px, cx),
 6803                        workspace,
 6804                        window,
 6805                        cx,
 6806                    );
 6807                },
 6808            ))
 6809            .on_action(cx.listener(
 6810                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6811                    adjust_open_docks_size_by_px(
 6812                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6813                        workspace,
 6814                        window,
 6815                        cx,
 6816                    );
 6817                },
 6818            ))
 6819            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6820            .on_action(cx.listener(
 6821                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6822                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6823                        let dock = active_dock.read(cx);
 6824                        if let Some(active_panel) = dock.active_panel() {
 6825                            if active_panel.pane(cx).is_none() {
 6826                                let mut recent_pane: Option<Entity<Pane>> = None;
 6827                                let mut recent_timestamp = 0;
 6828                                for pane_handle in workspace.panes() {
 6829                                    let pane = pane_handle.read(cx);
 6830                                    for entry in pane.activation_history() {
 6831                                        if entry.timestamp > recent_timestamp {
 6832                                            recent_timestamp = entry.timestamp;
 6833                                            recent_pane = Some(pane_handle.clone());
 6834                                        }
 6835                                    }
 6836                                }
 6837
 6838                                if let Some(pane) = recent_pane {
 6839                                    pane.update(cx, |pane, cx| {
 6840                                        let current_index = pane.active_item_index();
 6841                                        let items_len = pane.items_len();
 6842                                        if items_len > 0 {
 6843                                            let next_index = if current_index + 1 < items_len {
 6844                                                current_index + 1
 6845                                            } else {
 6846                                                0
 6847                                            };
 6848                                            pane.activate_item(
 6849                                                next_index, false, false, window, cx,
 6850                                            );
 6851                                        }
 6852                                    });
 6853                                    return;
 6854                                }
 6855                            }
 6856                        }
 6857                    }
 6858                    cx.propagate();
 6859                },
 6860            ))
 6861            .on_action(cx.listener(
 6862                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6863                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6864                        let dock = active_dock.read(cx);
 6865                        if let Some(active_panel) = dock.active_panel() {
 6866                            if active_panel.pane(cx).is_none() {
 6867                                let mut recent_pane: Option<Entity<Pane>> = None;
 6868                                let mut recent_timestamp = 0;
 6869                                for pane_handle in workspace.panes() {
 6870                                    let pane = pane_handle.read(cx);
 6871                                    for entry in pane.activation_history() {
 6872                                        if entry.timestamp > recent_timestamp {
 6873                                            recent_timestamp = entry.timestamp;
 6874                                            recent_pane = Some(pane_handle.clone());
 6875                                        }
 6876                                    }
 6877                                }
 6878
 6879                                if let Some(pane) = recent_pane {
 6880                                    pane.update(cx, |pane, cx| {
 6881                                        let current_index = pane.active_item_index();
 6882                                        let items_len = pane.items_len();
 6883                                        if items_len > 0 {
 6884                                            let prev_index = if current_index > 0 {
 6885                                                current_index - 1
 6886                                            } else {
 6887                                                items_len.saturating_sub(1)
 6888                                            };
 6889                                            pane.activate_item(
 6890                                                prev_index, false, false, window, cx,
 6891                                            );
 6892                                        }
 6893                                    });
 6894                                    return;
 6895                                }
 6896                            }
 6897                        }
 6898                    }
 6899                    cx.propagate();
 6900                },
 6901            ))
 6902            .on_action(cx.listener(
 6903                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6904                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6905                        let dock = active_dock.read(cx);
 6906                        if let Some(active_panel) = dock.active_panel() {
 6907                            if active_panel.pane(cx).is_none() {
 6908                                let active_pane = workspace.active_pane().clone();
 6909                                active_pane.update(cx, |pane, cx| {
 6910                                    pane.close_active_item(action, window, cx)
 6911                                        .detach_and_log_err(cx);
 6912                                });
 6913                                return;
 6914                            }
 6915                        }
 6916                    }
 6917                    cx.propagate();
 6918                },
 6919            ))
 6920            .on_action(
 6921                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6922                    let pane = workspace.active_pane().clone();
 6923                    if let Some(item) = pane.read(cx).active_item() {
 6924                        item.toggle_read_only(window, cx);
 6925                    }
 6926                }),
 6927            )
 6928            .on_action(cx.listener(Workspace::cancel))
 6929    }
 6930
 6931    #[cfg(any(test, feature = "test-support"))]
 6932    pub fn set_random_database_id(&mut self) {
 6933        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6934    }
 6935
 6936    #[cfg(any(test, feature = "test-support"))]
 6937    pub(crate) fn test_new(
 6938        project: Entity<Project>,
 6939        window: &mut Window,
 6940        cx: &mut Context<Self>,
 6941    ) -> Self {
 6942        use node_runtime::NodeRuntime;
 6943        use session::Session;
 6944
 6945        let client = project.read(cx).client();
 6946        let user_store = project.read(cx).user_store();
 6947        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6948        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6949        window.activate_window();
 6950        let app_state = Arc::new(AppState {
 6951            languages: project.read(cx).languages().clone(),
 6952            workspace_store,
 6953            client,
 6954            user_store,
 6955            fs: project.read(cx).fs().clone(),
 6956            build_window_options: |_, _| Default::default(),
 6957            node_runtime: NodeRuntime::unavailable(),
 6958            session,
 6959        });
 6960        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6961        workspace
 6962            .active_pane
 6963            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6964        workspace
 6965    }
 6966
 6967    pub fn register_action<A: Action>(
 6968        &mut self,
 6969        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6970    ) -> &mut Self {
 6971        let callback = Arc::new(callback);
 6972
 6973        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6974            let callback = callback.clone();
 6975            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6976                (callback)(workspace, event, window, cx)
 6977            }))
 6978        }));
 6979        self
 6980    }
 6981    pub fn register_action_renderer(
 6982        &mut self,
 6983        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6984    ) -> &mut Self {
 6985        self.workspace_actions.push(Box::new(callback));
 6986        self
 6987    }
 6988
 6989    fn add_workspace_actions_listeners(
 6990        &self,
 6991        mut div: Div,
 6992        window: &mut Window,
 6993        cx: &mut Context<Self>,
 6994    ) -> Div {
 6995        for action in self.workspace_actions.iter() {
 6996            div = (action)(div, self, window, cx)
 6997        }
 6998        div
 6999    }
 7000
 7001    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7002        self.modal_layer.read(cx).has_active_modal()
 7003    }
 7004
 7005    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7006        self.modal_layer.read(cx).active_modal()
 7007    }
 7008
 7009    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7010    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7011    /// If no modal is active, the new modal will be shown.
 7012    ///
 7013    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7014    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7015    /// will not be shown.
 7016    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7017    where
 7018        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7019    {
 7020        self.modal_layer.update(cx, |modal_layer, cx| {
 7021            modal_layer.toggle_modal(window, cx, build)
 7022        })
 7023    }
 7024
 7025    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7026        self.modal_layer
 7027            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7028    }
 7029
 7030    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7031        self.toast_layer
 7032            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7033    }
 7034
 7035    pub fn toggle_centered_layout(
 7036        &mut self,
 7037        _: &ToggleCenteredLayout,
 7038        _: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.centered_layout = !self.centered_layout;
 7042        if let Some(database_id) = self.database_id() {
 7043            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 7044                .detach_and_log_err(cx);
 7045        }
 7046        cx.notify();
 7047    }
 7048
 7049    fn adjust_padding(padding: Option<f32>) -> f32 {
 7050        padding
 7051            .unwrap_or(CenteredPaddingSettings::default().0)
 7052            .clamp(
 7053                CenteredPaddingSettings::MIN_PADDING,
 7054                CenteredPaddingSettings::MAX_PADDING,
 7055            )
 7056    }
 7057
 7058    fn render_dock(
 7059        &self,
 7060        position: DockPosition,
 7061        dock: &Entity<Dock>,
 7062        window: &mut Window,
 7063        cx: &mut App,
 7064    ) -> Option<Div> {
 7065        if self.zoomed_position == Some(position) {
 7066            return None;
 7067        }
 7068
 7069        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7070            let pane = panel.pane(cx)?;
 7071            let follower_states = &self.follower_states;
 7072            leader_border_for_pane(follower_states, &pane, window, cx)
 7073        });
 7074
 7075        Some(
 7076            div()
 7077                .flex()
 7078                .flex_none()
 7079                .overflow_hidden()
 7080                .child(dock.clone())
 7081                .children(leader_border),
 7082        )
 7083    }
 7084
 7085    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7086        window
 7087            .root::<MultiWorkspace>()
 7088            .flatten()
 7089            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7090    }
 7091
 7092    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7093        self.zoomed.as_ref()
 7094    }
 7095
 7096    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7097        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7098            return;
 7099        };
 7100        let windows = cx.windows();
 7101        let next_window =
 7102            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7103                || {
 7104                    windows
 7105                        .iter()
 7106                        .cycle()
 7107                        .skip_while(|window| window.window_id() != current_window_id)
 7108                        .nth(1)
 7109                },
 7110            );
 7111
 7112        if let Some(window) = next_window {
 7113            window
 7114                .update(cx, |_, window, _| window.activate_window())
 7115                .ok();
 7116        }
 7117    }
 7118
 7119    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7120        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7121            return;
 7122        };
 7123        let windows = cx.windows();
 7124        let prev_window =
 7125            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7126                || {
 7127                    windows
 7128                        .iter()
 7129                        .rev()
 7130                        .cycle()
 7131                        .skip_while(|window| window.window_id() != current_window_id)
 7132                        .nth(1)
 7133                },
 7134            );
 7135
 7136        if let Some(window) = prev_window {
 7137            window
 7138                .update(cx, |_, window, _| window.activate_window())
 7139                .ok();
 7140        }
 7141    }
 7142
 7143    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7144        if cx.stop_active_drag(window) {
 7145        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7146            dismiss_app_notification(&notification_id, cx);
 7147        } else {
 7148            cx.propagate();
 7149        }
 7150    }
 7151
 7152    fn adjust_dock_size_by_px(
 7153        &mut self,
 7154        panel_size: Pixels,
 7155        dock_pos: DockPosition,
 7156        px: Pixels,
 7157        window: &mut Window,
 7158        cx: &mut Context<Self>,
 7159    ) {
 7160        match dock_pos {
 7161            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7162            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7163            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7164        }
 7165    }
 7166
 7167    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7168        let workspace_width = self.bounds.size.width;
 7169        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7170
 7171        self.right_dock.read_with(cx, |right_dock, cx| {
 7172            let right_dock_size = right_dock
 7173                .active_panel_size(window, cx)
 7174                .unwrap_or(Pixels::ZERO);
 7175            if right_dock_size + size > workspace_width {
 7176                size = workspace_width - right_dock_size
 7177            }
 7178        });
 7179
 7180        self.left_dock.update(cx, |left_dock, cx| {
 7181            if WorkspaceSettings::get_global(cx)
 7182                .resize_all_panels_in_dock
 7183                .contains(&DockPosition::Left)
 7184            {
 7185                left_dock.resize_all_panels(Some(size), window, cx);
 7186            } else {
 7187                left_dock.resize_active_panel(Some(size), window, cx);
 7188            }
 7189        });
 7190    }
 7191
 7192    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7193        let workspace_width = self.bounds.size.width;
 7194        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7195        self.left_dock.read_with(cx, |left_dock, cx| {
 7196            let left_dock_size = left_dock
 7197                .active_panel_size(window, cx)
 7198                .unwrap_or(Pixels::ZERO);
 7199            if left_dock_size + size > workspace_width {
 7200                size = workspace_width - left_dock_size
 7201            }
 7202        });
 7203        self.right_dock.update(cx, |right_dock, cx| {
 7204            if WorkspaceSettings::get_global(cx)
 7205                .resize_all_panels_in_dock
 7206                .contains(&DockPosition::Right)
 7207            {
 7208                right_dock.resize_all_panels(Some(size), window, cx);
 7209            } else {
 7210                right_dock.resize_active_panel(Some(size), window, cx);
 7211            }
 7212        });
 7213    }
 7214
 7215    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7216        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7217        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7218            if WorkspaceSettings::get_global(cx)
 7219                .resize_all_panels_in_dock
 7220                .contains(&DockPosition::Bottom)
 7221            {
 7222                bottom_dock.resize_all_panels(Some(size), window, cx);
 7223            } else {
 7224                bottom_dock.resize_active_panel(Some(size), window, cx);
 7225            }
 7226        });
 7227    }
 7228
 7229    fn toggle_edit_predictions_all_files(
 7230        &mut self,
 7231        _: &ToggleEditPrediction,
 7232        _window: &mut Window,
 7233        cx: &mut Context<Self>,
 7234    ) {
 7235        let fs = self.project().read(cx).fs().clone();
 7236        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7237        update_settings_file(fs, cx, move |file, _| {
 7238            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7239        });
 7240    }
 7241
 7242    pub fn show_worktree_trust_security_modal(
 7243        &mut self,
 7244        toggle: bool,
 7245        window: &mut Window,
 7246        cx: &mut Context<Self>,
 7247    ) {
 7248        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7249            if toggle {
 7250                security_modal.update(cx, |security_modal, cx| {
 7251                    security_modal.dismiss(cx);
 7252                })
 7253            } else {
 7254                security_modal.update(cx, |security_modal, cx| {
 7255                    security_modal.refresh_restricted_paths(cx);
 7256                });
 7257            }
 7258        } else {
 7259            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7260                .map(|trusted_worktrees| {
 7261                    trusted_worktrees
 7262                        .read(cx)
 7263                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7264                })
 7265                .unwrap_or(false);
 7266            if has_restricted_worktrees {
 7267                let project = self.project().read(cx);
 7268                let remote_host = project
 7269                    .remote_connection_options(cx)
 7270                    .map(RemoteHostLocation::from);
 7271                let worktree_store = project.worktree_store().downgrade();
 7272                self.toggle_modal(window, cx, |_, cx| {
 7273                    SecurityModal::new(worktree_store, remote_host, cx)
 7274                });
 7275            }
 7276        }
 7277    }
 7278}
 7279
 7280pub trait AnyActiveCall {
 7281    fn entity(&self) -> AnyEntity;
 7282    fn is_in_room(&self, _: &App) -> bool;
 7283    fn room_id(&self, _: &App) -> Option<u64>;
 7284    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7285    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7286    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7287    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7288    fn is_sharing_project(&self, _: &App) -> bool;
 7289    fn has_remote_participants(&self, _: &App) -> bool;
 7290    fn local_participant_is_guest(&self, _: &App) -> bool;
 7291    fn client(&self, _: &App) -> Arc<Client>;
 7292    fn share_on_join(&self, _: &App) -> bool;
 7293    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7294    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7295    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7296    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7297    fn join_project(
 7298        &self,
 7299        _: u64,
 7300        _: Arc<LanguageRegistry>,
 7301        _: Arc<dyn Fs>,
 7302        _: &mut App,
 7303    ) -> Task<Result<Entity<Project>>>;
 7304    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7305    fn subscribe(
 7306        &self,
 7307        _: &mut Window,
 7308        _: &mut Context<Workspace>,
 7309        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7310    ) -> Subscription;
 7311    fn create_shared_screen(
 7312        &self,
 7313        _: PeerId,
 7314        _: &Entity<Pane>,
 7315        _: &mut Window,
 7316        _: &mut App,
 7317    ) -> Option<Entity<SharedScreen>>;
 7318}
 7319
 7320#[derive(Clone)]
 7321pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7322impl Global for GlobalAnyActiveCall {}
 7323
 7324impl GlobalAnyActiveCall {
 7325    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7326        cx.try_global()
 7327    }
 7328
 7329    pub(crate) fn global(cx: &App) -> &Self {
 7330        cx.global()
 7331    }
 7332}
 7333/// Workspace-local view of a remote participant's location.
 7334#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7335pub enum ParticipantLocation {
 7336    SharedProject { project_id: u64 },
 7337    UnsharedProject,
 7338    External,
 7339}
 7340
 7341impl ParticipantLocation {
 7342    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7343        match location
 7344            .and_then(|l| l.variant)
 7345            .context("participant location was not provided")?
 7346        {
 7347            proto::participant_location::Variant::SharedProject(project) => {
 7348                Ok(Self::SharedProject {
 7349                    project_id: project.id,
 7350                })
 7351            }
 7352            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7353            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7354        }
 7355    }
 7356}
 7357/// Workspace-local view of a remote collaborator's state.
 7358/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7359#[derive(Clone)]
 7360pub struct RemoteCollaborator {
 7361    pub user: Arc<User>,
 7362    pub peer_id: PeerId,
 7363    pub location: ParticipantLocation,
 7364    pub participant_index: ParticipantIndex,
 7365}
 7366
 7367pub enum ActiveCallEvent {
 7368    ParticipantLocationChanged { participant_id: PeerId },
 7369    RemoteVideoTracksChanged { participant_id: PeerId },
 7370}
 7371
 7372fn leader_border_for_pane(
 7373    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7374    pane: &Entity<Pane>,
 7375    _: &Window,
 7376    cx: &App,
 7377) -> Option<Div> {
 7378    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7379        if state.pane() == pane {
 7380            Some((*leader_id, state))
 7381        } else {
 7382            None
 7383        }
 7384    })?;
 7385
 7386    let mut leader_color = match leader_id {
 7387        CollaboratorId::PeerId(leader_peer_id) => {
 7388            let leader = GlobalAnyActiveCall::try_global(cx)?
 7389                .0
 7390                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7391
 7392            cx.theme()
 7393                .players()
 7394                .color_for_participant(leader.participant_index.0)
 7395                .cursor
 7396        }
 7397        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7398    };
 7399    leader_color.fade_out(0.3);
 7400    Some(
 7401        div()
 7402            .absolute()
 7403            .size_full()
 7404            .left_0()
 7405            .top_0()
 7406            .border_2()
 7407            .border_color(leader_color),
 7408    )
 7409}
 7410
 7411fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7412    ZED_WINDOW_POSITION
 7413        .zip(*ZED_WINDOW_SIZE)
 7414        .map(|(position, size)| Bounds {
 7415            origin: position,
 7416            size,
 7417        })
 7418}
 7419
 7420fn open_items(
 7421    serialized_workspace: Option<SerializedWorkspace>,
 7422    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7423    window: &mut Window,
 7424    cx: &mut Context<Workspace>,
 7425) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7426    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7427        Workspace::load_workspace(
 7428            serialized_workspace,
 7429            project_paths_to_open
 7430                .iter()
 7431                .map(|(_, project_path)| project_path)
 7432                .cloned()
 7433                .collect(),
 7434            window,
 7435            cx,
 7436        )
 7437    });
 7438
 7439    cx.spawn_in(window, async move |workspace, cx| {
 7440        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7441
 7442        if let Some(restored_items) = restored_items {
 7443            let restored_items = restored_items.await?;
 7444
 7445            let restored_project_paths = restored_items
 7446                .iter()
 7447                .filter_map(|item| {
 7448                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7449                        .ok()
 7450                        .flatten()
 7451                })
 7452                .collect::<HashSet<_>>();
 7453
 7454            for restored_item in restored_items {
 7455                opened_items.push(restored_item.map(Ok));
 7456            }
 7457
 7458            project_paths_to_open
 7459                .iter_mut()
 7460                .for_each(|(_, project_path)| {
 7461                    if let Some(project_path_to_open) = project_path
 7462                        && restored_project_paths.contains(project_path_to_open)
 7463                    {
 7464                        *project_path = None;
 7465                    }
 7466                });
 7467        } else {
 7468            for _ in 0..project_paths_to_open.len() {
 7469                opened_items.push(None);
 7470            }
 7471        }
 7472        assert!(opened_items.len() == project_paths_to_open.len());
 7473
 7474        let tasks =
 7475            project_paths_to_open
 7476                .into_iter()
 7477                .enumerate()
 7478                .map(|(ix, (abs_path, project_path))| {
 7479                    let workspace = workspace.clone();
 7480                    cx.spawn(async move |cx| {
 7481                        let file_project_path = project_path?;
 7482                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7483                            workspace.project().update(cx, |project, cx| {
 7484                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7485                            })
 7486                        });
 7487
 7488                        // We only want to open file paths here. If one of the items
 7489                        // here is a directory, it was already opened further above
 7490                        // with a `find_or_create_worktree`.
 7491                        if let Ok(task) = abs_path_task
 7492                            && task.await.is_none_or(|p| p.is_file())
 7493                        {
 7494                            return Some((
 7495                                ix,
 7496                                workspace
 7497                                    .update_in(cx, |workspace, window, cx| {
 7498                                        workspace.open_path(
 7499                                            file_project_path,
 7500                                            None,
 7501                                            true,
 7502                                            window,
 7503                                            cx,
 7504                                        )
 7505                                    })
 7506                                    .log_err()?
 7507                                    .await,
 7508                            ));
 7509                        }
 7510                        None
 7511                    })
 7512                });
 7513
 7514        let tasks = tasks.collect::<Vec<_>>();
 7515
 7516        let tasks = futures::future::join_all(tasks);
 7517        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7518            opened_items[ix] = Some(path_open_result);
 7519        }
 7520
 7521        Ok(opened_items)
 7522    })
 7523}
 7524
 7525enum ActivateInDirectionTarget {
 7526    Pane(Entity<Pane>),
 7527    Dock(Entity<Dock>),
 7528}
 7529
 7530fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7531    window
 7532        .update(cx, |multi_workspace, _, cx| {
 7533            let workspace = multi_workspace.workspace().clone();
 7534            workspace.update(cx, |workspace, cx| {
 7535                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7536                    struct DatabaseFailedNotification;
 7537
 7538                    workspace.show_notification(
 7539                        NotificationId::unique::<DatabaseFailedNotification>(),
 7540                        cx,
 7541                        |cx| {
 7542                            cx.new(|cx| {
 7543                                MessageNotification::new("Failed to load the database file.", cx)
 7544                                    .primary_message("File an Issue")
 7545                                    .primary_icon(IconName::Plus)
 7546                                    .primary_on_click(|window, cx| {
 7547                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7548                                    })
 7549                            })
 7550                        },
 7551                    );
 7552                }
 7553            });
 7554        })
 7555        .log_err();
 7556}
 7557
 7558fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7559    if val == 0 {
 7560        ThemeSettings::get_global(cx).ui_font_size(cx)
 7561    } else {
 7562        px(val as f32)
 7563    }
 7564}
 7565
 7566fn adjust_active_dock_size_by_px(
 7567    px: Pixels,
 7568    workspace: &mut Workspace,
 7569    window: &mut Window,
 7570    cx: &mut Context<Workspace>,
 7571) {
 7572    let Some(active_dock) = workspace
 7573        .all_docks()
 7574        .into_iter()
 7575        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7576    else {
 7577        return;
 7578    };
 7579    let dock = active_dock.read(cx);
 7580    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7581        return;
 7582    };
 7583    let dock_pos = dock.position();
 7584    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7585}
 7586
 7587fn adjust_open_docks_size_by_px(
 7588    px: Pixels,
 7589    workspace: &mut Workspace,
 7590    window: &mut Window,
 7591    cx: &mut Context<Workspace>,
 7592) {
 7593    let docks = workspace
 7594        .all_docks()
 7595        .into_iter()
 7596        .filter_map(|dock| {
 7597            if dock.read(cx).is_open() {
 7598                let dock = dock.read(cx);
 7599                let panel_size = dock.active_panel_size(window, cx)?;
 7600                let dock_pos = dock.position();
 7601                Some((panel_size, dock_pos, px))
 7602            } else {
 7603                None
 7604            }
 7605        })
 7606        .collect::<Vec<_>>();
 7607
 7608    docks
 7609        .into_iter()
 7610        .for_each(|(panel_size, dock_pos, offset)| {
 7611            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7612        });
 7613}
 7614
 7615impl Focusable for Workspace {
 7616    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7617        self.active_pane.focus_handle(cx)
 7618    }
 7619}
 7620
 7621#[derive(Clone)]
 7622struct DraggedDock(DockPosition);
 7623
 7624impl Render for DraggedDock {
 7625    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7626        gpui::Empty
 7627    }
 7628}
 7629
 7630impl Render for Workspace {
 7631    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7632        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7633        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7634            log::info!("Rendered first frame");
 7635        }
 7636
 7637        let centered_layout = self.centered_layout
 7638            && self.center.panes().len() == 1
 7639            && self.active_item(cx).is_some();
 7640        let render_padding = |size| {
 7641            (size > 0.0).then(|| {
 7642                div()
 7643                    .h_full()
 7644                    .w(relative(size))
 7645                    .bg(cx.theme().colors().editor_background)
 7646                    .border_color(cx.theme().colors().pane_group_border)
 7647            })
 7648        };
 7649        let paddings = if centered_layout {
 7650            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7651            (
 7652                render_padding(Self::adjust_padding(
 7653                    settings.left_padding.map(|padding| padding.0),
 7654                )),
 7655                render_padding(Self::adjust_padding(
 7656                    settings.right_padding.map(|padding| padding.0),
 7657                )),
 7658            )
 7659        } else {
 7660            (None, None)
 7661        };
 7662        let ui_font = theme::setup_ui_font(window, cx);
 7663        let expanded_left_panel = self
 7664            .left_dock
 7665            .read(cx)
 7666            .active_panel()
 7667            .filter(|_| self.left_dock_expanded_mode)
 7668            .map(|p| p.to_any());
 7669        let render_left_dock_with_pixel_width = expanded_left_panel.is_none();
 7670
 7671        let Self {
 7672            ref mut center,
 7673            ref zoomed,
 7674            ref follower_states,
 7675            ref active_call,
 7676            ref active_pane,
 7677            ref app_state,
 7678            ref project,
 7679            ref weak_self,
 7680            ..
 7681        } = *self;
 7682        let active_call = active_call.as_ref().map(|(call, _)| &*call.0);
 7683        let center_element = center.render(
 7684            zoomed.as_ref(),
 7685            expanded_left_panel,
 7686            &PaneRenderContext {
 7687                follower_states,
 7688                active_call,
 7689                active_pane,
 7690                app_state,
 7691                project,
 7692                workspace: weak_self,
 7693            },
 7694            window,
 7695            cx,
 7696        );
 7697
 7698        let theme = cx.theme().clone();
 7699        let colors = theme.colors();
 7700        let notification_entities = self
 7701            .notifications
 7702            .iter()
 7703            .map(|(_, notification)| notification.entity_id())
 7704            .collect::<Vec<_>>();
 7705        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7706
 7707        div()
 7708            .relative()
 7709            .size_full()
 7710            .flex()
 7711            .flex_col()
 7712            .font(ui_font)
 7713            .gap_0()
 7714            .justify_start()
 7715            .items_start()
 7716            .text_color(colors.text)
 7717            .overflow_hidden()
 7718            .children(self.titlebar_item.clone())
 7719            .on_modifiers_changed(move |_, _, cx| {
 7720                for &id in &notification_entities {
 7721                    cx.notify(id);
 7722                }
 7723            })
 7724            .child(
 7725                div()
 7726                    .size_full()
 7727                    .relative()
 7728                    .flex_1()
 7729                    .flex()
 7730                    .flex_col()
 7731                    .child(
 7732                        div()
 7733                            .id("workspace")
 7734                            .bg(colors.background)
 7735                            .relative()
 7736                            .flex_1()
 7737                            .w_full()
 7738                            .flex()
 7739                            .flex_col()
 7740                            .overflow_hidden()
 7741                            .border_t_1()
 7742                            .border_b_1()
 7743                            .border_color(colors.border)
 7744                            .child({
 7745                                let this = cx.entity();
 7746                                canvas(
 7747                                    move |bounds, window, cx| {
 7748                                        this.update(cx, |this, cx| {
 7749                                            let bounds_changed = this.bounds != bounds;
 7750                                            this.bounds = bounds;
 7751
 7752                                            if bounds_changed {
 7753                                                this.left_dock.update(cx, |dock, cx| {
 7754                                                    dock.clamp_panel_size(
 7755                                                        bounds.size.width,
 7756                                                        window,
 7757                                                        cx,
 7758                                                    )
 7759                                                });
 7760
 7761                                                this.right_dock.update(cx, |dock, cx| {
 7762                                                    dock.clamp_panel_size(
 7763                                                        bounds.size.width,
 7764                                                        window,
 7765                                                        cx,
 7766                                                    )
 7767                                                });
 7768
 7769                                                this.bottom_dock.update(cx, |dock, cx| {
 7770                                                    dock.clamp_panel_size(
 7771                                                        bounds.size.height,
 7772                                                        window,
 7773                                                        cx,
 7774                                                    )
 7775                                                });
 7776                                            }
 7777                                        })
 7778                                    },
 7779                                    |_, _, _, _| {},
 7780                                )
 7781                                .absolute()
 7782                                .size_full()
 7783                            })
 7784                            .when(self.zoomed.is_none(), |this| {
 7785                                this.on_drag_move(cx.listener(
 7786                                    move |workspace, e: &DragMoveEvent<DraggedDock>, window, cx| {
 7787                                        if workspace.previous_dock_drag_coordinates
 7788                                            != Some(e.event.position)
 7789                                        {
 7790                                            workspace.previous_dock_drag_coordinates =
 7791                                                Some(e.event.position);
 7792
 7793                                            match e.drag(cx).0 {
 7794                                                DockPosition::Left => {
 7795                                                    workspace.resize_left_dock(
 7796                                                        e.event.position.x
 7797                                                            - workspace.bounds.left(),
 7798                                                        window,
 7799                                                        cx,
 7800                                                    );
 7801                                                }
 7802                                                DockPosition::Right => {
 7803                                                    workspace.resize_right_dock(
 7804                                                        workspace.bounds.right()
 7805                                                            - e.event.position.x,
 7806                                                        window,
 7807                                                        cx,
 7808                                                    );
 7809                                                }
 7810                                                DockPosition::Bottom => {
 7811                                                    workspace.resize_bottom_dock(
 7812                                                        workspace.bounds.bottom()
 7813                                                            - e.event.position.y,
 7814                                                        window,
 7815                                                        cx,
 7816                                                    );
 7817                                                }
 7818                                            };
 7819                                            workspace.serialize_workspace(window, cx);
 7820                                        }
 7821                                    },
 7822                                ))
 7823                            })
 7824                            .child({
 7825                                match bottom_dock_layout {
 7826                                    BottomDockLayout::Full => div()
 7827                                        .flex()
 7828                                        .flex_col()
 7829                                        .h_full()
 7830                                        .child(
 7831                                            div()
 7832                                                .flex()
 7833                                                .flex_row()
 7834                                                .flex_1()
 7835                                                .overflow_hidden()
 7836                                                .when(render_left_dock_with_pixel_width, |this| {
 7837                                                    this.children(self.render_dock(
 7838                                                        DockPosition::Left,
 7839                                                        &self.left_dock,
 7840                                                        window,
 7841                                                        cx,
 7842                                                    ))
 7843                                                })
 7844                                                .child(
 7845                                                    div()
 7846                                                        .flex()
 7847                                                        .flex_col()
 7848                                                        .flex_1()
 7849                                                        .overflow_hidden()
 7850                                                        .child(
 7851                                                            h_flex()
 7852                                                                .flex_1()
 7853                                                                .when_some(paddings.0, |this, p| {
 7854                                                                    this.child(p.border_r_1())
 7855                                                                })
 7856                                                                .child(center_element)
 7857                                                                .when_some(
 7858                                                                    paddings.1,
 7859                                                                    |this, p| {
 7860                                                                        this.child(p.border_l_1())
 7861                                                                    },
 7862                                                                ),
 7863                                                        ),
 7864                                                )
 7865                                                .children(self.render_dock(
 7866                                                    DockPosition::Right,
 7867                                                    &self.right_dock,
 7868                                                    window,
 7869                                                    cx,
 7870                                                )),
 7871                                        )
 7872                                        .child(div().w_full().children(self.render_dock(
 7873                                            DockPosition::Bottom,
 7874                                            &self.bottom_dock,
 7875                                            window,
 7876                                            cx,
 7877                                        ))),
 7878
 7879                                    BottomDockLayout::LeftAligned => div()
 7880                                        .flex()
 7881                                        .flex_row()
 7882                                        .h_full()
 7883                                        .child(
 7884                                            div()
 7885                                                .flex()
 7886                                                .flex_col()
 7887                                                .flex_1()
 7888                                                .h_full()
 7889                                                .child(
 7890                                                    div()
 7891                                                        .flex()
 7892                                                        .flex_row()
 7893                                                        .flex_1()
 7894                                                        .when(
 7895                                                            render_left_dock_with_pixel_width,
 7896                                                            |this| {
 7897                                                                this.children(self.render_dock(
 7898                                                                    DockPosition::Left,
 7899                                                                    &self.left_dock,
 7900                                                                    window,
 7901                                                                    cx,
 7902                                                                ))
 7903                                                            },
 7904                                                        )
 7905                                                        .child(
 7906                                                            div()
 7907                                                                .flex()
 7908                                                                .flex_col()
 7909                                                                .flex_1()
 7910                                                                .overflow_hidden()
 7911                                                                .child(
 7912                                                                    h_flex()
 7913                                                                        .flex_1()
 7914                                                                        .when_some(
 7915                                                                            paddings.0,
 7916                                                                            |this, p| {
 7917                                                                                this.child(
 7918                                                                                    p.border_r_1(),
 7919                                                                                )
 7920                                                                            },
 7921                                                                        )
 7922                                                                        .child(center_element)
 7923                                                                        .when_some(
 7924                                                                            paddings.1,
 7925                                                                            |this, p| {
 7926                                                                                this.child(
 7927                                                                                    p.border_l_1(),
 7928                                                                                )
 7929                                                                            },
 7930                                                                        ),
 7931                                                                ),
 7932                                                        ),
 7933                                                )
 7934                                                .child(div().w_full().children(self.render_dock(
 7935                                                    DockPosition::Bottom,
 7936                                                    &self.bottom_dock,
 7937                                                    window,
 7938                                                    cx,
 7939                                                ))),
 7940                                        )
 7941                                        .children(self.render_dock(
 7942                                            DockPosition::Right,
 7943                                            &self.right_dock,
 7944                                            window,
 7945                                            cx,
 7946                                        )),
 7947
 7948                                    BottomDockLayout::RightAligned => div()
 7949                                        .flex()
 7950                                        .flex_row()
 7951                                        .h_full()
 7952                                        .when(render_left_dock_with_pixel_width, |this| {
 7953                                            this.children(self.render_dock(
 7954                                                DockPosition::Left,
 7955                                                &self.left_dock,
 7956                                                window,
 7957                                                cx,
 7958                                            ))
 7959                                        })
 7960                                        .child(
 7961                                            div()
 7962                                                .flex()
 7963                                                .flex_col()
 7964                                                .flex_1()
 7965                                                .h_full()
 7966                                                .child(
 7967                                                    div()
 7968                                                        .flex()
 7969                                                        .flex_row()
 7970                                                        .flex_1()
 7971                                                        .child(
 7972                                                            div()
 7973                                                                .flex()
 7974                                                                .flex_col()
 7975                                                                .flex_1()
 7976                                                                .overflow_hidden()
 7977                                                                .child(
 7978                                                                    h_flex()
 7979                                                                        .flex_1()
 7980                                                                        .when_some(
 7981                                                                            paddings.0,
 7982                                                                            |this, p| {
 7983                                                                                this.child(
 7984                                                                                    p.border_r_1(),
 7985                                                                                )
 7986                                                                            },
 7987                                                                        )
 7988                                                                        .child(center_element)
 7989                                                                        .when_some(
 7990                                                                            paddings.1,
 7991                                                                            |this, p| {
 7992                                                                                this.child(
 7993                                                                                    p.border_l_1(),
 7994                                                                                )
 7995                                                                            },
 7996                                                                        ),
 7997                                                                ),
 7998                                                        )
 7999                                                        .children(self.render_dock(
 8000                                                            DockPosition::Right,
 8001                                                            &self.right_dock,
 8002                                                            window,
 8003                                                            cx,
 8004                                                        )),
 8005                                                )
 8006                                                .child(div().w_full().children(self.render_dock(
 8007                                                    DockPosition::Bottom,
 8008                                                    &self.bottom_dock,
 8009                                                    window,
 8010                                                    cx,
 8011                                                ))),
 8012                                        ),
 8013
 8014                                    BottomDockLayout::Contained => div()
 8015                                        .flex()
 8016                                        .flex_row()
 8017                                        .h_full()
 8018                                        .when(render_left_dock_with_pixel_width, |this| {
 8019                                            this.children(self.render_dock(
 8020                                                DockPosition::Left,
 8021                                                &self.left_dock,
 8022                                                window,
 8023                                                cx,
 8024                                            ))
 8025                                        })
 8026                                        .child(
 8027                                            div()
 8028                                                .flex()
 8029                                                .flex_col()
 8030                                                .flex_1()
 8031                                                .overflow_hidden()
 8032                                                .child(
 8033                                                    h_flex()
 8034                                                        .flex_1()
 8035                                                        .when_some(paddings.0, |this, p| {
 8036                                                            this.child(p.border_r_1())
 8037                                                        })
 8038                                                        .child(center_element)
 8039                                                        .when_some(paddings.1, |this, p| {
 8040                                                            this.child(p.border_l_1())
 8041                                                        }),
 8042                                                )
 8043                                                .children(self.render_dock(
 8044                                                    DockPosition::Bottom,
 8045                                                    &self.bottom_dock,
 8046                                                    window,
 8047                                                    cx,
 8048                                                )),
 8049                                        )
 8050                                        .children(self.render_dock(
 8051                                            DockPosition::Right,
 8052                                            &self.right_dock,
 8053                                            window,
 8054                                            cx,
 8055                                        )),
 8056                                }
 8057                            })
 8058                            .children(self.zoomed.as_ref().and_then(|view| {
 8059                                let zoomed_view = view.upgrade()?;
 8060                                let div = div()
 8061                                    .occlude()
 8062                                    .absolute()
 8063                                    .overflow_hidden()
 8064                                    .border_color(colors.border)
 8065                                    .bg(colors.background)
 8066                                    .child(zoomed_view)
 8067                                    .inset_0()
 8068                                    .shadow_lg();
 8069
 8070                                if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8071                                    return Some(div);
 8072                                }
 8073
 8074                                Some(match self.zoomed_position {
 8075                                    Some(DockPosition::Left) => div.right_2().border_r_1(),
 8076                                    Some(DockPosition::Right) => div.left_2().border_l_1(),
 8077                                    Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8078                                    None => div.top_2().bottom_2().left_2().right_2().border_1(),
 8079                                })
 8080                            }))
 8081                            .children(self.render_notifications(window, cx)),
 8082                    )
 8083                    .when(self.status_bar_visible(cx), |parent| {
 8084                        parent.child(self.status_bar.clone())
 8085                    })
 8086                    .child(self.toast_layer.clone()),
 8087            )
 8088    }
 8089}
 8090
 8091impl WorkspaceStore {
 8092    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8093        Self {
 8094            workspaces: Default::default(),
 8095            _subscriptions: vec![
 8096                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8097                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8098            ],
 8099            client,
 8100        }
 8101    }
 8102
 8103    pub fn update_followers(
 8104        &self,
 8105        project_id: Option<u64>,
 8106        update: proto::update_followers::Variant,
 8107        cx: &App,
 8108    ) -> Option<()> {
 8109        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8110        let room_id = active_call.0.room_id(cx)?;
 8111        self.client
 8112            .send(proto::UpdateFollowers {
 8113                room_id,
 8114                project_id,
 8115                variant: Some(update),
 8116            })
 8117            .log_err()
 8118    }
 8119
 8120    pub async fn handle_follow(
 8121        this: Entity<Self>,
 8122        envelope: TypedEnvelope<proto::Follow>,
 8123        mut cx: AsyncApp,
 8124    ) -> Result<proto::FollowResponse> {
 8125        this.update(&mut cx, |this, cx| {
 8126            let follower = Follower {
 8127                project_id: envelope.payload.project_id,
 8128                peer_id: envelope.original_sender_id()?,
 8129            };
 8130
 8131            let mut response = proto::FollowResponse::default();
 8132
 8133            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8134                let Some(workspace) = weak_workspace.upgrade() else {
 8135                    return false;
 8136                };
 8137                window_handle
 8138                    .update(cx, |_, window, cx| {
 8139                        workspace.update(cx, |workspace, cx| {
 8140                            let handler_response =
 8141                                workspace.handle_follow(follower.project_id, window, cx);
 8142                            if let Some(active_view) = handler_response.active_view
 8143                                && workspace.project.read(cx).remote_id() == follower.project_id
 8144                            {
 8145                                response.active_view = Some(active_view)
 8146                            }
 8147                        });
 8148                    })
 8149                    .is_ok()
 8150            });
 8151
 8152            Ok(response)
 8153        })
 8154    }
 8155
 8156    async fn handle_update_followers(
 8157        this: Entity<Self>,
 8158        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8159        mut cx: AsyncApp,
 8160    ) -> Result<()> {
 8161        let leader_id = envelope.original_sender_id()?;
 8162        let update = envelope.payload;
 8163
 8164        this.update(&mut cx, |this, cx| {
 8165            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8166                let Some(workspace) = weak_workspace.upgrade() else {
 8167                    return false;
 8168                };
 8169                window_handle
 8170                    .update(cx, |_, window, cx| {
 8171                        workspace.update(cx, |workspace, cx| {
 8172                            let project_id = workspace.project.read(cx).remote_id();
 8173                            if update.project_id != project_id && update.project_id.is_some() {
 8174                                return;
 8175                            }
 8176                            workspace.handle_update_followers(
 8177                                leader_id,
 8178                                update.clone(),
 8179                                window,
 8180                                cx,
 8181                            );
 8182                        });
 8183                    })
 8184                    .is_ok()
 8185            });
 8186            Ok(())
 8187        })
 8188    }
 8189
 8190    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8191        self.workspaces.iter().map(|(_, weak)| weak)
 8192    }
 8193
 8194    pub fn workspaces_with_windows(
 8195        &self,
 8196    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8197        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8198    }
 8199}
 8200
 8201impl ViewId {
 8202    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8203        Ok(Self {
 8204            creator: message
 8205                .creator
 8206                .map(CollaboratorId::PeerId)
 8207                .context("creator is missing")?,
 8208            id: message.id,
 8209        })
 8210    }
 8211
 8212    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8213        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8214            Some(proto::ViewId {
 8215                creator: Some(peer_id),
 8216                id: self.id,
 8217            })
 8218        } else {
 8219            None
 8220        }
 8221    }
 8222}
 8223
 8224impl FollowerState {
 8225    fn pane(&self) -> &Entity<Pane> {
 8226        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8227    }
 8228}
 8229
 8230pub trait WorkspaceHandle {
 8231    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8232}
 8233
 8234impl WorkspaceHandle for Entity<Workspace> {
 8235    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8236        self.read(cx)
 8237            .worktrees(cx)
 8238            .flat_map(|worktree| {
 8239                let worktree_id = worktree.read(cx).id();
 8240                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8241                    worktree_id,
 8242                    path: f.path.clone(),
 8243                })
 8244            })
 8245            .collect::<Vec<_>>()
 8246    }
 8247}
 8248
 8249pub async fn last_opened_workspace_location(
 8250    fs: &dyn fs::Fs,
 8251) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8252    DB.last_workspace(fs)
 8253        .await
 8254        .log_err()
 8255        .flatten()
 8256        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8257}
 8258
 8259pub async fn last_session_workspace_locations(
 8260    last_session_id: &str,
 8261    last_session_window_stack: Option<Vec<WindowId>>,
 8262    fs: &dyn fs::Fs,
 8263) -> Option<Vec<SessionWorkspace>> {
 8264    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8265        .await
 8266        .log_err()
 8267}
 8268
 8269pub struct MultiWorkspaceRestoreResult {
 8270    pub window_handle: WindowHandle<MultiWorkspace>,
 8271    pub errors: Vec<anyhow::Error>,
 8272}
 8273
 8274pub async fn restore_multiworkspace(
 8275    multi_workspace: SerializedMultiWorkspace,
 8276    app_state: Arc<AppState>,
 8277    cx: &mut AsyncApp,
 8278) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8279    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8280    let mut group_iter = workspaces.into_iter();
 8281    let first = group_iter
 8282        .next()
 8283        .context("window group must not be empty")?;
 8284
 8285    let window_handle = if first.paths.is_empty() {
 8286        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8287            .await?
 8288    } else {
 8289        let (window, _items) = cx
 8290            .update(|cx| {
 8291                Workspace::new_local(
 8292                    first.paths.paths().to_vec(),
 8293                    app_state.clone(),
 8294                    None,
 8295                    None,
 8296                    None,
 8297                    true,
 8298                    cx,
 8299                )
 8300            })
 8301            .await?;
 8302        window
 8303    };
 8304
 8305    let mut errors = Vec::new();
 8306
 8307    for session_workspace in group_iter {
 8308        let error = if session_workspace.paths.is_empty() {
 8309            cx.update(|cx| {
 8310                open_workspace_by_id(
 8311                    session_workspace.workspace_id,
 8312                    app_state.clone(),
 8313                    Some(window_handle),
 8314                    cx,
 8315                )
 8316            })
 8317            .await
 8318            .err()
 8319        } else {
 8320            cx.update(|cx| {
 8321                Workspace::new_local(
 8322                    session_workspace.paths.paths().to_vec(),
 8323                    app_state.clone(),
 8324                    Some(window_handle),
 8325                    None,
 8326                    None,
 8327                    true,
 8328                    cx,
 8329                )
 8330            })
 8331            .await
 8332            .err()
 8333        };
 8334
 8335        if let Some(error) = error {
 8336            errors.push(error);
 8337        }
 8338    }
 8339
 8340    if let Some(target_id) = state.active_workspace_id {
 8341        window_handle
 8342            .update(cx, |multi_workspace, window, cx| {
 8343                let target_index = multi_workspace
 8344                    .workspaces()
 8345                    .iter()
 8346                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8347                if let Some(index) = target_index {
 8348                    multi_workspace.activate_index(index, window, cx);
 8349                } else if !multi_workspace.workspaces().is_empty() {
 8350                    multi_workspace.activate_index(0, window, cx);
 8351                }
 8352            })
 8353            .ok();
 8354    } else {
 8355        window_handle
 8356            .update(cx, |multi_workspace, window, cx| {
 8357                if !multi_workspace.workspaces().is_empty() {
 8358                    multi_workspace.activate_index(0, window, cx);
 8359                }
 8360            })
 8361            .ok();
 8362    }
 8363
 8364    if state.sidebar_open {
 8365        window_handle
 8366            .update(cx, |multi_workspace, _, cx| {
 8367                multi_workspace.open_sidebar(cx);
 8368            })
 8369            .ok();
 8370    }
 8371
 8372    window_handle
 8373        .update(cx, |_, window, _cx| {
 8374            window.activate_window();
 8375        })
 8376        .ok();
 8377
 8378    Ok(MultiWorkspaceRestoreResult {
 8379        window_handle,
 8380        errors,
 8381    })
 8382}
 8383
 8384actions!(
 8385    collab,
 8386    [
 8387        /// Opens the channel notes for the current call.
 8388        ///
 8389        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8390        /// channel in the collab panel.
 8391        ///
 8392        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8393        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8394        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8395        OpenChannelNotes,
 8396        /// Mutes your microphone.
 8397        Mute,
 8398        /// Deafens yourself (mute both microphone and speakers).
 8399        Deafen,
 8400        /// Leaves the current call.
 8401        LeaveCall,
 8402        /// Shares the current project with collaborators.
 8403        ShareProject,
 8404        /// Shares your screen with collaborators.
 8405        ScreenShare,
 8406        /// Copies the current room name and session id for debugging purposes.
 8407        CopyRoomId,
 8408    ]
 8409);
 8410actions!(
 8411    zed,
 8412    [
 8413        /// Opens the Zed log file.
 8414        OpenLog,
 8415        /// Reveals the Zed log file in the system file manager.
 8416        RevealLogInFileManager
 8417    ]
 8418);
 8419
 8420async fn join_channel_internal(
 8421    channel_id: ChannelId,
 8422    app_state: &Arc<AppState>,
 8423    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8424    requesting_workspace: Option<WeakEntity<Workspace>>,
 8425    active_call: &dyn AnyActiveCall,
 8426    cx: &mut AsyncApp,
 8427) -> Result<bool> {
 8428    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8429        if !active_call.is_in_room(cx) {
 8430            return (false, false);
 8431        }
 8432
 8433        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8434        let should_prompt = active_call.is_sharing_project(cx)
 8435            && active_call.has_remote_participants(cx)
 8436            && !already_in_channel;
 8437        (should_prompt, already_in_channel)
 8438    });
 8439
 8440    if already_in_channel {
 8441        let task = cx.update(|cx| {
 8442            if let Some((project, host)) = active_call.most_active_project(cx) {
 8443                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8444            } else {
 8445                None
 8446            }
 8447        });
 8448        if let Some(task) = task {
 8449            task.await?;
 8450        }
 8451        return anyhow::Ok(true);
 8452    }
 8453
 8454    if should_prompt {
 8455        if let Some(multi_workspace) = requesting_window {
 8456            let answer = multi_workspace
 8457                .update(cx, |_, window, cx| {
 8458                    window.prompt(
 8459                        PromptLevel::Warning,
 8460                        "Do you want to switch channels?",
 8461                        Some("Leaving this call will unshare your current project."),
 8462                        &["Yes, Join Channel", "Cancel"],
 8463                        cx,
 8464                    )
 8465                })?
 8466                .await;
 8467
 8468            if answer == Ok(1) {
 8469                return Ok(false);
 8470            }
 8471        } else {
 8472            return Ok(false);
 8473        }
 8474    }
 8475
 8476    let client = cx.update(|cx| active_call.client(cx));
 8477
 8478    let mut client_status = client.status();
 8479
 8480    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8481    'outer: loop {
 8482        let Some(status) = client_status.recv().await else {
 8483            anyhow::bail!("error connecting");
 8484        };
 8485
 8486        match status {
 8487            Status::Connecting
 8488            | Status::Authenticating
 8489            | Status::Authenticated
 8490            | Status::Reconnecting
 8491            | Status::Reauthenticating
 8492            | Status::Reauthenticated => continue,
 8493            Status::Connected { .. } => break 'outer,
 8494            Status::SignedOut | Status::AuthenticationError => {
 8495                return Err(ErrorCode::SignedOut.into());
 8496            }
 8497            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8498            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8499                return Err(ErrorCode::Disconnected.into());
 8500            }
 8501        }
 8502    }
 8503
 8504    let joined = cx
 8505        .update(|cx| active_call.join_channel(channel_id, cx))
 8506        .await?;
 8507
 8508    if !joined {
 8509        return anyhow::Ok(true);
 8510    }
 8511
 8512    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8513
 8514    let task = cx.update(|cx| {
 8515        if let Some((project, host)) = active_call.most_active_project(cx) {
 8516            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8517        }
 8518
 8519        // If you are the first to join a channel, see if you should share your project.
 8520        if !active_call.has_remote_participants(cx)
 8521            && !active_call.local_participant_is_guest(cx)
 8522            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8523        {
 8524            let project = workspace.update(cx, |workspace, cx| {
 8525                let project = workspace.project.read(cx);
 8526
 8527                if !active_call.share_on_join(cx) {
 8528                    return None;
 8529                }
 8530
 8531                if (project.is_local() || project.is_via_remote_server())
 8532                    && project.visible_worktrees(cx).any(|tree| {
 8533                        tree.read(cx)
 8534                            .root_entry()
 8535                            .is_some_and(|entry| entry.is_dir())
 8536                    })
 8537                {
 8538                    Some(workspace.project.clone())
 8539                } else {
 8540                    None
 8541                }
 8542            });
 8543            if let Some(project) = project {
 8544                let share_task = active_call.share_project(project, cx);
 8545                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8546                    share_task.await?;
 8547                    Ok(())
 8548                }));
 8549            }
 8550        }
 8551
 8552        None
 8553    });
 8554    if let Some(task) = task {
 8555        task.await?;
 8556        return anyhow::Ok(true);
 8557    }
 8558    anyhow::Ok(false)
 8559}
 8560
 8561pub fn join_channel(
 8562    channel_id: ChannelId,
 8563    app_state: Arc<AppState>,
 8564    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8565    requesting_workspace: Option<WeakEntity<Workspace>>,
 8566    cx: &mut App,
 8567) -> Task<Result<()>> {
 8568    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8569    cx.spawn(async move |cx| {
 8570        let result = join_channel_internal(
 8571            channel_id,
 8572            &app_state,
 8573            requesting_window,
 8574            requesting_workspace,
 8575            &*active_call.0,
 8576            cx,
 8577        )
 8578        .await;
 8579
 8580        // join channel succeeded, and opened a window
 8581        if matches!(result, Ok(true)) {
 8582            return anyhow::Ok(());
 8583        }
 8584
 8585        // find an existing workspace to focus and show call controls
 8586        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8587        if active_window.is_none() {
 8588            // no open workspaces, make one to show the error in (blergh)
 8589            let (window_handle, _) = cx
 8590                .update(|cx| {
 8591                    Workspace::new_local(
 8592                        vec![],
 8593                        app_state.clone(),
 8594                        requesting_window,
 8595                        None,
 8596                        None,
 8597                        true,
 8598                        cx,
 8599                    )
 8600                })
 8601                .await?;
 8602
 8603            window_handle
 8604                .update(cx, |_, window, _cx| {
 8605                    window.activate_window();
 8606                })
 8607                .ok();
 8608
 8609            if result.is_ok() {
 8610                cx.update(|cx| {
 8611                    cx.dispatch_action(&OpenChannelNotes);
 8612                });
 8613            }
 8614
 8615            active_window = Some(window_handle);
 8616        }
 8617
 8618        if let Err(err) = result {
 8619            log::error!("failed to join channel: {}", err);
 8620            if let Some(active_window) = active_window {
 8621                active_window
 8622                    .update(cx, |_, window, cx| {
 8623                        let detail: SharedString = match err.error_code() {
 8624                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8625                            ErrorCode::UpgradeRequired => concat!(
 8626                                "Your are running an unsupported version of Zed. ",
 8627                                "Please update to continue."
 8628                            )
 8629                            .into(),
 8630                            ErrorCode::NoSuchChannel => concat!(
 8631                                "No matching channel was found. ",
 8632                                "Please check the link and try again."
 8633                            )
 8634                            .into(),
 8635                            ErrorCode::Forbidden => concat!(
 8636                                "This channel is private, and you do not have access. ",
 8637                                "Please ask someone to add you and try again."
 8638                            )
 8639                            .into(),
 8640                            ErrorCode::Disconnected => {
 8641                                "Please check your internet connection and try again.".into()
 8642                            }
 8643                            _ => format!("{}\n\nPlease try again.", err).into(),
 8644                        };
 8645                        window.prompt(
 8646                            PromptLevel::Critical,
 8647                            "Failed to join channel",
 8648                            Some(&detail),
 8649                            &["Ok"],
 8650                            cx,
 8651                        )
 8652                    })?
 8653                    .await
 8654                    .ok();
 8655            }
 8656        }
 8657
 8658        // return ok, we showed the error to the user.
 8659        anyhow::Ok(())
 8660    })
 8661}
 8662
 8663pub async fn get_any_active_multi_workspace(
 8664    app_state: Arc<AppState>,
 8665    mut cx: AsyncApp,
 8666) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8667    // find an existing workspace to focus and show call controls
 8668    let active_window = activate_any_workspace_window(&mut cx);
 8669    if active_window.is_none() {
 8670        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8671            .await?;
 8672    }
 8673    activate_any_workspace_window(&mut cx).context("could not open zed")
 8674}
 8675
 8676fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8677    cx.update(|cx| {
 8678        if let Some(workspace_window) = cx
 8679            .active_window()
 8680            .and_then(|window| window.downcast::<MultiWorkspace>())
 8681        {
 8682            return Some(workspace_window);
 8683        }
 8684
 8685        for window in cx.windows() {
 8686            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8687                workspace_window
 8688                    .update(cx, |_, window, _| window.activate_window())
 8689                    .ok();
 8690                return Some(workspace_window);
 8691            }
 8692        }
 8693        None
 8694    })
 8695}
 8696
 8697pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8698    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8699}
 8700
 8701pub fn workspace_windows_for_location(
 8702    serialized_location: &SerializedWorkspaceLocation,
 8703    cx: &App,
 8704) -> Vec<WindowHandle<MultiWorkspace>> {
 8705    cx.windows()
 8706        .into_iter()
 8707        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8708        .filter(|multi_workspace| {
 8709            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8710                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8711                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8712                }
 8713                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8714                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8715                    a.distro_name == b.distro_name
 8716                }
 8717                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8718                    a.container_id == b.container_id
 8719                }
 8720                #[cfg(any(test, feature = "test-support"))]
 8721                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8722                    a.id == b.id
 8723                }
 8724                _ => false,
 8725            };
 8726
 8727            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8728                multi_workspace.workspaces().iter().any(|workspace| {
 8729                    match workspace.read(cx).workspace_location(cx) {
 8730                        WorkspaceLocation::Location(location, _) => {
 8731                            match (&location, serialized_location) {
 8732                                (
 8733                                    SerializedWorkspaceLocation::Local,
 8734                                    SerializedWorkspaceLocation::Local,
 8735                                ) => true,
 8736                                (
 8737                                    SerializedWorkspaceLocation::Remote(a),
 8738                                    SerializedWorkspaceLocation::Remote(b),
 8739                                ) => same_host(a, b),
 8740                                _ => false,
 8741                            }
 8742                        }
 8743                        _ => false,
 8744                    }
 8745                })
 8746            })
 8747        })
 8748        .collect()
 8749}
 8750
 8751pub async fn find_existing_workspace(
 8752    abs_paths: &[PathBuf],
 8753    open_options: &OpenOptions,
 8754    location: &SerializedWorkspaceLocation,
 8755    cx: &mut AsyncApp,
 8756) -> (
 8757    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8758    OpenVisible,
 8759) {
 8760    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8761    let mut open_visible = OpenVisible::All;
 8762    let mut best_match = None;
 8763
 8764    if open_options.open_new_workspace != Some(true) {
 8765        cx.update(|cx| {
 8766            for window in workspace_windows_for_location(location, cx) {
 8767                if let Ok(multi_workspace) = window.read(cx) {
 8768                    for workspace in multi_workspace.workspaces() {
 8769                        let project = workspace.read(cx).project.read(cx);
 8770                        let m = project.visibility_for_paths(
 8771                            abs_paths,
 8772                            open_options.open_new_workspace == None,
 8773                            cx,
 8774                        );
 8775                        if m > best_match {
 8776                            existing = Some((window, workspace.clone()));
 8777                            best_match = m;
 8778                        } else if best_match.is_none()
 8779                            && open_options.open_new_workspace == Some(false)
 8780                        {
 8781                            existing = Some((window, workspace.clone()))
 8782                        }
 8783                    }
 8784                }
 8785            }
 8786        });
 8787
 8788        let all_paths_are_files = existing
 8789            .as_ref()
 8790            .and_then(|(_, target_workspace)| {
 8791                cx.update(|cx| {
 8792                    let workspace = target_workspace.read(cx);
 8793                    let project = workspace.project.read(cx);
 8794                    let path_style = workspace.path_style(cx);
 8795                    Some(!abs_paths.iter().any(|path| {
 8796                        let path = util::paths::SanitizedPath::new(path);
 8797                        project.worktrees(cx).any(|worktree| {
 8798                            let worktree = worktree.read(cx);
 8799                            let abs_path = worktree.abs_path();
 8800                            path_style
 8801                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8802                                .and_then(|rel| worktree.entry_for_path(&rel))
 8803                                .is_some_and(|e| e.is_dir())
 8804                        })
 8805                    }))
 8806                })
 8807            })
 8808            .unwrap_or(false);
 8809
 8810        if open_options.open_new_workspace.is_none()
 8811            && existing.is_some()
 8812            && open_options.wait
 8813            && all_paths_are_files
 8814        {
 8815            cx.update(|cx| {
 8816                let windows = workspace_windows_for_location(location, cx);
 8817                let window = cx
 8818                    .active_window()
 8819                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8820                    .filter(|window| windows.contains(window))
 8821                    .or_else(|| windows.into_iter().next());
 8822                if let Some(window) = window {
 8823                    if let Ok(multi_workspace) = window.read(cx) {
 8824                        let active_workspace = multi_workspace.workspace().clone();
 8825                        existing = Some((window, active_workspace));
 8826                        open_visible = OpenVisible::None;
 8827                    }
 8828                }
 8829            });
 8830        }
 8831    }
 8832    (existing, open_visible)
 8833}
 8834
 8835#[derive(Default, Clone)]
 8836pub struct OpenOptions {
 8837    pub visible: Option<OpenVisible>,
 8838    pub focus: Option<bool>,
 8839    pub open_new_workspace: Option<bool>,
 8840    pub wait: bool,
 8841    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8842    pub env: Option<HashMap<String, String>>,
 8843}
 8844
 8845/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8846pub fn open_workspace_by_id(
 8847    workspace_id: WorkspaceId,
 8848    app_state: Arc<AppState>,
 8849    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8850    cx: &mut App,
 8851) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8852    let project_handle = Project::local(
 8853        app_state.client.clone(),
 8854        app_state.node_runtime.clone(),
 8855        app_state.user_store.clone(),
 8856        app_state.languages.clone(),
 8857        app_state.fs.clone(),
 8858        None,
 8859        project::LocalProjectFlags {
 8860            init_worktree_trust: true,
 8861            ..project::LocalProjectFlags::default()
 8862        },
 8863        cx,
 8864    );
 8865
 8866    cx.spawn(async move |cx| {
 8867        let serialized_workspace = persistence::DB
 8868            .workspace_for_id(workspace_id)
 8869            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8870
 8871        let centered_layout = serialized_workspace.centered_layout;
 8872
 8873        let (window, workspace) = if let Some(window) = requesting_window {
 8874            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8875                let workspace = cx.new(|cx| {
 8876                    let mut workspace = Workspace::new(
 8877                        Some(workspace_id),
 8878                        project_handle.clone(),
 8879                        app_state.clone(),
 8880                        window,
 8881                        cx,
 8882                    );
 8883                    workspace.centered_layout = centered_layout;
 8884                    workspace
 8885                });
 8886                multi_workspace.add_workspace(workspace.clone(), cx);
 8887                workspace
 8888            })?;
 8889            (window, workspace)
 8890        } else {
 8891            let window_bounds_override = window_bounds_env_override();
 8892
 8893            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8894                (Some(WindowBounds::Windowed(bounds)), None)
 8895            } else if let Some(display) = serialized_workspace.display
 8896                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8897            {
 8898                (Some(bounds.0), Some(display))
 8899            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8900                (Some(bounds), Some(display))
 8901            } else {
 8902                (None, None)
 8903            };
 8904
 8905            let options = cx.update(|cx| {
 8906                let mut options = (app_state.build_window_options)(display, cx);
 8907                options.window_bounds = window_bounds;
 8908                options
 8909            });
 8910
 8911            let window = cx.open_window(options, {
 8912                let app_state = app_state.clone();
 8913                let project_handle = project_handle.clone();
 8914                move |window, cx| {
 8915                    let workspace = cx.new(|cx| {
 8916                        let mut workspace = Workspace::new(
 8917                            Some(workspace_id),
 8918                            project_handle,
 8919                            app_state,
 8920                            window,
 8921                            cx,
 8922                        );
 8923                        workspace.centered_layout = centered_layout;
 8924                        workspace
 8925                    });
 8926                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8927                }
 8928            })?;
 8929
 8930            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8931                multi_workspace.workspace().clone()
 8932            })?;
 8933
 8934            (window, workspace)
 8935        };
 8936
 8937        notify_if_database_failed(window, cx);
 8938
 8939        // Restore items from the serialized workspace
 8940        window
 8941            .update(cx, |_, window, cx| {
 8942                workspace.update(cx, |_workspace, cx| {
 8943                    open_items(Some(serialized_workspace), vec![], window, cx)
 8944                })
 8945            })?
 8946            .await?;
 8947
 8948        window.update(cx, |_, window, cx| {
 8949            workspace.update(cx, |workspace, cx| {
 8950                workspace.serialize_workspace(window, cx);
 8951            });
 8952        })?;
 8953
 8954        Ok(window)
 8955    })
 8956}
 8957
 8958#[allow(clippy::type_complexity)]
 8959pub fn open_paths(
 8960    abs_paths: &[PathBuf],
 8961    app_state: Arc<AppState>,
 8962    open_options: OpenOptions,
 8963    cx: &mut App,
 8964) -> Task<
 8965    anyhow::Result<(
 8966        WindowHandle<MultiWorkspace>,
 8967        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8968    )>,
 8969> {
 8970    let abs_paths = abs_paths.to_vec();
 8971    #[cfg(target_os = "windows")]
 8972    let wsl_path = abs_paths
 8973        .iter()
 8974        .find_map(|p| util::paths::WslPath::from_path(p));
 8975
 8976    cx.spawn(async move |cx| {
 8977        let (mut existing, mut open_visible) = find_existing_workspace(
 8978            &abs_paths,
 8979            &open_options,
 8980            &SerializedWorkspaceLocation::Local,
 8981            cx,
 8982        )
 8983        .await;
 8984
 8985        // Fallback: if no workspace contains the paths and all paths are files,
 8986        // prefer an existing local workspace window (active window first).
 8987        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8988            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8989            let all_metadatas = futures::future::join_all(all_paths)
 8990                .await
 8991                .into_iter()
 8992                .filter_map(|result| result.ok().flatten())
 8993                .collect::<Vec<_>>();
 8994
 8995            if all_metadatas.iter().all(|file| !file.is_dir) {
 8996                cx.update(|cx| {
 8997                    let windows = workspace_windows_for_location(
 8998                        &SerializedWorkspaceLocation::Local,
 8999                        cx,
 9000                    );
 9001                    let window = cx
 9002                        .active_window()
 9003                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9004                        .filter(|window| windows.contains(window))
 9005                        .or_else(|| windows.into_iter().next());
 9006                    if let Some(window) = window {
 9007                        if let Ok(multi_workspace) = window.read(cx) {
 9008                            let active_workspace = multi_workspace.workspace().clone();
 9009                            existing = Some((window, active_workspace));
 9010                            open_visible = OpenVisible::None;
 9011                        }
 9012                    }
 9013                });
 9014            }
 9015        }
 9016
 9017        let result = if let Some((existing, target_workspace)) = existing {
 9018            let open_task = existing
 9019                .update(cx, |multi_workspace, window, cx| {
 9020                    window.activate_window();
 9021                    multi_workspace.activate(target_workspace.clone(), cx);
 9022                    target_workspace.update(cx, |workspace, cx| {
 9023                        workspace.open_paths(
 9024                            abs_paths,
 9025                            OpenOptions {
 9026                                visible: Some(open_visible),
 9027                                ..Default::default()
 9028                            },
 9029                            None,
 9030                            window,
 9031                            cx,
 9032                        )
 9033                    })
 9034                })?
 9035                .await;
 9036
 9037            _ = existing.update(cx, |multi_workspace, _, cx| {
 9038                let workspace = multi_workspace.workspace().clone();
 9039                workspace.update(cx, |workspace, cx| {
 9040                    for item in open_task.iter().flatten() {
 9041                        if let Err(e) = item {
 9042                            workspace.show_error(&e, cx);
 9043                        }
 9044                    }
 9045                });
 9046            });
 9047
 9048            Ok((existing, open_task))
 9049        } else {
 9050            let result = cx
 9051                .update(move |cx| {
 9052                    Workspace::new_local(
 9053                        abs_paths,
 9054                        app_state.clone(),
 9055                        open_options.replace_window,
 9056                        open_options.env,
 9057                        None,
 9058                        true,
 9059                        cx,
 9060                    )
 9061                })
 9062                .await;
 9063
 9064            if let Ok((ref window_handle, _)) = result {
 9065                window_handle
 9066                    .update(cx, |_, window, _cx| {
 9067                        window.activate_window();
 9068                    })
 9069                    .log_err();
 9070            }
 9071
 9072            result
 9073        };
 9074
 9075        #[cfg(target_os = "windows")]
 9076        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9077            && let Ok((multi_workspace_window, _)) = &result
 9078        {
 9079            multi_workspace_window
 9080                .update(cx, move |multi_workspace, _window, cx| {
 9081                    struct OpenInWsl;
 9082                    let workspace = multi_workspace.workspace().clone();
 9083                    workspace.update(cx, |workspace, cx| {
 9084                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9085                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9086                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9087                            cx.new(move |cx| {
 9088                                MessageNotification::new(msg, cx)
 9089                                    .primary_message("Open in WSL")
 9090                                    .primary_icon(IconName::FolderOpen)
 9091                                    .primary_on_click(move |window, cx| {
 9092                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9093                                                distro: remote::WslConnectionOptions {
 9094                                                        distro_name: distro.clone(),
 9095                                                    user: None,
 9096                                                },
 9097                                                paths: vec![path.clone().into()],
 9098                                            }), cx)
 9099                                    })
 9100                            })
 9101                        });
 9102                    });
 9103                })
 9104                .unwrap();
 9105        };
 9106        result
 9107    })
 9108}
 9109
 9110pub fn open_new(
 9111    open_options: OpenOptions,
 9112    app_state: Arc<AppState>,
 9113    cx: &mut App,
 9114    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9115) -> Task<anyhow::Result<()>> {
 9116    let task = Workspace::new_local(
 9117        Vec::new(),
 9118        app_state,
 9119        open_options.replace_window,
 9120        open_options.env,
 9121        Some(Box::new(init)),
 9122        true,
 9123        cx,
 9124    );
 9125    cx.spawn(async move |cx| {
 9126        let (window, _opened_paths) = task.await?;
 9127        window
 9128            .update(cx, |_, window, _cx| {
 9129                window.activate_window();
 9130            })
 9131            .ok();
 9132        Ok(())
 9133    })
 9134}
 9135
 9136pub fn create_and_open_local_file(
 9137    path: &'static Path,
 9138    window: &mut Window,
 9139    cx: &mut Context<Workspace>,
 9140    default_content: impl 'static + Send + FnOnce() -> Rope,
 9141) -> Task<Result<Box<dyn ItemHandle>>> {
 9142    cx.spawn_in(window, async move |workspace, cx| {
 9143        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9144        if !fs.is_file(path).await {
 9145            fs.create_file(path, Default::default()).await?;
 9146            fs.save(path, &default_content(), Default::default())
 9147                .await?;
 9148        }
 9149
 9150        workspace
 9151            .update_in(cx, |workspace, window, cx| {
 9152                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9153                    let path = workspace
 9154                        .project
 9155                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9156                    cx.spawn_in(window, async move |workspace, cx| {
 9157                        let path = path.await?;
 9158                        let mut items = workspace
 9159                            .update_in(cx, |workspace, window, cx| {
 9160                                workspace.open_paths(
 9161                                    vec![path.to_path_buf()],
 9162                                    OpenOptions {
 9163                                        visible: Some(OpenVisible::None),
 9164                                        ..Default::default()
 9165                                    },
 9166                                    None,
 9167                                    window,
 9168                                    cx,
 9169                                )
 9170                            })?
 9171                            .await;
 9172                        let item = items.pop().flatten();
 9173                        item.with_context(|| format!("path {path:?} is not a file"))?
 9174                    })
 9175                })
 9176            })?
 9177            .await?
 9178            .await
 9179    })
 9180}
 9181
 9182pub fn open_remote_project_with_new_connection(
 9183    window: WindowHandle<MultiWorkspace>,
 9184    remote_connection: Arc<dyn RemoteConnection>,
 9185    cancel_rx: oneshot::Receiver<()>,
 9186    delegate: Arc<dyn RemoteClientDelegate>,
 9187    app_state: Arc<AppState>,
 9188    paths: Vec<PathBuf>,
 9189    cx: &mut App,
 9190) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9191    cx.spawn(async move |cx| {
 9192        let (workspace_id, serialized_workspace) =
 9193            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9194                .await?;
 9195
 9196        let session = match cx
 9197            .update(|cx| {
 9198                remote::RemoteClient::new(
 9199                    ConnectionIdentifier::Workspace(workspace_id.0),
 9200                    remote_connection,
 9201                    cancel_rx,
 9202                    delegate,
 9203                    cx,
 9204                )
 9205            })
 9206            .await?
 9207        {
 9208            Some(result) => result,
 9209            None => return Ok(Vec::new()),
 9210        };
 9211
 9212        let project = cx.update(|cx| {
 9213            project::Project::remote(
 9214                session,
 9215                app_state.client.clone(),
 9216                app_state.node_runtime.clone(),
 9217                app_state.user_store.clone(),
 9218                app_state.languages.clone(),
 9219                app_state.fs.clone(),
 9220                true,
 9221                cx,
 9222            )
 9223        });
 9224
 9225        open_remote_project_inner(
 9226            project,
 9227            paths,
 9228            workspace_id,
 9229            serialized_workspace,
 9230            app_state,
 9231            window,
 9232            cx,
 9233        )
 9234        .await
 9235    })
 9236}
 9237
 9238pub fn open_remote_project_with_existing_connection(
 9239    connection_options: RemoteConnectionOptions,
 9240    project: Entity<Project>,
 9241    paths: Vec<PathBuf>,
 9242    app_state: Arc<AppState>,
 9243    window: WindowHandle<MultiWorkspace>,
 9244    cx: &mut AsyncApp,
 9245) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9246    cx.spawn(async move |cx| {
 9247        let (workspace_id, serialized_workspace) =
 9248            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9249
 9250        open_remote_project_inner(
 9251            project,
 9252            paths,
 9253            workspace_id,
 9254            serialized_workspace,
 9255            app_state,
 9256            window,
 9257            cx,
 9258        )
 9259        .await
 9260    })
 9261}
 9262
 9263async fn open_remote_project_inner(
 9264    project: Entity<Project>,
 9265    paths: Vec<PathBuf>,
 9266    workspace_id: WorkspaceId,
 9267    serialized_workspace: Option<SerializedWorkspace>,
 9268    app_state: Arc<AppState>,
 9269    window: WindowHandle<MultiWorkspace>,
 9270    cx: &mut AsyncApp,
 9271) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9272    let toolchains = DB.toolchains(workspace_id).await?;
 9273    for (toolchain, worktree_path, path) in toolchains {
 9274        project
 9275            .update(cx, |this, cx| {
 9276                let Some(worktree_id) =
 9277                    this.find_worktree(&worktree_path, cx)
 9278                        .and_then(|(worktree, rel_path)| {
 9279                            if rel_path.is_empty() {
 9280                                Some(worktree.read(cx).id())
 9281                            } else {
 9282                                None
 9283                            }
 9284                        })
 9285                else {
 9286                    return Task::ready(None);
 9287                };
 9288
 9289                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9290            })
 9291            .await;
 9292    }
 9293    let mut project_paths_to_open = vec![];
 9294    let mut project_path_errors = vec![];
 9295
 9296    for path in paths {
 9297        let result = cx
 9298            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9299            .await;
 9300        match result {
 9301            Ok((_, project_path)) => {
 9302                project_paths_to_open.push((path.clone(), Some(project_path)));
 9303            }
 9304            Err(error) => {
 9305                project_path_errors.push(error);
 9306            }
 9307        };
 9308    }
 9309
 9310    if project_paths_to_open.is_empty() {
 9311        return Err(project_path_errors.pop().context("no paths given")?);
 9312    }
 9313
 9314    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9315        telemetry::event!("SSH Project Opened");
 9316
 9317        let new_workspace = cx.new(|cx| {
 9318            let mut workspace =
 9319                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9320            workspace.update_history(cx);
 9321
 9322            if let Some(ref serialized) = serialized_workspace {
 9323                workspace.centered_layout = serialized.centered_layout;
 9324            }
 9325
 9326            workspace
 9327        });
 9328
 9329        multi_workspace.activate(new_workspace.clone(), cx);
 9330        new_workspace
 9331    })?;
 9332
 9333    let items = window
 9334        .update(cx, |_, window, cx| {
 9335            window.activate_window();
 9336            workspace.update(cx, |_workspace, cx| {
 9337                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9338            })
 9339        })?
 9340        .await?;
 9341
 9342    workspace.update(cx, |workspace, cx| {
 9343        for error in project_path_errors {
 9344            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9345                if let Some(path) = error.error_tag("path") {
 9346                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9347                }
 9348            } else {
 9349                workspace.show_error(&error, cx)
 9350            }
 9351        }
 9352    });
 9353
 9354    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9355}
 9356
 9357fn deserialize_remote_project(
 9358    connection_options: RemoteConnectionOptions,
 9359    paths: Vec<PathBuf>,
 9360    cx: &AsyncApp,
 9361) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9362    cx.background_spawn(async move {
 9363        let remote_connection_id = persistence::DB
 9364            .get_or_create_remote_connection(connection_options)
 9365            .await?;
 9366
 9367        let serialized_workspace =
 9368            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9369
 9370        let workspace_id = if let Some(workspace_id) =
 9371            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9372        {
 9373            workspace_id
 9374        } else {
 9375            persistence::DB.next_id().await?
 9376        };
 9377
 9378        Ok((workspace_id, serialized_workspace))
 9379    })
 9380}
 9381
 9382pub fn join_in_room_project(
 9383    project_id: u64,
 9384    follow_user_id: u64,
 9385    app_state: Arc<AppState>,
 9386    cx: &mut App,
 9387) -> Task<Result<()>> {
 9388    let windows = cx.windows();
 9389    cx.spawn(async move |cx| {
 9390        let existing_window_and_workspace: Option<(
 9391            WindowHandle<MultiWorkspace>,
 9392            Entity<Workspace>,
 9393        )> = windows.into_iter().find_map(|window_handle| {
 9394            window_handle
 9395                .downcast::<MultiWorkspace>()
 9396                .and_then(|window_handle| {
 9397                    window_handle
 9398                        .update(cx, |multi_workspace, _window, cx| {
 9399                            for workspace in multi_workspace.workspaces() {
 9400                                if workspace.read(cx).project().read(cx).remote_id()
 9401                                    == Some(project_id)
 9402                                {
 9403                                    return Some((window_handle, workspace.clone()));
 9404                                }
 9405                            }
 9406                            None
 9407                        })
 9408                        .unwrap_or(None)
 9409                })
 9410        });
 9411
 9412        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9413            existing_window_and_workspace
 9414        {
 9415            existing_window
 9416                .update(cx, |multi_workspace, _, cx| {
 9417                    multi_workspace.activate(target_workspace, cx);
 9418                })
 9419                .ok();
 9420            existing_window
 9421        } else {
 9422            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9423            let project = cx
 9424                .update(|cx| {
 9425                    active_call.0.join_project(
 9426                        project_id,
 9427                        app_state.languages.clone(),
 9428                        app_state.fs.clone(),
 9429                        cx,
 9430                    )
 9431                })
 9432                .await?;
 9433
 9434            let window_bounds_override = window_bounds_env_override();
 9435            cx.update(|cx| {
 9436                let mut options = (app_state.build_window_options)(None, cx);
 9437                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9438                cx.open_window(options, |window, cx| {
 9439                    let workspace = cx.new(|cx| {
 9440                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9441                    });
 9442                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9443                })
 9444            })?
 9445        };
 9446
 9447        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9448            cx.activate(true);
 9449            window.activate_window();
 9450
 9451            // We set the active workspace above, so this is the correct workspace.
 9452            let workspace = multi_workspace.workspace().clone();
 9453            workspace.update(cx, |workspace, cx| {
 9454                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9455                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9456                    .or_else(|| {
 9457                        // If we couldn't follow the given user, follow the host instead.
 9458                        let collaborator = workspace
 9459                            .project()
 9460                            .read(cx)
 9461                            .collaborators()
 9462                            .values()
 9463                            .find(|collaborator| collaborator.is_host)?;
 9464                        Some(collaborator.peer_id)
 9465                    });
 9466
 9467                if let Some(follow_peer_id) = follow_peer_id {
 9468                    workspace.follow(follow_peer_id, window, cx);
 9469                }
 9470            });
 9471        })?;
 9472
 9473        anyhow::Ok(())
 9474    })
 9475}
 9476
 9477pub fn reload(cx: &mut App) {
 9478    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9479    let mut workspace_windows = cx
 9480        .windows()
 9481        .into_iter()
 9482        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9483        .collect::<Vec<_>>();
 9484
 9485    // If multiple windows have unsaved changes, and need a save prompt,
 9486    // prompt in the active window before switching to a different window.
 9487    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9488
 9489    let mut prompt = None;
 9490    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9491        prompt = window
 9492            .update(cx, |_, window, cx| {
 9493                window.prompt(
 9494                    PromptLevel::Info,
 9495                    "Are you sure you want to restart?",
 9496                    None,
 9497                    &["Restart", "Cancel"],
 9498                    cx,
 9499                )
 9500            })
 9501            .ok();
 9502    }
 9503
 9504    cx.spawn(async move |cx| {
 9505        if let Some(prompt) = prompt {
 9506            let answer = prompt.await?;
 9507            if answer != 0 {
 9508                return anyhow::Ok(());
 9509            }
 9510        }
 9511
 9512        // If the user cancels any save prompt, then keep the app open.
 9513        for window in workspace_windows {
 9514            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9515                let workspace = multi_workspace.workspace().clone();
 9516                workspace.update(cx, |workspace, cx| {
 9517                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9518                })
 9519            }) && !should_close.await?
 9520            {
 9521                return anyhow::Ok(());
 9522            }
 9523        }
 9524        cx.update(|cx| cx.restart());
 9525        anyhow::Ok(())
 9526    })
 9527    .detach_and_log_err(cx);
 9528}
 9529
 9530fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9531    let mut parts = value.split(',');
 9532    let x: usize = parts.next()?.parse().ok()?;
 9533    let y: usize = parts.next()?.parse().ok()?;
 9534    Some(point(px(x as f32), px(y as f32)))
 9535}
 9536
 9537fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9538    let mut parts = value.split(',');
 9539    let width: usize = parts.next()?.parse().ok()?;
 9540    let height: usize = parts.next()?.parse().ok()?;
 9541    Some(size(px(width as f32), px(height as f32)))
 9542}
 9543
 9544/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9545/// appropriate.
 9546///
 9547/// The `border_radius_tiling` parameter allows overriding which corners get
 9548/// rounded, independently of the actual window tiling state. This is used
 9549/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9550/// we want square corners on the left (so the sidebar appears flush with the
 9551/// window edge) but we still need the shadow padding for proper visual
 9552/// appearance. Unlike actual window tiling, this only affects border radius -
 9553/// not padding or shadows.
 9554pub fn client_side_decorations(
 9555    element: impl IntoElement,
 9556    window: &mut Window,
 9557    cx: &mut App,
 9558    border_radius_tiling: Tiling,
 9559) -> Stateful<Div> {
 9560    const BORDER_SIZE: Pixels = px(1.0);
 9561    let decorations = window.window_decorations();
 9562    let tiling = match decorations {
 9563        Decorations::Server => Tiling::default(),
 9564        Decorations::Client { tiling } => tiling,
 9565    };
 9566
 9567    match decorations {
 9568        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9569        Decorations::Server => window.set_client_inset(px(0.0)),
 9570    }
 9571
 9572    struct GlobalResizeEdge(ResizeEdge);
 9573    impl Global for GlobalResizeEdge {}
 9574
 9575    div()
 9576        .id("window-backdrop")
 9577        .bg(transparent_black())
 9578        .map(|div| match decorations {
 9579            Decorations::Server => div,
 9580            Decorations::Client { .. } => div
 9581                .when(
 9582                    !(tiling.top
 9583                        || tiling.right
 9584                        || border_radius_tiling.top
 9585                        || border_radius_tiling.right),
 9586                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9587                )
 9588                .when(
 9589                    !(tiling.top
 9590                        || tiling.left
 9591                        || border_radius_tiling.top
 9592                        || border_radius_tiling.left),
 9593                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9594                )
 9595                .when(
 9596                    !(tiling.bottom
 9597                        || tiling.right
 9598                        || border_radius_tiling.bottom
 9599                        || border_radius_tiling.right),
 9600                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9601                )
 9602                .when(
 9603                    !(tiling.bottom
 9604                        || tiling.left
 9605                        || border_radius_tiling.bottom
 9606                        || border_radius_tiling.left),
 9607                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9608                )
 9609                .when(!tiling.top, |div| {
 9610                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9611                })
 9612                .when(!tiling.bottom, |div| {
 9613                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9614                })
 9615                .when(!tiling.left, |div| {
 9616                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9617                })
 9618                .when(!tiling.right, |div| {
 9619                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9620                })
 9621                .on_mouse_move(move |e, window, cx| {
 9622                    let size = window.window_bounds().get_bounds().size;
 9623                    let pos = e.position;
 9624
 9625                    let new_edge =
 9626                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9627
 9628                    let edge = cx.try_global::<GlobalResizeEdge>();
 9629                    if new_edge != edge.map(|edge| edge.0) {
 9630                        window
 9631                            .window_handle()
 9632                            .update(cx, |workspace, _, cx| {
 9633                                cx.notify(workspace.entity_id());
 9634                            })
 9635                            .ok();
 9636                    }
 9637                })
 9638                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9639                    let size = window.window_bounds().get_bounds().size;
 9640                    let pos = e.position;
 9641
 9642                    let edge = match resize_edge(
 9643                        pos,
 9644                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9645                        size,
 9646                        tiling,
 9647                    ) {
 9648                        Some(value) => value,
 9649                        None => return,
 9650                    };
 9651
 9652                    window.start_window_resize(edge);
 9653                }),
 9654        })
 9655        .size_full()
 9656        .child(
 9657            div()
 9658                .cursor(CursorStyle::Arrow)
 9659                .map(|div| match decorations {
 9660                    Decorations::Server => div,
 9661                    Decorations::Client { .. } => div
 9662                        .border_color(cx.theme().colors().border)
 9663                        .when(
 9664                            !(tiling.top
 9665                                || tiling.right
 9666                                || border_radius_tiling.top
 9667                                || border_radius_tiling.right),
 9668                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9669                        )
 9670                        .when(
 9671                            !(tiling.top
 9672                                || tiling.left
 9673                                || border_radius_tiling.top
 9674                                || border_radius_tiling.left),
 9675                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9676                        )
 9677                        .when(
 9678                            !(tiling.bottom
 9679                                || tiling.right
 9680                                || border_radius_tiling.bottom
 9681                                || border_radius_tiling.right),
 9682                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9683                        )
 9684                        .when(
 9685                            !(tiling.bottom
 9686                                || tiling.left
 9687                                || border_radius_tiling.bottom
 9688                                || border_radius_tiling.left),
 9689                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9690                        )
 9691                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9692                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9693                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9694                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9695                        .when(!tiling.is_tiled(), |div| {
 9696                            div.shadow(vec![gpui::BoxShadow {
 9697                                color: Hsla {
 9698                                    h: 0.,
 9699                                    s: 0.,
 9700                                    l: 0.,
 9701                                    a: 0.4,
 9702                                },
 9703                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9704                                spread_radius: px(0.),
 9705                                offset: point(px(0.0), px(0.0)),
 9706                            }])
 9707                        }),
 9708                })
 9709                .on_mouse_move(|_e, _, cx| {
 9710                    cx.stop_propagation();
 9711                })
 9712                .size_full()
 9713                .child(element),
 9714        )
 9715        .map(|div| match decorations {
 9716            Decorations::Server => div,
 9717            Decorations::Client { tiling, .. } => div.child(
 9718                canvas(
 9719                    |_bounds, window, _| {
 9720                        window.insert_hitbox(
 9721                            Bounds::new(
 9722                                point(px(0.0), px(0.0)),
 9723                                window.window_bounds().get_bounds().size,
 9724                            ),
 9725                            HitboxBehavior::Normal,
 9726                        )
 9727                    },
 9728                    move |_bounds, hitbox, window, cx| {
 9729                        let mouse = window.mouse_position();
 9730                        let size = window.window_bounds().get_bounds().size;
 9731                        let Some(edge) =
 9732                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9733                        else {
 9734                            return;
 9735                        };
 9736                        cx.set_global(GlobalResizeEdge(edge));
 9737                        window.set_cursor_style(
 9738                            match edge {
 9739                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9740                                ResizeEdge::Left | ResizeEdge::Right => {
 9741                                    CursorStyle::ResizeLeftRight
 9742                                }
 9743                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9744                                    CursorStyle::ResizeUpLeftDownRight
 9745                                }
 9746                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9747                                    CursorStyle::ResizeUpRightDownLeft
 9748                                }
 9749                            },
 9750                            &hitbox,
 9751                        );
 9752                    },
 9753                )
 9754                .size_full()
 9755                .absolute(),
 9756            ),
 9757        })
 9758}
 9759
 9760fn resize_edge(
 9761    pos: Point<Pixels>,
 9762    shadow_size: Pixels,
 9763    window_size: Size<Pixels>,
 9764    tiling: Tiling,
 9765) -> Option<ResizeEdge> {
 9766    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9767    if bounds.contains(&pos) {
 9768        return None;
 9769    }
 9770
 9771    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9772    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9773    if !tiling.top && top_left_bounds.contains(&pos) {
 9774        return Some(ResizeEdge::TopLeft);
 9775    }
 9776
 9777    let top_right_bounds = Bounds::new(
 9778        Point::new(window_size.width - corner_size.width, px(0.)),
 9779        corner_size,
 9780    );
 9781    if !tiling.top && top_right_bounds.contains(&pos) {
 9782        return Some(ResizeEdge::TopRight);
 9783    }
 9784
 9785    let bottom_left_bounds = Bounds::new(
 9786        Point::new(px(0.), window_size.height - corner_size.height),
 9787        corner_size,
 9788    );
 9789    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9790        return Some(ResizeEdge::BottomLeft);
 9791    }
 9792
 9793    let bottom_right_bounds = Bounds::new(
 9794        Point::new(
 9795            window_size.width - corner_size.width,
 9796            window_size.height - corner_size.height,
 9797        ),
 9798        corner_size,
 9799    );
 9800    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9801        return Some(ResizeEdge::BottomRight);
 9802    }
 9803
 9804    if !tiling.top && pos.y < shadow_size {
 9805        Some(ResizeEdge::Top)
 9806    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9807        Some(ResizeEdge::Bottom)
 9808    } else if !tiling.left && pos.x < shadow_size {
 9809        Some(ResizeEdge::Left)
 9810    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9811        Some(ResizeEdge::Right)
 9812    } else {
 9813        None
 9814    }
 9815}
 9816
 9817fn join_pane_into_active(
 9818    active_pane: &Entity<Pane>,
 9819    pane: &Entity<Pane>,
 9820    window: &mut Window,
 9821    cx: &mut App,
 9822) {
 9823    if pane == active_pane {
 9824    } else if pane.read(cx).items_len() == 0 {
 9825        pane.update(cx, |_, cx| {
 9826            cx.emit(pane::Event::Remove {
 9827                focus_on_pane: None,
 9828            });
 9829        })
 9830    } else {
 9831        move_all_items(pane, active_pane, window, cx);
 9832    }
 9833}
 9834
 9835fn move_all_items(
 9836    from_pane: &Entity<Pane>,
 9837    to_pane: &Entity<Pane>,
 9838    window: &mut Window,
 9839    cx: &mut App,
 9840) {
 9841    let destination_is_different = from_pane != to_pane;
 9842    let mut moved_items = 0;
 9843    for (item_ix, item_handle) in from_pane
 9844        .read(cx)
 9845        .items()
 9846        .enumerate()
 9847        .map(|(ix, item)| (ix, item.clone()))
 9848        .collect::<Vec<_>>()
 9849    {
 9850        let ix = item_ix - moved_items;
 9851        if destination_is_different {
 9852            // Close item from previous pane
 9853            from_pane.update(cx, |source, cx| {
 9854                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9855            });
 9856            moved_items += 1;
 9857        }
 9858
 9859        // This automatically removes duplicate items in the pane
 9860        to_pane.update(cx, |destination, cx| {
 9861            destination.add_item(item_handle, true, true, None, window, cx);
 9862            window.focus(&destination.focus_handle(cx), cx)
 9863        });
 9864    }
 9865}
 9866
 9867pub fn move_item(
 9868    source: &Entity<Pane>,
 9869    destination: &Entity<Pane>,
 9870    item_id_to_move: EntityId,
 9871    destination_index: usize,
 9872    activate: bool,
 9873    window: &mut Window,
 9874    cx: &mut App,
 9875) {
 9876    let Some((item_ix, item_handle)) = source
 9877        .read(cx)
 9878        .items()
 9879        .enumerate()
 9880        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9881        .map(|(ix, item)| (ix, item.clone()))
 9882    else {
 9883        // Tab was closed during drag
 9884        return;
 9885    };
 9886
 9887    if source != destination {
 9888        // Close item from previous pane
 9889        source.update(cx, |source, cx| {
 9890            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9891        });
 9892    }
 9893
 9894    // This automatically removes duplicate items in the pane
 9895    destination.update(cx, |destination, cx| {
 9896        destination.add_item_inner(
 9897            item_handle,
 9898            activate,
 9899            activate,
 9900            activate,
 9901            Some(destination_index),
 9902            window,
 9903            cx,
 9904        );
 9905        if activate {
 9906            window.focus(&destination.focus_handle(cx), cx)
 9907        }
 9908    });
 9909}
 9910
 9911pub fn move_active_item(
 9912    source: &Entity<Pane>,
 9913    destination: &Entity<Pane>,
 9914    focus_destination: bool,
 9915    close_if_empty: bool,
 9916    window: &mut Window,
 9917    cx: &mut App,
 9918) {
 9919    if source == destination {
 9920        return;
 9921    }
 9922    let Some(active_item) = source.read(cx).active_item() else {
 9923        return;
 9924    };
 9925    source.update(cx, |source_pane, cx| {
 9926        let item_id = active_item.item_id();
 9927        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9928        destination.update(cx, |target_pane, cx| {
 9929            target_pane.add_item(
 9930                active_item,
 9931                focus_destination,
 9932                focus_destination,
 9933                Some(target_pane.items_len()),
 9934                window,
 9935                cx,
 9936            );
 9937        });
 9938    });
 9939}
 9940
 9941pub fn clone_active_item(
 9942    workspace_id: Option<WorkspaceId>,
 9943    source: &Entity<Pane>,
 9944    destination: &Entity<Pane>,
 9945    focus_destination: bool,
 9946    window: &mut Window,
 9947    cx: &mut App,
 9948) {
 9949    if source == destination {
 9950        return;
 9951    }
 9952    let Some(active_item) = source.read(cx).active_item() else {
 9953        return;
 9954    };
 9955    if !active_item.can_split(cx) {
 9956        return;
 9957    }
 9958    let destination = destination.downgrade();
 9959    let task = active_item.clone_on_split(workspace_id, window, cx);
 9960    window
 9961        .spawn(cx, async move |cx| {
 9962            let Some(clone) = task.await else {
 9963                return;
 9964            };
 9965            destination
 9966                .update_in(cx, |target_pane, window, cx| {
 9967                    target_pane.add_item(
 9968                        clone,
 9969                        focus_destination,
 9970                        focus_destination,
 9971                        Some(target_pane.items_len()),
 9972                        window,
 9973                        cx,
 9974                    );
 9975                })
 9976                .log_err();
 9977        })
 9978        .detach();
 9979}
 9980
 9981#[derive(Debug)]
 9982pub struct WorkspacePosition {
 9983    pub window_bounds: Option<WindowBounds>,
 9984    pub display: Option<Uuid>,
 9985    pub centered_layout: bool,
 9986}
 9987
 9988pub fn remote_workspace_position_from_db(
 9989    connection_options: RemoteConnectionOptions,
 9990    paths_to_open: &[PathBuf],
 9991    cx: &App,
 9992) -> Task<Result<WorkspacePosition>> {
 9993    let paths = paths_to_open.to_vec();
 9994
 9995    cx.background_spawn(async move {
 9996        let remote_connection_id = persistence::DB
 9997            .get_or_create_remote_connection(connection_options)
 9998            .await
 9999            .context("fetching serialized ssh project")?;
10000        let serialized_workspace =
10001            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
10002
10003        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10004            (Some(WindowBounds::Windowed(bounds)), None)
10005        } else {
10006            let restorable_bounds = serialized_workspace
10007                .as_ref()
10008                .and_then(|workspace| {
10009                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10010                })
10011                .or_else(|| persistence::read_default_window_bounds());
10012
10013            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10014                (Some(serialized_bounds), Some(serialized_display))
10015            } else {
10016                (None, None)
10017            }
10018        };
10019
10020        let centered_layout = serialized_workspace
10021            .as_ref()
10022            .map(|w| w.centered_layout)
10023            .unwrap_or(false);
10024
10025        Ok(WorkspacePosition {
10026            window_bounds,
10027            display,
10028            centered_layout,
10029        })
10030    })
10031}
10032
10033pub fn with_active_or_new_workspace(
10034    cx: &mut App,
10035    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10036) {
10037    match cx
10038        .active_window()
10039        .and_then(|w| w.downcast::<MultiWorkspace>())
10040    {
10041        Some(multi_workspace) => {
10042            cx.defer(move |cx| {
10043                multi_workspace
10044                    .update(cx, |multi_workspace, window, cx| {
10045                        let workspace = multi_workspace.workspace().clone();
10046                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10047                    })
10048                    .log_err();
10049            });
10050        }
10051        None => {
10052            let app_state = AppState::global(cx);
10053            if let Some(app_state) = app_state.upgrade() {
10054                open_new(
10055                    OpenOptions::default(),
10056                    app_state,
10057                    cx,
10058                    move |workspace, window, cx| f(workspace, window, cx),
10059                )
10060                .detach_and_log_err(cx);
10061            }
10062        }
10063    }
10064}
10065
10066#[cfg(test)]
10067mod tests {
10068    use std::{cell::RefCell, rc::Rc};
10069
10070    use super::*;
10071    use crate::{
10072        dock::{PanelEvent, test::TestPanel},
10073        item::{
10074            ItemBufferKind, ItemEvent,
10075            test::{TestItem, TestProjectItem},
10076        },
10077    };
10078    use fs::FakeFs;
10079    use gpui::{
10080        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10081        UpdateGlobal, VisualTestContext, px,
10082    };
10083    use project::{Project, ProjectEntryId};
10084    use serde_json::json;
10085    use settings::SettingsStore;
10086    use util::rel_path::rel_path;
10087
10088    #[gpui::test]
10089    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10090        init_test(cx);
10091
10092        let fs = FakeFs::new(cx.executor());
10093        let project = Project::test(fs, [], cx).await;
10094        let (workspace, cx) =
10095            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10096
10097        // Adding an item with no ambiguity renders the tab without detail.
10098        let item1 = cx.new(|cx| {
10099            let mut item = TestItem::new(cx);
10100            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10101            item
10102        });
10103        workspace.update_in(cx, |workspace, window, cx| {
10104            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10105        });
10106        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10107
10108        // Adding an item that creates ambiguity increases the level of detail on
10109        // both tabs.
10110        let item2 = cx.new_window_entity(|_window, cx| {
10111            let mut item = TestItem::new(cx);
10112            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10113            item
10114        });
10115        workspace.update_in(cx, |workspace, window, cx| {
10116            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10117        });
10118        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10119        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10120
10121        // Adding an item that creates ambiguity increases the level of detail only
10122        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10123        // we stop at the highest detail available.
10124        let item3 = cx.new(|cx| {
10125            let mut item = TestItem::new(cx);
10126            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10127            item
10128        });
10129        workspace.update_in(cx, |workspace, window, cx| {
10130            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10131        });
10132        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10133        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10134        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10135    }
10136
10137    #[gpui::test]
10138    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10139        init_test(cx);
10140
10141        let fs = FakeFs::new(cx.executor());
10142        fs.insert_tree(
10143            "/root1",
10144            json!({
10145                "one.txt": "",
10146                "two.txt": "",
10147            }),
10148        )
10149        .await;
10150        fs.insert_tree(
10151            "/root2",
10152            json!({
10153                "three.txt": "",
10154            }),
10155        )
10156        .await;
10157
10158        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10159        let (workspace, cx) =
10160            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10161        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10162        let worktree_id = project.update(cx, |project, cx| {
10163            project.worktrees(cx).next().unwrap().read(cx).id()
10164        });
10165
10166        let item1 = cx.new(|cx| {
10167            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10168        });
10169        let item2 = cx.new(|cx| {
10170            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10171        });
10172
10173        // Add an item to an empty pane
10174        workspace.update_in(cx, |workspace, window, cx| {
10175            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10176        });
10177        project.update(cx, |project, cx| {
10178            assert_eq!(
10179                project.active_entry(),
10180                project
10181                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10182                    .map(|e| e.id)
10183            );
10184        });
10185        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10186
10187        // Add a second item to a non-empty pane
10188        workspace.update_in(cx, |workspace, window, cx| {
10189            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10190        });
10191        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10192        project.update(cx, |project, cx| {
10193            assert_eq!(
10194                project.active_entry(),
10195                project
10196                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10197                    .map(|e| e.id)
10198            );
10199        });
10200
10201        // Close the active item
10202        pane.update_in(cx, |pane, window, cx| {
10203            pane.close_active_item(&Default::default(), window, cx)
10204        })
10205        .await
10206        .unwrap();
10207        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10208        project.update(cx, |project, cx| {
10209            assert_eq!(
10210                project.active_entry(),
10211                project
10212                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10213                    .map(|e| e.id)
10214            );
10215        });
10216
10217        // Add a project folder
10218        project
10219            .update(cx, |project, cx| {
10220                project.find_or_create_worktree("root2", true, cx)
10221            })
10222            .await
10223            .unwrap();
10224        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10225
10226        // Remove a project folder
10227        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10228        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10229    }
10230
10231    #[gpui::test]
10232    async fn test_close_window(cx: &mut TestAppContext) {
10233        init_test(cx);
10234
10235        let fs = FakeFs::new(cx.executor());
10236        fs.insert_tree("/root", json!({ "one": "" })).await;
10237
10238        let project = Project::test(fs, ["root".as_ref()], cx).await;
10239        let (workspace, cx) =
10240            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10241
10242        // When there are no dirty items, there's nothing to do.
10243        let item1 = cx.new(TestItem::new);
10244        workspace.update_in(cx, |w, window, cx| {
10245            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10246        });
10247        let task = workspace.update_in(cx, |w, window, cx| {
10248            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10249        });
10250        assert!(task.await.unwrap());
10251
10252        // When there are dirty untitled items, prompt to save each one. If the user
10253        // cancels any prompt, then abort.
10254        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10255        let item3 = cx.new(|cx| {
10256            TestItem::new(cx)
10257                .with_dirty(true)
10258                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10259        });
10260        workspace.update_in(cx, |w, window, cx| {
10261            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10262            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10263        });
10264        let task = workspace.update_in(cx, |w, window, cx| {
10265            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10266        });
10267        cx.executor().run_until_parked();
10268        cx.simulate_prompt_answer("Cancel"); // cancel save all
10269        cx.executor().run_until_parked();
10270        assert!(!cx.has_pending_prompt());
10271        assert!(!task.await.unwrap());
10272    }
10273
10274    #[gpui::test]
10275    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10276        init_test(cx);
10277
10278        let fs = FakeFs::new(cx.executor());
10279        fs.insert_tree("/root", json!({ "one": "" })).await;
10280
10281        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10282        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10283        let multi_workspace_handle =
10284            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10285        cx.run_until_parked();
10286
10287        let workspace_a = multi_workspace_handle
10288            .read_with(cx, |mw, _| mw.workspace().clone())
10289            .unwrap();
10290
10291        let workspace_b = multi_workspace_handle
10292            .update(cx, |mw, window, cx| {
10293                mw.test_add_workspace(project_b, window, cx)
10294            })
10295            .unwrap();
10296
10297        // Activate workspace A
10298        multi_workspace_handle
10299            .update(cx, |mw, window, cx| {
10300                mw.activate_index(0, window, cx);
10301            })
10302            .unwrap();
10303
10304        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10305
10306        // Workspace A has a clean item
10307        let item_a = cx.new(TestItem::new);
10308        workspace_a.update_in(cx, |w, window, cx| {
10309            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10310        });
10311
10312        // Workspace B has a dirty item
10313        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10314        workspace_b.update_in(cx, |w, window, cx| {
10315            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10316        });
10317
10318        // Verify workspace A is active
10319        multi_workspace_handle
10320            .read_with(cx, |mw, _| {
10321                assert_eq!(mw.active_workspace_index(), 0);
10322            })
10323            .unwrap();
10324
10325        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10326        multi_workspace_handle
10327            .update(cx, |mw, window, cx| {
10328                mw.close_window(&CloseWindow, window, cx);
10329            })
10330            .unwrap();
10331        cx.run_until_parked();
10332
10333        // Workspace B should now be active since it has dirty items that need attention
10334        multi_workspace_handle
10335            .read_with(cx, |mw, _| {
10336                assert_eq!(
10337                    mw.active_workspace_index(),
10338                    1,
10339                    "workspace B should be activated when it prompts"
10340                );
10341            })
10342            .unwrap();
10343
10344        // User cancels the save prompt from workspace B
10345        cx.simulate_prompt_answer("Cancel");
10346        cx.run_until_parked();
10347
10348        // Window should still exist because workspace B's close was cancelled
10349        assert!(
10350            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10351            "window should still exist after cancelling one workspace's close"
10352        );
10353    }
10354
10355    #[gpui::test]
10356    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10357        init_test(cx);
10358
10359        // Register TestItem as a serializable item
10360        cx.update(|cx| {
10361            register_serializable_item::<TestItem>(cx);
10362        });
10363
10364        let fs = FakeFs::new(cx.executor());
10365        fs.insert_tree("/root", json!({ "one": "" })).await;
10366
10367        let project = Project::test(fs, ["root".as_ref()], cx).await;
10368        let (workspace, cx) =
10369            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10370
10371        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10372        let item1 = cx.new(|cx| {
10373            TestItem::new(cx)
10374                .with_dirty(true)
10375                .with_serialize(|| Some(Task::ready(Ok(()))))
10376        });
10377        let item2 = cx.new(|cx| {
10378            TestItem::new(cx)
10379                .with_dirty(true)
10380                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10381                .with_serialize(|| Some(Task::ready(Ok(()))))
10382        });
10383        workspace.update_in(cx, |w, window, cx| {
10384            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10385            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10386        });
10387        let task = workspace.update_in(cx, |w, window, cx| {
10388            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10389        });
10390        assert!(task.await.unwrap());
10391    }
10392
10393    #[gpui::test]
10394    async fn test_close_pane_items(cx: &mut TestAppContext) {
10395        init_test(cx);
10396
10397        let fs = FakeFs::new(cx.executor());
10398
10399        let project = Project::test(fs, None, cx).await;
10400        let (workspace, cx) =
10401            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10402
10403        let item1 = cx.new(|cx| {
10404            TestItem::new(cx)
10405                .with_dirty(true)
10406                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10407        });
10408        let item2 = cx.new(|cx| {
10409            TestItem::new(cx)
10410                .with_dirty(true)
10411                .with_conflict(true)
10412                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10413        });
10414        let item3 = cx.new(|cx| {
10415            TestItem::new(cx)
10416                .with_dirty(true)
10417                .with_conflict(true)
10418                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10419        });
10420        let item4 = cx.new(|cx| {
10421            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10422                let project_item = TestProjectItem::new_untitled(cx);
10423                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10424                project_item
10425            }])
10426        });
10427        let pane = workspace.update_in(cx, |workspace, window, cx| {
10428            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10429            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10430            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10431            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10432            workspace.active_pane().clone()
10433        });
10434
10435        let close_items = pane.update_in(cx, |pane, window, cx| {
10436            pane.activate_item(1, true, true, window, cx);
10437            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10438            let item1_id = item1.item_id();
10439            let item3_id = item3.item_id();
10440            let item4_id = item4.item_id();
10441            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10442                [item1_id, item3_id, item4_id].contains(&id)
10443            })
10444        });
10445        cx.executor().run_until_parked();
10446
10447        assert!(cx.has_pending_prompt());
10448        cx.simulate_prompt_answer("Save all");
10449
10450        cx.executor().run_until_parked();
10451
10452        // Item 1 is saved. There's a prompt to save item 3.
10453        pane.update(cx, |pane, cx| {
10454            assert_eq!(item1.read(cx).save_count, 1);
10455            assert_eq!(item1.read(cx).save_as_count, 0);
10456            assert_eq!(item1.read(cx).reload_count, 0);
10457            assert_eq!(pane.items_len(), 3);
10458            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10459        });
10460        assert!(cx.has_pending_prompt());
10461
10462        // Cancel saving item 3.
10463        cx.simulate_prompt_answer("Discard");
10464        cx.executor().run_until_parked();
10465
10466        // Item 3 is reloaded. There's a prompt to save item 4.
10467        pane.update(cx, |pane, cx| {
10468            assert_eq!(item3.read(cx).save_count, 0);
10469            assert_eq!(item3.read(cx).save_as_count, 0);
10470            assert_eq!(item3.read(cx).reload_count, 1);
10471            assert_eq!(pane.items_len(), 2);
10472            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10473        });
10474
10475        // There's a prompt for a path for item 4.
10476        cx.simulate_new_path_selection(|_| Some(Default::default()));
10477        close_items.await.unwrap();
10478
10479        // The requested items are closed.
10480        pane.update(cx, |pane, cx| {
10481            assert_eq!(item4.read(cx).save_count, 0);
10482            assert_eq!(item4.read(cx).save_as_count, 1);
10483            assert_eq!(item4.read(cx).reload_count, 0);
10484            assert_eq!(pane.items_len(), 1);
10485            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10486        });
10487    }
10488
10489    #[gpui::test]
10490    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10491        init_test(cx);
10492
10493        let fs = FakeFs::new(cx.executor());
10494        let project = Project::test(fs, [], cx).await;
10495        let (workspace, cx) =
10496            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10497
10498        // Create several workspace items with single project entries, and two
10499        // workspace items with multiple project entries.
10500        let single_entry_items = (0..=4)
10501            .map(|project_entry_id| {
10502                cx.new(|cx| {
10503                    TestItem::new(cx)
10504                        .with_dirty(true)
10505                        .with_project_items(&[dirty_project_item(
10506                            project_entry_id,
10507                            &format!("{project_entry_id}.txt"),
10508                            cx,
10509                        )])
10510                })
10511            })
10512            .collect::<Vec<_>>();
10513        let item_2_3 = cx.new(|cx| {
10514            TestItem::new(cx)
10515                .with_dirty(true)
10516                .with_buffer_kind(ItemBufferKind::Multibuffer)
10517                .with_project_items(&[
10518                    single_entry_items[2].read(cx).project_items[0].clone(),
10519                    single_entry_items[3].read(cx).project_items[0].clone(),
10520                ])
10521        });
10522        let item_3_4 = cx.new(|cx| {
10523            TestItem::new(cx)
10524                .with_dirty(true)
10525                .with_buffer_kind(ItemBufferKind::Multibuffer)
10526                .with_project_items(&[
10527                    single_entry_items[3].read(cx).project_items[0].clone(),
10528                    single_entry_items[4].read(cx).project_items[0].clone(),
10529                ])
10530        });
10531
10532        // Create two panes that contain the following project entries:
10533        //   left pane:
10534        //     multi-entry items:   (2, 3)
10535        //     single-entry items:  0, 2, 3, 4
10536        //   right pane:
10537        //     single-entry items:  4, 1
10538        //     multi-entry items:   (3, 4)
10539        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10540            let left_pane = workspace.active_pane().clone();
10541            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10542            workspace.add_item_to_active_pane(
10543                single_entry_items[0].boxed_clone(),
10544                None,
10545                true,
10546                window,
10547                cx,
10548            );
10549            workspace.add_item_to_active_pane(
10550                single_entry_items[2].boxed_clone(),
10551                None,
10552                true,
10553                window,
10554                cx,
10555            );
10556            workspace.add_item_to_active_pane(
10557                single_entry_items[3].boxed_clone(),
10558                None,
10559                true,
10560                window,
10561                cx,
10562            );
10563            workspace.add_item_to_active_pane(
10564                single_entry_items[4].boxed_clone(),
10565                None,
10566                true,
10567                window,
10568                cx,
10569            );
10570
10571            let right_pane =
10572                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10573
10574            let boxed_clone = single_entry_items[1].boxed_clone();
10575            let right_pane = window.spawn(cx, async move |cx| {
10576                right_pane.await.inspect(|right_pane| {
10577                    right_pane
10578                        .update_in(cx, |pane, window, cx| {
10579                            pane.add_item(boxed_clone, true, true, None, window, cx);
10580                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10581                        })
10582                        .unwrap();
10583                })
10584            });
10585
10586            (left_pane, right_pane)
10587        });
10588        let right_pane = right_pane.await.unwrap();
10589        cx.focus(&right_pane);
10590
10591        let close = right_pane.update_in(cx, |pane, window, cx| {
10592            pane.close_all_items(&CloseAllItems::default(), window, cx)
10593                .unwrap()
10594        });
10595        cx.executor().run_until_parked();
10596
10597        let msg = cx.pending_prompt().unwrap().0;
10598        assert!(msg.contains("1.txt"));
10599        assert!(!msg.contains("2.txt"));
10600        assert!(!msg.contains("3.txt"));
10601        assert!(!msg.contains("4.txt"));
10602
10603        // With best-effort close, cancelling item 1 keeps it open but items 4
10604        // and (3,4) still close since their entries exist in left pane.
10605        cx.simulate_prompt_answer("Cancel");
10606        close.await;
10607
10608        right_pane.read_with(cx, |pane, _| {
10609            assert_eq!(pane.items_len(), 1);
10610        });
10611
10612        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10613        left_pane
10614            .update_in(cx, |left_pane, window, cx| {
10615                left_pane.close_item_by_id(
10616                    single_entry_items[3].entity_id(),
10617                    SaveIntent::Skip,
10618                    window,
10619                    cx,
10620                )
10621            })
10622            .await
10623            .unwrap();
10624
10625        let close = left_pane.update_in(cx, |pane, window, cx| {
10626            pane.close_all_items(&CloseAllItems::default(), window, cx)
10627                .unwrap()
10628        });
10629        cx.executor().run_until_parked();
10630
10631        let details = cx.pending_prompt().unwrap().1;
10632        assert!(details.contains("0.txt"));
10633        assert!(details.contains("3.txt"));
10634        assert!(details.contains("4.txt"));
10635        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10636        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10637        // assert!(!details.contains("2.txt"));
10638
10639        cx.simulate_prompt_answer("Save all");
10640        cx.executor().run_until_parked();
10641        close.await;
10642
10643        left_pane.read_with(cx, |pane, _| {
10644            assert_eq!(pane.items_len(), 0);
10645        });
10646    }
10647
10648    #[gpui::test]
10649    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10650        init_test(cx);
10651
10652        let fs = FakeFs::new(cx.executor());
10653        let project = Project::test(fs, [], cx).await;
10654        let (workspace, cx) =
10655            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10656        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10657
10658        let item = cx.new(|cx| {
10659            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10660        });
10661        let item_id = item.entity_id();
10662        workspace.update_in(cx, |workspace, window, cx| {
10663            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10664        });
10665
10666        // Autosave on window change.
10667        item.update(cx, |item, cx| {
10668            SettingsStore::update_global(cx, |settings, cx| {
10669                settings.update_user_settings(cx, |settings| {
10670                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10671                })
10672            });
10673            item.is_dirty = true;
10674        });
10675
10676        // Deactivating the window saves the file.
10677        cx.deactivate_window();
10678        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10679
10680        // Re-activating the window doesn't save the file.
10681        cx.update(|window, _| window.activate_window());
10682        cx.executor().run_until_parked();
10683        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10684
10685        // Autosave on focus change.
10686        item.update_in(cx, |item, window, cx| {
10687            cx.focus_self(window);
10688            SettingsStore::update_global(cx, |settings, cx| {
10689                settings.update_user_settings(cx, |settings| {
10690                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10691                })
10692            });
10693            item.is_dirty = true;
10694        });
10695        // Blurring the item saves the file.
10696        item.update_in(cx, |_, window, _| window.blur());
10697        cx.executor().run_until_parked();
10698        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10699
10700        // Deactivating the window still saves the file.
10701        item.update_in(cx, |item, window, cx| {
10702            cx.focus_self(window);
10703            item.is_dirty = true;
10704        });
10705        cx.deactivate_window();
10706        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10707
10708        // Autosave after delay.
10709        item.update(cx, |item, cx| {
10710            SettingsStore::update_global(cx, |settings, cx| {
10711                settings.update_user_settings(cx, |settings| {
10712                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10713                        milliseconds: 500.into(),
10714                    });
10715                })
10716            });
10717            item.is_dirty = true;
10718            cx.emit(ItemEvent::Edit);
10719        });
10720
10721        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10722        cx.executor().advance_clock(Duration::from_millis(250));
10723        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10724
10725        // After delay expires, the file is saved.
10726        cx.executor().advance_clock(Duration::from_millis(250));
10727        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10728
10729        // Autosave after delay, should save earlier than delay if tab is closed
10730        item.update(cx, |item, cx| {
10731            item.is_dirty = true;
10732            cx.emit(ItemEvent::Edit);
10733        });
10734        cx.executor().advance_clock(Duration::from_millis(250));
10735        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10736
10737        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10738        pane.update_in(cx, |pane, window, cx| {
10739            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10740        })
10741        .await
10742        .unwrap();
10743        assert!(!cx.has_pending_prompt());
10744        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10745
10746        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10747        workspace.update_in(cx, |workspace, window, cx| {
10748            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10749        });
10750        item.update_in(cx, |item, _window, cx| {
10751            item.is_dirty = true;
10752            for project_item in &mut item.project_items {
10753                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10754            }
10755        });
10756        cx.run_until_parked();
10757        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10758
10759        // Autosave on focus change, ensuring closing the tab counts as such.
10760        item.update(cx, |item, cx| {
10761            SettingsStore::update_global(cx, |settings, cx| {
10762                settings.update_user_settings(cx, |settings| {
10763                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10764                })
10765            });
10766            item.is_dirty = true;
10767            for project_item in &mut item.project_items {
10768                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10769            }
10770        });
10771
10772        pane.update_in(cx, |pane, window, cx| {
10773            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10774        })
10775        .await
10776        .unwrap();
10777        assert!(!cx.has_pending_prompt());
10778        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10779
10780        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10781        workspace.update_in(cx, |workspace, window, cx| {
10782            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10783        });
10784        item.update_in(cx, |item, window, cx| {
10785            item.project_items[0].update(cx, |item, _| {
10786                item.entry_id = None;
10787            });
10788            item.is_dirty = true;
10789            window.blur();
10790        });
10791        cx.run_until_parked();
10792        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10793
10794        // Ensure autosave is prevented for deleted files also when closing the buffer.
10795        let _close_items = pane.update_in(cx, |pane, window, cx| {
10796            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10797        });
10798        cx.run_until_parked();
10799        assert!(cx.has_pending_prompt());
10800        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10801    }
10802
10803    #[gpui::test]
10804    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10805        init_test(cx);
10806
10807        let fs = FakeFs::new(cx.executor());
10808        let project = Project::test(fs, [], cx).await;
10809        let (workspace, cx) =
10810            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10811
10812        // Create a multibuffer-like item with two child focus handles,
10813        // simulating individual buffer editors within a multibuffer.
10814        let item = cx.new(|cx| {
10815            TestItem::new(cx)
10816                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10817                .with_child_focus_handles(2, cx)
10818        });
10819        workspace.update_in(cx, |workspace, window, cx| {
10820            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10821        });
10822
10823        // Set autosave to OnFocusChange and focus the first child handle,
10824        // simulating the user's cursor being inside one of the multibuffer's excerpts.
10825        item.update_in(cx, |item, window, cx| {
10826            SettingsStore::update_global(cx, |settings, cx| {
10827                settings.update_user_settings(cx, |settings| {
10828                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10829                })
10830            });
10831            item.is_dirty = true;
10832            window.focus(&item.child_focus_handles[0], cx);
10833        });
10834        cx.executor().run_until_parked();
10835        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10836
10837        // Moving focus from one child to another within the same item should
10838        // NOT trigger autosave — focus is still within the item's focus hierarchy.
10839        item.update_in(cx, |item, window, cx| {
10840            window.focus(&item.child_focus_handles[1], cx);
10841        });
10842        cx.executor().run_until_parked();
10843        item.read_with(cx, |item, _| {
10844            assert_eq!(
10845                item.save_count, 0,
10846                "Switching focus between children within the same item should not autosave"
10847            );
10848        });
10849
10850        // Blurring the item saves the file. This is the core regression scenario:
10851        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10852        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10853        // the leaf is always a child focus handle, so `on_blur` never detected
10854        // focus leaving the item.
10855        item.update_in(cx, |_, window, _| window.blur());
10856        cx.executor().run_until_parked();
10857        item.read_with(cx, |item, _| {
10858            assert_eq!(
10859                item.save_count, 1,
10860                "Blurring should trigger autosave when focus was on a child of the item"
10861            );
10862        });
10863
10864        // Deactivating the window should also trigger autosave when a child of
10865        // the multibuffer item currently owns focus.
10866        item.update_in(cx, |item, window, cx| {
10867            item.is_dirty = true;
10868            window.focus(&item.child_focus_handles[0], cx);
10869        });
10870        cx.executor().run_until_parked();
10871        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10872
10873        cx.deactivate_window();
10874        item.read_with(cx, |item, _| {
10875            assert_eq!(
10876                item.save_count, 2,
10877                "Deactivating window should trigger autosave when focus was on a child"
10878            );
10879        });
10880    }
10881
10882    #[gpui::test]
10883    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10884        init_test(cx);
10885
10886        let fs = FakeFs::new(cx.executor());
10887
10888        let project = Project::test(fs, [], cx).await;
10889        let (workspace, cx) =
10890            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10891
10892        let item = cx.new(|cx| {
10893            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10894        });
10895        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10896        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10897        let toolbar_notify_count = Rc::new(RefCell::new(0));
10898
10899        workspace.update_in(cx, |workspace, window, cx| {
10900            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10901            let toolbar_notification_count = toolbar_notify_count.clone();
10902            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10903                *toolbar_notification_count.borrow_mut() += 1
10904            })
10905            .detach();
10906        });
10907
10908        pane.read_with(cx, |pane, _| {
10909            assert!(!pane.can_navigate_backward());
10910            assert!(!pane.can_navigate_forward());
10911        });
10912
10913        item.update_in(cx, |item, _, cx| {
10914            item.set_state("one".to_string(), cx);
10915        });
10916
10917        // Toolbar must be notified to re-render the navigation buttons
10918        assert_eq!(*toolbar_notify_count.borrow(), 1);
10919
10920        pane.read_with(cx, |pane, _| {
10921            assert!(pane.can_navigate_backward());
10922            assert!(!pane.can_navigate_forward());
10923        });
10924
10925        workspace
10926            .update_in(cx, |workspace, window, cx| {
10927                workspace.go_back(pane.downgrade(), window, cx)
10928            })
10929            .await
10930            .unwrap();
10931
10932        assert_eq!(*toolbar_notify_count.borrow(), 2);
10933        pane.read_with(cx, |pane, _| {
10934            assert!(!pane.can_navigate_backward());
10935            assert!(pane.can_navigate_forward());
10936        });
10937    }
10938
10939    #[gpui::test]
10940    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10941        init_test(cx);
10942        let fs = FakeFs::new(cx.executor());
10943        let project = Project::test(fs, [], cx).await;
10944        let (multi_workspace, cx) =
10945            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10946        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10947
10948        workspace.update_in(cx, |workspace, window, cx| {
10949            let first_item = cx.new(|cx| {
10950                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10951            });
10952            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10953            workspace.split_pane(
10954                workspace.active_pane().clone(),
10955                SplitDirection::Right,
10956                window,
10957                cx,
10958            );
10959            workspace.split_pane(
10960                workspace.active_pane().clone(),
10961                SplitDirection::Right,
10962                window,
10963                cx,
10964            );
10965        });
10966
10967        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10968            let panes = workspace.center.panes();
10969            assert!(panes.len() >= 2);
10970            (
10971                panes.first().expect("at least one pane").entity_id(),
10972                panes.last().expect("at least one pane").entity_id(),
10973            )
10974        });
10975
10976        workspace.update_in(cx, |workspace, window, cx| {
10977            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10978        });
10979        workspace.update(cx, |workspace, _| {
10980            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10981            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10982        });
10983
10984        cx.dispatch_action(ActivateLastPane);
10985
10986        workspace.update(cx, |workspace, _| {
10987            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10988        });
10989    }
10990
10991    #[gpui::test]
10992    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10993        init_test(cx);
10994        let fs = FakeFs::new(cx.executor());
10995
10996        let project = Project::test(fs, [], cx).await;
10997        let (workspace, cx) =
10998            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10999
11000        let panel = workspace.update_in(cx, |workspace, window, cx| {
11001            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11002            let position = panel.read(cx).position(window, cx);
11003            workspace.add_panel(panel.clone(), position, window, cx);
11004
11005            workspace
11006                .right_dock()
11007                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11008
11009            panel
11010        });
11011
11012        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11013        pane.update_in(cx, |pane, window, cx| {
11014            let item = cx.new(TestItem::new);
11015            pane.add_item(Box::new(item), true, true, None, window, cx);
11016        });
11017
11018        // Transfer focus from center to panel
11019        workspace.update_in(cx, |workspace, window, cx| {
11020            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11021        });
11022
11023        workspace.update_in(cx, |workspace, window, cx| {
11024            assert!(workspace.right_dock().read(cx).is_open());
11025            assert!(!panel.is_zoomed(window, cx));
11026            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11027        });
11028
11029        // Transfer focus from panel to center
11030        workspace.update_in(cx, |workspace, window, cx| {
11031            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11032        });
11033
11034        workspace.update_in(cx, |workspace, window, cx| {
11035            assert!(workspace.right_dock().read(cx).is_open());
11036            assert!(!panel.is_zoomed(window, cx));
11037            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11038        });
11039
11040        // Close the dock
11041        workspace.update_in(cx, |workspace, window, cx| {
11042            workspace.toggle_dock(DockPosition::Right, window, cx);
11043        });
11044
11045        workspace.update_in(cx, |workspace, window, cx| {
11046            assert!(!workspace.right_dock().read(cx).is_open());
11047            assert!(!panel.is_zoomed(window, cx));
11048            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11049        });
11050
11051        // Open the dock
11052        workspace.update_in(cx, |workspace, window, cx| {
11053            workspace.toggle_dock(DockPosition::Right, window, cx);
11054        });
11055
11056        workspace.update_in(cx, |workspace, window, cx| {
11057            assert!(workspace.right_dock().read(cx).is_open());
11058            assert!(!panel.is_zoomed(window, cx));
11059            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11060        });
11061
11062        // Focus and zoom panel
11063        panel.update_in(cx, |panel, window, cx| {
11064            cx.focus_self(window);
11065            panel.set_zoomed(true, window, cx)
11066        });
11067
11068        workspace.update_in(cx, |workspace, window, cx| {
11069            assert!(workspace.right_dock().read(cx).is_open());
11070            assert!(panel.is_zoomed(window, cx));
11071            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11072        });
11073
11074        // Transfer focus to the center closes the dock
11075        workspace.update_in(cx, |workspace, window, cx| {
11076            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11077        });
11078
11079        workspace.update_in(cx, |workspace, window, cx| {
11080            assert!(!workspace.right_dock().read(cx).is_open());
11081            assert!(panel.is_zoomed(window, cx));
11082            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11083        });
11084
11085        // Transferring focus back to the panel keeps it zoomed
11086        workspace.update_in(cx, |workspace, window, cx| {
11087            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11088        });
11089
11090        workspace.update_in(cx, |workspace, window, cx| {
11091            assert!(workspace.right_dock().read(cx).is_open());
11092            assert!(panel.is_zoomed(window, cx));
11093            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11094        });
11095
11096        // Close the dock while it is zoomed
11097        workspace.update_in(cx, |workspace, window, cx| {
11098            workspace.toggle_dock(DockPosition::Right, window, cx)
11099        });
11100
11101        workspace.update_in(cx, |workspace, window, cx| {
11102            assert!(!workspace.right_dock().read(cx).is_open());
11103            assert!(panel.is_zoomed(window, cx));
11104            assert!(workspace.zoomed.is_none());
11105            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11106        });
11107
11108        // Opening the dock, when it's zoomed, retains focus
11109        workspace.update_in(cx, |workspace, window, cx| {
11110            workspace.toggle_dock(DockPosition::Right, window, cx)
11111        });
11112
11113        workspace.update_in(cx, |workspace, window, cx| {
11114            assert!(workspace.right_dock().read(cx).is_open());
11115            assert!(panel.is_zoomed(window, cx));
11116            assert!(workspace.zoomed.is_some());
11117            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11118        });
11119
11120        // Unzoom and close the panel, zoom the active pane.
11121        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11122        workspace.update_in(cx, |workspace, window, cx| {
11123            workspace.toggle_dock(DockPosition::Right, window, cx)
11124        });
11125        pane.update_in(cx, |pane, window, cx| {
11126            pane.toggle_zoom(&Default::default(), window, cx)
11127        });
11128
11129        // Opening a dock unzooms the pane.
11130        workspace.update_in(cx, |workspace, window, cx| {
11131            workspace.toggle_dock(DockPosition::Right, window, cx)
11132        });
11133        workspace.update_in(cx, |workspace, window, cx| {
11134            let pane = pane.read(cx);
11135            assert!(!pane.is_zoomed());
11136            assert!(!pane.focus_handle(cx).is_focused(window));
11137            assert!(workspace.right_dock().read(cx).is_open());
11138            assert!(workspace.zoomed.is_none());
11139        });
11140    }
11141
11142    #[gpui::test]
11143    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11144        init_test(cx);
11145        let fs = FakeFs::new(cx.executor());
11146
11147        let project = Project::test(fs, [], cx).await;
11148        let (workspace, cx) =
11149            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11150
11151        let panel = workspace.update_in(cx, |workspace, window, cx| {
11152            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11153            let position = panel.read(cx).position(window, cx);
11154            workspace.add_panel(panel.clone(), position, window, cx);
11155            panel
11156        });
11157
11158        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11159        pane.update_in(cx, |pane, window, cx| {
11160            let item = cx.new(TestItem::new);
11161            pane.add_item(Box::new(item), true, true, None, window, cx);
11162        });
11163
11164        // Enable close_panel_on_toggle
11165        cx.update_global(|store: &mut SettingsStore, cx| {
11166            store.update_user_settings(cx, |settings| {
11167                settings.workspace.close_panel_on_toggle = Some(true);
11168            });
11169        });
11170
11171        // Panel starts closed. Toggling should open and focus it.
11172        workspace.update_in(cx, |workspace, window, cx| {
11173            assert!(!workspace.right_dock().read(cx).is_open());
11174            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11175        });
11176
11177        workspace.update_in(cx, |workspace, window, cx| {
11178            assert!(
11179                workspace.right_dock().read(cx).is_open(),
11180                "Dock should be open after toggling from center"
11181            );
11182            assert!(
11183                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11184                "Panel should be focused after toggling from center"
11185            );
11186        });
11187
11188        // Panel is open and focused. Toggling should close the panel and
11189        // return focus to the center.
11190        workspace.update_in(cx, |workspace, window, cx| {
11191            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11192        });
11193
11194        workspace.update_in(cx, |workspace, window, cx| {
11195            assert!(
11196                !workspace.right_dock().read(cx).is_open(),
11197                "Dock should be closed after toggling from focused panel"
11198            );
11199            assert!(
11200                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11201                "Panel should not be focused after toggling from focused panel"
11202            );
11203        });
11204
11205        // Open the dock and focus something else so the panel is open but not
11206        // focused. Toggling should focus the panel (not close it).
11207        workspace.update_in(cx, |workspace, window, cx| {
11208            workspace
11209                .right_dock()
11210                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11211            window.focus(&pane.read(cx).focus_handle(cx), cx);
11212        });
11213
11214        workspace.update_in(cx, |workspace, window, cx| {
11215            assert!(workspace.right_dock().read(cx).is_open());
11216            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11217            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11218        });
11219
11220        workspace.update_in(cx, |workspace, window, cx| {
11221            assert!(
11222                workspace.right_dock().read(cx).is_open(),
11223                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11224            );
11225            assert!(
11226                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11227                "Panel should be focused after toggling an open-but-unfocused panel"
11228            );
11229        });
11230
11231        // Now disable the setting and verify the original behavior: toggling
11232        // from a focused panel moves focus to center but leaves the dock open.
11233        cx.update_global(|store: &mut SettingsStore, cx| {
11234            store.update_user_settings(cx, |settings| {
11235                settings.workspace.close_panel_on_toggle = Some(false);
11236            });
11237        });
11238
11239        workspace.update_in(cx, |workspace, window, cx| {
11240            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11241        });
11242
11243        workspace.update_in(cx, |workspace, window, cx| {
11244            assert!(
11245                workspace.right_dock().read(cx).is_open(),
11246                "Dock should remain open when setting is disabled"
11247            );
11248            assert!(
11249                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11250                "Panel should not be focused after toggling with setting disabled"
11251            );
11252        });
11253    }
11254
11255    #[gpui::test]
11256    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11257        init_test(cx);
11258        let fs = FakeFs::new(cx.executor());
11259
11260        let project = Project::test(fs, [], cx).await;
11261        let (workspace, cx) =
11262            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11263
11264        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11265            workspace.active_pane().clone()
11266        });
11267
11268        // Add an item to the pane so it can be zoomed
11269        workspace.update_in(cx, |workspace, window, cx| {
11270            let item = cx.new(TestItem::new);
11271            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11272        });
11273
11274        // Initially not zoomed
11275        workspace.update_in(cx, |workspace, _window, cx| {
11276            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11277            assert!(
11278                workspace.zoomed.is_none(),
11279                "Workspace should track no zoomed pane"
11280            );
11281            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11282        });
11283
11284        // Zoom In
11285        pane.update_in(cx, |pane, window, cx| {
11286            pane.zoom_in(&crate::ZoomIn, window, cx);
11287        });
11288
11289        workspace.update_in(cx, |workspace, window, cx| {
11290            assert!(
11291                pane.read(cx).is_zoomed(),
11292                "Pane should be zoomed after ZoomIn"
11293            );
11294            assert!(
11295                workspace.zoomed.is_some(),
11296                "Workspace should track the zoomed pane"
11297            );
11298            assert!(
11299                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11300                "ZoomIn should focus the pane"
11301            );
11302        });
11303
11304        // Zoom In again is a no-op
11305        pane.update_in(cx, |pane, window, cx| {
11306            pane.zoom_in(&crate::ZoomIn, window, cx);
11307        });
11308
11309        workspace.update_in(cx, |workspace, window, cx| {
11310            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11311            assert!(
11312                workspace.zoomed.is_some(),
11313                "Workspace still tracks zoomed pane"
11314            );
11315            assert!(
11316                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11317                "Pane remains focused after repeated ZoomIn"
11318            );
11319        });
11320
11321        // Zoom Out
11322        pane.update_in(cx, |pane, window, cx| {
11323            pane.zoom_out(&crate::ZoomOut, window, cx);
11324        });
11325
11326        workspace.update_in(cx, |workspace, _window, cx| {
11327            assert!(
11328                !pane.read(cx).is_zoomed(),
11329                "Pane should unzoom after ZoomOut"
11330            );
11331            assert!(
11332                workspace.zoomed.is_none(),
11333                "Workspace clears zoom tracking after ZoomOut"
11334            );
11335        });
11336
11337        // Zoom Out again is a no-op
11338        pane.update_in(cx, |pane, window, cx| {
11339            pane.zoom_out(&crate::ZoomOut, window, cx);
11340        });
11341
11342        workspace.update_in(cx, |workspace, _window, cx| {
11343            assert!(
11344                !pane.read(cx).is_zoomed(),
11345                "Second ZoomOut keeps pane unzoomed"
11346            );
11347            assert!(
11348                workspace.zoomed.is_none(),
11349                "Workspace remains without zoomed pane"
11350            );
11351        });
11352    }
11353
11354    #[gpui::test]
11355    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11356        init_test(cx);
11357        let fs = FakeFs::new(cx.executor());
11358
11359        let project = Project::test(fs, [], cx).await;
11360        let (workspace, cx) =
11361            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11362        workspace.update_in(cx, |workspace, window, cx| {
11363            // Open two docks
11364            let left_dock = workspace.dock_at_position(DockPosition::Left);
11365            let right_dock = workspace.dock_at_position(DockPosition::Right);
11366
11367            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11368            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11369
11370            assert!(left_dock.read(cx).is_open());
11371            assert!(right_dock.read(cx).is_open());
11372        });
11373
11374        workspace.update_in(cx, |workspace, window, cx| {
11375            // Toggle all docks - should close both
11376            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11377
11378            let left_dock = workspace.dock_at_position(DockPosition::Left);
11379            let right_dock = workspace.dock_at_position(DockPosition::Right);
11380            assert!(!left_dock.read(cx).is_open());
11381            assert!(!right_dock.read(cx).is_open());
11382        });
11383
11384        workspace.update_in(cx, |workspace, window, cx| {
11385            // Toggle again - should reopen both
11386            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11387
11388            let left_dock = workspace.dock_at_position(DockPosition::Left);
11389            let right_dock = workspace.dock_at_position(DockPosition::Right);
11390            assert!(left_dock.read(cx).is_open());
11391            assert!(right_dock.read(cx).is_open());
11392        });
11393    }
11394
11395    #[gpui::test]
11396    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11397        init_test(cx);
11398        let fs = FakeFs::new(cx.executor());
11399
11400        let project = Project::test(fs, [], cx).await;
11401        let (workspace, cx) =
11402            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11403        workspace.update_in(cx, |workspace, window, cx| {
11404            // Open two docks
11405            let left_dock = workspace.dock_at_position(DockPosition::Left);
11406            let right_dock = workspace.dock_at_position(DockPosition::Right);
11407
11408            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11409            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11410
11411            assert!(left_dock.read(cx).is_open());
11412            assert!(right_dock.read(cx).is_open());
11413        });
11414
11415        workspace.update_in(cx, |workspace, window, cx| {
11416            // Close them manually
11417            workspace.toggle_dock(DockPosition::Left, window, cx);
11418            workspace.toggle_dock(DockPosition::Right, window, cx);
11419
11420            let left_dock = workspace.dock_at_position(DockPosition::Left);
11421            let right_dock = workspace.dock_at_position(DockPosition::Right);
11422            assert!(!left_dock.read(cx).is_open());
11423            assert!(!right_dock.read(cx).is_open());
11424        });
11425
11426        workspace.update_in(cx, |workspace, window, cx| {
11427            // Toggle all docks - only last closed (right dock) should reopen
11428            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11429
11430            let left_dock = workspace.dock_at_position(DockPosition::Left);
11431            let right_dock = workspace.dock_at_position(DockPosition::Right);
11432            assert!(!left_dock.read(cx).is_open());
11433            assert!(right_dock.read(cx).is_open());
11434        });
11435    }
11436
11437    #[gpui::test]
11438    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11439        init_test(cx);
11440        let fs = FakeFs::new(cx.executor());
11441        let project = Project::test(fs, [], cx).await;
11442        let (multi_workspace, cx) =
11443            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11444        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11445
11446        // Open two docks (left and right) with one panel each
11447        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11448            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11449            let position = left_panel.read(cx).position(window, cx);
11450            workspace.add_panel(left_panel.clone(), position, window, cx);
11451
11452            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11453            let position = right_panel.read(cx).position(window, cx);
11454            workspace.add_panel(right_panel.clone(), position, window, cx);
11455
11456            workspace.toggle_dock(DockPosition::Left, window, cx);
11457            workspace.toggle_dock(DockPosition::Right, window, cx);
11458
11459            // Verify initial state
11460            assert!(
11461                workspace.left_dock().read(cx).is_open(),
11462                "Left dock should be open"
11463            );
11464            assert_eq!(
11465                workspace
11466                    .left_dock()
11467                    .read(cx)
11468                    .visible_panel()
11469                    .unwrap()
11470                    .panel_id(),
11471                left_panel.panel_id(),
11472                "Left panel should be visible in left dock"
11473            );
11474            assert!(
11475                workspace.right_dock().read(cx).is_open(),
11476                "Right dock should be open"
11477            );
11478            assert_eq!(
11479                workspace
11480                    .right_dock()
11481                    .read(cx)
11482                    .visible_panel()
11483                    .unwrap()
11484                    .panel_id(),
11485                right_panel.panel_id(),
11486                "Right panel should be visible in right dock"
11487            );
11488            assert!(
11489                !workspace.bottom_dock().read(cx).is_open(),
11490                "Bottom dock should be closed"
11491            );
11492
11493            (left_panel, right_panel)
11494        });
11495
11496        // Focus the left panel and move it to the next position (bottom dock)
11497        workspace.update_in(cx, |workspace, window, cx| {
11498            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11499            assert!(
11500                left_panel.read(cx).focus_handle(cx).is_focused(window),
11501                "Left panel should be focused"
11502            );
11503        });
11504
11505        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11506
11507        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11508        workspace.update(cx, |workspace, cx| {
11509            assert!(
11510                !workspace.left_dock().read(cx).is_open(),
11511                "Left dock should be closed"
11512            );
11513            assert!(
11514                workspace.bottom_dock().read(cx).is_open(),
11515                "Bottom dock should now be open"
11516            );
11517            assert_eq!(
11518                left_panel.read(cx).position,
11519                DockPosition::Bottom,
11520                "Left panel should now be in the bottom dock"
11521            );
11522            assert_eq!(
11523                workspace
11524                    .bottom_dock()
11525                    .read(cx)
11526                    .visible_panel()
11527                    .unwrap()
11528                    .panel_id(),
11529                left_panel.panel_id(),
11530                "Left panel should be the visible panel in the bottom dock"
11531            );
11532        });
11533
11534        // Toggle all docks off
11535        workspace.update_in(cx, |workspace, window, cx| {
11536            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11537            assert!(
11538                !workspace.left_dock().read(cx).is_open(),
11539                "Left dock should be closed"
11540            );
11541            assert!(
11542                !workspace.right_dock().read(cx).is_open(),
11543                "Right dock should be closed"
11544            );
11545            assert!(
11546                !workspace.bottom_dock().read(cx).is_open(),
11547                "Bottom dock should be closed"
11548            );
11549        });
11550
11551        // Toggle all docks back on and verify positions are restored
11552        workspace.update_in(cx, |workspace, window, cx| {
11553            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11554            assert!(
11555                !workspace.left_dock().read(cx).is_open(),
11556                "Left dock should remain closed"
11557            );
11558            assert!(
11559                workspace.right_dock().read(cx).is_open(),
11560                "Right dock should remain open"
11561            );
11562            assert!(
11563                workspace.bottom_dock().read(cx).is_open(),
11564                "Bottom dock should remain open"
11565            );
11566            assert_eq!(
11567                left_panel.read(cx).position,
11568                DockPosition::Bottom,
11569                "Left panel should remain in the bottom dock"
11570            );
11571            assert_eq!(
11572                right_panel.read(cx).position,
11573                DockPosition::Right,
11574                "Right panel should remain in the right dock"
11575            );
11576            assert_eq!(
11577                workspace
11578                    .bottom_dock()
11579                    .read(cx)
11580                    .visible_panel()
11581                    .unwrap()
11582                    .panel_id(),
11583                left_panel.panel_id(),
11584                "Left panel should be the visible panel in the right dock"
11585            );
11586        });
11587    }
11588
11589    #[gpui::test]
11590    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11591        init_test(cx);
11592
11593        let fs = FakeFs::new(cx.executor());
11594
11595        let project = Project::test(fs, None, cx).await;
11596        let (workspace, cx) =
11597            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11598
11599        // Let's arrange the panes like this:
11600        //
11601        // +-----------------------+
11602        // |         top           |
11603        // +------+--------+-------+
11604        // | left | center | right |
11605        // +------+--------+-------+
11606        // |        bottom         |
11607        // +-----------------------+
11608
11609        let top_item = cx.new(|cx| {
11610            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11611        });
11612        let bottom_item = cx.new(|cx| {
11613            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11614        });
11615        let left_item = cx.new(|cx| {
11616            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11617        });
11618        let right_item = cx.new(|cx| {
11619            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11620        });
11621        let center_item = cx.new(|cx| {
11622            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11623        });
11624
11625        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11626            let top_pane_id = workspace.active_pane().entity_id();
11627            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11628            workspace.split_pane(
11629                workspace.active_pane().clone(),
11630                SplitDirection::Down,
11631                window,
11632                cx,
11633            );
11634            top_pane_id
11635        });
11636        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11637            let bottom_pane_id = workspace.active_pane().entity_id();
11638            workspace.add_item_to_active_pane(
11639                Box::new(bottom_item.clone()),
11640                None,
11641                false,
11642                window,
11643                cx,
11644            );
11645            workspace.split_pane(
11646                workspace.active_pane().clone(),
11647                SplitDirection::Up,
11648                window,
11649                cx,
11650            );
11651            bottom_pane_id
11652        });
11653        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11654            let left_pane_id = workspace.active_pane().entity_id();
11655            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11656            workspace.split_pane(
11657                workspace.active_pane().clone(),
11658                SplitDirection::Right,
11659                window,
11660                cx,
11661            );
11662            left_pane_id
11663        });
11664        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11665            let right_pane_id = workspace.active_pane().entity_id();
11666            workspace.add_item_to_active_pane(
11667                Box::new(right_item.clone()),
11668                None,
11669                false,
11670                window,
11671                cx,
11672            );
11673            workspace.split_pane(
11674                workspace.active_pane().clone(),
11675                SplitDirection::Left,
11676                window,
11677                cx,
11678            );
11679            right_pane_id
11680        });
11681        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11682            let center_pane_id = workspace.active_pane().entity_id();
11683            workspace.add_item_to_active_pane(
11684                Box::new(center_item.clone()),
11685                None,
11686                false,
11687                window,
11688                cx,
11689            );
11690            center_pane_id
11691        });
11692        cx.executor().run_until_parked();
11693
11694        workspace.update_in(cx, |workspace, window, cx| {
11695            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11696
11697            // Join into next from center pane into right
11698            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11699        });
11700
11701        workspace.update_in(cx, |workspace, window, cx| {
11702            let active_pane = workspace.active_pane();
11703            assert_eq!(right_pane_id, active_pane.entity_id());
11704            assert_eq!(2, active_pane.read(cx).items_len());
11705            let item_ids_in_pane =
11706                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11707            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11708            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11709
11710            // Join into next from right pane into bottom
11711            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11712        });
11713
11714        workspace.update_in(cx, |workspace, window, cx| {
11715            let active_pane = workspace.active_pane();
11716            assert_eq!(bottom_pane_id, active_pane.entity_id());
11717            assert_eq!(3, active_pane.read(cx).items_len());
11718            let item_ids_in_pane =
11719                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11720            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11721            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11722            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11723
11724            // Join into next from bottom pane into left
11725            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11726        });
11727
11728        workspace.update_in(cx, |workspace, window, cx| {
11729            let active_pane = workspace.active_pane();
11730            assert_eq!(left_pane_id, active_pane.entity_id());
11731            assert_eq!(4, active_pane.read(cx).items_len());
11732            let item_ids_in_pane =
11733                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11734            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11735            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11736            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11737            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11738
11739            // Join into next from left pane into top
11740            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11741        });
11742
11743        workspace.update_in(cx, |workspace, window, cx| {
11744            let active_pane = workspace.active_pane();
11745            assert_eq!(top_pane_id, active_pane.entity_id());
11746            assert_eq!(5, active_pane.read(cx).items_len());
11747            let item_ids_in_pane =
11748                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11749            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11750            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11751            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11752            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11753            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11754
11755            // Single pane left: no-op
11756            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11757        });
11758
11759        workspace.update(cx, |workspace, _cx| {
11760            let active_pane = workspace.active_pane();
11761            assert_eq!(top_pane_id, active_pane.entity_id());
11762        });
11763    }
11764
11765    fn add_an_item_to_active_pane(
11766        cx: &mut VisualTestContext,
11767        workspace: &Entity<Workspace>,
11768        item_id: u64,
11769    ) -> Entity<TestItem> {
11770        let item = cx.new(|cx| {
11771            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11772                item_id,
11773                "item{item_id}.txt",
11774                cx,
11775            )])
11776        });
11777        workspace.update_in(cx, |workspace, window, cx| {
11778            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11779        });
11780        item
11781    }
11782
11783    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11784        workspace.update_in(cx, |workspace, window, cx| {
11785            workspace.split_pane(
11786                workspace.active_pane().clone(),
11787                SplitDirection::Right,
11788                window,
11789                cx,
11790            )
11791        })
11792    }
11793
11794    #[gpui::test]
11795    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11796        init_test(cx);
11797        let fs = FakeFs::new(cx.executor());
11798        let project = Project::test(fs, None, cx).await;
11799        let (workspace, cx) =
11800            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11801
11802        add_an_item_to_active_pane(cx, &workspace, 1);
11803        split_pane(cx, &workspace);
11804        add_an_item_to_active_pane(cx, &workspace, 2);
11805        split_pane(cx, &workspace); // empty pane
11806        split_pane(cx, &workspace);
11807        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11808
11809        cx.executor().run_until_parked();
11810
11811        workspace.update(cx, |workspace, cx| {
11812            let num_panes = workspace.panes().len();
11813            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11814            let active_item = workspace
11815                .active_pane()
11816                .read(cx)
11817                .active_item()
11818                .expect("item is in focus");
11819
11820            assert_eq!(num_panes, 4);
11821            assert_eq!(num_items_in_current_pane, 1);
11822            assert_eq!(active_item.item_id(), last_item.item_id());
11823        });
11824
11825        workspace.update_in(cx, |workspace, window, cx| {
11826            workspace.join_all_panes(window, cx);
11827        });
11828
11829        workspace.update(cx, |workspace, cx| {
11830            let num_panes = workspace.panes().len();
11831            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11832            let active_item = workspace
11833                .active_pane()
11834                .read(cx)
11835                .active_item()
11836                .expect("item is in focus");
11837
11838            assert_eq!(num_panes, 1);
11839            assert_eq!(num_items_in_current_pane, 3);
11840            assert_eq!(active_item.item_id(), last_item.item_id());
11841        });
11842    }
11843    struct TestModal(FocusHandle);
11844
11845    impl TestModal {
11846        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11847            Self(cx.focus_handle())
11848        }
11849    }
11850
11851    impl EventEmitter<DismissEvent> for TestModal {}
11852
11853    impl Focusable for TestModal {
11854        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11855            self.0.clone()
11856        }
11857    }
11858
11859    impl ModalView for TestModal {}
11860
11861    impl Render for TestModal {
11862        fn render(
11863            &mut self,
11864            _window: &mut Window,
11865            _cx: &mut Context<TestModal>,
11866        ) -> impl IntoElement {
11867            div().track_focus(&self.0)
11868        }
11869    }
11870
11871    #[gpui::test]
11872    async fn test_panels(cx: &mut gpui::TestAppContext) {
11873        init_test(cx);
11874        let fs = FakeFs::new(cx.executor());
11875
11876        let project = Project::test(fs, [], cx).await;
11877        let (multi_workspace, cx) =
11878            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11879        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11880
11881        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11882            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11883            let position = panel_1.read(cx).position(window, cx);
11884            workspace.add_panel(panel_1.clone(), position, window, cx);
11885            workspace.toggle_dock(DockPosition::Left, window, cx);
11886            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11887            let position = panel_2.read(cx).position(window, cx);
11888            workspace.add_panel(panel_2.clone(), position, window, cx);
11889            workspace.toggle_dock(DockPosition::Right, window, cx);
11890
11891            let left_dock = workspace.left_dock();
11892            assert_eq!(
11893                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11894                panel_1.panel_id()
11895            );
11896            assert_eq!(
11897                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11898                panel_1.size(window, cx)
11899            );
11900
11901            left_dock.update(cx, |left_dock, cx| {
11902                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11903            });
11904            assert_eq!(
11905                workspace
11906                    .right_dock()
11907                    .read(cx)
11908                    .visible_panel()
11909                    .unwrap()
11910                    .panel_id(),
11911                panel_2.panel_id(),
11912            );
11913
11914            (panel_1, panel_2)
11915        });
11916
11917        // Move panel_1 to the right
11918        panel_1.update_in(cx, |panel_1, window, cx| {
11919            panel_1.set_position(DockPosition::Right, window, cx)
11920        });
11921
11922        workspace.update_in(cx, |workspace, window, cx| {
11923            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11924            // Since it was the only panel on the left, the left dock should now be closed.
11925            assert!(!workspace.left_dock().read(cx).is_open());
11926            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11927            let right_dock = workspace.right_dock();
11928            assert_eq!(
11929                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11930                panel_1.panel_id()
11931            );
11932            assert_eq!(
11933                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11934                px(1337.)
11935            );
11936
11937            // Now we move panel_2 to the left
11938            panel_2.set_position(DockPosition::Left, window, cx);
11939        });
11940
11941        workspace.update(cx, |workspace, cx| {
11942            // Since panel_2 was not visible on the right, we don't open the left dock.
11943            assert!(!workspace.left_dock().read(cx).is_open());
11944            // And the right dock is unaffected in its displaying of panel_1
11945            assert!(workspace.right_dock().read(cx).is_open());
11946            assert_eq!(
11947                workspace
11948                    .right_dock()
11949                    .read(cx)
11950                    .visible_panel()
11951                    .unwrap()
11952                    .panel_id(),
11953                panel_1.panel_id(),
11954            );
11955        });
11956
11957        // Move panel_1 back to the left
11958        panel_1.update_in(cx, |panel_1, window, cx| {
11959            panel_1.set_position(DockPosition::Left, window, cx)
11960        });
11961
11962        workspace.update_in(cx, |workspace, window, cx| {
11963            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11964            let left_dock = workspace.left_dock();
11965            assert!(left_dock.read(cx).is_open());
11966            assert_eq!(
11967                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11968                panel_1.panel_id()
11969            );
11970            assert_eq!(
11971                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11972                px(1337.)
11973            );
11974            // And the right dock should be closed as it no longer has any panels.
11975            assert!(!workspace.right_dock().read(cx).is_open());
11976
11977            // Now we move panel_1 to the bottom
11978            panel_1.set_position(DockPosition::Bottom, window, cx);
11979        });
11980
11981        workspace.update_in(cx, |workspace, window, cx| {
11982            // Since panel_1 was visible on the left, we close the left dock.
11983            assert!(!workspace.left_dock().read(cx).is_open());
11984            // The bottom dock is sized based on the panel's default size,
11985            // since the panel orientation changed from vertical to horizontal.
11986            let bottom_dock = workspace.bottom_dock();
11987            assert_eq!(
11988                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11989                panel_1.size(window, cx),
11990            );
11991            // Close bottom dock and move panel_1 back to the left.
11992            bottom_dock.update(cx, |bottom_dock, cx| {
11993                bottom_dock.set_open(false, window, cx)
11994            });
11995            panel_1.set_position(DockPosition::Left, window, cx);
11996        });
11997
11998        // Emit activated event on panel 1
11999        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12000
12001        // Now the left dock is open and panel_1 is active and focused.
12002        workspace.update_in(cx, |workspace, window, cx| {
12003            let left_dock = workspace.left_dock();
12004            assert!(left_dock.read(cx).is_open());
12005            assert_eq!(
12006                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12007                panel_1.panel_id(),
12008            );
12009            assert!(panel_1.focus_handle(cx).is_focused(window));
12010        });
12011
12012        // Emit closed event on panel 2, which is not active
12013        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12014
12015        // Wo don't close the left dock, because panel_2 wasn't the active panel
12016        workspace.update(cx, |workspace, cx| {
12017            let left_dock = workspace.left_dock();
12018            assert!(left_dock.read(cx).is_open());
12019            assert_eq!(
12020                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12021                panel_1.panel_id(),
12022            );
12023        });
12024
12025        // Emitting a ZoomIn event shows the panel as zoomed.
12026        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12027        workspace.read_with(cx, |workspace, _| {
12028            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12029            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12030        });
12031
12032        // Move panel to another dock while it is zoomed
12033        panel_1.update_in(cx, |panel, window, cx| {
12034            panel.set_position(DockPosition::Right, window, cx)
12035        });
12036        workspace.read_with(cx, |workspace, _| {
12037            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12038
12039            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12040        });
12041
12042        // This is a helper for getting a:
12043        // - valid focus on an element,
12044        // - that isn't a part of the panes and panels system of the Workspace,
12045        // - and doesn't trigger the 'on_focus_lost' API.
12046        let focus_other_view = {
12047            let workspace = workspace.clone();
12048            move |cx: &mut VisualTestContext| {
12049                workspace.update_in(cx, |workspace, window, cx| {
12050                    if workspace.active_modal::<TestModal>(cx).is_some() {
12051                        workspace.toggle_modal(window, cx, TestModal::new);
12052                        workspace.toggle_modal(window, cx, TestModal::new);
12053                    } else {
12054                        workspace.toggle_modal(window, cx, TestModal::new);
12055                    }
12056                })
12057            }
12058        };
12059
12060        // If focus is transferred to another view that's not a panel or another pane, we still show
12061        // the panel as zoomed.
12062        focus_other_view(cx);
12063        workspace.read_with(cx, |workspace, _| {
12064            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12065            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12066        });
12067
12068        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12069        workspace.update_in(cx, |_workspace, window, cx| {
12070            cx.focus_self(window);
12071        });
12072        workspace.read_with(cx, |workspace, _| {
12073            assert_eq!(workspace.zoomed, None);
12074            assert_eq!(workspace.zoomed_position, None);
12075        });
12076
12077        // If focus is transferred again to another view that's not a panel or a pane, we won't
12078        // show the panel as zoomed because it wasn't zoomed before.
12079        focus_other_view(cx);
12080        workspace.read_with(cx, |workspace, _| {
12081            assert_eq!(workspace.zoomed, None);
12082            assert_eq!(workspace.zoomed_position, None);
12083        });
12084
12085        // When the panel is activated, it is zoomed again.
12086        cx.dispatch_action(ToggleRightDock);
12087        workspace.read_with(cx, |workspace, _| {
12088            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12089            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12090        });
12091
12092        // Emitting a ZoomOut event unzooms the panel.
12093        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12094        workspace.read_with(cx, |workspace, _| {
12095            assert_eq!(workspace.zoomed, None);
12096            assert_eq!(workspace.zoomed_position, None);
12097        });
12098
12099        // Emit closed event on panel 1, which is active
12100        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12101
12102        // Now the left dock is closed, because panel_1 was the active panel
12103        workspace.update(cx, |workspace, cx| {
12104            let right_dock = workspace.right_dock();
12105            assert!(!right_dock.read(cx).is_open());
12106        });
12107    }
12108
12109    #[gpui::test]
12110    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12111        init_test(cx);
12112
12113        let fs = FakeFs::new(cx.background_executor.clone());
12114        let project = Project::test(fs, [], cx).await;
12115        let (workspace, cx) =
12116            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12117        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12118
12119        let dirty_regular_buffer = cx.new(|cx| {
12120            TestItem::new(cx)
12121                .with_dirty(true)
12122                .with_label("1.txt")
12123                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12124        });
12125        let dirty_regular_buffer_2 = cx.new(|cx| {
12126            TestItem::new(cx)
12127                .with_dirty(true)
12128                .with_label("2.txt")
12129                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12130        });
12131        let dirty_multi_buffer_with_both = cx.new(|cx| {
12132            TestItem::new(cx)
12133                .with_dirty(true)
12134                .with_buffer_kind(ItemBufferKind::Multibuffer)
12135                .with_label("Fake Project Search")
12136                .with_project_items(&[
12137                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12138                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12139                ])
12140        });
12141        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12142        workspace.update_in(cx, |workspace, window, cx| {
12143            workspace.add_item(
12144                pane.clone(),
12145                Box::new(dirty_regular_buffer.clone()),
12146                None,
12147                false,
12148                false,
12149                window,
12150                cx,
12151            );
12152            workspace.add_item(
12153                pane.clone(),
12154                Box::new(dirty_regular_buffer_2.clone()),
12155                None,
12156                false,
12157                false,
12158                window,
12159                cx,
12160            );
12161            workspace.add_item(
12162                pane.clone(),
12163                Box::new(dirty_multi_buffer_with_both.clone()),
12164                None,
12165                false,
12166                false,
12167                window,
12168                cx,
12169            );
12170        });
12171
12172        pane.update_in(cx, |pane, window, cx| {
12173            pane.activate_item(2, true, true, window, cx);
12174            assert_eq!(
12175                pane.active_item().unwrap().item_id(),
12176                multi_buffer_with_both_files_id,
12177                "Should select the multi buffer in the pane"
12178            );
12179        });
12180        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12181            pane.close_other_items(
12182                &CloseOtherItems {
12183                    save_intent: Some(SaveIntent::Save),
12184                    close_pinned: true,
12185                },
12186                None,
12187                window,
12188                cx,
12189            )
12190        });
12191        cx.background_executor.run_until_parked();
12192        assert!(!cx.has_pending_prompt());
12193        close_all_but_multi_buffer_task
12194            .await
12195            .expect("Closing all buffers but the multi buffer failed");
12196        pane.update(cx, |pane, cx| {
12197            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12198            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12199            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12200            assert_eq!(pane.items_len(), 1);
12201            assert_eq!(
12202                pane.active_item().unwrap().item_id(),
12203                multi_buffer_with_both_files_id,
12204                "Should have only the multi buffer left in the pane"
12205            );
12206            assert!(
12207                dirty_multi_buffer_with_both.read(cx).is_dirty,
12208                "The multi buffer containing the unsaved buffer should still be dirty"
12209            );
12210        });
12211
12212        dirty_regular_buffer.update(cx, |buffer, cx| {
12213            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12214        });
12215
12216        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12217            pane.close_active_item(
12218                &CloseActiveItem {
12219                    save_intent: Some(SaveIntent::Close),
12220                    close_pinned: false,
12221                },
12222                window,
12223                cx,
12224            )
12225        });
12226        cx.background_executor.run_until_parked();
12227        assert!(
12228            cx.has_pending_prompt(),
12229            "Dirty multi buffer should prompt a save dialog"
12230        );
12231        cx.simulate_prompt_answer("Save");
12232        cx.background_executor.run_until_parked();
12233        close_multi_buffer_task
12234            .await
12235            .expect("Closing the multi buffer failed");
12236        pane.update(cx, |pane, cx| {
12237            assert_eq!(
12238                dirty_multi_buffer_with_both.read(cx).save_count,
12239                1,
12240                "Multi buffer item should get be saved"
12241            );
12242            // Test impl does not save inner items, so we do not assert them
12243            assert_eq!(
12244                pane.items_len(),
12245                0,
12246                "No more items should be left in the pane"
12247            );
12248            assert!(pane.active_item().is_none());
12249        });
12250    }
12251
12252    #[gpui::test]
12253    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12254        cx: &mut TestAppContext,
12255    ) {
12256        init_test(cx);
12257
12258        let fs = FakeFs::new(cx.background_executor.clone());
12259        let project = Project::test(fs, [], cx).await;
12260        let (workspace, cx) =
12261            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12262        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12263
12264        let dirty_regular_buffer = cx.new(|cx| {
12265            TestItem::new(cx)
12266                .with_dirty(true)
12267                .with_label("1.txt")
12268                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12269        });
12270        let dirty_regular_buffer_2 = cx.new(|cx| {
12271            TestItem::new(cx)
12272                .with_dirty(true)
12273                .with_label("2.txt")
12274                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12275        });
12276        let clear_regular_buffer = cx.new(|cx| {
12277            TestItem::new(cx)
12278                .with_label("3.txt")
12279                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12280        });
12281
12282        let dirty_multi_buffer_with_both = cx.new(|cx| {
12283            TestItem::new(cx)
12284                .with_dirty(true)
12285                .with_buffer_kind(ItemBufferKind::Multibuffer)
12286                .with_label("Fake Project Search")
12287                .with_project_items(&[
12288                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12289                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12290                    clear_regular_buffer.read(cx).project_items[0].clone(),
12291                ])
12292        });
12293        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12294        workspace.update_in(cx, |workspace, window, cx| {
12295            workspace.add_item(
12296                pane.clone(),
12297                Box::new(dirty_regular_buffer.clone()),
12298                None,
12299                false,
12300                false,
12301                window,
12302                cx,
12303            );
12304            workspace.add_item(
12305                pane.clone(),
12306                Box::new(dirty_multi_buffer_with_both.clone()),
12307                None,
12308                false,
12309                false,
12310                window,
12311                cx,
12312            );
12313        });
12314
12315        pane.update_in(cx, |pane, window, cx| {
12316            pane.activate_item(1, true, true, window, cx);
12317            assert_eq!(
12318                pane.active_item().unwrap().item_id(),
12319                multi_buffer_with_both_files_id,
12320                "Should select the multi buffer in the pane"
12321            );
12322        });
12323        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12324            pane.close_active_item(
12325                &CloseActiveItem {
12326                    save_intent: None,
12327                    close_pinned: false,
12328                },
12329                window,
12330                cx,
12331            )
12332        });
12333        cx.background_executor.run_until_parked();
12334        assert!(
12335            cx.has_pending_prompt(),
12336            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12337        );
12338    }
12339
12340    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12341    /// closed when they are deleted from disk.
12342    #[gpui::test]
12343    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12344        init_test(cx);
12345
12346        // Enable the close_on_disk_deletion setting
12347        cx.update_global(|store: &mut SettingsStore, cx| {
12348            store.update_user_settings(cx, |settings| {
12349                settings.workspace.close_on_file_delete = Some(true);
12350            });
12351        });
12352
12353        let fs = FakeFs::new(cx.background_executor.clone());
12354        let project = Project::test(fs, [], cx).await;
12355        let (workspace, cx) =
12356            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12357        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12358
12359        // Create a test item that simulates a file
12360        let item = cx.new(|cx| {
12361            TestItem::new(cx)
12362                .with_label("test.txt")
12363                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12364        });
12365
12366        // Add item to workspace
12367        workspace.update_in(cx, |workspace, window, cx| {
12368            workspace.add_item(
12369                pane.clone(),
12370                Box::new(item.clone()),
12371                None,
12372                false,
12373                false,
12374                window,
12375                cx,
12376            );
12377        });
12378
12379        // Verify the item is in the pane
12380        pane.read_with(cx, |pane, _| {
12381            assert_eq!(pane.items().count(), 1);
12382        });
12383
12384        // Simulate file deletion by setting the item's deleted state
12385        item.update(cx, |item, _| {
12386            item.set_has_deleted_file(true);
12387        });
12388
12389        // Emit UpdateTab event to trigger the close behavior
12390        cx.run_until_parked();
12391        item.update(cx, |_, cx| {
12392            cx.emit(ItemEvent::UpdateTab);
12393        });
12394
12395        // Allow the close operation to complete
12396        cx.run_until_parked();
12397
12398        // Verify the item was automatically closed
12399        pane.read_with(cx, |pane, _| {
12400            assert_eq!(
12401                pane.items().count(),
12402                0,
12403                "Item should be automatically closed when file is deleted"
12404            );
12405        });
12406    }
12407
12408    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12409    /// open with a strikethrough when they are deleted from disk.
12410    #[gpui::test]
12411    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12412        init_test(cx);
12413
12414        // Ensure close_on_disk_deletion is disabled (default)
12415        cx.update_global(|store: &mut SettingsStore, cx| {
12416            store.update_user_settings(cx, |settings| {
12417                settings.workspace.close_on_file_delete = Some(false);
12418            });
12419        });
12420
12421        let fs = FakeFs::new(cx.background_executor.clone());
12422        let project = Project::test(fs, [], cx).await;
12423        let (workspace, cx) =
12424            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12425        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12426
12427        // Create a test item that simulates a file
12428        let item = cx.new(|cx| {
12429            TestItem::new(cx)
12430                .with_label("test.txt")
12431                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12432        });
12433
12434        // Add item to workspace
12435        workspace.update_in(cx, |workspace, window, cx| {
12436            workspace.add_item(
12437                pane.clone(),
12438                Box::new(item.clone()),
12439                None,
12440                false,
12441                false,
12442                window,
12443                cx,
12444            );
12445        });
12446
12447        // Verify the item is in the pane
12448        pane.read_with(cx, |pane, _| {
12449            assert_eq!(pane.items().count(), 1);
12450        });
12451
12452        // Simulate file deletion
12453        item.update(cx, |item, _| {
12454            item.set_has_deleted_file(true);
12455        });
12456
12457        // Emit UpdateTab event
12458        cx.run_until_parked();
12459        item.update(cx, |_, cx| {
12460            cx.emit(ItemEvent::UpdateTab);
12461        });
12462
12463        // Allow any potential close operation to complete
12464        cx.run_until_parked();
12465
12466        // Verify the item remains open (with strikethrough)
12467        pane.read_with(cx, |pane, _| {
12468            assert_eq!(
12469                pane.items().count(),
12470                1,
12471                "Item should remain open when close_on_disk_deletion is disabled"
12472            );
12473        });
12474
12475        // Verify the item shows as deleted
12476        item.read_with(cx, |item, _| {
12477            assert!(
12478                item.has_deleted_file,
12479                "Item should be marked as having deleted file"
12480            );
12481        });
12482    }
12483
12484    /// Tests that dirty files are not automatically closed when deleted from disk,
12485    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12486    /// unsaved changes without being prompted.
12487    #[gpui::test]
12488    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12489        init_test(cx);
12490
12491        // Enable the close_on_file_delete setting
12492        cx.update_global(|store: &mut SettingsStore, cx| {
12493            store.update_user_settings(cx, |settings| {
12494                settings.workspace.close_on_file_delete = Some(true);
12495            });
12496        });
12497
12498        let fs = FakeFs::new(cx.background_executor.clone());
12499        let project = Project::test(fs, [], cx).await;
12500        let (workspace, cx) =
12501            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12502        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12503
12504        // Create a dirty test item
12505        let item = cx.new(|cx| {
12506            TestItem::new(cx)
12507                .with_dirty(true)
12508                .with_label("test.txt")
12509                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12510        });
12511
12512        // Add item to workspace
12513        workspace.update_in(cx, |workspace, window, cx| {
12514            workspace.add_item(
12515                pane.clone(),
12516                Box::new(item.clone()),
12517                None,
12518                false,
12519                false,
12520                window,
12521                cx,
12522            );
12523        });
12524
12525        // Simulate file deletion
12526        item.update(cx, |item, _| {
12527            item.set_has_deleted_file(true);
12528        });
12529
12530        // Emit UpdateTab event to trigger the close behavior
12531        cx.run_until_parked();
12532        item.update(cx, |_, cx| {
12533            cx.emit(ItemEvent::UpdateTab);
12534        });
12535
12536        // Allow any potential close operation to complete
12537        cx.run_until_parked();
12538
12539        // Verify the item remains open (dirty files are not auto-closed)
12540        pane.read_with(cx, |pane, _| {
12541            assert_eq!(
12542                pane.items().count(),
12543                1,
12544                "Dirty items should not be automatically closed even when file is deleted"
12545            );
12546        });
12547
12548        // Verify the item is marked as deleted and still dirty
12549        item.read_with(cx, |item, _| {
12550            assert!(
12551                item.has_deleted_file,
12552                "Item should be marked as having deleted file"
12553            );
12554            assert!(item.is_dirty, "Item should still be dirty");
12555        });
12556    }
12557
12558    /// Tests that navigation history is cleaned up when files are auto-closed
12559    /// due to deletion from disk.
12560    #[gpui::test]
12561    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12562        init_test(cx);
12563
12564        // Enable the close_on_file_delete setting
12565        cx.update_global(|store: &mut SettingsStore, cx| {
12566            store.update_user_settings(cx, |settings| {
12567                settings.workspace.close_on_file_delete = Some(true);
12568            });
12569        });
12570
12571        let fs = FakeFs::new(cx.background_executor.clone());
12572        let project = Project::test(fs, [], cx).await;
12573        let (workspace, cx) =
12574            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12575        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12576
12577        // Create test items
12578        let item1 = cx.new(|cx| {
12579            TestItem::new(cx)
12580                .with_label("test1.txt")
12581                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12582        });
12583        let item1_id = item1.item_id();
12584
12585        let item2 = cx.new(|cx| {
12586            TestItem::new(cx)
12587                .with_label("test2.txt")
12588                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12589        });
12590
12591        // Add items to workspace
12592        workspace.update_in(cx, |workspace, window, cx| {
12593            workspace.add_item(
12594                pane.clone(),
12595                Box::new(item1.clone()),
12596                None,
12597                false,
12598                false,
12599                window,
12600                cx,
12601            );
12602            workspace.add_item(
12603                pane.clone(),
12604                Box::new(item2.clone()),
12605                None,
12606                false,
12607                false,
12608                window,
12609                cx,
12610            );
12611        });
12612
12613        // Activate item1 to ensure it gets navigation entries
12614        pane.update_in(cx, |pane, window, cx| {
12615            pane.activate_item(0, true, true, window, cx);
12616        });
12617
12618        // Switch to item2 and back to create navigation history
12619        pane.update_in(cx, |pane, window, cx| {
12620            pane.activate_item(1, true, true, window, cx);
12621        });
12622        cx.run_until_parked();
12623
12624        pane.update_in(cx, |pane, window, cx| {
12625            pane.activate_item(0, true, true, window, cx);
12626        });
12627        cx.run_until_parked();
12628
12629        // Simulate file deletion for item1
12630        item1.update(cx, |item, _| {
12631            item.set_has_deleted_file(true);
12632        });
12633
12634        // Emit UpdateTab event to trigger the close behavior
12635        item1.update(cx, |_, cx| {
12636            cx.emit(ItemEvent::UpdateTab);
12637        });
12638        cx.run_until_parked();
12639
12640        // Verify item1 was closed
12641        pane.read_with(cx, |pane, _| {
12642            assert_eq!(
12643                pane.items().count(),
12644                1,
12645                "Should have 1 item remaining after auto-close"
12646            );
12647        });
12648
12649        // Check navigation history after close
12650        let has_item = pane.read_with(cx, |pane, cx| {
12651            let mut has_item = false;
12652            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12653                if entry.item.id() == item1_id {
12654                    has_item = true;
12655                }
12656            });
12657            has_item
12658        });
12659
12660        assert!(
12661            !has_item,
12662            "Navigation history should not contain closed item entries"
12663        );
12664    }
12665
12666    #[gpui::test]
12667    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12668        cx: &mut TestAppContext,
12669    ) {
12670        init_test(cx);
12671
12672        let fs = FakeFs::new(cx.background_executor.clone());
12673        let project = Project::test(fs, [], cx).await;
12674        let (workspace, cx) =
12675            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12676        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12677
12678        let dirty_regular_buffer = cx.new(|cx| {
12679            TestItem::new(cx)
12680                .with_dirty(true)
12681                .with_label("1.txt")
12682                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12683        });
12684        let dirty_regular_buffer_2 = cx.new(|cx| {
12685            TestItem::new(cx)
12686                .with_dirty(true)
12687                .with_label("2.txt")
12688                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12689        });
12690        let clear_regular_buffer = cx.new(|cx| {
12691            TestItem::new(cx)
12692                .with_label("3.txt")
12693                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12694        });
12695
12696        let dirty_multi_buffer = cx.new(|cx| {
12697            TestItem::new(cx)
12698                .with_dirty(true)
12699                .with_buffer_kind(ItemBufferKind::Multibuffer)
12700                .with_label("Fake Project Search")
12701                .with_project_items(&[
12702                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12703                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12704                    clear_regular_buffer.read(cx).project_items[0].clone(),
12705                ])
12706        });
12707        workspace.update_in(cx, |workspace, window, cx| {
12708            workspace.add_item(
12709                pane.clone(),
12710                Box::new(dirty_regular_buffer.clone()),
12711                None,
12712                false,
12713                false,
12714                window,
12715                cx,
12716            );
12717            workspace.add_item(
12718                pane.clone(),
12719                Box::new(dirty_regular_buffer_2.clone()),
12720                None,
12721                false,
12722                false,
12723                window,
12724                cx,
12725            );
12726            workspace.add_item(
12727                pane.clone(),
12728                Box::new(dirty_multi_buffer.clone()),
12729                None,
12730                false,
12731                false,
12732                window,
12733                cx,
12734            );
12735        });
12736
12737        pane.update_in(cx, |pane, window, cx| {
12738            pane.activate_item(2, true, true, window, cx);
12739            assert_eq!(
12740                pane.active_item().unwrap().item_id(),
12741                dirty_multi_buffer.item_id(),
12742                "Should select the multi buffer in the pane"
12743            );
12744        });
12745        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12746            pane.close_active_item(
12747                &CloseActiveItem {
12748                    save_intent: None,
12749                    close_pinned: false,
12750                },
12751                window,
12752                cx,
12753            )
12754        });
12755        cx.background_executor.run_until_parked();
12756        assert!(
12757            !cx.has_pending_prompt(),
12758            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12759        );
12760        close_multi_buffer_task
12761            .await
12762            .expect("Closing multi buffer failed");
12763        pane.update(cx, |pane, cx| {
12764            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12765            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12766            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12767            assert_eq!(
12768                pane.items()
12769                    .map(|item| item.item_id())
12770                    .sorted()
12771                    .collect::<Vec<_>>(),
12772                vec![
12773                    dirty_regular_buffer.item_id(),
12774                    dirty_regular_buffer_2.item_id(),
12775                ],
12776                "Should have no multi buffer left in the pane"
12777            );
12778            assert!(dirty_regular_buffer.read(cx).is_dirty);
12779            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12780        });
12781    }
12782
12783    #[gpui::test]
12784    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12785        init_test(cx);
12786        let fs = FakeFs::new(cx.executor());
12787        let project = Project::test(fs, [], cx).await;
12788        let (multi_workspace, cx) =
12789            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12790        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12791
12792        // Add a new panel to the right dock, opening the dock and setting the
12793        // focus to the new panel.
12794        let panel = workspace.update_in(cx, |workspace, window, cx| {
12795            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12796            let position = panel.read(cx).position(window, cx);
12797            workspace.add_panel(panel.clone(), position, window, cx);
12798
12799            workspace
12800                .right_dock()
12801                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12802
12803            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12804
12805            panel
12806        });
12807
12808        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12809        // panel to the next valid position which, in this case, is the left
12810        // dock.
12811        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12812        workspace.update(cx, |workspace, cx| {
12813            assert!(workspace.left_dock().read(cx).is_open());
12814            assert_eq!(panel.read(cx).position, DockPosition::Left);
12815        });
12816
12817        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12818        // panel to the next valid position which, in this case, is the bottom
12819        // dock.
12820        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12821        workspace.update(cx, |workspace, cx| {
12822            assert!(workspace.bottom_dock().read(cx).is_open());
12823            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12824        });
12825
12826        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12827        // around moving the panel to its initial position, the right dock.
12828        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12829        workspace.update(cx, |workspace, cx| {
12830            assert!(workspace.right_dock().read(cx).is_open());
12831            assert_eq!(panel.read(cx).position, DockPosition::Right);
12832        });
12833
12834        // Remove focus from the panel, ensuring that, if the panel is not
12835        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12836        // the panel's position, so the panel is still in the right dock.
12837        workspace.update_in(cx, |workspace, window, cx| {
12838            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12839        });
12840
12841        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12842        workspace.update(cx, |workspace, cx| {
12843            assert!(workspace.right_dock().read(cx).is_open());
12844            assert_eq!(panel.read(cx).position, DockPosition::Right);
12845        });
12846    }
12847
12848    #[gpui::test]
12849    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12850        init_test(cx);
12851
12852        let fs = FakeFs::new(cx.executor());
12853        let project = Project::test(fs, [], cx).await;
12854        let (workspace, cx) =
12855            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12856
12857        let item_1 = cx.new(|cx| {
12858            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12859        });
12860        workspace.update_in(cx, |workspace, window, cx| {
12861            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12862            workspace.move_item_to_pane_in_direction(
12863                &MoveItemToPaneInDirection {
12864                    direction: SplitDirection::Right,
12865                    focus: true,
12866                    clone: false,
12867                },
12868                window,
12869                cx,
12870            );
12871            workspace.move_item_to_pane_at_index(
12872                &MoveItemToPane {
12873                    destination: 3,
12874                    focus: true,
12875                    clone: false,
12876                },
12877                window,
12878                cx,
12879            );
12880
12881            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12882            assert_eq!(
12883                pane_items_paths(&workspace.active_pane, cx),
12884                vec!["first.txt".to_string()],
12885                "Single item was not moved anywhere"
12886            );
12887        });
12888
12889        let item_2 = cx.new(|cx| {
12890            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12891        });
12892        workspace.update_in(cx, |workspace, window, cx| {
12893            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12894            assert_eq!(
12895                pane_items_paths(&workspace.panes[0], cx),
12896                vec!["first.txt".to_string(), "second.txt".to_string()],
12897            );
12898            workspace.move_item_to_pane_in_direction(
12899                &MoveItemToPaneInDirection {
12900                    direction: SplitDirection::Right,
12901                    focus: true,
12902                    clone: false,
12903                },
12904                window,
12905                cx,
12906            );
12907
12908            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12909            assert_eq!(
12910                pane_items_paths(&workspace.panes[0], cx),
12911                vec!["first.txt".to_string()],
12912                "After moving, one item should be left in the original pane"
12913            );
12914            assert_eq!(
12915                pane_items_paths(&workspace.panes[1], cx),
12916                vec!["second.txt".to_string()],
12917                "New item should have been moved to the new pane"
12918            );
12919        });
12920
12921        let item_3 = cx.new(|cx| {
12922            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12923        });
12924        workspace.update_in(cx, |workspace, window, cx| {
12925            let original_pane = workspace.panes[0].clone();
12926            workspace.set_active_pane(&original_pane, window, cx);
12927            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12928            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12929            assert_eq!(
12930                pane_items_paths(&workspace.active_pane, cx),
12931                vec!["first.txt".to_string(), "third.txt".to_string()],
12932                "New pane should be ready to move one item out"
12933            );
12934
12935            workspace.move_item_to_pane_at_index(
12936                &MoveItemToPane {
12937                    destination: 3,
12938                    focus: true,
12939                    clone: false,
12940                },
12941                window,
12942                cx,
12943            );
12944            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12945            assert_eq!(
12946                pane_items_paths(&workspace.active_pane, cx),
12947                vec!["first.txt".to_string()],
12948                "After moving, one item should be left in the original pane"
12949            );
12950            assert_eq!(
12951                pane_items_paths(&workspace.panes[1], cx),
12952                vec!["second.txt".to_string()],
12953                "Previously created pane should be unchanged"
12954            );
12955            assert_eq!(
12956                pane_items_paths(&workspace.panes[2], cx),
12957                vec!["third.txt".to_string()],
12958                "New item should have been moved to the new pane"
12959            );
12960        });
12961    }
12962
12963    #[gpui::test]
12964    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12965        init_test(cx);
12966
12967        let fs = FakeFs::new(cx.executor());
12968        let project = Project::test(fs, [], cx).await;
12969        let (workspace, cx) =
12970            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12971
12972        let item_1 = cx.new(|cx| {
12973            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12974        });
12975        workspace.update_in(cx, |workspace, window, cx| {
12976            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12977            workspace.move_item_to_pane_in_direction(
12978                &MoveItemToPaneInDirection {
12979                    direction: SplitDirection::Right,
12980                    focus: true,
12981                    clone: true,
12982                },
12983                window,
12984                cx,
12985            );
12986        });
12987        cx.run_until_parked();
12988        workspace.update_in(cx, |workspace, window, cx| {
12989            workspace.move_item_to_pane_at_index(
12990                &MoveItemToPane {
12991                    destination: 3,
12992                    focus: true,
12993                    clone: true,
12994                },
12995                window,
12996                cx,
12997            );
12998        });
12999        cx.run_until_parked();
13000
13001        workspace.update(cx, |workspace, cx| {
13002            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13003            for pane in workspace.panes() {
13004                assert_eq!(
13005                    pane_items_paths(pane, cx),
13006                    vec!["first.txt".to_string()],
13007                    "Single item exists in all panes"
13008                );
13009            }
13010        });
13011
13012        // verify that the active pane has been updated after waiting for the
13013        // pane focus event to fire and resolve
13014        workspace.read_with(cx, |workspace, _app| {
13015            assert_eq!(
13016                workspace.active_pane(),
13017                &workspace.panes[2],
13018                "The third pane should be the active one: {:?}",
13019                workspace.panes
13020            );
13021        })
13022    }
13023
13024    #[gpui::test]
13025    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13026        init_test(cx);
13027
13028        let fs = FakeFs::new(cx.executor());
13029        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13030
13031        let project = Project::test(fs, ["root".as_ref()], cx).await;
13032        let (workspace, cx) =
13033            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13034
13035        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13036        // Add item to pane A with project path
13037        let item_a = cx.new(|cx| {
13038            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13039        });
13040        workspace.update_in(cx, |workspace, window, cx| {
13041            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13042        });
13043
13044        // Split to create pane B
13045        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13046            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13047        });
13048
13049        // Add item with SAME project path to pane B, and pin it
13050        let item_b = cx.new(|cx| {
13051            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13052        });
13053        pane_b.update_in(cx, |pane, window, cx| {
13054            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13055            pane.set_pinned_count(1);
13056        });
13057
13058        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13059        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13060
13061        // close_pinned: false should only close the unpinned copy
13062        workspace.update_in(cx, |workspace, window, cx| {
13063            workspace.close_item_in_all_panes(
13064                &CloseItemInAllPanes {
13065                    save_intent: Some(SaveIntent::Close),
13066                    close_pinned: false,
13067                },
13068                window,
13069                cx,
13070            )
13071        });
13072        cx.executor().run_until_parked();
13073
13074        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13075        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13076        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13077        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13078
13079        // Split again, seeing as closing the previous item also closed its
13080        // pane, so only pane remains, which does not allow us to properly test
13081        // that both items close when `close_pinned: true`.
13082        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13083            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13084        });
13085
13086        // Add an item with the same project path to pane C so that
13087        // close_item_in_all_panes can determine what to close across all panes
13088        // (it reads the active item from the active pane, and split_pane
13089        // creates an empty pane).
13090        let item_c = cx.new(|cx| {
13091            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13092        });
13093        pane_c.update_in(cx, |pane, window, cx| {
13094            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13095        });
13096
13097        // close_pinned: true should close the pinned copy too
13098        workspace.update_in(cx, |workspace, window, cx| {
13099            let panes_count = workspace.panes().len();
13100            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13101
13102            workspace.close_item_in_all_panes(
13103                &CloseItemInAllPanes {
13104                    save_intent: Some(SaveIntent::Close),
13105                    close_pinned: true,
13106                },
13107                window,
13108                cx,
13109            )
13110        });
13111        cx.executor().run_until_parked();
13112
13113        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13114        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13115        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13116        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13117    }
13118
13119    mod register_project_item_tests {
13120
13121        use super::*;
13122
13123        // View
13124        struct TestPngItemView {
13125            focus_handle: FocusHandle,
13126        }
13127        // Model
13128        struct TestPngItem {}
13129
13130        impl project::ProjectItem for TestPngItem {
13131            fn try_open(
13132                _project: &Entity<Project>,
13133                path: &ProjectPath,
13134                cx: &mut App,
13135            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13136                if path.path.extension().unwrap() == "png" {
13137                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13138                } else {
13139                    None
13140                }
13141            }
13142
13143            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13144                None
13145            }
13146
13147            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13148                None
13149            }
13150
13151            fn is_dirty(&self) -> bool {
13152                false
13153            }
13154        }
13155
13156        impl Item for TestPngItemView {
13157            type Event = ();
13158            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13159                "".into()
13160            }
13161        }
13162        impl EventEmitter<()> for TestPngItemView {}
13163        impl Focusable for TestPngItemView {
13164            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13165                self.focus_handle.clone()
13166            }
13167        }
13168
13169        impl Render for TestPngItemView {
13170            fn render(
13171                &mut self,
13172                _window: &mut Window,
13173                _cx: &mut Context<Self>,
13174            ) -> impl IntoElement {
13175                Empty
13176            }
13177        }
13178
13179        impl ProjectItem for TestPngItemView {
13180            type Item = TestPngItem;
13181
13182            fn for_project_item(
13183                _project: Entity<Project>,
13184                _pane: Option<&Pane>,
13185                _item: Entity<Self::Item>,
13186                _: &mut Window,
13187                cx: &mut Context<Self>,
13188            ) -> Self
13189            where
13190                Self: Sized,
13191            {
13192                Self {
13193                    focus_handle: cx.focus_handle(),
13194                }
13195            }
13196        }
13197
13198        // View
13199        struct TestIpynbItemView {
13200            focus_handle: FocusHandle,
13201        }
13202        // Model
13203        struct TestIpynbItem {}
13204
13205        impl project::ProjectItem for TestIpynbItem {
13206            fn try_open(
13207                _project: &Entity<Project>,
13208                path: &ProjectPath,
13209                cx: &mut App,
13210            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13211                if path.path.extension().unwrap() == "ipynb" {
13212                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13213                } else {
13214                    None
13215                }
13216            }
13217
13218            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13219                None
13220            }
13221
13222            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13223                None
13224            }
13225
13226            fn is_dirty(&self) -> bool {
13227                false
13228            }
13229        }
13230
13231        impl Item for TestIpynbItemView {
13232            type Event = ();
13233            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13234                "".into()
13235            }
13236        }
13237        impl EventEmitter<()> for TestIpynbItemView {}
13238        impl Focusable for TestIpynbItemView {
13239            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13240                self.focus_handle.clone()
13241            }
13242        }
13243
13244        impl Render for TestIpynbItemView {
13245            fn render(
13246                &mut self,
13247                _window: &mut Window,
13248                _cx: &mut Context<Self>,
13249            ) -> impl IntoElement {
13250                Empty
13251            }
13252        }
13253
13254        impl ProjectItem for TestIpynbItemView {
13255            type Item = TestIpynbItem;
13256
13257            fn for_project_item(
13258                _project: Entity<Project>,
13259                _pane: Option<&Pane>,
13260                _item: Entity<Self::Item>,
13261                _: &mut Window,
13262                cx: &mut Context<Self>,
13263            ) -> Self
13264            where
13265                Self: Sized,
13266            {
13267                Self {
13268                    focus_handle: cx.focus_handle(),
13269                }
13270            }
13271        }
13272
13273        struct TestAlternatePngItemView {
13274            focus_handle: FocusHandle,
13275        }
13276
13277        impl Item for TestAlternatePngItemView {
13278            type Event = ();
13279            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13280                "".into()
13281            }
13282        }
13283
13284        impl EventEmitter<()> for TestAlternatePngItemView {}
13285        impl Focusable for TestAlternatePngItemView {
13286            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13287                self.focus_handle.clone()
13288            }
13289        }
13290
13291        impl Render for TestAlternatePngItemView {
13292            fn render(
13293                &mut self,
13294                _window: &mut Window,
13295                _cx: &mut Context<Self>,
13296            ) -> impl IntoElement {
13297                Empty
13298            }
13299        }
13300
13301        impl ProjectItem for TestAlternatePngItemView {
13302            type Item = TestPngItem;
13303
13304            fn for_project_item(
13305                _project: Entity<Project>,
13306                _pane: Option<&Pane>,
13307                _item: Entity<Self::Item>,
13308                _: &mut Window,
13309                cx: &mut Context<Self>,
13310            ) -> Self
13311            where
13312                Self: Sized,
13313            {
13314                Self {
13315                    focus_handle: cx.focus_handle(),
13316                }
13317            }
13318        }
13319
13320        #[gpui::test]
13321        async fn test_register_project_item(cx: &mut TestAppContext) {
13322            init_test(cx);
13323
13324            cx.update(|cx| {
13325                register_project_item::<TestPngItemView>(cx);
13326                register_project_item::<TestIpynbItemView>(cx);
13327            });
13328
13329            let fs = FakeFs::new(cx.executor());
13330            fs.insert_tree(
13331                "/root1",
13332                json!({
13333                    "one.png": "BINARYDATAHERE",
13334                    "two.ipynb": "{ totally a notebook }",
13335                    "three.txt": "editing text, sure why not?"
13336                }),
13337            )
13338            .await;
13339
13340            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13341            let (workspace, cx) =
13342                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13343
13344            let worktree_id = project.update(cx, |project, cx| {
13345                project.worktrees(cx).next().unwrap().read(cx).id()
13346            });
13347
13348            let handle = workspace
13349                .update_in(cx, |workspace, window, cx| {
13350                    let project_path = (worktree_id, rel_path("one.png"));
13351                    workspace.open_path(project_path, None, true, window, cx)
13352                })
13353                .await
13354                .unwrap();
13355
13356            // Now we can check if the handle we got back errored or not
13357            assert_eq!(
13358                handle.to_any_view().entity_type(),
13359                TypeId::of::<TestPngItemView>()
13360            );
13361
13362            let handle = workspace
13363                .update_in(cx, |workspace, window, cx| {
13364                    let project_path = (worktree_id, rel_path("two.ipynb"));
13365                    workspace.open_path(project_path, None, true, window, cx)
13366                })
13367                .await
13368                .unwrap();
13369
13370            assert_eq!(
13371                handle.to_any_view().entity_type(),
13372                TypeId::of::<TestIpynbItemView>()
13373            );
13374
13375            let handle = workspace
13376                .update_in(cx, |workspace, window, cx| {
13377                    let project_path = (worktree_id, rel_path("three.txt"));
13378                    workspace.open_path(project_path, None, true, window, cx)
13379                })
13380                .await;
13381            assert!(handle.is_err());
13382        }
13383
13384        #[gpui::test]
13385        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13386            init_test(cx);
13387
13388            cx.update(|cx| {
13389                register_project_item::<TestPngItemView>(cx);
13390                register_project_item::<TestAlternatePngItemView>(cx);
13391            });
13392
13393            let fs = FakeFs::new(cx.executor());
13394            fs.insert_tree(
13395                "/root1",
13396                json!({
13397                    "one.png": "BINARYDATAHERE",
13398                    "two.ipynb": "{ totally a notebook }",
13399                    "three.txt": "editing text, sure why not?"
13400                }),
13401            )
13402            .await;
13403            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13404            let (workspace, cx) =
13405                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13406            let worktree_id = project.update(cx, |project, cx| {
13407                project.worktrees(cx).next().unwrap().read(cx).id()
13408            });
13409
13410            let handle = workspace
13411                .update_in(cx, |workspace, window, cx| {
13412                    let project_path = (worktree_id, rel_path("one.png"));
13413                    workspace.open_path(project_path, None, true, window, cx)
13414                })
13415                .await
13416                .unwrap();
13417
13418            // This _must_ be the second item registered
13419            assert_eq!(
13420                handle.to_any_view().entity_type(),
13421                TypeId::of::<TestAlternatePngItemView>()
13422            );
13423
13424            let handle = workspace
13425                .update_in(cx, |workspace, window, cx| {
13426                    let project_path = (worktree_id, rel_path("three.txt"));
13427                    workspace.open_path(project_path, None, true, window, cx)
13428                })
13429                .await;
13430            assert!(handle.is_err());
13431        }
13432    }
13433
13434    #[gpui::test]
13435    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13436        init_test(cx);
13437
13438        let fs = FakeFs::new(cx.executor());
13439        let project = Project::test(fs, [], cx).await;
13440        let (workspace, _cx) =
13441            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13442
13443        // Test with status bar shown (default)
13444        workspace.read_with(cx, |workspace, cx| {
13445            let visible = workspace.status_bar_visible(cx);
13446            assert!(visible, "Status bar should be visible by default");
13447        });
13448
13449        // Test with status bar hidden
13450        cx.update_global(|store: &mut SettingsStore, cx| {
13451            store.update_user_settings(cx, |settings| {
13452                settings.status_bar.get_or_insert_default().show = Some(false);
13453            });
13454        });
13455
13456        workspace.read_with(cx, |workspace, cx| {
13457            let visible = workspace.status_bar_visible(cx);
13458            assert!(!visible, "Status bar should be hidden when show is false");
13459        });
13460
13461        // Test with status bar shown explicitly
13462        cx.update_global(|store: &mut SettingsStore, cx| {
13463            store.update_user_settings(cx, |settings| {
13464                settings.status_bar.get_or_insert_default().show = Some(true);
13465            });
13466        });
13467
13468        workspace.read_with(cx, |workspace, cx| {
13469            let visible = workspace.status_bar_visible(cx);
13470            assert!(visible, "Status bar should be visible when show is true");
13471        });
13472    }
13473
13474    #[gpui::test]
13475    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13476        init_test(cx);
13477
13478        let fs = FakeFs::new(cx.executor());
13479        let project = Project::test(fs, [], cx).await;
13480        let (multi_workspace, cx) =
13481            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13482        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13483        let panel = workspace.update_in(cx, |workspace, window, cx| {
13484            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13485            let position = panel.read(cx).position(window, cx);
13486            workspace.add_panel(panel.clone(), position, window, cx);
13487
13488            workspace
13489                .right_dock()
13490                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13491
13492            panel
13493        });
13494
13495        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13496        let item_a = cx.new(TestItem::new);
13497        let item_b = cx.new(TestItem::new);
13498        let item_a_id = item_a.entity_id();
13499        let item_b_id = item_b.entity_id();
13500
13501        pane.update_in(cx, |pane, window, cx| {
13502            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13503            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13504        });
13505
13506        pane.read_with(cx, |pane, _| {
13507            assert_eq!(pane.items_len(), 2);
13508            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13509        });
13510
13511        workspace.update_in(cx, |workspace, window, cx| {
13512            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13513        });
13514
13515        workspace.update_in(cx, |_, window, cx| {
13516            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13517        });
13518
13519        // Assert that the `pane::CloseActiveItem` action is handled at the
13520        // workspace level when one of the dock panels is focused and, in that
13521        // case, the center pane's active item is closed but the focus is not
13522        // moved.
13523        cx.dispatch_action(pane::CloseActiveItem::default());
13524        cx.run_until_parked();
13525
13526        pane.read_with(cx, |pane, _| {
13527            assert_eq!(pane.items_len(), 1);
13528            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13529        });
13530
13531        workspace.update_in(cx, |workspace, window, cx| {
13532            assert!(workspace.right_dock().read(cx).is_open());
13533            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13534        });
13535    }
13536
13537    #[gpui::test]
13538    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13539        init_test(cx);
13540        let fs = FakeFs::new(cx.executor());
13541
13542        let project_a = Project::test(fs.clone(), [], cx).await;
13543        let project_b = Project::test(fs, [], cx).await;
13544
13545        let multi_workspace_handle =
13546            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13547        cx.run_until_parked();
13548
13549        let workspace_a = multi_workspace_handle
13550            .read_with(cx, |mw, _| mw.workspace().clone())
13551            .unwrap();
13552
13553        let _workspace_b = multi_workspace_handle
13554            .update(cx, |mw, window, cx| {
13555                mw.test_add_workspace(project_b, window, cx)
13556            })
13557            .unwrap();
13558
13559        // Switch to workspace A
13560        multi_workspace_handle
13561            .update(cx, |mw, window, cx| {
13562                mw.activate_index(0, window, cx);
13563            })
13564            .unwrap();
13565
13566        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13567
13568        // Add a panel to workspace A's right dock and open the dock
13569        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13570            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13571            let position = panel.read(cx).position(window, cx);
13572            workspace.add_panel(panel.clone(), position, window, cx);
13573            workspace
13574                .right_dock()
13575                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13576            panel
13577        });
13578
13579        // Focus the panel through the workspace (matching existing test pattern)
13580        workspace_a.update_in(cx, |workspace, window, cx| {
13581            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13582        });
13583
13584        // Zoom the panel
13585        panel.update_in(cx, |panel, window, cx| {
13586            panel.set_zoomed(true, window, cx);
13587        });
13588
13589        // Verify the panel is zoomed and the dock is open
13590        workspace_a.update_in(cx, |workspace, window, cx| {
13591            assert!(
13592                workspace.right_dock().read(cx).is_open(),
13593                "dock should be open before switch"
13594            );
13595            assert!(
13596                panel.is_zoomed(window, cx),
13597                "panel should be zoomed before switch"
13598            );
13599            assert!(
13600                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13601                "panel should be focused before switch"
13602            );
13603        });
13604
13605        // Switch to workspace B
13606        multi_workspace_handle
13607            .update(cx, |mw, window, cx| {
13608                mw.activate_index(1, window, cx);
13609            })
13610            .unwrap();
13611        cx.run_until_parked();
13612
13613        // Switch back to workspace A
13614        multi_workspace_handle
13615            .update(cx, |mw, window, cx| {
13616                mw.activate_index(0, window, cx);
13617            })
13618            .unwrap();
13619        cx.run_until_parked();
13620
13621        // Verify the panel is still zoomed and the dock is still open
13622        workspace_a.update_in(cx, |workspace, window, cx| {
13623            assert!(
13624                workspace.right_dock().read(cx).is_open(),
13625                "dock should still be open after switching back"
13626            );
13627            assert!(
13628                panel.is_zoomed(window, cx),
13629                "panel should still be zoomed after switching back"
13630            );
13631        });
13632    }
13633
13634    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13635        pane.read(cx)
13636            .items()
13637            .flat_map(|item| {
13638                item.project_paths(cx)
13639                    .into_iter()
13640                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13641            })
13642            .collect()
13643    }
13644
13645    pub fn init_test(cx: &mut TestAppContext) {
13646        cx.update(|cx| {
13647            let settings_store = SettingsStore::test(cx);
13648            cx.set_global(settings_store);
13649            theme::init(theme::LoadThemes::JustBase, cx);
13650        });
13651    }
13652
13653    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13654        let item = TestProjectItem::new(id, path, cx);
13655        item.update(cx, |item, _| {
13656            item.is_dirty = true;
13657        });
13658        item
13659    }
13660
13661    #[gpui::test]
13662    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13663        cx: &mut gpui::TestAppContext,
13664    ) {
13665        init_test(cx);
13666        let fs = FakeFs::new(cx.executor());
13667
13668        let project = Project::test(fs, [], cx).await;
13669        let (workspace, cx) =
13670            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13671
13672        let panel = workspace.update_in(cx, |workspace, window, cx| {
13673            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13674            let position = panel.read(cx).position(window, cx);
13675            workspace.add_panel(panel.clone(), position, window, cx);
13676            workspace
13677                .right_dock()
13678                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13679            panel
13680        });
13681
13682        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13683        pane.update_in(cx, |pane, window, cx| {
13684            let item = cx.new(TestItem::new);
13685            pane.add_item(Box::new(item), true, true, None, window, cx);
13686        });
13687
13688        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13689        // mirrors the real-world flow and avoids side effects from directly
13690        // focusing the panel while the center pane is active.
13691        workspace.update_in(cx, |workspace, window, cx| {
13692            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13693        });
13694
13695        panel.update_in(cx, |panel, window, cx| {
13696            panel.set_zoomed(true, window, cx);
13697        });
13698
13699        workspace.update_in(cx, |workspace, window, cx| {
13700            assert!(workspace.right_dock().read(cx).is_open());
13701            assert!(panel.is_zoomed(window, cx));
13702            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13703        });
13704
13705        // Simulate a spurious pane::Event::Focus on the center pane while the
13706        // panel still has focus. This mirrors what happens during macOS window
13707        // activation: the center pane fires a focus event even though actual
13708        // focus remains on the dock panel.
13709        pane.update_in(cx, |_, _, cx| {
13710            cx.emit(pane::Event::Focus);
13711        });
13712
13713        // The dock must remain open because the panel had focus at the time the
13714        // event was processed. Before the fix, dock_to_preserve was None for
13715        // panels that don't implement pane(), causing the dock to close.
13716        workspace.update_in(cx, |workspace, window, cx| {
13717            assert!(
13718                workspace.right_dock().read(cx).is_open(),
13719                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13720            );
13721            assert!(panel.is_zoomed(window, cx));
13722        });
13723    }
13724}