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