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;
   10mod path_list;
   11mod persistence;
   12pub mod searchable;
   13mod security_modal;
   14pub mod shared_screen;
   15pub use shared_screen::SharedScreen;
   16mod status_bar;
   17pub mod tasks;
   18mod theme_preview;
   19mod toast_layer;
   20mod toolbar;
   21pub mod welcome;
   22mod workspace_settings;
   23
   24pub use crate::notifications::NotificationFrame;
   25pub use dock::Panel;
   26pub use multi_workspace::{
   27    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
   28    NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
   29    ToggleWorkspaceSidebar,
   30};
   31pub use path_list::PathList;
   32pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   33
   34use anyhow::{Context as _, Result, anyhow};
   35use client::{
   36    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   37    proto::{self, ErrorCode, PanelId, PeerId},
   38};
   39use collections::{HashMap, HashSet, hash_map};
   40use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   41use fs::Fs;
   42use futures::{
   43    Future, FutureExt, StreamExt,
   44    channel::{
   45        mpsc::{self, UnboundedReceiver, UnboundedSender},
   46        oneshot,
   47    },
   48    future::{Shared, try_join_all},
   49};
   50use gpui::{
   51    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   52    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   53    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   54    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   55    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   56    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   57};
   58pub use history_manager::*;
   59pub use item::{
   60    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   61    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   62};
   63use itertools::Itertools;
   64use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   65pub use modal_layer::*;
   66use node_runtime::NodeRuntime;
   67use notifications::{
   68    DetachAndPromptErr, Notifications, dismiss_app_notification,
   69    simple_message_notification::MessageNotification,
   70};
   71pub use pane::*;
   72pub use pane_group::{
   73    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   74    SplitDirection,
   75};
   76use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   77pub use persistence::{
   78    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   79    model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
   80    read_serialized_multi_workspaces,
   81};
   82use postage::stream::Stream;
   83use project::{
   84    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   85    WorktreeSettings,
   86    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   87    project_settings::ProjectSettings,
   88    toolchain_store::ToolchainStoreEvent,
   89    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   90};
   91use remote::{
   92    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   93    remote_client::ConnectionIdentifier,
   94};
   95use schemars::JsonSchema;
   96use serde::Deserialize;
   97use session::AppSession;
   98use settings::{
   99    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  100};
  101
  102use sqlez::{
  103    bindable::{Bind, Column, StaticColumnCount},
  104    statement::Statement,
  105};
  106use status_bar::StatusBar;
  107pub use status_bar::StatusItemView;
  108use std::{
  109    any::TypeId,
  110    borrow::Cow,
  111    cell::RefCell,
  112    cmp,
  113    collections::VecDeque,
  114    env,
  115    hash::Hash,
  116    path::{Path, PathBuf},
  117    process::ExitStatus,
  118    rc::Rc,
  119    sync::{
  120        Arc, LazyLock, Weak,
  121        atomic::{AtomicBool, AtomicUsize},
  122    },
  123    time::Duration,
  124};
  125use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  126use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  127pub use toolbar::{
  128    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  129};
  130pub use ui;
  131use ui::{Window, prelude::*};
  132use util::{
  133    ResultExt, TryFutureExt,
  134    paths::{PathStyle, SanitizedPath},
  135    rel_path::RelPath,
  136    serde::default_true,
  137};
  138use uuid::Uuid;
  139pub use workspace_settings::{
  140    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  141    WorkspaceSettings,
  142};
  143use zed_actions::{Spawn, feedback::FileBugReport};
  144
  145use crate::{item::ItemBufferKind, notifications::NotificationId};
  146use crate::{
  147    persistence::{
  148        SerializedAxis,
  149        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  150    },
  151    security_modal::SecurityModal,
  152};
  153
  154pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  155
  156static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  157    env::var("ZED_WINDOW_SIZE")
  158        .ok()
  159        .as_deref()
  160        .and_then(parse_pixel_size_env_var)
  161});
  162
  163static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  164    env::var("ZED_WINDOW_POSITION")
  165        .ok()
  166        .as_deref()
  167        .and_then(parse_pixel_position_env_var)
  168});
  169
  170pub trait TerminalProvider {
  171    fn spawn(
  172        &self,
  173        task: SpawnInTerminal,
  174        window: &mut Window,
  175        cx: &mut App,
  176    ) -> Task<Option<Result<ExitStatus>>>;
  177}
  178
  179pub trait DebuggerProvider {
  180    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  181    fn start_session(
  182        &self,
  183        definition: DebugScenario,
  184        task_context: SharedTaskContext,
  185        active_buffer: Option<Entity<Buffer>>,
  186        worktree_id: Option<WorktreeId>,
  187        window: &mut Window,
  188        cx: &mut App,
  189    );
  190
  191    fn spawn_task_or_modal(
  192        &self,
  193        workspace: &mut Workspace,
  194        action: &Spawn,
  195        window: &mut Window,
  196        cx: &mut Context<Workspace>,
  197    );
  198
  199    fn task_scheduled(&self, cx: &mut App);
  200    fn debug_scenario_scheduled(&self, cx: &mut App);
  201    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  202
  203    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  204}
  205
  206actions!(
  207    workspace,
  208    [
  209        /// Activates the next pane in the workspace.
  210        ActivateNextPane,
  211        /// Activates the previous pane in the workspace.
  212        ActivatePreviousPane,
  213        /// Activates the last pane in the workspace.
  214        ActivateLastPane,
  215        /// Switches to the next window.
  216        ActivateNextWindow,
  217        /// Switches to the previous window.
  218        ActivatePreviousWindow,
  219        /// Adds a folder to the current project.
  220        AddFolderToProject,
  221        /// Clears all notifications.
  222        ClearAllNotifications,
  223        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  224        ClearNavigationHistory,
  225        /// Closes the active dock.
  226        CloseActiveDock,
  227        /// Closes all docks.
  228        CloseAllDocks,
  229        /// Toggles all docks.
  230        ToggleAllDocks,
  231        /// Closes the current window.
  232        CloseWindow,
  233        /// Closes the current project.
  234        CloseProject,
  235        /// Opens the feedback dialog.
  236        Feedback,
  237        /// Follows the next collaborator in the session.
  238        FollowNextCollaborator,
  239        /// Moves the focused panel to the next position.
  240        MoveFocusedPanelToNextPosition,
  241        /// Creates a new file.
  242        NewFile,
  243        /// Creates a new file in a vertical split.
  244        NewFileSplitVertical,
  245        /// Creates a new file in a horizontal split.
  246        NewFileSplitHorizontal,
  247        /// Opens a new search.
  248        NewSearch,
  249        /// Opens a new window.
  250        NewWindow,
  251        /// Opens a file or directory.
  252        Open,
  253        /// Opens multiple files.
  254        OpenFiles,
  255        /// Opens the current location in terminal.
  256        OpenInTerminal,
  257        /// Opens the component preview.
  258        OpenComponentPreview,
  259        /// Reloads the active item.
  260        ReloadActiveItem,
  261        /// Resets the active dock to its default size.
  262        ResetActiveDockSize,
  263        /// Resets all open docks to their default sizes.
  264        ResetOpenDocksSize,
  265        /// Reloads the application
  266        Reload,
  267        /// Saves the current file with a new name.
  268        SaveAs,
  269        /// Saves without formatting.
  270        SaveWithoutFormat,
  271        /// Shuts down all debug adapters.
  272        ShutdownDebugAdapters,
  273        /// Suppresses the current notification.
  274        SuppressNotification,
  275        /// Toggles the bottom dock.
  276        ToggleBottomDock,
  277        /// Toggles centered layout mode.
  278        ToggleCenteredLayout,
  279        /// Toggles edit prediction feature globally for all files.
  280        ToggleEditPrediction,
  281        /// Toggles the left dock.
  282        ToggleLeftDock,
  283        /// Toggles the right dock.
  284        ToggleRightDock,
  285        /// Toggles zoom on the active pane.
  286        ToggleZoom,
  287        /// Toggles read-only mode for the active item (if supported by that item).
  288        ToggleReadOnlyFile,
  289        /// Zooms in on the active pane.
  290        ZoomIn,
  291        /// Zooms out of the active pane.
  292        ZoomOut,
  293        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  294        /// If the modal is shown already, closes it without trusting any worktree.
  295        ToggleWorktreeSecurity,
  296        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  297        /// Requires restart to take effect on already opened projects.
  298        ClearTrustedWorktrees,
  299        /// Stops following a collaborator.
  300        Unfollow,
  301        /// Restores the banner.
  302        RestoreBanner,
  303        /// Toggles expansion of the selected item.
  304        ToggleExpandItem,
  305    ]
  306);
  307
  308/// Activates a specific pane by its index.
  309#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  310#[action(namespace = workspace)]
  311pub struct ActivatePane(pub usize);
  312
  313/// Moves an item to a specific pane by index.
  314#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  315#[action(namespace = workspace)]
  316#[serde(deny_unknown_fields)]
  317pub struct MoveItemToPane {
  318    #[serde(default = "default_1")]
  319    pub destination: usize,
  320    #[serde(default = "default_true")]
  321    pub focus: bool,
  322    #[serde(default)]
  323    pub clone: bool,
  324}
  325
  326fn default_1() -> usize {
  327    1
  328}
  329
  330/// Moves an item to a pane in the specified direction.
  331#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  332#[action(namespace = workspace)]
  333#[serde(deny_unknown_fields)]
  334pub struct MoveItemToPaneInDirection {
  335    #[serde(default = "default_right")]
  336    pub direction: SplitDirection,
  337    #[serde(default = "default_true")]
  338    pub focus: bool,
  339    #[serde(default)]
  340    pub clone: bool,
  341}
  342
  343/// Creates a new file in a split of the desired direction.
  344#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  345#[action(namespace = workspace)]
  346#[serde(deny_unknown_fields)]
  347pub struct NewFileSplit(pub SplitDirection);
  348
  349fn default_right() -> SplitDirection {
  350    SplitDirection::Right
  351}
  352
  353/// Saves all open files in the workspace.
  354#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  355#[action(namespace = workspace)]
  356#[serde(deny_unknown_fields)]
  357pub struct SaveAll {
  358    #[serde(default)]
  359    pub save_intent: Option<SaveIntent>,
  360}
  361
  362/// Saves the current file with the specified options.
  363#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  364#[action(namespace = workspace)]
  365#[serde(deny_unknown_fields)]
  366pub struct Save {
  367    #[serde(default)]
  368    pub save_intent: Option<SaveIntent>,
  369}
  370
  371/// Closes all items and panes in the workspace.
  372#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  373#[action(namespace = workspace)]
  374#[serde(deny_unknown_fields)]
  375pub struct CloseAllItemsAndPanes {
  376    #[serde(default)]
  377    pub save_intent: Option<SaveIntent>,
  378}
  379
  380/// Closes all inactive tabs and panes in the workspace.
  381#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  382#[action(namespace = workspace)]
  383#[serde(deny_unknown_fields)]
  384pub struct CloseInactiveTabsAndPanes {
  385    #[serde(default)]
  386    pub save_intent: Option<SaveIntent>,
  387}
  388
  389/// Closes the active item across all panes.
  390#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  391#[action(namespace = workspace)]
  392#[serde(deny_unknown_fields)]
  393pub struct CloseItemInAllPanes {
  394    #[serde(default)]
  395    pub save_intent: Option<SaveIntent>,
  396    #[serde(default)]
  397    pub close_pinned: bool,
  398}
  399
  400/// Sends a sequence of keystrokes to the active element.
  401#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  402#[action(namespace = workspace)]
  403pub struct SendKeystrokes(pub String);
  404
  405actions!(
  406    project_symbols,
  407    [
  408        /// Toggles the project symbols search.
  409        #[action(name = "Toggle")]
  410        ToggleProjectSymbols
  411    ]
  412);
  413
  414/// Toggles the file finder interface.
  415#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  416#[action(namespace = file_finder, name = "Toggle")]
  417#[serde(deny_unknown_fields)]
  418pub struct ToggleFileFinder {
  419    #[serde(default)]
  420    pub separate_history: bool,
  421}
  422
  423/// Opens a new terminal in the center.
  424#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  425#[action(namespace = workspace)]
  426#[serde(deny_unknown_fields)]
  427pub struct NewCenterTerminal {
  428    /// If true, creates a local terminal even in remote projects.
  429    #[serde(default)]
  430    pub local: bool,
  431}
  432
  433/// Opens a new terminal.
  434#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  435#[action(namespace = workspace)]
  436#[serde(deny_unknown_fields)]
  437pub struct NewTerminal {
  438    /// If true, creates a local terminal even in remote projects.
  439    #[serde(default)]
  440    pub local: bool,
  441}
  442
  443/// Increases size of a currently focused dock by a given amount of pixels.
  444#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  445#[action(namespace = workspace)]
  446#[serde(deny_unknown_fields)]
  447pub struct IncreaseActiveDockSize {
  448    /// For 0px parameter, uses UI font size value.
  449    #[serde(default)]
  450    pub px: u32,
  451}
  452
  453/// Decreases size of a currently focused dock by a given amount of pixels.
  454#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  455#[action(namespace = workspace)]
  456#[serde(deny_unknown_fields)]
  457pub struct DecreaseActiveDockSize {
  458    /// For 0px parameter, uses UI font size value.
  459    #[serde(default)]
  460    pub px: u32,
  461}
  462
  463/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  464#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  465#[action(namespace = workspace)]
  466#[serde(deny_unknown_fields)]
  467pub struct IncreaseOpenDocksSize {
  468    /// For 0px parameter, uses UI font size value.
  469    #[serde(default)]
  470    pub px: u32,
  471}
  472
  473/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  474#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  475#[action(namespace = workspace)]
  476#[serde(deny_unknown_fields)]
  477pub struct DecreaseOpenDocksSize {
  478    /// For 0px parameter, uses UI font size value.
  479    #[serde(default)]
  480    pub px: u32,
  481}
  482
  483actions!(
  484    workspace,
  485    [
  486        /// Activates the pane to the left.
  487        ActivatePaneLeft,
  488        /// Activates the pane to the right.
  489        ActivatePaneRight,
  490        /// Activates the pane above.
  491        ActivatePaneUp,
  492        /// Activates the pane below.
  493        ActivatePaneDown,
  494        /// Swaps the current pane with the one to the left.
  495        SwapPaneLeft,
  496        /// Swaps the current pane with the one to the right.
  497        SwapPaneRight,
  498        /// Swaps the current pane with the one above.
  499        SwapPaneUp,
  500        /// Swaps the current pane with the one below.
  501        SwapPaneDown,
  502        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  503        SwapPaneAdjacent,
  504        /// Move the current pane to be at the far left.
  505        MovePaneLeft,
  506        /// Move the current pane to be at the far right.
  507        MovePaneRight,
  508        /// Move the current pane to be at the very top.
  509        MovePaneUp,
  510        /// Move the current pane to be at the very bottom.
  511        MovePaneDown,
  512    ]
  513);
  514
  515#[derive(PartialEq, Eq, Debug)]
  516pub enum CloseIntent {
  517    /// Quit the program entirely.
  518    Quit,
  519    /// Close a window.
  520    CloseWindow,
  521    /// Replace the workspace in an existing window.
  522    ReplaceWindow,
  523}
  524
  525#[derive(Clone)]
  526pub struct Toast {
  527    id: NotificationId,
  528    msg: Cow<'static, str>,
  529    autohide: bool,
  530    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  531}
  532
  533impl Toast {
  534    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  535        Toast {
  536            id,
  537            msg: msg.into(),
  538            on_click: None,
  539            autohide: false,
  540        }
  541    }
  542
  543    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  544    where
  545        M: Into<Cow<'static, str>>,
  546        F: Fn(&mut Window, &mut App) + 'static,
  547    {
  548        self.on_click = Some((message.into(), Arc::new(on_click)));
  549        self
  550    }
  551
  552    pub fn autohide(mut self) -> Self {
  553        self.autohide = true;
  554        self
  555    }
  556}
  557
  558impl PartialEq for Toast {
  559    fn eq(&self, other: &Self) -> bool {
  560        self.id == other.id
  561            && self.msg == other.msg
  562            && self.on_click.is_some() == other.on_click.is_some()
  563    }
  564}
  565
  566/// Opens a new terminal with the specified working directory.
  567#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  568#[action(namespace = workspace)]
  569#[serde(deny_unknown_fields)]
  570pub struct OpenTerminal {
  571    pub working_directory: PathBuf,
  572    /// If true, creates a local terminal even in remote projects.
  573    #[serde(default)]
  574    pub local: bool,
  575}
  576
  577#[derive(
  578    Clone,
  579    Copy,
  580    Debug,
  581    Default,
  582    Hash,
  583    PartialEq,
  584    Eq,
  585    PartialOrd,
  586    Ord,
  587    serde::Serialize,
  588    serde::Deserialize,
  589)]
  590pub struct WorkspaceId(i64);
  591
  592impl WorkspaceId {
  593    pub fn from_i64(value: i64) -> Self {
  594        Self(value)
  595    }
  596}
  597
  598impl StaticColumnCount for WorkspaceId {}
  599impl Bind for WorkspaceId {
  600    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  601        self.0.bind(statement, start_index)
  602    }
  603}
  604impl Column for WorkspaceId {
  605    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  606        i64::column(statement, start_index)
  607            .map(|(i, next_index)| (Self(i), next_index))
  608            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  609    }
  610}
  611impl From<WorkspaceId> for i64 {
  612    fn from(val: WorkspaceId) -> Self {
  613        val.0
  614    }
  615}
  616
  617fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  618    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  619        workspace_window
  620            .update(cx, |multi_workspace, window, cx| {
  621                let workspace = multi_workspace.workspace().clone();
  622                workspace.update(cx, |workspace, cx| {
  623                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  624                });
  625            })
  626            .ok();
  627    } else {
  628        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, cx);
  629        cx.spawn(async move |cx| {
  630            let (window, _) = task.await?;
  631            window.update(cx, |multi_workspace, window, cx| {
  632                window.activate_window();
  633                let workspace = multi_workspace.workspace().clone();
  634                workspace.update(cx, |workspace, cx| {
  635                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  636                });
  637            })?;
  638            anyhow::Ok(())
  639        })
  640        .detach_and_log_err(cx);
  641    }
  642}
  643
  644pub fn prompt_for_open_path_and_open(
  645    workspace: &mut Workspace,
  646    app_state: Arc<AppState>,
  647    options: PathPromptOptions,
  648    window: &mut Window,
  649    cx: &mut Context<Workspace>,
  650) {
  651    let paths = workspace.prompt_for_open_path(
  652        options,
  653        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  654        window,
  655        cx,
  656    );
  657    cx.spawn_in(window, async move |this, cx| {
  658        let Some(paths) = paths.await.log_err().flatten() else {
  659            return;
  660        };
  661        if let Some(task) = this
  662            .update_in(cx, |this, window, cx| {
  663                this.open_workspace_for_paths(false, paths, window, cx)
  664            })
  665            .log_err()
  666        {
  667            task.await.log_err();
  668        }
  669    })
  670    .detach();
  671}
  672
  673pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  674    component::init();
  675    theme_preview::init(cx);
  676    toast_layer::init(cx);
  677    history_manager::init(app_state.fs.clone(), cx);
  678
  679    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  680        .on_action(|_: &Reload, cx| reload(cx))
  681        .on_action({
  682            let app_state = Arc::downgrade(&app_state);
  683            move |_: &Open, cx: &mut App| {
  684                if let Some(app_state) = app_state.upgrade() {
  685                    prompt_and_open_paths(
  686                        app_state,
  687                        PathPromptOptions {
  688                            files: true,
  689                            directories: true,
  690                            multiple: true,
  691                            prompt: None,
  692                        },
  693                        cx,
  694                    );
  695                }
  696            }
  697        })
  698        .on_action({
  699            let app_state = Arc::downgrade(&app_state);
  700            move |_: &OpenFiles, cx: &mut App| {
  701                let directories = cx.can_select_mixed_files_and_dirs();
  702                if let Some(app_state) = app_state.upgrade() {
  703                    prompt_and_open_paths(
  704                        app_state,
  705                        PathPromptOptions {
  706                            files: true,
  707                            directories,
  708                            multiple: true,
  709                            prompt: None,
  710                        },
  711                        cx,
  712                    );
  713                }
  714            }
  715        });
  716}
  717
  718type BuildProjectItemFn =
  719    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  720
  721type BuildProjectItemForPathFn =
  722    fn(
  723        &Entity<Project>,
  724        &ProjectPath,
  725        &mut Window,
  726        &mut App,
  727    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  728
  729#[derive(Clone, Default)]
  730struct ProjectItemRegistry {
  731    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  732    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  733}
  734
  735impl ProjectItemRegistry {
  736    fn register<T: ProjectItem>(&mut self) {
  737        self.build_project_item_fns_by_type.insert(
  738            TypeId::of::<T::Item>(),
  739            |item, project, pane, window, cx| {
  740                let item = item.downcast().unwrap();
  741                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  742                    as Box<dyn ItemHandle>
  743            },
  744        );
  745        self.build_project_item_for_path_fns
  746            .push(|project, project_path, window, cx| {
  747                let project_path = project_path.clone();
  748                let is_file = project
  749                    .read(cx)
  750                    .entry_for_path(&project_path, cx)
  751                    .is_some_and(|entry| entry.is_file());
  752                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  753                let is_local = project.read(cx).is_local();
  754                let project_item =
  755                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  756                let project = project.clone();
  757                Some(window.spawn(cx, async move |cx| {
  758                    match project_item.await.with_context(|| {
  759                        format!(
  760                            "opening project path {:?}",
  761                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  762                        )
  763                    }) {
  764                        Ok(project_item) => {
  765                            let project_item = project_item;
  766                            let project_entry_id: Option<ProjectEntryId> =
  767                                project_item.read_with(cx, project::ProjectItem::entry_id);
  768                            let build_workspace_item = Box::new(
  769                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  770                                    Box::new(cx.new(|cx| {
  771                                        T::for_project_item(
  772                                            project,
  773                                            Some(pane),
  774                                            project_item,
  775                                            window,
  776                                            cx,
  777                                        )
  778                                    })) as Box<dyn ItemHandle>
  779                                },
  780                            ) as Box<_>;
  781                            Ok((project_entry_id, build_workspace_item))
  782                        }
  783                        Err(e) => {
  784                            log::warn!("Failed to open a project item: {e:#}");
  785                            if e.error_code() == ErrorCode::Internal {
  786                                if let Some(abs_path) =
  787                                    entry_abs_path.as_deref().filter(|_| is_file)
  788                                {
  789                                    if let Some(broken_project_item_view) =
  790                                        cx.update(|window, cx| {
  791                                            T::for_broken_project_item(
  792                                                abs_path, is_local, &e, window, cx,
  793                                            )
  794                                        })?
  795                                    {
  796                                        let build_workspace_item = Box::new(
  797                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  798                                                cx.new(|_| broken_project_item_view).boxed_clone()
  799                                            },
  800                                        )
  801                                        as Box<_>;
  802                                        return Ok((None, build_workspace_item));
  803                                    }
  804                                }
  805                            }
  806                            Err(e)
  807                        }
  808                    }
  809                }))
  810            });
  811    }
  812
  813    fn open_path(
  814        &self,
  815        project: &Entity<Project>,
  816        path: &ProjectPath,
  817        window: &mut Window,
  818        cx: &mut App,
  819    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  820        let Some(open_project_item) = self
  821            .build_project_item_for_path_fns
  822            .iter()
  823            .rev()
  824            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  825        else {
  826            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  827        };
  828        open_project_item
  829    }
  830
  831    fn build_item<T: project::ProjectItem>(
  832        &self,
  833        item: Entity<T>,
  834        project: Entity<Project>,
  835        pane: Option<&Pane>,
  836        window: &mut Window,
  837        cx: &mut App,
  838    ) -> Option<Box<dyn ItemHandle>> {
  839        let build = self
  840            .build_project_item_fns_by_type
  841            .get(&TypeId::of::<T>())?;
  842        Some(build(item.into_any(), project, pane, window, cx))
  843    }
  844}
  845
  846type WorkspaceItemBuilder =
  847    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  848
  849impl Global for ProjectItemRegistry {}
  850
  851/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  852/// items will get a chance to open the file, starting from the project item that
  853/// was added last.
  854pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  855    cx.default_global::<ProjectItemRegistry>().register::<I>();
  856}
  857
  858#[derive(Default)]
  859pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  860
  861struct FollowableViewDescriptor {
  862    from_state_proto: fn(
  863        Entity<Workspace>,
  864        ViewId,
  865        &mut Option<proto::view::Variant>,
  866        &mut Window,
  867        &mut App,
  868    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  869    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  870}
  871
  872impl Global for FollowableViewRegistry {}
  873
  874impl FollowableViewRegistry {
  875    pub fn register<I: FollowableItem>(cx: &mut App) {
  876        cx.default_global::<Self>().0.insert(
  877            TypeId::of::<I>(),
  878            FollowableViewDescriptor {
  879                from_state_proto: |workspace, id, state, window, cx| {
  880                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  881                        cx.foreground_executor()
  882                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  883                    })
  884                },
  885                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  886            },
  887        );
  888    }
  889
  890    pub fn from_state_proto(
  891        workspace: Entity<Workspace>,
  892        view_id: ViewId,
  893        mut state: Option<proto::view::Variant>,
  894        window: &mut Window,
  895        cx: &mut App,
  896    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  897        cx.update_default_global(|this: &mut Self, cx| {
  898            this.0.values().find_map(|descriptor| {
  899                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  900            })
  901        })
  902    }
  903
  904    pub fn to_followable_view(
  905        view: impl Into<AnyView>,
  906        cx: &App,
  907    ) -> Option<Box<dyn FollowableItemHandle>> {
  908        let this = cx.try_global::<Self>()?;
  909        let view = view.into();
  910        let descriptor = this.0.get(&view.entity_type())?;
  911        Some((descriptor.to_followable_view)(&view))
  912    }
  913}
  914
  915#[derive(Copy, Clone)]
  916struct SerializableItemDescriptor {
  917    deserialize: fn(
  918        Entity<Project>,
  919        WeakEntity<Workspace>,
  920        WorkspaceId,
  921        ItemId,
  922        &mut Window,
  923        &mut Context<Pane>,
  924    ) -> Task<Result<Box<dyn ItemHandle>>>,
  925    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  926    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  927}
  928
  929#[derive(Default)]
  930struct SerializableItemRegistry {
  931    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  932    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  933}
  934
  935impl Global for SerializableItemRegistry {}
  936
  937impl SerializableItemRegistry {
  938    fn deserialize(
  939        item_kind: &str,
  940        project: Entity<Project>,
  941        workspace: WeakEntity<Workspace>,
  942        workspace_id: WorkspaceId,
  943        item_item: ItemId,
  944        window: &mut Window,
  945        cx: &mut Context<Pane>,
  946    ) -> Task<Result<Box<dyn ItemHandle>>> {
  947        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  948            return Task::ready(Err(anyhow!(
  949                "cannot deserialize {}, descriptor not found",
  950                item_kind
  951            )));
  952        };
  953
  954        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  955    }
  956
  957    fn cleanup(
  958        item_kind: &str,
  959        workspace_id: WorkspaceId,
  960        loaded_items: Vec<ItemId>,
  961        window: &mut Window,
  962        cx: &mut App,
  963    ) -> Task<Result<()>> {
  964        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  965            return Task::ready(Err(anyhow!(
  966                "cannot cleanup {}, descriptor not found",
  967                item_kind
  968            )));
  969        };
  970
  971        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  972    }
  973
  974    fn view_to_serializable_item_handle(
  975        view: AnyView,
  976        cx: &App,
  977    ) -> Option<Box<dyn SerializableItemHandle>> {
  978        let this = cx.try_global::<Self>()?;
  979        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  980        Some((descriptor.view_to_serializable_item)(view))
  981    }
  982
  983    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  984        let this = cx.try_global::<Self>()?;
  985        this.descriptors_by_kind.get(item_kind).copied()
  986    }
  987}
  988
  989pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  990    let serialized_item_kind = I::serialized_item_kind();
  991
  992    let registry = cx.default_global::<SerializableItemRegistry>();
  993    let descriptor = SerializableItemDescriptor {
  994        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  995            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  996            cx.foreground_executor()
  997                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
  998        },
  999        cleanup: |workspace_id, loaded_items, window, cx| {
 1000            I::cleanup(workspace_id, loaded_items, window, cx)
 1001        },
 1002        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1003    };
 1004    registry
 1005        .descriptors_by_kind
 1006        .insert(Arc::from(serialized_item_kind), descriptor);
 1007    registry
 1008        .descriptors_by_type
 1009        .insert(TypeId::of::<I>(), descriptor);
 1010}
 1011
 1012pub struct AppState {
 1013    pub languages: Arc<LanguageRegistry>,
 1014    pub client: Arc<Client>,
 1015    pub user_store: Entity<UserStore>,
 1016    pub workspace_store: Entity<WorkspaceStore>,
 1017    pub fs: Arc<dyn fs::Fs>,
 1018    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1019    pub node_runtime: NodeRuntime,
 1020    pub session: Entity<AppSession>,
 1021}
 1022
 1023struct GlobalAppState(Weak<AppState>);
 1024
 1025impl Global for GlobalAppState {}
 1026
 1027pub struct WorkspaceStore {
 1028    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1029    client: Arc<Client>,
 1030    _subscriptions: Vec<client::Subscription>,
 1031}
 1032
 1033#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1034pub enum CollaboratorId {
 1035    PeerId(PeerId),
 1036    Agent,
 1037}
 1038
 1039impl From<PeerId> for CollaboratorId {
 1040    fn from(peer_id: PeerId) -> Self {
 1041        CollaboratorId::PeerId(peer_id)
 1042    }
 1043}
 1044
 1045impl From<&PeerId> for CollaboratorId {
 1046    fn from(peer_id: &PeerId) -> Self {
 1047        CollaboratorId::PeerId(*peer_id)
 1048    }
 1049}
 1050
 1051#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1052struct Follower {
 1053    project_id: Option<u64>,
 1054    peer_id: PeerId,
 1055}
 1056
 1057impl AppState {
 1058    #[track_caller]
 1059    pub fn global(cx: &App) -> Weak<Self> {
 1060        cx.global::<GlobalAppState>().0.clone()
 1061    }
 1062    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1063        cx.try_global::<GlobalAppState>()
 1064            .map(|state| state.0.clone())
 1065    }
 1066    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1067        cx.set_global(GlobalAppState(state));
 1068    }
 1069
 1070    #[cfg(any(test, feature = "test-support"))]
 1071    pub fn test(cx: &mut App) -> Arc<Self> {
 1072        use fs::Fs;
 1073        use node_runtime::NodeRuntime;
 1074        use session::Session;
 1075        use settings::SettingsStore;
 1076
 1077        if !cx.has_global::<SettingsStore>() {
 1078            let settings_store = SettingsStore::test(cx);
 1079            cx.set_global(settings_store);
 1080        }
 1081
 1082        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1083        <dyn Fs>::set_global(fs.clone(), cx);
 1084        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1085        let clock = Arc::new(clock::FakeSystemClock::new());
 1086        let http_client = http_client::FakeHttpClient::with_404_response();
 1087        let client = Client::new(clock, http_client, cx);
 1088        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1089        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1090        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1091
 1092        theme::init(theme::LoadThemes::JustBase, cx);
 1093        client::init(&client, cx);
 1094
 1095        Arc::new(Self {
 1096            client,
 1097            fs,
 1098            languages,
 1099            user_store,
 1100            workspace_store,
 1101            node_runtime: NodeRuntime::unavailable(),
 1102            build_window_options: |_, _| Default::default(),
 1103            session,
 1104        })
 1105    }
 1106}
 1107
 1108struct DelayedDebouncedEditAction {
 1109    task: Option<Task<()>>,
 1110    cancel_channel: Option<oneshot::Sender<()>>,
 1111}
 1112
 1113impl DelayedDebouncedEditAction {
 1114    fn new() -> DelayedDebouncedEditAction {
 1115        DelayedDebouncedEditAction {
 1116            task: None,
 1117            cancel_channel: None,
 1118        }
 1119    }
 1120
 1121    fn fire_new<F>(
 1122        &mut self,
 1123        delay: Duration,
 1124        window: &mut Window,
 1125        cx: &mut Context<Workspace>,
 1126        func: F,
 1127    ) where
 1128        F: 'static
 1129            + Send
 1130            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1131    {
 1132        if let Some(channel) = self.cancel_channel.take() {
 1133            _ = channel.send(());
 1134        }
 1135
 1136        let (sender, mut receiver) = oneshot::channel::<()>();
 1137        self.cancel_channel = Some(sender);
 1138
 1139        let previous_task = self.task.take();
 1140        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1141            let mut timer = cx.background_executor().timer(delay).fuse();
 1142            if let Some(previous_task) = previous_task {
 1143                previous_task.await;
 1144            }
 1145
 1146            futures::select_biased! {
 1147                _ = receiver => return,
 1148                    _ = timer => {}
 1149            }
 1150
 1151            if let Some(result) = workspace
 1152                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1153                .log_err()
 1154            {
 1155                result.await.log_err();
 1156            }
 1157        }));
 1158    }
 1159}
 1160
 1161pub enum Event {
 1162    PaneAdded(Entity<Pane>),
 1163    PaneRemoved,
 1164    ItemAdded {
 1165        item: Box<dyn ItemHandle>,
 1166    },
 1167    ActiveItemChanged,
 1168    ItemRemoved {
 1169        item_id: EntityId,
 1170    },
 1171    UserSavedItem {
 1172        pane: WeakEntity<Pane>,
 1173        item: Box<dyn WeakItemHandle>,
 1174        save_intent: SaveIntent,
 1175    },
 1176    ContactRequestedJoin(u64),
 1177    WorkspaceCreated(WeakEntity<Workspace>),
 1178    OpenBundledFile {
 1179        text: Cow<'static, str>,
 1180        title: &'static str,
 1181        language: &'static str,
 1182    },
 1183    ZoomChanged,
 1184    ModalOpened,
 1185    Activate,
 1186}
 1187
 1188#[derive(Debug, Clone)]
 1189pub enum OpenVisible {
 1190    All,
 1191    None,
 1192    OnlyFiles,
 1193    OnlyDirectories,
 1194}
 1195
 1196enum WorkspaceLocation {
 1197    // Valid local paths or SSH project to serialize
 1198    Location(SerializedWorkspaceLocation, PathList),
 1199    // No valid location found hence clear session id
 1200    DetachFromSession,
 1201    // No valid location found to serialize
 1202    None,
 1203}
 1204
 1205type PromptForNewPath = Box<
 1206    dyn Fn(
 1207        &mut Workspace,
 1208        DirectoryLister,
 1209        Option<String>,
 1210        &mut Window,
 1211        &mut Context<Workspace>,
 1212    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1213>;
 1214
 1215type PromptForOpenPath = Box<
 1216    dyn Fn(
 1217        &mut Workspace,
 1218        DirectoryLister,
 1219        &mut Window,
 1220        &mut Context<Workspace>,
 1221    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1222>;
 1223
 1224#[derive(Default)]
 1225struct DispatchingKeystrokes {
 1226    dispatched: HashSet<Vec<Keystroke>>,
 1227    queue: VecDeque<Keystroke>,
 1228    task: Option<Shared<Task<()>>>,
 1229}
 1230
 1231/// Collects everything project-related for a certain window opened.
 1232/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1233///
 1234/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1235/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1236/// that can be used to register a global action to be triggered from any place in the window.
 1237pub struct Workspace {
 1238    weak_self: WeakEntity<Self>,
 1239    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1240    zoomed: Option<AnyWeakView>,
 1241    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1242    zoomed_position: Option<DockPosition>,
 1243    center: PaneGroup,
 1244    left_dock: Entity<Dock>,
 1245    bottom_dock: Entity<Dock>,
 1246    right_dock: Entity<Dock>,
 1247    panes: Vec<Entity<Pane>>,
 1248    active_worktree_override: Option<WorktreeId>,
 1249    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1250    active_pane: Entity<Pane>,
 1251    last_active_center_pane: Option<WeakEntity<Pane>>,
 1252    last_active_view_id: Option<proto::ViewId>,
 1253    status_bar: Entity<StatusBar>,
 1254    modal_layer: Entity<ModalLayer>,
 1255    toast_layer: Entity<ToastLayer>,
 1256    titlebar_item: Option<AnyView>,
 1257    notifications: Notifications,
 1258    suppressed_notifications: HashSet<NotificationId>,
 1259    project: Entity<Project>,
 1260    follower_states: HashMap<CollaboratorId, FollowerState>,
 1261    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1262    window_edited: bool,
 1263    last_window_title: Option<String>,
 1264    dirty_items: HashMap<EntityId, Subscription>,
 1265    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1266    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1267    database_id: Option<WorkspaceId>,
 1268    app_state: Arc<AppState>,
 1269    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1270    _subscriptions: Vec<Subscription>,
 1271    _apply_leader_updates: Task<Result<()>>,
 1272    _observe_current_user: Task<Result<()>>,
 1273    _schedule_serialize_workspace: Option<Task<()>>,
 1274    _serialize_workspace_task: Option<Task<()>>,
 1275    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1276    pane_history_timestamp: Arc<AtomicUsize>,
 1277    bounds: Bounds<Pixels>,
 1278    pub centered_layout: bool,
 1279    bounds_save_task_queued: Option<Task<()>>,
 1280    on_prompt_for_new_path: Option<PromptForNewPath>,
 1281    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1282    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1283    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1284    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1285    _items_serializer: Task<Result<()>>,
 1286    session_id: Option<String>,
 1287    scheduled_tasks: Vec<Task<()>>,
 1288    last_open_dock_positions: Vec<DockPosition>,
 1289    removing: bool,
 1290}
 1291
 1292impl EventEmitter<Event> for Workspace {}
 1293
 1294#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1295pub struct ViewId {
 1296    pub creator: CollaboratorId,
 1297    pub id: u64,
 1298}
 1299
 1300pub struct FollowerState {
 1301    center_pane: Entity<Pane>,
 1302    dock_pane: Option<Entity<Pane>>,
 1303    active_view_id: Option<ViewId>,
 1304    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1305}
 1306
 1307struct FollowerView {
 1308    view: Box<dyn FollowableItemHandle>,
 1309    location: Option<proto::PanelId>,
 1310}
 1311
 1312impl Workspace {
 1313    pub fn new(
 1314        workspace_id: Option<WorkspaceId>,
 1315        project: Entity<Project>,
 1316        app_state: Arc<AppState>,
 1317        window: &mut Window,
 1318        cx: &mut Context<Self>,
 1319    ) -> Self {
 1320        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1321            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1322                if let TrustedWorktreesEvent::Trusted(..) = e {
 1323                    // Do not persist auto trusted worktrees
 1324                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1325                        worktrees_store.update(cx, |worktrees_store, cx| {
 1326                            worktrees_store.schedule_serialization(
 1327                                cx,
 1328                                |new_trusted_worktrees, cx| {
 1329                                    let timeout =
 1330                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1331                                    cx.background_spawn(async move {
 1332                                        timeout.await;
 1333                                        persistence::DB
 1334                                            .save_trusted_worktrees(new_trusted_worktrees)
 1335                                            .await
 1336                                            .log_err();
 1337                                    })
 1338                                },
 1339                            )
 1340                        });
 1341                    }
 1342                }
 1343            })
 1344            .detach();
 1345
 1346            cx.observe_global::<SettingsStore>(|_, cx| {
 1347                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1348                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1349                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1350                            trusted_worktrees.auto_trust_all(cx);
 1351                        })
 1352                    }
 1353                }
 1354            })
 1355            .detach();
 1356        }
 1357
 1358        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1359            match event {
 1360                project::Event::RemoteIdChanged(_) => {
 1361                    this.update_window_title(window, cx);
 1362                }
 1363
 1364                project::Event::CollaboratorLeft(peer_id) => {
 1365                    this.collaborator_left(*peer_id, window, cx);
 1366                }
 1367
 1368                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1369                    this.update_window_title(window, cx);
 1370                    if this
 1371                        .project()
 1372                        .read(cx)
 1373                        .worktree_for_id(id, cx)
 1374                        .is_some_and(|wt| wt.read(cx).is_visible())
 1375                    {
 1376                        this.serialize_workspace(window, cx);
 1377                        this.update_history(cx);
 1378                    }
 1379                }
 1380                project::Event::WorktreeUpdatedEntries(..) => {
 1381                    this.update_window_title(window, cx);
 1382                    this.serialize_workspace(window, cx);
 1383                }
 1384
 1385                project::Event::DisconnectedFromHost => {
 1386                    this.update_window_edited(window, cx);
 1387                    let leaders_to_unfollow =
 1388                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1389                    for leader_id in leaders_to_unfollow {
 1390                        this.unfollow(leader_id, window, cx);
 1391                    }
 1392                }
 1393
 1394                project::Event::DisconnectedFromRemote {
 1395                    server_not_running: _,
 1396                } => {
 1397                    this.update_window_edited(window, cx);
 1398                }
 1399
 1400                project::Event::Closed => {
 1401                    window.remove_window();
 1402                }
 1403
 1404                project::Event::DeletedEntry(_, entry_id) => {
 1405                    for pane in this.panes.iter() {
 1406                        pane.update(cx, |pane, cx| {
 1407                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1408                        });
 1409                    }
 1410                }
 1411
 1412                project::Event::Toast {
 1413                    notification_id,
 1414                    message,
 1415                    link,
 1416                } => this.show_notification(
 1417                    NotificationId::named(notification_id.clone()),
 1418                    cx,
 1419                    |cx| {
 1420                        let mut notification = MessageNotification::new(message.clone(), cx);
 1421                        if let Some(link) = link {
 1422                            notification = notification
 1423                                .more_info_message(link.label)
 1424                                .more_info_url(link.url);
 1425                        }
 1426
 1427                        cx.new(|_| notification)
 1428                    },
 1429                ),
 1430
 1431                project::Event::HideToast { notification_id } => {
 1432                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1433                }
 1434
 1435                project::Event::LanguageServerPrompt(request) => {
 1436                    struct LanguageServerPrompt;
 1437
 1438                    this.show_notification(
 1439                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1440                        cx,
 1441                        |cx| {
 1442                            cx.new(|cx| {
 1443                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1444                            })
 1445                        },
 1446                    );
 1447                }
 1448
 1449                project::Event::AgentLocationChanged => {
 1450                    this.handle_agent_location_changed(window, cx)
 1451                }
 1452
 1453                _ => {}
 1454            }
 1455            cx.notify()
 1456        })
 1457        .detach();
 1458
 1459        cx.subscribe_in(
 1460            &project.read(cx).breakpoint_store(),
 1461            window,
 1462            |workspace, _, event, window, cx| match event {
 1463                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1464                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1465                    workspace.serialize_workspace(window, cx);
 1466                }
 1467                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1468            },
 1469        )
 1470        .detach();
 1471        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1472            cx.subscribe_in(
 1473                &toolchain_store,
 1474                window,
 1475                |workspace, _, event, window, cx| match event {
 1476                    ToolchainStoreEvent::CustomToolchainsModified => {
 1477                        workspace.serialize_workspace(window, cx);
 1478                    }
 1479                    _ => {}
 1480                },
 1481            )
 1482            .detach();
 1483        }
 1484
 1485        cx.on_focus_lost(window, |this, window, cx| {
 1486            let focus_handle = this.focus_handle(cx);
 1487            window.focus(&focus_handle, cx);
 1488        })
 1489        .detach();
 1490
 1491        let weak_handle = cx.entity().downgrade();
 1492        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1493
 1494        let center_pane = cx.new(|cx| {
 1495            let mut center_pane = Pane::new(
 1496                weak_handle.clone(),
 1497                project.clone(),
 1498                pane_history_timestamp.clone(),
 1499                None,
 1500                NewFile.boxed_clone(),
 1501                true,
 1502                window,
 1503                cx,
 1504            );
 1505            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1506            center_pane.set_should_display_welcome_page(true);
 1507            center_pane
 1508        });
 1509        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1510            .detach();
 1511
 1512        window.focus(&center_pane.focus_handle(cx), cx);
 1513
 1514        cx.emit(Event::PaneAdded(center_pane.clone()));
 1515
 1516        let any_window_handle = window.window_handle();
 1517        app_state.workspace_store.update(cx, |store, _| {
 1518            store
 1519                .workspaces
 1520                .insert((any_window_handle, weak_handle.clone()));
 1521        });
 1522
 1523        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1524        let mut connection_status = app_state.client.status();
 1525        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1526            current_user.next().await;
 1527            connection_status.next().await;
 1528            let mut stream =
 1529                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1530
 1531            while stream.recv().await.is_some() {
 1532                this.update(cx, |_, cx| cx.notify())?;
 1533            }
 1534            anyhow::Ok(())
 1535        });
 1536
 1537        // All leader updates are enqueued and then processed in a single task, so
 1538        // that each asynchronous operation can be run in order.
 1539        let (leader_updates_tx, mut leader_updates_rx) =
 1540            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1541        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1542            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1543                Self::process_leader_update(&this, leader_id, update, cx)
 1544                    .await
 1545                    .log_err();
 1546            }
 1547
 1548            Ok(())
 1549        });
 1550
 1551        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1552        let modal_layer = cx.new(|_| ModalLayer::new());
 1553        let toast_layer = cx.new(|_| ToastLayer::new());
 1554        cx.subscribe(
 1555            &modal_layer,
 1556            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1557                cx.emit(Event::ModalOpened);
 1558            },
 1559        )
 1560        .detach();
 1561
 1562        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1563        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1564        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1565        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1566        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1567        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1568        let status_bar = cx.new(|cx| {
 1569            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1570            status_bar.add_left_item(left_dock_buttons, window, cx);
 1571            status_bar.add_right_item(right_dock_buttons, window, cx);
 1572            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1573            status_bar
 1574        });
 1575
 1576        let session_id = app_state.session.read(cx).id().to_owned();
 1577
 1578        let mut active_call = None;
 1579        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1580            let subscriptions =
 1581                vec![
 1582                    call.0
 1583                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1584                ];
 1585            active_call = Some((call, subscriptions));
 1586        }
 1587
 1588        let (serializable_items_tx, serializable_items_rx) =
 1589            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1590        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1591            Self::serialize_items(&this, serializable_items_rx, cx).await
 1592        });
 1593
 1594        let subscriptions = vec![
 1595            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1596            cx.observe_window_bounds(window, move |this, window, cx| {
 1597                if this.bounds_save_task_queued.is_some() {
 1598                    return;
 1599                }
 1600                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1601                    cx.background_executor()
 1602                        .timer(Duration::from_millis(100))
 1603                        .await;
 1604                    this.update_in(cx, |this, window, cx| {
 1605                        this.save_window_bounds(window, cx).detach();
 1606                        this.bounds_save_task_queued.take();
 1607                    })
 1608                    .ok();
 1609                }));
 1610                cx.notify();
 1611            }),
 1612            cx.observe_window_appearance(window, |_, window, cx| {
 1613                let window_appearance = window.appearance();
 1614
 1615                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1616
 1617                GlobalTheme::reload_theme(cx);
 1618                GlobalTheme::reload_icon_theme(cx);
 1619            }),
 1620            cx.on_release({
 1621                let weak_handle = weak_handle.clone();
 1622                move |this, cx| {
 1623                    this.app_state.workspace_store.update(cx, move |store, _| {
 1624                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1625                    })
 1626                }
 1627            }),
 1628        ];
 1629
 1630        cx.defer_in(window, move |this, window, cx| {
 1631            this.update_window_title(window, cx);
 1632            this.show_initial_notifications(cx);
 1633        });
 1634
 1635        let mut center = PaneGroup::new(center_pane.clone());
 1636        center.set_is_center(true);
 1637        center.mark_positions(cx);
 1638
 1639        Workspace {
 1640            weak_self: weak_handle.clone(),
 1641            zoomed: None,
 1642            zoomed_position: None,
 1643            previous_dock_drag_coordinates: None,
 1644            center,
 1645            panes: vec![center_pane.clone()],
 1646            panes_by_item: Default::default(),
 1647            active_pane: center_pane.clone(),
 1648            last_active_center_pane: Some(center_pane.downgrade()),
 1649            last_active_view_id: None,
 1650            status_bar,
 1651            modal_layer,
 1652            toast_layer,
 1653            titlebar_item: None,
 1654            active_worktree_override: None,
 1655            notifications: Notifications::default(),
 1656            suppressed_notifications: HashSet::default(),
 1657            left_dock,
 1658            bottom_dock,
 1659            right_dock,
 1660            project: project.clone(),
 1661            follower_states: Default::default(),
 1662            last_leaders_by_pane: Default::default(),
 1663            dispatching_keystrokes: Default::default(),
 1664            window_edited: false,
 1665            last_window_title: None,
 1666            dirty_items: Default::default(),
 1667            active_call,
 1668            database_id: workspace_id,
 1669            app_state,
 1670            _observe_current_user,
 1671            _apply_leader_updates,
 1672            _schedule_serialize_workspace: None,
 1673            _serialize_workspace_task: None,
 1674            _schedule_serialize_ssh_paths: None,
 1675            leader_updates_tx,
 1676            _subscriptions: subscriptions,
 1677            pane_history_timestamp,
 1678            workspace_actions: Default::default(),
 1679            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1680            bounds: Default::default(),
 1681            centered_layout: false,
 1682            bounds_save_task_queued: None,
 1683            on_prompt_for_new_path: None,
 1684            on_prompt_for_open_path: None,
 1685            terminal_provider: None,
 1686            debugger_provider: None,
 1687            serializable_items_tx,
 1688            _items_serializer,
 1689            session_id: Some(session_id),
 1690
 1691            scheduled_tasks: Vec::new(),
 1692            last_open_dock_positions: Vec::new(),
 1693            removing: false,
 1694        }
 1695    }
 1696
 1697    pub fn new_local(
 1698        abs_paths: Vec<PathBuf>,
 1699        app_state: Arc<AppState>,
 1700        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1701        env: Option<HashMap<String, String>>,
 1702        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1703        cx: &mut App,
 1704    ) -> Task<
 1705        anyhow::Result<(
 1706            WindowHandle<MultiWorkspace>,
 1707            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1708        )>,
 1709    > {
 1710        let project_handle = Project::local(
 1711            app_state.client.clone(),
 1712            app_state.node_runtime.clone(),
 1713            app_state.user_store.clone(),
 1714            app_state.languages.clone(),
 1715            app_state.fs.clone(),
 1716            env,
 1717            Default::default(),
 1718            cx,
 1719        );
 1720
 1721        cx.spawn(async move |cx| {
 1722            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1723            for path in abs_paths.into_iter() {
 1724                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1725                    paths_to_open.push(canonical)
 1726                } else {
 1727                    paths_to_open.push(path)
 1728                }
 1729            }
 1730
 1731            let serialized_workspace =
 1732                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1733
 1734            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1735                paths_to_open = paths.ordered_paths().cloned().collect();
 1736                if !paths.is_lexicographically_ordered() {
 1737                    project_handle.update(cx, |project, cx| {
 1738                        project.set_worktrees_reordered(true, cx);
 1739                    });
 1740                }
 1741            }
 1742
 1743            // Get project paths for all of the abs_paths
 1744            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1745                Vec::with_capacity(paths_to_open.len());
 1746
 1747            for path in paths_to_open.into_iter() {
 1748                if let Some((_, project_entry)) = cx
 1749                    .update(|cx| {
 1750                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1751                    })
 1752                    .await
 1753                    .log_err()
 1754                {
 1755                    project_paths.push((path, Some(project_entry)));
 1756                } else {
 1757                    project_paths.push((path, None));
 1758                }
 1759            }
 1760
 1761            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1762                serialized_workspace.id
 1763            } else {
 1764                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1765            };
 1766
 1767            let toolchains = DB.toolchains(workspace_id).await?;
 1768
 1769            for (toolchain, worktree_path, path) in toolchains {
 1770                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1771                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1772                    this.find_worktree(&worktree_path, cx)
 1773                        .and_then(|(worktree, rel_path)| {
 1774                            if rel_path.is_empty() {
 1775                                Some(worktree.read(cx).id())
 1776                            } else {
 1777                                None
 1778                            }
 1779                        })
 1780                }) else {
 1781                    // We did not find a worktree with a given path, but that's whatever.
 1782                    continue;
 1783                };
 1784                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1785                    continue;
 1786                }
 1787
 1788                project_handle
 1789                    .update(cx, |this, cx| {
 1790                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1791                    })
 1792                    .await;
 1793            }
 1794            if let Some(workspace) = serialized_workspace.as_ref() {
 1795                project_handle.update(cx, |this, cx| {
 1796                    for (scope, toolchains) in &workspace.user_toolchains {
 1797                        for toolchain in toolchains {
 1798                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1799                        }
 1800                    }
 1801                });
 1802            }
 1803
 1804            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1805                if let Some(window) = requesting_window {
 1806                    let centered_layout = serialized_workspace
 1807                        .as_ref()
 1808                        .map(|w| w.centered_layout)
 1809                        .unwrap_or(false);
 1810
 1811                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1812                        let workspace = cx.new(|cx| {
 1813                            let mut workspace = Workspace::new(
 1814                                Some(workspace_id),
 1815                                project_handle.clone(),
 1816                                app_state.clone(),
 1817                                window,
 1818                                cx,
 1819                            );
 1820
 1821                            workspace.centered_layout = centered_layout;
 1822
 1823                            // Call init callback to add items before window renders
 1824                            if let Some(init) = init {
 1825                                init(&mut workspace, window, cx);
 1826                            }
 1827
 1828                            workspace
 1829                        });
 1830                        multi_workspace.activate(workspace.clone(), cx);
 1831                        workspace
 1832                    })?;
 1833                    (window, workspace)
 1834                } else {
 1835                    let window_bounds_override = window_bounds_env_override();
 1836
 1837                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1838                        (Some(WindowBounds::Windowed(bounds)), None)
 1839                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1840                        && let Some(display) = workspace.display
 1841                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1842                    {
 1843                        // Reopening an existing workspace - restore its saved bounds
 1844                        (Some(bounds.0), Some(display))
 1845                    } else if let Some((display, bounds)) =
 1846                        persistence::read_default_window_bounds()
 1847                    {
 1848                        // New or empty workspace - use the last known window bounds
 1849                        (Some(bounds), Some(display))
 1850                    } else {
 1851                        // New window - let GPUI's default_bounds() handle cascading
 1852                        (None, None)
 1853                    };
 1854
 1855                    // Use the serialized workspace to construct the new window
 1856                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1857                    options.window_bounds = window_bounds;
 1858                    let centered_layout = serialized_workspace
 1859                        .as_ref()
 1860                        .map(|w| w.centered_layout)
 1861                        .unwrap_or(false);
 1862                    let window = cx.open_window(options, {
 1863                        let app_state = app_state.clone();
 1864                        let project_handle = project_handle.clone();
 1865                        move |window, cx| {
 1866                            let workspace = cx.new(|cx| {
 1867                                let mut workspace = Workspace::new(
 1868                                    Some(workspace_id),
 1869                                    project_handle,
 1870                                    app_state,
 1871                                    window,
 1872                                    cx,
 1873                                );
 1874                                workspace.centered_layout = centered_layout;
 1875
 1876                                // Call init callback to add items before window renders
 1877                                if let Some(init) = init {
 1878                                    init(&mut workspace, window, cx);
 1879                                }
 1880
 1881                                workspace
 1882                            });
 1883                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1884                        }
 1885                    })?;
 1886                    let workspace =
 1887                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1888                            multi_workspace.workspace().clone()
 1889                        })?;
 1890                    (window, workspace)
 1891                };
 1892
 1893            notify_if_database_failed(window, cx);
 1894            // Check if this is an empty workspace (no paths to open)
 1895            // An empty workspace is one where project_paths is empty
 1896            let is_empty_workspace = project_paths.is_empty();
 1897            // Check if serialized workspace has paths before it's moved
 1898            let serialized_workspace_has_paths = serialized_workspace
 1899                .as_ref()
 1900                .map(|ws| !ws.paths.is_empty())
 1901                .unwrap_or(false);
 1902
 1903            let opened_items = window
 1904                .update(cx, |_, window, cx| {
 1905                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1906                        open_items(serialized_workspace, project_paths, window, cx)
 1907                    })
 1908                })?
 1909                .await
 1910                .unwrap_or_default();
 1911
 1912            // Restore default dock state for empty workspaces
 1913            // Only restore if:
 1914            // 1. This is an empty workspace (no paths), AND
 1915            // 2. The serialized workspace either doesn't exist or has no paths
 1916            if is_empty_workspace && !serialized_workspace_has_paths {
 1917                if let Some(default_docks) = persistence::read_default_dock_state() {
 1918                    window
 1919                        .update(cx, |_, window, cx| {
 1920                            workspace.update(cx, |workspace, cx| {
 1921                                for (dock, serialized_dock) in [
 1922                                    (&workspace.right_dock, &default_docks.right),
 1923                                    (&workspace.left_dock, &default_docks.left),
 1924                                    (&workspace.bottom_dock, &default_docks.bottom),
 1925                                ] {
 1926                                    dock.update(cx, |dock, cx| {
 1927                                        dock.serialized_dock = Some(serialized_dock.clone());
 1928                                        dock.restore_state(window, cx);
 1929                                    });
 1930                                }
 1931                                cx.notify();
 1932                            });
 1933                        })
 1934                        .log_err();
 1935                }
 1936            }
 1937
 1938            window
 1939                .update(cx, |_, _window, cx| {
 1940                    workspace.update(cx, |this: &mut Workspace, cx| {
 1941                        this.update_history(cx);
 1942                    });
 1943                })
 1944                .log_err();
 1945            Ok((window, opened_items))
 1946        })
 1947    }
 1948
 1949    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1950        self.weak_self.clone()
 1951    }
 1952
 1953    pub fn left_dock(&self) -> &Entity<Dock> {
 1954        &self.left_dock
 1955    }
 1956
 1957    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1958        &self.bottom_dock
 1959    }
 1960
 1961    pub fn set_bottom_dock_layout(
 1962        &mut self,
 1963        layout: BottomDockLayout,
 1964        window: &mut Window,
 1965        cx: &mut Context<Self>,
 1966    ) {
 1967        let fs = self.project().read(cx).fs();
 1968        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1969            content.workspace.bottom_dock_layout = Some(layout);
 1970        });
 1971
 1972        cx.notify();
 1973        self.serialize_workspace(window, cx);
 1974    }
 1975
 1976    pub fn right_dock(&self) -> &Entity<Dock> {
 1977        &self.right_dock
 1978    }
 1979
 1980    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1981        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1982    }
 1983
 1984    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1985        match position {
 1986            DockPosition::Left => &self.left_dock,
 1987            DockPosition::Bottom => &self.bottom_dock,
 1988            DockPosition::Right => &self.right_dock,
 1989        }
 1990    }
 1991
 1992    pub fn is_edited(&self) -> bool {
 1993        self.window_edited
 1994    }
 1995
 1996    pub fn add_panel<T: Panel>(
 1997        &mut self,
 1998        panel: Entity<T>,
 1999        window: &mut Window,
 2000        cx: &mut Context<Self>,
 2001    ) {
 2002        let focus_handle = panel.panel_focus_handle(cx);
 2003        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2004            .detach();
 2005
 2006        let dock_position = panel.position(window, cx);
 2007        let dock = self.dock_at_position(dock_position);
 2008
 2009        dock.update(cx, |dock, cx| {
 2010            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2011        });
 2012    }
 2013
 2014    pub fn remove_panel<T: Panel>(
 2015        &mut self,
 2016        panel: &Entity<T>,
 2017        window: &mut Window,
 2018        cx: &mut Context<Self>,
 2019    ) {
 2020        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2021            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2022        }
 2023    }
 2024
 2025    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2026        &self.status_bar
 2027    }
 2028
 2029    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2030        self.status_bar.update(cx, |status_bar, cx| {
 2031            status_bar.set_workspace_sidebar_open(open, cx);
 2032        });
 2033    }
 2034
 2035    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2036        StatusBarSettings::get_global(cx).show
 2037    }
 2038
 2039    pub fn app_state(&self) -> &Arc<AppState> {
 2040        &self.app_state
 2041    }
 2042
 2043    pub fn user_store(&self) -> &Entity<UserStore> {
 2044        &self.app_state.user_store
 2045    }
 2046
 2047    pub fn project(&self) -> &Entity<Project> {
 2048        &self.project
 2049    }
 2050
 2051    pub fn path_style(&self, cx: &App) -> PathStyle {
 2052        self.project.read(cx).path_style(cx)
 2053    }
 2054
 2055    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2056        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2057
 2058        for pane_handle in &self.panes {
 2059            let pane = pane_handle.read(cx);
 2060
 2061            for entry in pane.activation_history() {
 2062                history.insert(
 2063                    entry.entity_id,
 2064                    history
 2065                        .get(&entry.entity_id)
 2066                        .cloned()
 2067                        .unwrap_or(0)
 2068                        .max(entry.timestamp),
 2069                );
 2070            }
 2071        }
 2072
 2073        history
 2074    }
 2075
 2076    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2077        let mut recent_item: Option<Entity<T>> = None;
 2078        let mut recent_timestamp = 0;
 2079        for pane_handle in &self.panes {
 2080            let pane = pane_handle.read(cx);
 2081            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2082                pane.items().map(|item| (item.item_id(), item)).collect();
 2083            for entry in pane.activation_history() {
 2084                if entry.timestamp > recent_timestamp
 2085                    && let Some(&item) = item_map.get(&entry.entity_id)
 2086                    && let Some(typed_item) = item.act_as::<T>(cx)
 2087                {
 2088                    recent_timestamp = entry.timestamp;
 2089                    recent_item = Some(typed_item);
 2090                }
 2091            }
 2092        }
 2093        recent_item
 2094    }
 2095
 2096    pub fn recent_navigation_history_iter(
 2097        &self,
 2098        cx: &App,
 2099    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2100        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2101        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2102
 2103        for pane in &self.panes {
 2104            let pane = pane.read(cx);
 2105
 2106            pane.nav_history()
 2107                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2108                    if let Some(fs_path) = &fs_path {
 2109                        abs_paths_opened
 2110                            .entry(fs_path.clone())
 2111                            .or_default()
 2112                            .insert(project_path.clone());
 2113                    }
 2114                    let timestamp = entry.timestamp;
 2115                    match history.entry(project_path) {
 2116                        hash_map::Entry::Occupied(mut entry) => {
 2117                            let (_, old_timestamp) = entry.get();
 2118                            if &timestamp > old_timestamp {
 2119                                entry.insert((fs_path, timestamp));
 2120                            }
 2121                        }
 2122                        hash_map::Entry::Vacant(entry) => {
 2123                            entry.insert((fs_path, timestamp));
 2124                        }
 2125                    }
 2126                });
 2127
 2128            if let Some(item) = pane.active_item()
 2129                && let Some(project_path) = item.project_path(cx)
 2130            {
 2131                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2132
 2133                if let Some(fs_path) = &fs_path {
 2134                    abs_paths_opened
 2135                        .entry(fs_path.clone())
 2136                        .or_default()
 2137                        .insert(project_path.clone());
 2138                }
 2139
 2140                history.insert(project_path, (fs_path, std::usize::MAX));
 2141            }
 2142        }
 2143
 2144        history
 2145            .into_iter()
 2146            .sorted_by_key(|(_, (_, order))| *order)
 2147            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2148            .rev()
 2149            .filter(move |(history_path, abs_path)| {
 2150                let latest_project_path_opened = abs_path
 2151                    .as_ref()
 2152                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2153                    .and_then(|project_paths| {
 2154                        project_paths
 2155                            .iter()
 2156                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2157                    });
 2158
 2159                latest_project_path_opened.is_none_or(|path| path == history_path)
 2160            })
 2161    }
 2162
 2163    pub fn recent_navigation_history(
 2164        &self,
 2165        limit: Option<usize>,
 2166        cx: &App,
 2167    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2168        self.recent_navigation_history_iter(cx)
 2169            .take(limit.unwrap_or(usize::MAX))
 2170            .collect()
 2171    }
 2172
 2173    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2174        for pane in &self.panes {
 2175            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2176        }
 2177    }
 2178
 2179    fn navigate_history(
 2180        &mut self,
 2181        pane: WeakEntity<Pane>,
 2182        mode: NavigationMode,
 2183        window: &mut Window,
 2184        cx: &mut Context<Workspace>,
 2185    ) -> Task<Result<()>> {
 2186        self.navigate_history_impl(
 2187            pane,
 2188            mode,
 2189            window,
 2190            &mut |history, cx| history.pop(mode, cx),
 2191            cx,
 2192        )
 2193    }
 2194
 2195    fn navigate_tag_history(
 2196        &mut self,
 2197        pane: WeakEntity<Pane>,
 2198        mode: TagNavigationMode,
 2199        window: &mut Window,
 2200        cx: &mut Context<Workspace>,
 2201    ) -> Task<Result<()>> {
 2202        self.navigate_history_impl(
 2203            pane,
 2204            NavigationMode::Normal,
 2205            window,
 2206            &mut |history, _cx| history.pop_tag(mode),
 2207            cx,
 2208        )
 2209    }
 2210
 2211    fn navigate_history_impl(
 2212        &mut self,
 2213        pane: WeakEntity<Pane>,
 2214        mode: NavigationMode,
 2215        window: &mut Window,
 2216        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2217        cx: &mut Context<Workspace>,
 2218    ) -> Task<Result<()>> {
 2219        let to_load = if let Some(pane) = pane.upgrade() {
 2220            pane.update(cx, |pane, cx| {
 2221                window.focus(&pane.focus_handle(cx), cx);
 2222                loop {
 2223                    // Retrieve the weak item handle from the history.
 2224                    let entry = cb(pane.nav_history_mut(), cx)?;
 2225
 2226                    // If the item is still present in this pane, then activate it.
 2227                    if let Some(index) = entry
 2228                        .item
 2229                        .upgrade()
 2230                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2231                    {
 2232                        let prev_active_item_index = pane.active_item_index();
 2233                        pane.nav_history_mut().set_mode(mode);
 2234                        pane.activate_item(index, true, true, window, cx);
 2235                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2236
 2237                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2238                        if let Some(data) = entry.data {
 2239                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2240                        }
 2241
 2242                        if navigated {
 2243                            break None;
 2244                        }
 2245                    } else {
 2246                        // If the item is no longer present in this pane, then retrieve its
 2247                        // path info in order to reopen it.
 2248                        break pane
 2249                            .nav_history()
 2250                            .path_for_item(entry.item.id())
 2251                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2252                    }
 2253                }
 2254            })
 2255        } else {
 2256            None
 2257        };
 2258
 2259        if let Some((project_path, abs_path, entry)) = to_load {
 2260            // If the item was no longer present, then load it again from its previous path, first try the local path
 2261            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2262
 2263            cx.spawn_in(window, async move  |workspace, cx| {
 2264                let open_by_project_path = open_by_project_path.await;
 2265                let mut navigated = false;
 2266                match open_by_project_path
 2267                    .with_context(|| format!("Navigating to {project_path:?}"))
 2268                {
 2269                    Ok((project_entry_id, build_item)) => {
 2270                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2271                            pane.nav_history_mut().set_mode(mode);
 2272                            pane.active_item().map(|p| p.item_id())
 2273                        })?;
 2274
 2275                        pane.update_in(cx, |pane, window, cx| {
 2276                            let item = pane.open_item(
 2277                                project_entry_id,
 2278                                project_path,
 2279                                true,
 2280                                entry.is_preview,
 2281                                true,
 2282                                None,
 2283                                window, cx,
 2284                                build_item,
 2285                            );
 2286                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2287                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2288                            if let Some(data) = entry.data {
 2289                                navigated |= item.navigate(data, window, cx);
 2290                            }
 2291                        })?;
 2292                    }
 2293                    Err(open_by_project_path_e) => {
 2294                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2295                        // and its worktree is now dropped
 2296                        if let Some(abs_path) = abs_path {
 2297                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2298                                pane.nav_history_mut().set_mode(mode);
 2299                                pane.active_item().map(|p| p.item_id())
 2300                            })?;
 2301                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2302                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2303                            })?;
 2304                            match open_by_abs_path
 2305                                .await
 2306                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2307                            {
 2308                                Ok(item) => {
 2309                                    pane.update_in(cx, |pane, window, cx| {
 2310                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2311                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2312                                        if let Some(data) = entry.data {
 2313                                            navigated |= item.navigate(data, window, cx);
 2314                                        }
 2315                                    })?;
 2316                                }
 2317                                Err(open_by_abs_path_e) => {
 2318                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2319                                }
 2320                            }
 2321                        }
 2322                    }
 2323                }
 2324
 2325                if !navigated {
 2326                    workspace
 2327                        .update_in(cx, |workspace, window, cx| {
 2328                            Self::navigate_history(workspace, pane, mode, window, cx)
 2329                        })?
 2330                        .await?;
 2331                }
 2332
 2333                Ok(())
 2334            })
 2335        } else {
 2336            Task::ready(Ok(()))
 2337        }
 2338    }
 2339
 2340    pub fn go_back(
 2341        &mut self,
 2342        pane: WeakEntity<Pane>,
 2343        window: &mut Window,
 2344        cx: &mut Context<Workspace>,
 2345    ) -> Task<Result<()>> {
 2346        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2347    }
 2348
 2349    pub fn go_forward(
 2350        &mut self,
 2351        pane: WeakEntity<Pane>,
 2352        window: &mut Window,
 2353        cx: &mut Context<Workspace>,
 2354    ) -> Task<Result<()>> {
 2355        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2356    }
 2357
 2358    pub fn reopen_closed_item(
 2359        &mut self,
 2360        window: &mut Window,
 2361        cx: &mut Context<Workspace>,
 2362    ) -> Task<Result<()>> {
 2363        self.navigate_history(
 2364            self.active_pane().downgrade(),
 2365            NavigationMode::ReopeningClosedItem,
 2366            window,
 2367            cx,
 2368        )
 2369    }
 2370
 2371    pub fn client(&self) -> &Arc<Client> {
 2372        &self.app_state.client
 2373    }
 2374
 2375    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2376        self.titlebar_item = Some(item);
 2377        cx.notify();
 2378    }
 2379
 2380    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2381        self.on_prompt_for_new_path = Some(prompt)
 2382    }
 2383
 2384    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2385        self.on_prompt_for_open_path = Some(prompt)
 2386    }
 2387
 2388    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2389        self.terminal_provider = Some(Box::new(provider));
 2390    }
 2391
 2392    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2393        self.debugger_provider = Some(Arc::new(provider));
 2394    }
 2395
 2396    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2397        self.debugger_provider.clone()
 2398    }
 2399
 2400    pub fn prompt_for_open_path(
 2401        &mut self,
 2402        path_prompt_options: PathPromptOptions,
 2403        lister: DirectoryLister,
 2404        window: &mut Window,
 2405        cx: &mut Context<Self>,
 2406    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2407        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2408            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2409            let rx = prompt(self, lister, window, cx);
 2410            self.on_prompt_for_open_path = Some(prompt);
 2411            rx
 2412        } else {
 2413            let (tx, rx) = oneshot::channel();
 2414            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2415
 2416            cx.spawn_in(window, async move |workspace, cx| {
 2417                let Ok(result) = abs_path.await else {
 2418                    return Ok(());
 2419                };
 2420
 2421                match result {
 2422                    Ok(result) => {
 2423                        tx.send(result).ok();
 2424                    }
 2425                    Err(err) => {
 2426                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2427                            workspace.show_portal_error(err.to_string(), cx);
 2428                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2429                            let rx = prompt(workspace, lister, window, cx);
 2430                            workspace.on_prompt_for_open_path = Some(prompt);
 2431                            rx
 2432                        })?;
 2433                        if let Ok(path) = rx.await {
 2434                            tx.send(path).ok();
 2435                        }
 2436                    }
 2437                };
 2438                anyhow::Ok(())
 2439            })
 2440            .detach();
 2441
 2442            rx
 2443        }
 2444    }
 2445
 2446    pub fn prompt_for_new_path(
 2447        &mut self,
 2448        lister: DirectoryLister,
 2449        suggested_name: Option<String>,
 2450        window: &mut Window,
 2451        cx: &mut Context<Self>,
 2452    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2453        if self.project.read(cx).is_via_collab()
 2454            || self.project.read(cx).is_via_remote_server()
 2455            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2456        {
 2457            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2458            let rx = prompt(self, lister, suggested_name, window, cx);
 2459            self.on_prompt_for_new_path = Some(prompt);
 2460            return rx;
 2461        }
 2462
 2463        let (tx, rx) = oneshot::channel();
 2464        cx.spawn_in(window, async move |workspace, cx| {
 2465            let abs_path = workspace.update(cx, |workspace, cx| {
 2466                let relative_to = workspace
 2467                    .most_recent_active_path(cx)
 2468                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2469                    .or_else(|| {
 2470                        let project = workspace.project.read(cx);
 2471                        project.visible_worktrees(cx).find_map(|worktree| {
 2472                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2473                        })
 2474                    })
 2475                    .or_else(std::env::home_dir)
 2476                    .unwrap_or_else(|| PathBuf::from(""));
 2477                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2478            })?;
 2479            let abs_path = match abs_path.await? {
 2480                Ok(path) => path,
 2481                Err(err) => {
 2482                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2483                        workspace.show_portal_error(err.to_string(), cx);
 2484
 2485                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2486                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2487                        workspace.on_prompt_for_new_path = Some(prompt);
 2488                        rx
 2489                    })?;
 2490                    if let Ok(path) = rx.await {
 2491                        tx.send(path).ok();
 2492                    }
 2493                    return anyhow::Ok(());
 2494                }
 2495            };
 2496
 2497            tx.send(abs_path.map(|path| vec![path])).ok();
 2498            anyhow::Ok(())
 2499        })
 2500        .detach();
 2501
 2502        rx
 2503    }
 2504
 2505    pub fn titlebar_item(&self) -> Option<AnyView> {
 2506        self.titlebar_item.clone()
 2507    }
 2508
 2509    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2510    /// When set, git-related operations should use this worktree instead of deriving
 2511    /// the active worktree from the focused file.
 2512    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2513        self.active_worktree_override
 2514    }
 2515
 2516    pub fn set_active_worktree_override(
 2517        &mut self,
 2518        worktree_id: Option<WorktreeId>,
 2519        cx: &mut Context<Self>,
 2520    ) {
 2521        self.active_worktree_override = worktree_id;
 2522        cx.notify();
 2523    }
 2524
 2525    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2526        self.active_worktree_override = None;
 2527        cx.notify();
 2528    }
 2529
 2530    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2531    ///
 2532    /// If the given workspace has a local project, then it will be passed
 2533    /// to the callback. Otherwise, a new empty window will be created.
 2534    pub fn with_local_workspace<T, F>(
 2535        &mut self,
 2536        window: &mut Window,
 2537        cx: &mut Context<Self>,
 2538        callback: F,
 2539    ) -> Task<Result<T>>
 2540    where
 2541        T: 'static,
 2542        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2543    {
 2544        if self.project.read(cx).is_local() {
 2545            Task::ready(Ok(callback(self, window, cx)))
 2546        } else {
 2547            let env = self.project.read(cx).cli_environment(cx);
 2548            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2549            cx.spawn_in(window, async move |_vh, cx| {
 2550                let (multi_workspace_window, _) = task.await?;
 2551                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2552                    let workspace = multi_workspace.workspace().clone();
 2553                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2554                })
 2555            })
 2556        }
 2557    }
 2558
 2559    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2560    ///
 2561    /// If the given workspace has a local project, then it will be passed
 2562    /// to the callback. Otherwise, a new empty window will be created.
 2563    pub fn with_local_or_wsl_workspace<T, F>(
 2564        &mut self,
 2565        window: &mut Window,
 2566        cx: &mut Context<Self>,
 2567        callback: F,
 2568    ) -> Task<Result<T>>
 2569    where
 2570        T: 'static,
 2571        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2572    {
 2573        let project = self.project.read(cx);
 2574        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2575            Task::ready(Ok(callback(self, window, cx)))
 2576        } else {
 2577            let env = self.project.read(cx).cli_environment(cx);
 2578            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2579            cx.spawn_in(window, async move |_vh, cx| {
 2580                let (multi_workspace_window, _) = task.await?;
 2581                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2582                    let workspace = multi_workspace.workspace().clone();
 2583                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2584                })
 2585            })
 2586        }
 2587    }
 2588
 2589    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2590        self.project.read(cx).worktrees(cx)
 2591    }
 2592
 2593    pub fn visible_worktrees<'a>(
 2594        &self,
 2595        cx: &'a App,
 2596    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2597        self.project.read(cx).visible_worktrees(cx)
 2598    }
 2599
 2600    #[cfg(any(test, feature = "test-support"))]
 2601    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2602        let futures = self
 2603            .worktrees(cx)
 2604            .filter_map(|worktree| worktree.read(cx).as_local())
 2605            .map(|worktree| worktree.scan_complete())
 2606            .collect::<Vec<_>>();
 2607        async move {
 2608            for future in futures {
 2609                future.await;
 2610            }
 2611        }
 2612    }
 2613
 2614    pub fn close_global(cx: &mut App) {
 2615        cx.defer(|cx| {
 2616            cx.windows().iter().find(|window| {
 2617                window
 2618                    .update(cx, |_, window, _| {
 2619                        if window.is_window_active() {
 2620                            //This can only get called when the window's project connection has been lost
 2621                            //so we don't need to prompt the user for anything and instead just close the window
 2622                            window.remove_window();
 2623                            true
 2624                        } else {
 2625                            false
 2626                        }
 2627                    })
 2628                    .unwrap_or(false)
 2629            });
 2630        });
 2631    }
 2632
 2633    pub fn move_focused_panel_to_next_position(
 2634        &mut self,
 2635        _: &MoveFocusedPanelToNextPosition,
 2636        window: &mut Window,
 2637        cx: &mut Context<Self>,
 2638    ) {
 2639        let docks = self.all_docks();
 2640        let active_dock = docks
 2641            .into_iter()
 2642            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2643
 2644        if let Some(dock) = active_dock {
 2645            dock.update(cx, |dock, cx| {
 2646                let active_panel = dock
 2647                    .active_panel()
 2648                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2649
 2650                if let Some(panel) = active_panel {
 2651                    panel.move_to_next_position(window, cx);
 2652                }
 2653            })
 2654        }
 2655    }
 2656
 2657    pub fn prepare_to_close(
 2658        &mut self,
 2659        close_intent: CloseIntent,
 2660        window: &mut Window,
 2661        cx: &mut Context<Self>,
 2662    ) -> Task<Result<bool>> {
 2663        let active_call = self.active_global_call();
 2664
 2665        cx.spawn_in(window, async move |this, cx| {
 2666            this.update(cx, |this, _| {
 2667                if close_intent == CloseIntent::CloseWindow {
 2668                    this.removing = true;
 2669                }
 2670            })?;
 2671
 2672            let workspace_count = cx.update(|_window, cx| {
 2673                cx.windows()
 2674                    .iter()
 2675                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2676                    .count()
 2677            })?;
 2678
 2679            #[cfg(target_os = "macos")]
 2680            let save_last_workspace = false;
 2681
 2682            // On Linux and Windows, closing the last window should restore the last workspace.
 2683            #[cfg(not(target_os = "macos"))]
 2684            let save_last_workspace = {
 2685                let remaining_workspaces = cx.update(|_window, cx| {
 2686                    cx.windows()
 2687                        .iter()
 2688                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2689                        .filter_map(|multi_workspace| {
 2690                            multi_workspace
 2691                                .update(cx, |multi_workspace, _, cx| {
 2692                                    multi_workspace.workspace().read(cx).removing
 2693                                })
 2694                                .ok()
 2695                        })
 2696                        .filter(|removing| !removing)
 2697                        .count()
 2698                })?;
 2699
 2700                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2701            };
 2702
 2703            if let Some(active_call) = active_call
 2704                && workspace_count == 1
 2705                && cx
 2706                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2707                    .unwrap_or(false)
 2708            {
 2709                if close_intent == CloseIntent::CloseWindow {
 2710                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2711                    let answer = cx.update(|window, cx| {
 2712                        window.prompt(
 2713                            PromptLevel::Warning,
 2714                            "Do you want to leave the current call?",
 2715                            None,
 2716                            &["Close window and hang up", "Cancel"],
 2717                            cx,
 2718                        )
 2719                    })?;
 2720
 2721                    if answer.await.log_err() == Some(1) {
 2722                        return anyhow::Ok(false);
 2723                    } else {
 2724                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2725                            task.await.log_err();
 2726                        }
 2727                    }
 2728                }
 2729                if close_intent == CloseIntent::ReplaceWindow {
 2730                    _ = cx.update(|_window, cx| {
 2731                        let multi_workspace = cx
 2732                            .windows()
 2733                            .iter()
 2734                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2735                            .next()
 2736                            .unwrap();
 2737                        let project = multi_workspace
 2738                            .read(cx)?
 2739                            .workspace()
 2740                            .read(cx)
 2741                            .project
 2742                            .clone();
 2743                        if project.read(cx).is_shared() {
 2744                            active_call.0.unshare_project(project, cx)?;
 2745                        }
 2746                        Ok::<_, anyhow::Error>(())
 2747                    });
 2748                }
 2749            }
 2750
 2751            let save_result = this
 2752                .update_in(cx, |this, window, cx| {
 2753                    this.save_all_internal(SaveIntent::Close, window, cx)
 2754                })?
 2755                .await;
 2756
 2757            // If we're not quitting, but closing, we remove the workspace from
 2758            // the current session.
 2759            if close_intent != CloseIntent::Quit
 2760                && !save_last_workspace
 2761                && save_result.as_ref().is_ok_and(|&res| res)
 2762            {
 2763                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2764                    .await;
 2765            }
 2766
 2767            save_result
 2768        })
 2769    }
 2770
 2771    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2772        self.save_all_internal(
 2773            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2774            window,
 2775            cx,
 2776        )
 2777        .detach_and_log_err(cx);
 2778    }
 2779
 2780    fn send_keystrokes(
 2781        &mut self,
 2782        action: &SendKeystrokes,
 2783        window: &mut Window,
 2784        cx: &mut Context<Self>,
 2785    ) {
 2786        let keystrokes: Vec<Keystroke> = action
 2787            .0
 2788            .split(' ')
 2789            .flat_map(|k| Keystroke::parse(k).log_err())
 2790            .map(|k| {
 2791                cx.keyboard_mapper()
 2792                    .map_key_equivalent(k, false)
 2793                    .inner()
 2794                    .clone()
 2795            })
 2796            .collect();
 2797        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2798    }
 2799
 2800    pub fn send_keystrokes_impl(
 2801        &mut self,
 2802        keystrokes: Vec<Keystroke>,
 2803        window: &mut Window,
 2804        cx: &mut Context<Self>,
 2805    ) -> Shared<Task<()>> {
 2806        let mut state = self.dispatching_keystrokes.borrow_mut();
 2807        if !state.dispatched.insert(keystrokes.clone()) {
 2808            cx.propagate();
 2809            return state.task.clone().unwrap();
 2810        }
 2811
 2812        state.queue.extend(keystrokes);
 2813
 2814        let keystrokes = self.dispatching_keystrokes.clone();
 2815        if state.task.is_none() {
 2816            state.task = Some(
 2817                window
 2818                    .spawn(cx, async move |cx| {
 2819                        // limit to 100 keystrokes to avoid infinite recursion.
 2820                        for _ in 0..100 {
 2821                            let mut state = keystrokes.borrow_mut();
 2822                            let Some(keystroke) = state.queue.pop_front() else {
 2823                                state.dispatched.clear();
 2824                                state.task.take();
 2825                                return;
 2826                            };
 2827                            drop(state);
 2828                            cx.update(|window, cx| {
 2829                                let focused = window.focused(cx);
 2830                                window.dispatch_keystroke(keystroke.clone(), cx);
 2831                                if window.focused(cx) != focused {
 2832                                    // dispatch_keystroke may cause the focus to change.
 2833                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2834                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2835                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2836                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2837                                    // )
 2838                                    window.draw(cx).clear();
 2839                                }
 2840                            })
 2841                            .ok();
 2842                        }
 2843
 2844                        *keystrokes.borrow_mut() = Default::default();
 2845                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2846                    })
 2847                    .shared(),
 2848            );
 2849        }
 2850        state.task.clone().unwrap()
 2851    }
 2852
 2853    fn save_all_internal(
 2854        &mut self,
 2855        mut save_intent: SaveIntent,
 2856        window: &mut Window,
 2857        cx: &mut Context<Self>,
 2858    ) -> Task<Result<bool>> {
 2859        if self.project.read(cx).is_disconnected(cx) {
 2860            return Task::ready(Ok(true));
 2861        }
 2862        let dirty_items = self
 2863            .panes
 2864            .iter()
 2865            .flat_map(|pane| {
 2866                pane.read(cx).items().filter_map(|item| {
 2867                    if item.is_dirty(cx) {
 2868                        item.tab_content_text(0, cx);
 2869                        Some((pane.downgrade(), item.boxed_clone()))
 2870                    } else {
 2871                        None
 2872                    }
 2873                })
 2874            })
 2875            .collect::<Vec<_>>();
 2876
 2877        let project = self.project.clone();
 2878        cx.spawn_in(window, async move |workspace, cx| {
 2879            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2880                let (serialize_tasks, remaining_dirty_items) =
 2881                    workspace.update_in(cx, |workspace, window, cx| {
 2882                        let mut remaining_dirty_items = Vec::new();
 2883                        let mut serialize_tasks = Vec::new();
 2884                        for (pane, item) in dirty_items {
 2885                            if let Some(task) = item
 2886                                .to_serializable_item_handle(cx)
 2887                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2888                            {
 2889                                serialize_tasks.push(task);
 2890                            } else {
 2891                                remaining_dirty_items.push((pane, item));
 2892                            }
 2893                        }
 2894                        (serialize_tasks, remaining_dirty_items)
 2895                    })?;
 2896
 2897                futures::future::try_join_all(serialize_tasks).await?;
 2898
 2899                if !remaining_dirty_items.is_empty() {
 2900                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2901                }
 2902
 2903                if remaining_dirty_items.len() > 1 {
 2904                    let answer = workspace.update_in(cx, |_, window, cx| {
 2905                        let detail = Pane::file_names_for_prompt(
 2906                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2907                            cx,
 2908                        );
 2909                        window.prompt(
 2910                            PromptLevel::Warning,
 2911                            "Do you want to save all changes in the following files?",
 2912                            Some(&detail),
 2913                            &["Save all", "Discard all", "Cancel"],
 2914                            cx,
 2915                        )
 2916                    })?;
 2917                    match answer.await.log_err() {
 2918                        Some(0) => save_intent = SaveIntent::SaveAll,
 2919                        Some(1) => save_intent = SaveIntent::Skip,
 2920                        Some(2) => return Ok(false),
 2921                        _ => {}
 2922                    }
 2923                }
 2924
 2925                remaining_dirty_items
 2926            } else {
 2927                dirty_items
 2928            };
 2929
 2930            for (pane, item) in dirty_items {
 2931                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2932                    (
 2933                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2934                        item.project_entry_ids(cx),
 2935                    )
 2936                })?;
 2937                if (singleton || !project_entry_ids.is_empty())
 2938                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2939                {
 2940                    return Ok(false);
 2941                }
 2942            }
 2943            Ok(true)
 2944        })
 2945    }
 2946
 2947    pub fn open_workspace_for_paths(
 2948        &mut self,
 2949        replace_current_window: bool,
 2950        paths: Vec<PathBuf>,
 2951        window: &mut Window,
 2952        cx: &mut Context<Self>,
 2953    ) -> Task<Result<()>> {
 2954        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 2955        let is_remote = self.project.read(cx).is_via_collab();
 2956        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2957        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2958
 2959        let window_to_replace = if replace_current_window {
 2960            window_handle
 2961        } else if is_remote || has_worktree || has_dirty_items {
 2962            None
 2963        } else {
 2964            window_handle
 2965        };
 2966        let app_state = self.app_state.clone();
 2967
 2968        cx.spawn(async move |_, cx| {
 2969            cx.update(|cx| {
 2970                open_paths(
 2971                    &paths,
 2972                    app_state,
 2973                    OpenOptions {
 2974                        replace_window: window_to_replace,
 2975                        ..Default::default()
 2976                    },
 2977                    cx,
 2978                )
 2979            })
 2980            .await?;
 2981            Ok(())
 2982        })
 2983    }
 2984
 2985    #[allow(clippy::type_complexity)]
 2986    pub fn open_paths(
 2987        &mut self,
 2988        mut abs_paths: Vec<PathBuf>,
 2989        options: OpenOptions,
 2990        pane: Option<WeakEntity<Pane>>,
 2991        window: &mut Window,
 2992        cx: &mut Context<Self>,
 2993    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2994        let fs = self.app_state.fs.clone();
 2995
 2996        let caller_ordered_abs_paths = abs_paths.clone();
 2997
 2998        // Sort the paths to ensure we add worktrees for parents before their children.
 2999        abs_paths.sort_unstable();
 3000        cx.spawn_in(window, async move |this, cx| {
 3001            let mut tasks = Vec::with_capacity(abs_paths.len());
 3002
 3003            for abs_path in &abs_paths {
 3004                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3005                    OpenVisible::All => Some(true),
 3006                    OpenVisible::None => Some(false),
 3007                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3008                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3009                        Some(None) => Some(true),
 3010                        None => None,
 3011                    },
 3012                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3013                        Some(Some(metadata)) => Some(metadata.is_dir),
 3014                        Some(None) => Some(false),
 3015                        None => None,
 3016                    },
 3017                };
 3018                let project_path = match visible {
 3019                    Some(visible) => match this
 3020                        .update(cx, |this, cx| {
 3021                            Workspace::project_path_for_path(
 3022                                this.project.clone(),
 3023                                abs_path,
 3024                                visible,
 3025                                cx,
 3026                            )
 3027                        })
 3028                        .log_err()
 3029                    {
 3030                        Some(project_path) => project_path.await.log_err(),
 3031                        None => None,
 3032                    },
 3033                    None => None,
 3034                };
 3035
 3036                let this = this.clone();
 3037                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3038                let fs = fs.clone();
 3039                let pane = pane.clone();
 3040                let task = cx.spawn(async move |cx| {
 3041                    let (_worktree, project_path) = project_path?;
 3042                    if fs.is_dir(&abs_path).await {
 3043                        // Opening a directory should not race to update the active entry.
 3044                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3045                        None
 3046                    } else {
 3047                        Some(
 3048                            this.update_in(cx, |this, window, cx| {
 3049                                this.open_path(
 3050                                    project_path,
 3051                                    pane,
 3052                                    options.focus.unwrap_or(true),
 3053                                    window,
 3054                                    cx,
 3055                                )
 3056                            })
 3057                            .ok()?
 3058                            .await,
 3059                        )
 3060                    }
 3061                });
 3062                tasks.push(task);
 3063            }
 3064
 3065            let results = futures::future::join_all(tasks).await;
 3066
 3067            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3068            let mut winner: Option<(PathBuf, bool)> = None;
 3069            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3070                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3071                    if !metadata.is_dir {
 3072                        winner = Some((abs_path, false));
 3073                        break;
 3074                    }
 3075                    if winner.is_none() {
 3076                        winner = Some((abs_path, true));
 3077                    }
 3078                } else if winner.is_none() {
 3079                    winner = Some((abs_path, false));
 3080                }
 3081            }
 3082
 3083            // Compute the winner entry id on the foreground thread and emit once, after all
 3084            // paths finish opening. This avoids races between concurrently-opening paths
 3085            // (directories in particular) and makes the resulting project panel selection
 3086            // deterministic.
 3087            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3088                'emit_winner: {
 3089                    let winner_abs_path: Arc<Path> =
 3090                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3091
 3092                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3093                        OpenVisible::All => true,
 3094                        OpenVisible::None => false,
 3095                        OpenVisible::OnlyFiles => !winner_is_dir,
 3096                        OpenVisible::OnlyDirectories => winner_is_dir,
 3097                    };
 3098
 3099                    let Some(worktree_task) = this
 3100                        .update(cx, |workspace, cx| {
 3101                            workspace.project.update(cx, |project, cx| {
 3102                                project.find_or_create_worktree(
 3103                                    winner_abs_path.as_ref(),
 3104                                    visible,
 3105                                    cx,
 3106                                )
 3107                            })
 3108                        })
 3109                        .ok()
 3110                    else {
 3111                        break 'emit_winner;
 3112                    };
 3113
 3114                    let Ok((worktree, _)) = worktree_task.await else {
 3115                        break 'emit_winner;
 3116                    };
 3117
 3118                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3119                        let worktree = worktree.read(cx);
 3120                        let worktree_abs_path = worktree.abs_path();
 3121                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3122                            worktree.root_entry()
 3123                        } else {
 3124                            winner_abs_path
 3125                                .strip_prefix(worktree_abs_path.as_ref())
 3126                                .ok()
 3127                                .and_then(|relative_path| {
 3128                                    let relative_path =
 3129                                        RelPath::new(relative_path, PathStyle::local())
 3130                                            .log_err()?;
 3131                                    worktree.entry_for_path(&relative_path)
 3132                                })
 3133                        }?;
 3134                        Some(entry.id)
 3135                    }) else {
 3136                        break 'emit_winner;
 3137                    };
 3138
 3139                    this.update(cx, |workspace, cx| {
 3140                        workspace.project.update(cx, |_, cx| {
 3141                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3142                        });
 3143                    })
 3144                    .ok();
 3145                }
 3146            }
 3147
 3148            results
 3149        })
 3150    }
 3151
 3152    pub fn open_resolved_path(
 3153        &mut self,
 3154        path: ResolvedPath,
 3155        window: &mut Window,
 3156        cx: &mut Context<Self>,
 3157    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3158        match path {
 3159            ResolvedPath::ProjectPath { project_path, .. } => {
 3160                self.open_path(project_path, None, true, window, cx)
 3161            }
 3162            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3163                PathBuf::from(path),
 3164                OpenOptions {
 3165                    visible: Some(OpenVisible::None),
 3166                    ..Default::default()
 3167                },
 3168                window,
 3169                cx,
 3170            ),
 3171        }
 3172    }
 3173
 3174    pub fn absolute_path_of_worktree(
 3175        &self,
 3176        worktree_id: WorktreeId,
 3177        cx: &mut Context<Self>,
 3178    ) -> Option<PathBuf> {
 3179        self.project
 3180            .read(cx)
 3181            .worktree_for_id(worktree_id, cx)
 3182            // TODO: use `abs_path` or `root_dir`
 3183            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3184    }
 3185
 3186    fn add_folder_to_project(
 3187        &mut self,
 3188        _: &AddFolderToProject,
 3189        window: &mut Window,
 3190        cx: &mut Context<Self>,
 3191    ) {
 3192        let project = self.project.read(cx);
 3193        if project.is_via_collab() {
 3194            self.show_error(
 3195                &anyhow!("You cannot add folders to someone else's project"),
 3196                cx,
 3197            );
 3198            return;
 3199        }
 3200        let paths = self.prompt_for_open_path(
 3201            PathPromptOptions {
 3202                files: false,
 3203                directories: true,
 3204                multiple: true,
 3205                prompt: None,
 3206            },
 3207            DirectoryLister::Project(self.project.clone()),
 3208            window,
 3209            cx,
 3210        );
 3211        cx.spawn_in(window, async move |this, cx| {
 3212            if let Some(paths) = paths.await.log_err().flatten() {
 3213                let results = this
 3214                    .update_in(cx, |this, window, cx| {
 3215                        this.open_paths(
 3216                            paths,
 3217                            OpenOptions {
 3218                                visible: Some(OpenVisible::All),
 3219                                ..Default::default()
 3220                            },
 3221                            None,
 3222                            window,
 3223                            cx,
 3224                        )
 3225                    })?
 3226                    .await;
 3227                for result in results.into_iter().flatten() {
 3228                    result.log_err();
 3229                }
 3230            }
 3231            anyhow::Ok(())
 3232        })
 3233        .detach_and_log_err(cx);
 3234    }
 3235
 3236    pub fn project_path_for_path(
 3237        project: Entity<Project>,
 3238        abs_path: &Path,
 3239        visible: bool,
 3240        cx: &mut App,
 3241    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3242        let entry = project.update(cx, |project, cx| {
 3243            project.find_or_create_worktree(abs_path, visible, cx)
 3244        });
 3245        cx.spawn(async move |cx| {
 3246            let (worktree, path) = entry.await?;
 3247            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3248            Ok((worktree, ProjectPath { worktree_id, path }))
 3249        })
 3250    }
 3251
 3252    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3253        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3254    }
 3255
 3256    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3257        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3258    }
 3259
 3260    pub fn items_of_type<'a, T: Item>(
 3261        &'a self,
 3262        cx: &'a App,
 3263    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3264        self.panes
 3265            .iter()
 3266            .flat_map(|pane| pane.read(cx).items_of_type())
 3267    }
 3268
 3269    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3270        self.active_pane().read(cx).active_item()
 3271    }
 3272
 3273    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3274        let item = self.active_item(cx)?;
 3275        item.to_any_view().downcast::<I>().ok()
 3276    }
 3277
 3278    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3279        self.active_item(cx).and_then(|item| item.project_path(cx))
 3280    }
 3281
 3282    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3283        self.recent_navigation_history_iter(cx)
 3284            .filter_map(|(path, abs_path)| {
 3285                let worktree = self
 3286                    .project
 3287                    .read(cx)
 3288                    .worktree_for_id(path.worktree_id, cx)?;
 3289                if worktree.read(cx).is_visible() {
 3290                    abs_path
 3291                } else {
 3292                    None
 3293                }
 3294            })
 3295            .next()
 3296    }
 3297
 3298    pub fn save_active_item(
 3299        &mut self,
 3300        save_intent: SaveIntent,
 3301        window: &mut Window,
 3302        cx: &mut App,
 3303    ) -> Task<Result<()>> {
 3304        let project = self.project.clone();
 3305        let pane = self.active_pane();
 3306        let item = pane.read(cx).active_item();
 3307        let pane = pane.downgrade();
 3308
 3309        window.spawn(cx, async move |cx| {
 3310            if let Some(item) = item {
 3311                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3312                    .await
 3313                    .map(|_| ())
 3314            } else {
 3315                Ok(())
 3316            }
 3317        })
 3318    }
 3319
 3320    pub fn close_inactive_items_and_panes(
 3321        &mut self,
 3322        action: &CloseInactiveTabsAndPanes,
 3323        window: &mut Window,
 3324        cx: &mut Context<Self>,
 3325    ) {
 3326        if let Some(task) = self.close_all_internal(
 3327            true,
 3328            action.save_intent.unwrap_or(SaveIntent::Close),
 3329            window,
 3330            cx,
 3331        ) {
 3332            task.detach_and_log_err(cx)
 3333        }
 3334    }
 3335
 3336    pub fn close_all_items_and_panes(
 3337        &mut self,
 3338        action: &CloseAllItemsAndPanes,
 3339        window: &mut Window,
 3340        cx: &mut Context<Self>,
 3341    ) {
 3342        if let Some(task) = self.close_all_internal(
 3343            false,
 3344            action.save_intent.unwrap_or(SaveIntent::Close),
 3345            window,
 3346            cx,
 3347        ) {
 3348            task.detach_and_log_err(cx)
 3349        }
 3350    }
 3351
 3352    /// Closes the active item across all panes.
 3353    pub fn close_item_in_all_panes(
 3354        &mut self,
 3355        action: &CloseItemInAllPanes,
 3356        window: &mut Window,
 3357        cx: &mut Context<Self>,
 3358    ) {
 3359        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3360            return;
 3361        };
 3362
 3363        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3364        let close_pinned = action.close_pinned;
 3365
 3366        if let Some(project_path) = active_item.project_path(cx) {
 3367            self.close_items_with_project_path(
 3368                &project_path,
 3369                save_intent,
 3370                close_pinned,
 3371                window,
 3372                cx,
 3373            );
 3374        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3375            let item_id = active_item.item_id();
 3376            self.active_pane().update(cx, |pane, cx| {
 3377                pane.close_item_by_id(item_id, save_intent, window, cx)
 3378                    .detach_and_log_err(cx);
 3379            });
 3380        }
 3381    }
 3382
 3383    /// Closes all items with the given project path across all panes.
 3384    pub fn close_items_with_project_path(
 3385        &mut self,
 3386        project_path: &ProjectPath,
 3387        save_intent: SaveIntent,
 3388        close_pinned: bool,
 3389        window: &mut Window,
 3390        cx: &mut Context<Self>,
 3391    ) {
 3392        let panes = self.panes().to_vec();
 3393        for pane in panes {
 3394            pane.update(cx, |pane, cx| {
 3395                pane.close_items_for_project_path(
 3396                    project_path,
 3397                    save_intent,
 3398                    close_pinned,
 3399                    window,
 3400                    cx,
 3401                )
 3402                .detach_and_log_err(cx);
 3403            });
 3404        }
 3405    }
 3406
 3407    fn close_all_internal(
 3408        &mut self,
 3409        retain_active_pane: bool,
 3410        save_intent: SaveIntent,
 3411        window: &mut Window,
 3412        cx: &mut Context<Self>,
 3413    ) -> Option<Task<Result<()>>> {
 3414        let current_pane = self.active_pane();
 3415
 3416        let mut tasks = Vec::new();
 3417
 3418        if retain_active_pane {
 3419            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3420                pane.close_other_items(
 3421                    &CloseOtherItems {
 3422                        save_intent: None,
 3423                        close_pinned: false,
 3424                    },
 3425                    None,
 3426                    window,
 3427                    cx,
 3428                )
 3429            });
 3430
 3431            tasks.push(current_pane_close);
 3432        }
 3433
 3434        for pane in self.panes() {
 3435            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3436                continue;
 3437            }
 3438
 3439            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3440                pane.close_all_items(
 3441                    &CloseAllItems {
 3442                        save_intent: Some(save_intent),
 3443                        close_pinned: false,
 3444                    },
 3445                    window,
 3446                    cx,
 3447                )
 3448            });
 3449
 3450            tasks.push(close_pane_items)
 3451        }
 3452
 3453        if tasks.is_empty() {
 3454            None
 3455        } else {
 3456            Some(cx.spawn_in(window, async move |_, _| {
 3457                for task in tasks {
 3458                    task.await?
 3459                }
 3460                Ok(())
 3461            }))
 3462        }
 3463    }
 3464
 3465    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3466        self.dock_at_position(position).read(cx).is_open()
 3467    }
 3468
 3469    pub fn toggle_dock(
 3470        &mut self,
 3471        dock_side: DockPosition,
 3472        window: &mut Window,
 3473        cx: &mut Context<Self>,
 3474    ) {
 3475        let mut focus_center = false;
 3476        let mut reveal_dock = false;
 3477
 3478        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3479        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3480
 3481        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3482            telemetry::event!(
 3483                "Panel Button Clicked",
 3484                name = panel.persistent_name(),
 3485                toggle_state = !was_visible
 3486            );
 3487        }
 3488        if was_visible {
 3489            self.save_open_dock_positions(cx);
 3490        }
 3491
 3492        let dock = self.dock_at_position(dock_side);
 3493        dock.update(cx, |dock, cx| {
 3494            dock.set_open(!was_visible, window, cx);
 3495
 3496            if dock.active_panel().is_none() {
 3497                let Some(panel_ix) = dock
 3498                    .first_enabled_panel_idx(cx)
 3499                    .log_with_level(log::Level::Info)
 3500                else {
 3501                    return;
 3502                };
 3503                dock.activate_panel(panel_ix, window, cx);
 3504            }
 3505
 3506            if let Some(active_panel) = dock.active_panel() {
 3507                if was_visible {
 3508                    if active_panel
 3509                        .panel_focus_handle(cx)
 3510                        .contains_focused(window, cx)
 3511                    {
 3512                        focus_center = true;
 3513                    }
 3514                } else {
 3515                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3516                    window.focus(focus_handle, cx);
 3517                    reveal_dock = true;
 3518                }
 3519            }
 3520        });
 3521
 3522        if reveal_dock {
 3523            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3524        }
 3525
 3526        if focus_center {
 3527            self.active_pane
 3528                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3529        }
 3530
 3531        cx.notify();
 3532        self.serialize_workspace(window, cx);
 3533    }
 3534
 3535    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3536        self.all_docks().into_iter().find(|&dock| {
 3537            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3538        })
 3539    }
 3540
 3541    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3542        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3543            self.save_open_dock_positions(cx);
 3544            dock.update(cx, |dock, cx| {
 3545                dock.set_open(false, window, cx);
 3546            });
 3547            return true;
 3548        }
 3549        false
 3550    }
 3551
 3552    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3553        self.save_open_dock_positions(cx);
 3554        for dock in self.all_docks() {
 3555            dock.update(cx, |dock, cx| {
 3556                dock.set_open(false, window, cx);
 3557            });
 3558        }
 3559
 3560        cx.focus_self(window);
 3561        cx.notify();
 3562        self.serialize_workspace(window, cx);
 3563    }
 3564
 3565    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3566        self.all_docks()
 3567            .into_iter()
 3568            .filter_map(|dock| {
 3569                let dock_ref = dock.read(cx);
 3570                if dock_ref.is_open() {
 3571                    Some(dock_ref.position())
 3572                } else {
 3573                    None
 3574                }
 3575            })
 3576            .collect()
 3577    }
 3578
 3579    /// Saves the positions of currently open docks.
 3580    ///
 3581    /// Updates `last_open_dock_positions` with positions of all currently open
 3582    /// docks, to later be restored by the 'Toggle All Docks' action.
 3583    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3584        let open_dock_positions = self.get_open_dock_positions(cx);
 3585        if !open_dock_positions.is_empty() {
 3586            self.last_open_dock_positions = open_dock_positions;
 3587        }
 3588    }
 3589
 3590    /// Toggles all docks between open and closed states.
 3591    ///
 3592    /// If any docks are open, closes all and remembers their positions. If all
 3593    /// docks are closed, restores the last remembered dock configuration.
 3594    fn toggle_all_docks(
 3595        &mut self,
 3596        _: &ToggleAllDocks,
 3597        window: &mut Window,
 3598        cx: &mut Context<Self>,
 3599    ) {
 3600        let open_dock_positions = self.get_open_dock_positions(cx);
 3601
 3602        if !open_dock_positions.is_empty() {
 3603            self.close_all_docks(window, cx);
 3604        } else if !self.last_open_dock_positions.is_empty() {
 3605            self.restore_last_open_docks(window, cx);
 3606        }
 3607    }
 3608
 3609    /// Reopens docks from the most recently remembered configuration.
 3610    ///
 3611    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3612    /// and clears the stored positions.
 3613    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3614        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3615
 3616        for position in positions_to_open {
 3617            let dock = self.dock_at_position(position);
 3618            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3619        }
 3620
 3621        cx.focus_self(window);
 3622        cx.notify();
 3623        self.serialize_workspace(window, cx);
 3624    }
 3625
 3626    /// Transfer focus to the panel of the given type.
 3627    pub fn focus_panel<T: Panel>(
 3628        &mut self,
 3629        window: &mut Window,
 3630        cx: &mut Context<Self>,
 3631    ) -> Option<Entity<T>> {
 3632        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3633        panel.to_any().downcast().ok()
 3634    }
 3635
 3636    /// Focus the panel of the given type if it isn't already focused. If it is
 3637    /// already focused, then transfer focus back to the workspace center.
 3638    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3639    /// panel when transferring focus back to the center.
 3640    pub fn toggle_panel_focus<T: Panel>(
 3641        &mut self,
 3642        window: &mut Window,
 3643        cx: &mut Context<Self>,
 3644    ) -> bool {
 3645        let mut did_focus_panel = false;
 3646        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3647            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3648            did_focus_panel
 3649        });
 3650
 3651        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3652            self.close_panel::<T>(window, cx);
 3653        }
 3654
 3655        telemetry::event!(
 3656            "Panel Button Clicked",
 3657            name = T::persistent_name(),
 3658            toggle_state = did_focus_panel
 3659        );
 3660
 3661        did_focus_panel
 3662    }
 3663
 3664    pub fn activate_panel_for_proto_id(
 3665        &mut self,
 3666        panel_id: PanelId,
 3667        window: &mut Window,
 3668        cx: &mut Context<Self>,
 3669    ) -> Option<Arc<dyn PanelHandle>> {
 3670        let mut panel = None;
 3671        for dock in self.all_docks() {
 3672            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3673                panel = dock.update(cx, |dock, cx| {
 3674                    dock.activate_panel(panel_index, window, cx);
 3675                    dock.set_open(true, window, cx);
 3676                    dock.active_panel().cloned()
 3677                });
 3678                break;
 3679            }
 3680        }
 3681
 3682        if panel.is_some() {
 3683            cx.notify();
 3684            self.serialize_workspace(window, cx);
 3685        }
 3686
 3687        panel
 3688    }
 3689
 3690    /// Focus or unfocus the given panel type, depending on the given callback.
 3691    fn focus_or_unfocus_panel<T: Panel>(
 3692        &mut self,
 3693        window: &mut Window,
 3694        cx: &mut Context<Self>,
 3695        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3696    ) -> Option<Arc<dyn PanelHandle>> {
 3697        let mut result_panel = None;
 3698        let mut serialize = false;
 3699        for dock in self.all_docks() {
 3700            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3701                let mut focus_center = false;
 3702                let panel = dock.update(cx, |dock, cx| {
 3703                    dock.activate_panel(panel_index, window, cx);
 3704
 3705                    let panel = dock.active_panel().cloned();
 3706                    if let Some(panel) = panel.as_ref() {
 3707                        if should_focus(&**panel, window, cx) {
 3708                            dock.set_open(true, window, cx);
 3709                            panel.panel_focus_handle(cx).focus(window, cx);
 3710                        } else {
 3711                            focus_center = true;
 3712                        }
 3713                    }
 3714                    panel
 3715                });
 3716
 3717                if focus_center {
 3718                    self.active_pane
 3719                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3720                }
 3721
 3722                result_panel = panel;
 3723                serialize = true;
 3724                break;
 3725            }
 3726        }
 3727
 3728        if serialize {
 3729            self.serialize_workspace(window, cx);
 3730        }
 3731
 3732        cx.notify();
 3733        result_panel
 3734    }
 3735
 3736    /// Open the panel of the given type
 3737    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3738        for dock in self.all_docks() {
 3739            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3740                dock.update(cx, |dock, cx| {
 3741                    dock.activate_panel(panel_index, window, cx);
 3742                    dock.set_open(true, window, cx);
 3743                });
 3744            }
 3745        }
 3746    }
 3747
 3748    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3749        for dock in self.all_docks().iter() {
 3750            dock.update(cx, |dock, cx| {
 3751                if dock.panel::<T>().is_some() {
 3752                    dock.set_open(false, window, cx)
 3753                }
 3754            })
 3755        }
 3756    }
 3757
 3758    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3759        self.all_docks()
 3760            .iter()
 3761            .find_map(|dock| dock.read(cx).panel::<T>())
 3762    }
 3763
 3764    fn dismiss_zoomed_items_to_reveal(
 3765        &mut self,
 3766        dock_to_reveal: Option<DockPosition>,
 3767        window: &mut Window,
 3768        cx: &mut Context<Self>,
 3769    ) {
 3770        // If a center pane is zoomed, unzoom it.
 3771        for pane in &self.panes {
 3772            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3773                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3774            }
 3775        }
 3776
 3777        // If another dock is zoomed, hide it.
 3778        let mut focus_center = false;
 3779        for dock in self.all_docks() {
 3780            dock.update(cx, |dock, cx| {
 3781                if Some(dock.position()) != dock_to_reveal
 3782                    && let Some(panel) = dock.active_panel()
 3783                    && panel.is_zoomed(window, cx)
 3784                {
 3785                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3786                    dock.set_open(false, window, cx);
 3787                }
 3788            });
 3789        }
 3790
 3791        if focus_center {
 3792            self.active_pane
 3793                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3794        }
 3795
 3796        if self.zoomed_position != dock_to_reveal {
 3797            self.zoomed = None;
 3798            self.zoomed_position = None;
 3799            cx.emit(Event::ZoomChanged);
 3800        }
 3801
 3802        cx.notify();
 3803    }
 3804
 3805    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3806        let pane = cx.new(|cx| {
 3807            let mut pane = Pane::new(
 3808                self.weak_handle(),
 3809                self.project.clone(),
 3810                self.pane_history_timestamp.clone(),
 3811                None,
 3812                NewFile.boxed_clone(),
 3813                true,
 3814                window,
 3815                cx,
 3816            );
 3817            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3818            pane
 3819        });
 3820        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3821            .detach();
 3822        self.panes.push(pane.clone());
 3823
 3824        window.focus(&pane.focus_handle(cx), cx);
 3825
 3826        cx.emit(Event::PaneAdded(pane.clone()));
 3827        pane
 3828    }
 3829
 3830    pub fn add_item_to_center(
 3831        &mut self,
 3832        item: Box<dyn ItemHandle>,
 3833        window: &mut Window,
 3834        cx: &mut Context<Self>,
 3835    ) -> bool {
 3836        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3837            if let Some(center_pane) = center_pane.upgrade() {
 3838                center_pane.update(cx, |pane, cx| {
 3839                    pane.add_item(item, true, true, None, window, cx)
 3840                });
 3841                true
 3842            } else {
 3843                false
 3844            }
 3845        } else {
 3846            false
 3847        }
 3848    }
 3849
 3850    pub fn add_item_to_active_pane(
 3851        &mut self,
 3852        item: Box<dyn ItemHandle>,
 3853        destination_index: Option<usize>,
 3854        focus_item: bool,
 3855        window: &mut Window,
 3856        cx: &mut App,
 3857    ) {
 3858        self.add_item(
 3859            self.active_pane.clone(),
 3860            item,
 3861            destination_index,
 3862            false,
 3863            focus_item,
 3864            window,
 3865            cx,
 3866        )
 3867    }
 3868
 3869    pub fn add_item(
 3870        &mut self,
 3871        pane: Entity<Pane>,
 3872        item: Box<dyn ItemHandle>,
 3873        destination_index: Option<usize>,
 3874        activate_pane: bool,
 3875        focus_item: bool,
 3876        window: &mut Window,
 3877        cx: &mut App,
 3878    ) {
 3879        pane.update(cx, |pane, cx| {
 3880            pane.add_item(
 3881                item,
 3882                activate_pane,
 3883                focus_item,
 3884                destination_index,
 3885                window,
 3886                cx,
 3887            )
 3888        });
 3889    }
 3890
 3891    pub fn split_item(
 3892        &mut self,
 3893        split_direction: SplitDirection,
 3894        item: Box<dyn ItemHandle>,
 3895        window: &mut Window,
 3896        cx: &mut Context<Self>,
 3897    ) {
 3898        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3899        self.add_item(new_pane, item, None, true, true, window, cx);
 3900    }
 3901
 3902    pub fn open_abs_path(
 3903        &mut self,
 3904        abs_path: PathBuf,
 3905        options: OpenOptions,
 3906        window: &mut Window,
 3907        cx: &mut Context<Self>,
 3908    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3909        cx.spawn_in(window, async move |workspace, cx| {
 3910            let open_paths_task_result = workspace
 3911                .update_in(cx, |workspace, window, cx| {
 3912                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3913                })
 3914                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3915                .await;
 3916            anyhow::ensure!(
 3917                open_paths_task_result.len() == 1,
 3918                "open abs path {abs_path:?} task returned incorrect number of results"
 3919            );
 3920            match open_paths_task_result
 3921                .into_iter()
 3922                .next()
 3923                .expect("ensured single task result")
 3924            {
 3925                Some(open_result) => {
 3926                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3927                }
 3928                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3929            }
 3930        })
 3931    }
 3932
 3933    pub fn split_abs_path(
 3934        &mut self,
 3935        abs_path: PathBuf,
 3936        visible: bool,
 3937        window: &mut Window,
 3938        cx: &mut Context<Self>,
 3939    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3940        let project_path_task =
 3941            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3942        cx.spawn_in(window, async move |this, cx| {
 3943            let (_, path) = project_path_task.await?;
 3944            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3945                .await
 3946        })
 3947    }
 3948
 3949    pub fn open_path(
 3950        &mut self,
 3951        path: impl Into<ProjectPath>,
 3952        pane: Option<WeakEntity<Pane>>,
 3953        focus_item: bool,
 3954        window: &mut Window,
 3955        cx: &mut App,
 3956    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3957        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3958    }
 3959
 3960    pub fn open_path_preview(
 3961        &mut self,
 3962        path: impl Into<ProjectPath>,
 3963        pane: Option<WeakEntity<Pane>>,
 3964        focus_item: bool,
 3965        allow_preview: bool,
 3966        activate: bool,
 3967        window: &mut Window,
 3968        cx: &mut App,
 3969    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3970        let pane = pane.unwrap_or_else(|| {
 3971            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3972                self.panes
 3973                    .first()
 3974                    .expect("There must be an active pane")
 3975                    .downgrade()
 3976            })
 3977        });
 3978
 3979        let project_path = path.into();
 3980        let task = self.load_path(project_path.clone(), window, cx);
 3981        window.spawn(cx, async move |cx| {
 3982            let (project_entry_id, build_item) = task.await?;
 3983
 3984            pane.update_in(cx, |pane, window, cx| {
 3985                pane.open_item(
 3986                    project_entry_id,
 3987                    project_path,
 3988                    focus_item,
 3989                    allow_preview,
 3990                    activate,
 3991                    None,
 3992                    window,
 3993                    cx,
 3994                    build_item,
 3995                )
 3996            })
 3997        })
 3998    }
 3999
 4000    pub fn split_path(
 4001        &mut self,
 4002        path: impl Into<ProjectPath>,
 4003        window: &mut Window,
 4004        cx: &mut Context<Self>,
 4005    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4006        self.split_path_preview(path, false, None, window, cx)
 4007    }
 4008
 4009    pub fn split_path_preview(
 4010        &mut self,
 4011        path: impl Into<ProjectPath>,
 4012        allow_preview: bool,
 4013        split_direction: Option<SplitDirection>,
 4014        window: &mut Window,
 4015        cx: &mut Context<Self>,
 4016    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4017        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4018            self.panes
 4019                .first()
 4020                .expect("There must be an active pane")
 4021                .downgrade()
 4022        });
 4023
 4024        if let Member::Pane(center_pane) = &self.center.root
 4025            && center_pane.read(cx).items_len() == 0
 4026        {
 4027            return self.open_path(path, Some(pane), true, window, cx);
 4028        }
 4029
 4030        let project_path = path.into();
 4031        let task = self.load_path(project_path.clone(), window, cx);
 4032        cx.spawn_in(window, async move |this, cx| {
 4033            let (project_entry_id, build_item) = task.await?;
 4034            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4035                let pane = pane.upgrade()?;
 4036                let new_pane = this.split_pane(
 4037                    pane,
 4038                    split_direction.unwrap_or(SplitDirection::Right),
 4039                    window,
 4040                    cx,
 4041                );
 4042                new_pane.update(cx, |new_pane, cx| {
 4043                    Some(new_pane.open_item(
 4044                        project_entry_id,
 4045                        project_path,
 4046                        true,
 4047                        allow_preview,
 4048                        true,
 4049                        None,
 4050                        window,
 4051                        cx,
 4052                        build_item,
 4053                    ))
 4054                })
 4055            })
 4056            .map(|option| option.context("pane was dropped"))?
 4057        })
 4058    }
 4059
 4060    fn load_path(
 4061        &mut self,
 4062        path: ProjectPath,
 4063        window: &mut Window,
 4064        cx: &mut App,
 4065    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4066        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4067        registry.open_path(self.project(), &path, window, cx)
 4068    }
 4069
 4070    pub fn find_project_item<T>(
 4071        &self,
 4072        pane: &Entity<Pane>,
 4073        project_item: &Entity<T::Item>,
 4074        cx: &App,
 4075    ) -> Option<Entity<T>>
 4076    where
 4077        T: ProjectItem,
 4078    {
 4079        use project::ProjectItem as _;
 4080        let project_item = project_item.read(cx);
 4081        let entry_id = project_item.entry_id(cx);
 4082        let project_path = project_item.project_path(cx);
 4083
 4084        let mut item = None;
 4085        if let Some(entry_id) = entry_id {
 4086            item = pane.read(cx).item_for_entry(entry_id, cx);
 4087        }
 4088        if item.is_none()
 4089            && let Some(project_path) = project_path
 4090        {
 4091            item = pane.read(cx).item_for_path(project_path, cx);
 4092        }
 4093
 4094        item.and_then(|item| item.downcast::<T>())
 4095    }
 4096
 4097    pub fn is_project_item_open<T>(
 4098        &self,
 4099        pane: &Entity<Pane>,
 4100        project_item: &Entity<T::Item>,
 4101        cx: &App,
 4102    ) -> bool
 4103    where
 4104        T: ProjectItem,
 4105    {
 4106        self.find_project_item::<T>(pane, project_item, cx)
 4107            .is_some()
 4108    }
 4109
 4110    pub fn open_project_item<T>(
 4111        &mut self,
 4112        pane: Entity<Pane>,
 4113        project_item: Entity<T::Item>,
 4114        activate_pane: bool,
 4115        focus_item: bool,
 4116        keep_old_preview: bool,
 4117        allow_new_preview: bool,
 4118        window: &mut Window,
 4119        cx: &mut Context<Self>,
 4120    ) -> Entity<T>
 4121    where
 4122        T: ProjectItem,
 4123    {
 4124        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4125
 4126        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4127            if !keep_old_preview
 4128                && let Some(old_id) = old_item_id
 4129                && old_id != item.item_id()
 4130            {
 4131                // switching to a different item, so unpreview old active item
 4132                pane.update(cx, |pane, _| {
 4133                    pane.unpreview_item_if_preview(old_id);
 4134                });
 4135            }
 4136
 4137            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4138            if !allow_new_preview {
 4139                pane.update(cx, |pane, _| {
 4140                    pane.unpreview_item_if_preview(item.item_id());
 4141                });
 4142            }
 4143            return item;
 4144        }
 4145
 4146        let item = pane.update(cx, |pane, cx| {
 4147            cx.new(|cx| {
 4148                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4149            })
 4150        });
 4151        let mut destination_index = None;
 4152        pane.update(cx, |pane, cx| {
 4153            if !keep_old_preview && let Some(old_id) = old_item_id {
 4154                pane.unpreview_item_if_preview(old_id);
 4155            }
 4156            if allow_new_preview {
 4157                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4158            }
 4159        });
 4160
 4161        self.add_item(
 4162            pane,
 4163            Box::new(item.clone()),
 4164            destination_index,
 4165            activate_pane,
 4166            focus_item,
 4167            window,
 4168            cx,
 4169        );
 4170        item
 4171    }
 4172
 4173    pub fn open_shared_screen(
 4174        &mut self,
 4175        peer_id: PeerId,
 4176        window: &mut Window,
 4177        cx: &mut Context<Self>,
 4178    ) {
 4179        if let Some(shared_screen) =
 4180            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4181        {
 4182            self.active_pane.update(cx, |pane, cx| {
 4183                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4184            });
 4185        }
 4186    }
 4187
 4188    pub fn activate_item(
 4189        &mut self,
 4190        item: &dyn ItemHandle,
 4191        activate_pane: bool,
 4192        focus_item: bool,
 4193        window: &mut Window,
 4194        cx: &mut App,
 4195    ) -> bool {
 4196        let result = self.panes.iter().find_map(|pane| {
 4197            pane.read(cx)
 4198                .index_for_item(item)
 4199                .map(|ix| (pane.clone(), ix))
 4200        });
 4201        if let Some((pane, ix)) = result {
 4202            pane.update(cx, |pane, cx| {
 4203                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4204            });
 4205            true
 4206        } else {
 4207            false
 4208        }
 4209    }
 4210
 4211    fn activate_pane_at_index(
 4212        &mut self,
 4213        action: &ActivatePane,
 4214        window: &mut Window,
 4215        cx: &mut Context<Self>,
 4216    ) {
 4217        let panes = self.center.panes();
 4218        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4219            window.focus(&pane.focus_handle(cx), cx);
 4220        } else {
 4221            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4222                .detach();
 4223        }
 4224    }
 4225
 4226    fn move_item_to_pane_at_index(
 4227        &mut self,
 4228        action: &MoveItemToPane,
 4229        window: &mut Window,
 4230        cx: &mut Context<Self>,
 4231    ) {
 4232        let panes = self.center.panes();
 4233        let destination = match panes.get(action.destination) {
 4234            Some(&destination) => destination.clone(),
 4235            None => {
 4236                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4237                    return;
 4238                }
 4239                let direction = SplitDirection::Right;
 4240                let split_off_pane = self
 4241                    .find_pane_in_direction(direction, cx)
 4242                    .unwrap_or_else(|| self.active_pane.clone());
 4243                let new_pane = self.add_pane(window, cx);
 4244                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4245                new_pane
 4246            }
 4247        };
 4248
 4249        if action.clone {
 4250            if self
 4251                .active_pane
 4252                .read(cx)
 4253                .active_item()
 4254                .is_some_and(|item| item.can_split(cx))
 4255            {
 4256                clone_active_item(
 4257                    self.database_id(),
 4258                    &self.active_pane,
 4259                    &destination,
 4260                    action.focus,
 4261                    window,
 4262                    cx,
 4263                );
 4264                return;
 4265            }
 4266        }
 4267        move_active_item(
 4268            &self.active_pane,
 4269            &destination,
 4270            action.focus,
 4271            true,
 4272            window,
 4273            cx,
 4274        )
 4275    }
 4276
 4277    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4278        let panes = self.center.panes();
 4279        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4280            let next_ix = (ix + 1) % panes.len();
 4281            let next_pane = panes[next_ix].clone();
 4282            window.focus(&next_pane.focus_handle(cx), cx);
 4283        }
 4284    }
 4285
 4286    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4287        let panes = self.center.panes();
 4288        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4289            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4290            let prev_pane = panes[prev_ix].clone();
 4291            window.focus(&prev_pane.focus_handle(cx), cx);
 4292        }
 4293    }
 4294
 4295    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4296        let last_pane = self.center.last_pane();
 4297        window.focus(&last_pane.focus_handle(cx), cx);
 4298    }
 4299
 4300    pub fn activate_pane_in_direction(
 4301        &mut self,
 4302        direction: SplitDirection,
 4303        window: &mut Window,
 4304        cx: &mut App,
 4305    ) {
 4306        use ActivateInDirectionTarget as Target;
 4307        enum Origin {
 4308            LeftDock,
 4309            RightDock,
 4310            BottomDock,
 4311            Center,
 4312        }
 4313
 4314        let origin: Origin = [
 4315            (&self.left_dock, Origin::LeftDock),
 4316            (&self.right_dock, Origin::RightDock),
 4317            (&self.bottom_dock, Origin::BottomDock),
 4318        ]
 4319        .into_iter()
 4320        .find_map(|(dock, origin)| {
 4321            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4322                Some(origin)
 4323            } else {
 4324                None
 4325            }
 4326        })
 4327        .unwrap_or(Origin::Center);
 4328
 4329        let get_last_active_pane = || {
 4330            let pane = self
 4331                .last_active_center_pane
 4332                .clone()
 4333                .unwrap_or_else(|| {
 4334                    self.panes
 4335                        .first()
 4336                        .expect("There must be an active pane")
 4337                        .downgrade()
 4338                })
 4339                .upgrade()?;
 4340            (pane.read(cx).items_len() != 0).then_some(pane)
 4341        };
 4342
 4343        let try_dock =
 4344            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4345
 4346        let target = match (origin, direction) {
 4347            // We're in the center, so we first try to go to a different pane,
 4348            // otherwise try to go to a dock.
 4349            (Origin::Center, direction) => {
 4350                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4351                    Some(Target::Pane(pane))
 4352                } else {
 4353                    match direction {
 4354                        SplitDirection::Up => None,
 4355                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4356                        SplitDirection::Left => try_dock(&self.left_dock),
 4357                        SplitDirection::Right => try_dock(&self.right_dock),
 4358                    }
 4359                }
 4360            }
 4361
 4362            (Origin::LeftDock, SplitDirection::Right) => {
 4363                if let Some(last_active_pane) = get_last_active_pane() {
 4364                    Some(Target::Pane(last_active_pane))
 4365                } else {
 4366                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4367                }
 4368            }
 4369
 4370            (Origin::LeftDock, SplitDirection::Down)
 4371            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4372
 4373            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4374            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4375            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4376
 4377            (Origin::RightDock, SplitDirection::Left) => {
 4378                if let Some(last_active_pane) = get_last_active_pane() {
 4379                    Some(Target::Pane(last_active_pane))
 4380                } else {
 4381                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4382                }
 4383            }
 4384
 4385            _ => None,
 4386        };
 4387
 4388        match target {
 4389            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4390                let pane = pane.read(cx);
 4391                if let Some(item) = pane.active_item() {
 4392                    item.item_focus_handle(cx).focus(window, cx);
 4393                } else {
 4394                    log::error!(
 4395                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4396                    );
 4397                }
 4398            }
 4399            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4400                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4401                window.defer(cx, move |window, cx| {
 4402                    let dock = dock.read(cx);
 4403                    if let Some(panel) = dock.active_panel() {
 4404                        panel.panel_focus_handle(cx).focus(window, cx);
 4405                    } else {
 4406                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4407                    }
 4408                })
 4409            }
 4410            None => {}
 4411        }
 4412    }
 4413
 4414    pub fn move_item_to_pane_in_direction(
 4415        &mut self,
 4416        action: &MoveItemToPaneInDirection,
 4417        window: &mut Window,
 4418        cx: &mut Context<Self>,
 4419    ) {
 4420        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4421            Some(destination) => destination,
 4422            None => {
 4423                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4424                    return;
 4425                }
 4426                let new_pane = self.add_pane(window, cx);
 4427                self.center
 4428                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4429                new_pane
 4430            }
 4431        };
 4432
 4433        if action.clone {
 4434            if self
 4435                .active_pane
 4436                .read(cx)
 4437                .active_item()
 4438                .is_some_and(|item| item.can_split(cx))
 4439            {
 4440                clone_active_item(
 4441                    self.database_id(),
 4442                    &self.active_pane,
 4443                    &destination,
 4444                    action.focus,
 4445                    window,
 4446                    cx,
 4447                );
 4448                return;
 4449            }
 4450        }
 4451        move_active_item(
 4452            &self.active_pane,
 4453            &destination,
 4454            action.focus,
 4455            true,
 4456            window,
 4457            cx,
 4458        );
 4459    }
 4460
 4461    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4462        self.center.bounding_box_for_pane(pane)
 4463    }
 4464
 4465    pub fn find_pane_in_direction(
 4466        &mut self,
 4467        direction: SplitDirection,
 4468        cx: &App,
 4469    ) -> Option<Entity<Pane>> {
 4470        self.center
 4471            .find_pane_in_direction(&self.active_pane, direction, cx)
 4472            .cloned()
 4473    }
 4474
 4475    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4476        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4477            self.center.swap(&self.active_pane, &to, cx);
 4478            cx.notify();
 4479        }
 4480    }
 4481
 4482    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4483        if self
 4484            .center
 4485            .move_to_border(&self.active_pane, direction, cx)
 4486            .unwrap()
 4487        {
 4488            cx.notify();
 4489        }
 4490    }
 4491
 4492    pub fn resize_pane(
 4493        &mut self,
 4494        axis: gpui::Axis,
 4495        amount: Pixels,
 4496        window: &mut Window,
 4497        cx: &mut Context<Self>,
 4498    ) {
 4499        let docks = self.all_docks();
 4500        let active_dock = docks
 4501            .into_iter()
 4502            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4503
 4504        if let Some(dock) = active_dock {
 4505            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4506                return;
 4507            };
 4508            match dock.read(cx).position() {
 4509                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4510                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4511                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4512            }
 4513        } else {
 4514            self.center
 4515                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4516        }
 4517        cx.notify();
 4518    }
 4519
 4520    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4521        self.center.reset_pane_sizes(cx);
 4522        cx.notify();
 4523    }
 4524
 4525    fn handle_pane_focused(
 4526        &mut self,
 4527        pane: Entity<Pane>,
 4528        window: &mut Window,
 4529        cx: &mut Context<Self>,
 4530    ) {
 4531        // This is explicitly hoisted out of the following check for pane identity as
 4532        // terminal panel panes are not registered as a center panes.
 4533        self.status_bar.update(cx, |status_bar, cx| {
 4534            status_bar.set_active_pane(&pane, window, cx);
 4535        });
 4536        if self.active_pane != pane {
 4537            self.set_active_pane(&pane, window, cx);
 4538        }
 4539
 4540        if self.last_active_center_pane.is_none() {
 4541            self.last_active_center_pane = Some(pane.downgrade());
 4542        }
 4543
 4544        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4545        // This prevents the dock from closing when focus events fire during window activation.
 4546        // We also preserve any dock whose active panel itself has focus — this covers
 4547        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4548        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4549            let dock_read = dock.read(cx);
 4550            if let Some(panel) = dock_read.active_panel() {
 4551                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4552                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4553                {
 4554                    return Some(dock_read.position());
 4555                }
 4556            }
 4557            None
 4558        });
 4559
 4560        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4561        if pane.read(cx).is_zoomed() {
 4562            self.zoomed = Some(pane.downgrade().into());
 4563        } else {
 4564            self.zoomed = None;
 4565        }
 4566        self.zoomed_position = None;
 4567        cx.emit(Event::ZoomChanged);
 4568        self.update_active_view_for_followers(window, cx);
 4569        pane.update(cx, |pane, _| {
 4570            pane.track_alternate_file_items();
 4571        });
 4572
 4573        cx.notify();
 4574    }
 4575
 4576    fn set_active_pane(
 4577        &mut self,
 4578        pane: &Entity<Pane>,
 4579        window: &mut Window,
 4580        cx: &mut Context<Self>,
 4581    ) {
 4582        self.active_pane = pane.clone();
 4583        self.active_item_path_changed(true, window, cx);
 4584        self.last_active_center_pane = Some(pane.downgrade());
 4585    }
 4586
 4587    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4588        self.update_active_view_for_followers(window, cx);
 4589    }
 4590
 4591    fn handle_pane_event(
 4592        &mut self,
 4593        pane: &Entity<Pane>,
 4594        event: &pane::Event,
 4595        window: &mut Window,
 4596        cx: &mut Context<Self>,
 4597    ) {
 4598        let mut serialize_workspace = true;
 4599        match event {
 4600            pane::Event::AddItem { item } => {
 4601                item.added_to_pane(self, pane.clone(), window, cx);
 4602                cx.emit(Event::ItemAdded {
 4603                    item: item.boxed_clone(),
 4604                });
 4605            }
 4606            pane::Event::Split { direction, mode } => {
 4607                match mode {
 4608                    SplitMode::ClonePane => {
 4609                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4610                            .detach();
 4611                    }
 4612                    SplitMode::EmptyPane => {
 4613                        self.split_pane(pane.clone(), *direction, window, cx);
 4614                    }
 4615                    SplitMode::MovePane => {
 4616                        self.split_and_move(pane.clone(), *direction, window, cx);
 4617                    }
 4618                };
 4619            }
 4620            pane::Event::JoinIntoNext => {
 4621                self.join_pane_into_next(pane.clone(), window, cx);
 4622            }
 4623            pane::Event::JoinAll => {
 4624                self.join_all_panes(window, cx);
 4625            }
 4626            pane::Event::Remove { focus_on_pane } => {
 4627                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4628            }
 4629            pane::Event::ActivateItem {
 4630                local,
 4631                focus_changed,
 4632            } => {
 4633                window.invalidate_character_coordinates();
 4634
 4635                pane.update(cx, |pane, _| {
 4636                    pane.track_alternate_file_items();
 4637                });
 4638                if *local {
 4639                    self.unfollow_in_pane(pane, window, cx);
 4640                }
 4641                serialize_workspace = *focus_changed || pane != self.active_pane();
 4642                if pane == self.active_pane() {
 4643                    self.active_item_path_changed(*focus_changed, window, cx);
 4644                    self.update_active_view_for_followers(window, cx);
 4645                } else if *local {
 4646                    self.set_active_pane(pane, window, cx);
 4647                }
 4648            }
 4649            pane::Event::UserSavedItem { item, save_intent } => {
 4650                cx.emit(Event::UserSavedItem {
 4651                    pane: pane.downgrade(),
 4652                    item: item.boxed_clone(),
 4653                    save_intent: *save_intent,
 4654                });
 4655                serialize_workspace = false;
 4656            }
 4657            pane::Event::ChangeItemTitle => {
 4658                if *pane == self.active_pane {
 4659                    self.active_item_path_changed(false, window, cx);
 4660                }
 4661                serialize_workspace = false;
 4662            }
 4663            pane::Event::RemovedItem { item } => {
 4664                cx.emit(Event::ActiveItemChanged);
 4665                self.update_window_edited(window, cx);
 4666                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4667                    && entry.get().entity_id() == pane.entity_id()
 4668                {
 4669                    entry.remove();
 4670                }
 4671                cx.emit(Event::ItemRemoved {
 4672                    item_id: item.item_id(),
 4673                });
 4674            }
 4675            pane::Event::Focus => {
 4676                window.invalidate_character_coordinates();
 4677                self.handle_pane_focused(pane.clone(), window, cx);
 4678            }
 4679            pane::Event::ZoomIn => {
 4680                if *pane == self.active_pane {
 4681                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4682                    if pane.read(cx).has_focus(window, cx) {
 4683                        self.zoomed = Some(pane.downgrade().into());
 4684                        self.zoomed_position = None;
 4685                        cx.emit(Event::ZoomChanged);
 4686                    }
 4687                    cx.notify();
 4688                }
 4689            }
 4690            pane::Event::ZoomOut => {
 4691                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4692                if self.zoomed_position.is_none() {
 4693                    self.zoomed = None;
 4694                    cx.emit(Event::ZoomChanged);
 4695                }
 4696                cx.notify();
 4697            }
 4698            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4699        }
 4700
 4701        if serialize_workspace {
 4702            self.serialize_workspace(window, cx);
 4703        }
 4704    }
 4705
 4706    pub fn unfollow_in_pane(
 4707        &mut self,
 4708        pane: &Entity<Pane>,
 4709        window: &mut Window,
 4710        cx: &mut Context<Workspace>,
 4711    ) -> Option<CollaboratorId> {
 4712        let leader_id = self.leader_for_pane(pane)?;
 4713        self.unfollow(leader_id, window, cx);
 4714        Some(leader_id)
 4715    }
 4716
 4717    pub fn split_pane(
 4718        &mut self,
 4719        pane_to_split: Entity<Pane>,
 4720        split_direction: SplitDirection,
 4721        window: &mut Window,
 4722        cx: &mut Context<Self>,
 4723    ) -> Entity<Pane> {
 4724        let new_pane = self.add_pane(window, cx);
 4725        self.center
 4726            .split(&pane_to_split, &new_pane, split_direction, cx);
 4727        cx.notify();
 4728        new_pane
 4729    }
 4730
 4731    pub fn split_and_move(
 4732        &mut self,
 4733        pane: Entity<Pane>,
 4734        direction: SplitDirection,
 4735        window: &mut Window,
 4736        cx: &mut Context<Self>,
 4737    ) {
 4738        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4739            return;
 4740        };
 4741        let new_pane = self.add_pane(window, cx);
 4742        new_pane.update(cx, |pane, cx| {
 4743            pane.add_item(item, true, true, None, window, cx)
 4744        });
 4745        self.center.split(&pane, &new_pane, direction, cx);
 4746        cx.notify();
 4747    }
 4748
 4749    pub fn split_and_clone(
 4750        &mut self,
 4751        pane: Entity<Pane>,
 4752        direction: SplitDirection,
 4753        window: &mut Window,
 4754        cx: &mut Context<Self>,
 4755    ) -> Task<Option<Entity<Pane>>> {
 4756        let Some(item) = pane.read(cx).active_item() else {
 4757            return Task::ready(None);
 4758        };
 4759        if !item.can_split(cx) {
 4760            return Task::ready(None);
 4761        }
 4762        let task = item.clone_on_split(self.database_id(), window, cx);
 4763        cx.spawn_in(window, async move |this, cx| {
 4764            if let Some(clone) = task.await {
 4765                this.update_in(cx, |this, window, cx| {
 4766                    let new_pane = this.add_pane(window, cx);
 4767                    let nav_history = pane.read(cx).fork_nav_history();
 4768                    new_pane.update(cx, |pane, cx| {
 4769                        pane.set_nav_history(nav_history, cx);
 4770                        pane.add_item(clone, true, true, None, window, cx)
 4771                    });
 4772                    this.center.split(&pane, &new_pane, direction, cx);
 4773                    cx.notify();
 4774                    new_pane
 4775                })
 4776                .ok()
 4777            } else {
 4778                None
 4779            }
 4780        })
 4781    }
 4782
 4783    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4784        let active_item = self.active_pane.read(cx).active_item();
 4785        for pane in &self.panes {
 4786            join_pane_into_active(&self.active_pane, pane, window, cx);
 4787        }
 4788        if let Some(active_item) = active_item {
 4789            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4790        }
 4791        cx.notify();
 4792    }
 4793
 4794    pub fn join_pane_into_next(
 4795        &mut self,
 4796        pane: Entity<Pane>,
 4797        window: &mut Window,
 4798        cx: &mut Context<Self>,
 4799    ) {
 4800        let next_pane = self
 4801            .find_pane_in_direction(SplitDirection::Right, cx)
 4802            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4803            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4804            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4805        let Some(next_pane) = next_pane else {
 4806            return;
 4807        };
 4808        move_all_items(&pane, &next_pane, window, cx);
 4809        cx.notify();
 4810    }
 4811
 4812    fn remove_pane(
 4813        &mut self,
 4814        pane: Entity<Pane>,
 4815        focus_on: Option<Entity<Pane>>,
 4816        window: &mut Window,
 4817        cx: &mut Context<Self>,
 4818    ) {
 4819        if self.center.remove(&pane, cx).unwrap() {
 4820            self.force_remove_pane(&pane, &focus_on, window, cx);
 4821            self.unfollow_in_pane(&pane, window, cx);
 4822            self.last_leaders_by_pane.remove(&pane.downgrade());
 4823            for removed_item in pane.read(cx).items() {
 4824                self.panes_by_item.remove(&removed_item.item_id());
 4825            }
 4826
 4827            cx.notify();
 4828        } else {
 4829            self.active_item_path_changed(true, window, cx);
 4830        }
 4831        cx.emit(Event::PaneRemoved);
 4832    }
 4833
 4834    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4835        &mut self.panes
 4836    }
 4837
 4838    pub fn panes(&self) -> &[Entity<Pane>] {
 4839        &self.panes
 4840    }
 4841
 4842    pub fn active_pane(&self) -> &Entity<Pane> {
 4843        &self.active_pane
 4844    }
 4845
 4846    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4847        for dock in self.all_docks() {
 4848            if dock.focus_handle(cx).contains_focused(window, cx)
 4849                && let Some(pane) = dock
 4850                    .read(cx)
 4851                    .active_panel()
 4852                    .and_then(|panel| panel.pane(cx))
 4853            {
 4854                return pane;
 4855            }
 4856        }
 4857        self.active_pane().clone()
 4858    }
 4859
 4860    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4861        self.find_pane_in_direction(SplitDirection::Right, cx)
 4862            .unwrap_or_else(|| {
 4863                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4864            })
 4865    }
 4866
 4867    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4868        self.pane_for_item_id(handle.item_id())
 4869    }
 4870
 4871    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 4872        let weak_pane = self.panes_by_item.get(&item_id)?;
 4873        weak_pane.upgrade()
 4874    }
 4875
 4876    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 4877        self.panes
 4878            .iter()
 4879            .find(|pane| pane.entity_id() == entity_id)
 4880            .cloned()
 4881    }
 4882
 4883    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4884        self.follower_states.retain(|leader_id, state| {
 4885            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4886                for item in state.items_by_leader_view_id.values() {
 4887                    item.view.set_leader_id(None, window, cx);
 4888                }
 4889                false
 4890            } else {
 4891                true
 4892            }
 4893        });
 4894        cx.notify();
 4895    }
 4896
 4897    pub fn start_following(
 4898        &mut self,
 4899        leader_id: impl Into<CollaboratorId>,
 4900        window: &mut Window,
 4901        cx: &mut Context<Self>,
 4902    ) -> Option<Task<Result<()>>> {
 4903        let leader_id = leader_id.into();
 4904        let pane = self.active_pane().clone();
 4905
 4906        self.last_leaders_by_pane
 4907            .insert(pane.downgrade(), leader_id);
 4908        self.unfollow(leader_id, window, cx);
 4909        self.unfollow_in_pane(&pane, window, cx);
 4910        self.follower_states.insert(
 4911            leader_id,
 4912            FollowerState {
 4913                center_pane: pane.clone(),
 4914                dock_pane: None,
 4915                active_view_id: None,
 4916                items_by_leader_view_id: Default::default(),
 4917            },
 4918        );
 4919        cx.notify();
 4920
 4921        match leader_id {
 4922            CollaboratorId::PeerId(leader_peer_id) => {
 4923                let room_id = self.active_call()?.room_id(cx)?;
 4924                let project_id = self.project.read(cx).remote_id();
 4925                let request = self.app_state.client.request(proto::Follow {
 4926                    room_id,
 4927                    project_id,
 4928                    leader_id: Some(leader_peer_id),
 4929                });
 4930
 4931                Some(cx.spawn_in(window, async move |this, cx| {
 4932                    let response = request.await?;
 4933                    this.update(cx, |this, _| {
 4934                        let state = this
 4935                            .follower_states
 4936                            .get_mut(&leader_id)
 4937                            .context("following interrupted")?;
 4938                        state.active_view_id = response
 4939                            .active_view
 4940                            .as_ref()
 4941                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4942                        anyhow::Ok(())
 4943                    })??;
 4944                    if let Some(view) = response.active_view {
 4945                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4946                    }
 4947                    this.update_in(cx, |this, window, cx| {
 4948                        this.leader_updated(leader_id, window, cx)
 4949                    })?;
 4950                    Ok(())
 4951                }))
 4952            }
 4953            CollaboratorId::Agent => {
 4954                self.leader_updated(leader_id, window, cx)?;
 4955                Some(Task::ready(Ok(())))
 4956            }
 4957        }
 4958    }
 4959
 4960    pub fn follow_next_collaborator(
 4961        &mut self,
 4962        _: &FollowNextCollaborator,
 4963        window: &mut Window,
 4964        cx: &mut Context<Self>,
 4965    ) {
 4966        let collaborators = self.project.read(cx).collaborators();
 4967        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4968            let mut collaborators = collaborators.keys().copied();
 4969            for peer_id in collaborators.by_ref() {
 4970                if CollaboratorId::PeerId(peer_id) == leader_id {
 4971                    break;
 4972                }
 4973            }
 4974            collaborators.next().map(CollaboratorId::PeerId)
 4975        } else if let Some(last_leader_id) =
 4976            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4977        {
 4978            match last_leader_id {
 4979                CollaboratorId::PeerId(peer_id) => {
 4980                    if collaborators.contains_key(peer_id) {
 4981                        Some(*last_leader_id)
 4982                    } else {
 4983                        None
 4984                    }
 4985                }
 4986                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4987            }
 4988        } else {
 4989            None
 4990        };
 4991
 4992        let pane = self.active_pane.clone();
 4993        let Some(leader_id) = next_leader_id.or_else(|| {
 4994            Some(CollaboratorId::PeerId(
 4995                collaborators.keys().copied().next()?,
 4996            ))
 4997        }) else {
 4998            return;
 4999        };
 5000        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5001            return;
 5002        }
 5003        if let Some(task) = self.start_following(leader_id, window, cx) {
 5004            task.detach_and_log_err(cx)
 5005        }
 5006    }
 5007
 5008    pub fn follow(
 5009        &mut self,
 5010        leader_id: impl Into<CollaboratorId>,
 5011        window: &mut Window,
 5012        cx: &mut Context<Self>,
 5013    ) {
 5014        let leader_id = leader_id.into();
 5015
 5016        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5017            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5018                return;
 5019            };
 5020            let Some(remote_participant) =
 5021                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5022            else {
 5023                return;
 5024            };
 5025
 5026            let project = self.project.read(cx);
 5027
 5028            let other_project_id = match remote_participant.location {
 5029                ParticipantLocation::External => None,
 5030                ParticipantLocation::UnsharedProject => None,
 5031                ParticipantLocation::SharedProject { project_id } => {
 5032                    if Some(project_id) == project.remote_id() {
 5033                        None
 5034                    } else {
 5035                        Some(project_id)
 5036                    }
 5037                }
 5038            };
 5039
 5040            // if they are active in another project, follow there.
 5041            if let Some(project_id) = other_project_id {
 5042                let app_state = self.app_state.clone();
 5043                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5044                    .detach_and_log_err(cx);
 5045            }
 5046        }
 5047
 5048        // if you're already following, find the right pane and focus it.
 5049        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5050            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5051
 5052            return;
 5053        }
 5054
 5055        // Otherwise, follow.
 5056        if let Some(task) = self.start_following(leader_id, window, cx) {
 5057            task.detach_and_log_err(cx)
 5058        }
 5059    }
 5060
 5061    pub fn unfollow(
 5062        &mut self,
 5063        leader_id: impl Into<CollaboratorId>,
 5064        window: &mut Window,
 5065        cx: &mut Context<Self>,
 5066    ) -> Option<()> {
 5067        cx.notify();
 5068
 5069        let leader_id = leader_id.into();
 5070        let state = self.follower_states.remove(&leader_id)?;
 5071        for (_, item) in state.items_by_leader_view_id {
 5072            item.view.set_leader_id(None, window, cx);
 5073        }
 5074
 5075        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5076            let project_id = self.project.read(cx).remote_id();
 5077            let room_id = self.active_call()?.room_id(cx)?;
 5078            self.app_state
 5079                .client
 5080                .send(proto::Unfollow {
 5081                    room_id,
 5082                    project_id,
 5083                    leader_id: Some(leader_peer_id),
 5084                })
 5085                .log_err();
 5086        }
 5087
 5088        Some(())
 5089    }
 5090
 5091    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5092        self.follower_states.contains_key(&id.into())
 5093    }
 5094
 5095    fn active_item_path_changed(
 5096        &mut self,
 5097        focus_changed: bool,
 5098        window: &mut Window,
 5099        cx: &mut Context<Self>,
 5100    ) {
 5101        cx.emit(Event::ActiveItemChanged);
 5102        let active_entry = self.active_project_path(cx);
 5103        self.project.update(cx, |project, cx| {
 5104            project.set_active_path(active_entry.clone(), cx)
 5105        });
 5106
 5107        if focus_changed && let Some(project_path) = &active_entry {
 5108            let git_store_entity = self.project.read(cx).git_store().clone();
 5109            git_store_entity.update(cx, |git_store, cx| {
 5110                git_store.set_active_repo_for_path(project_path, cx);
 5111            });
 5112        }
 5113
 5114        self.update_window_title(window, cx);
 5115    }
 5116
 5117    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5118        let project = self.project().read(cx);
 5119        let mut title = String::new();
 5120
 5121        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5122            let name = {
 5123                let settings_location = SettingsLocation {
 5124                    worktree_id: worktree.read(cx).id(),
 5125                    path: RelPath::empty(),
 5126                };
 5127
 5128                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5129                match &settings.project_name {
 5130                    Some(name) => name.as_str(),
 5131                    None => worktree.read(cx).root_name_str(),
 5132                }
 5133            };
 5134            if i > 0 {
 5135                title.push_str(", ");
 5136            }
 5137            title.push_str(name);
 5138        }
 5139
 5140        if title.is_empty() {
 5141            title = "empty project".to_string();
 5142        }
 5143
 5144        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5145            let filename = path.path.file_name().or_else(|| {
 5146                Some(
 5147                    project
 5148                        .worktree_for_id(path.worktree_id, cx)?
 5149                        .read(cx)
 5150                        .root_name_str(),
 5151                )
 5152            });
 5153
 5154            if let Some(filename) = filename {
 5155                title.push_str("");
 5156                title.push_str(filename.as_ref());
 5157            }
 5158        }
 5159
 5160        if project.is_via_collab() {
 5161            title.push_str("");
 5162        } else if project.is_shared() {
 5163            title.push_str("");
 5164        }
 5165
 5166        if let Some(last_title) = self.last_window_title.as_ref()
 5167            && &title == last_title
 5168        {
 5169            return;
 5170        }
 5171        window.set_window_title(&title);
 5172        SystemWindowTabController::update_tab_title(
 5173            cx,
 5174            window.window_handle().window_id(),
 5175            SharedString::from(&title),
 5176        );
 5177        self.last_window_title = Some(title);
 5178    }
 5179
 5180    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5181        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5182        if is_edited != self.window_edited {
 5183            self.window_edited = is_edited;
 5184            window.set_window_edited(self.window_edited)
 5185        }
 5186    }
 5187
 5188    fn update_item_dirty_state(
 5189        &mut self,
 5190        item: &dyn ItemHandle,
 5191        window: &mut Window,
 5192        cx: &mut App,
 5193    ) {
 5194        let is_dirty = item.is_dirty(cx);
 5195        let item_id = item.item_id();
 5196        let was_dirty = self.dirty_items.contains_key(&item_id);
 5197        if is_dirty == was_dirty {
 5198            return;
 5199        }
 5200        if was_dirty {
 5201            self.dirty_items.remove(&item_id);
 5202            self.update_window_edited(window, cx);
 5203            return;
 5204        }
 5205
 5206        let workspace = self.weak_handle();
 5207        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5208            return;
 5209        };
 5210        let on_release_callback = Box::new(move |cx: &mut App| {
 5211            window_handle
 5212                .update(cx, |_, window, cx| {
 5213                    workspace
 5214                        .update(cx, |workspace, cx| {
 5215                            workspace.dirty_items.remove(&item_id);
 5216                            workspace.update_window_edited(window, cx)
 5217                        })
 5218                        .ok();
 5219                })
 5220                .ok();
 5221        });
 5222
 5223        let s = item.on_release(cx, on_release_callback);
 5224        self.dirty_items.insert(item_id, s);
 5225        self.update_window_edited(window, cx);
 5226    }
 5227
 5228    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5229        if self.notifications.is_empty() {
 5230            None
 5231        } else {
 5232            Some(
 5233                div()
 5234                    .absolute()
 5235                    .right_3()
 5236                    .bottom_3()
 5237                    .w_112()
 5238                    .h_full()
 5239                    .flex()
 5240                    .flex_col()
 5241                    .justify_end()
 5242                    .gap_2()
 5243                    .children(
 5244                        self.notifications
 5245                            .iter()
 5246                            .map(|(_, notification)| notification.clone().into_any()),
 5247                    ),
 5248            )
 5249        }
 5250    }
 5251
 5252    // RPC handlers
 5253
 5254    fn active_view_for_follower(
 5255        &self,
 5256        follower_project_id: Option<u64>,
 5257        window: &mut Window,
 5258        cx: &mut Context<Self>,
 5259    ) -> Option<proto::View> {
 5260        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5261        let item = item?;
 5262        let leader_id = self
 5263            .pane_for(&*item)
 5264            .and_then(|pane| self.leader_for_pane(&pane));
 5265        let leader_peer_id = match leader_id {
 5266            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5267            Some(CollaboratorId::Agent) | None => None,
 5268        };
 5269
 5270        let item_handle = item.to_followable_item_handle(cx)?;
 5271        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5272        let variant = item_handle.to_state_proto(window, cx)?;
 5273
 5274        if item_handle.is_project_item(window, cx)
 5275            && (follower_project_id.is_none()
 5276                || follower_project_id != self.project.read(cx).remote_id())
 5277        {
 5278            return None;
 5279        }
 5280
 5281        Some(proto::View {
 5282            id: id.to_proto(),
 5283            leader_id: leader_peer_id,
 5284            variant: Some(variant),
 5285            panel_id: panel_id.map(|id| id as i32),
 5286        })
 5287    }
 5288
 5289    fn handle_follow(
 5290        &mut self,
 5291        follower_project_id: Option<u64>,
 5292        window: &mut Window,
 5293        cx: &mut Context<Self>,
 5294    ) -> proto::FollowResponse {
 5295        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5296
 5297        cx.notify();
 5298        proto::FollowResponse {
 5299            views: active_view.iter().cloned().collect(),
 5300            active_view,
 5301        }
 5302    }
 5303
 5304    fn handle_update_followers(
 5305        &mut self,
 5306        leader_id: PeerId,
 5307        message: proto::UpdateFollowers,
 5308        _window: &mut Window,
 5309        _cx: &mut Context<Self>,
 5310    ) {
 5311        self.leader_updates_tx
 5312            .unbounded_send((leader_id, message))
 5313            .ok();
 5314    }
 5315
 5316    async fn process_leader_update(
 5317        this: &WeakEntity<Self>,
 5318        leader_id: PeerId,
 5319        update: proto::UpdateFollowers,
 5320        cx: &mut AsyncWindowContext,
 5321    ) -> Result<()> {
 5322        match update.variant.context("invalid update")? {
 5323            proto::update_followers::Variant::CreateView(view) => {
 5324                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5325                let should_add_view = this.update(cx, |this, _| {
 5326                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5327                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5328                    } else {
 5329                        anyhow::Ok(false)
 5330                    }
 5331                })??;
 5332
 5333                if should_add_view {
 5334                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5335                }
 5336            }
 5337            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5338                let should_add_view = this.update(cx, |this, _| {
 5339                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5340                        state.active_view_id = update_active_view
 5341                            .view
 5342                            .as_ref()
 5343                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5344
 5345                        if state.active_view_id.is_some_and(|view_id| {
 5346                            !state.items_by_leader_view_id.contains_key(&view_id)
 5347                        }) {
 5348                            anyhow::Ok(true)
 5349                        } else {
 5350                            anyhow::Ok(false)
 5351                        }
 5352                    } else {
 5353                        anyhow::Ok(false)
 5354                    }
 5355                })??;
 5356
 5357                if should_add_view && let Some(view) = update_active_view.view {
 5358                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5359                }
 5360            }
 5361            proto::update_followers::Variant::UpdateView(update_view) => {
 5362                let variant = update_view.variant.context("missing update view variant")?;
 5363                let id = update_view.id.context("missing update view id")?;
 5364                let mut tasks = Vec::new();
 5365                this.update_in(cx, |this, window, cx| {
 5366                    let project = this.project.clone();
 5367                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5368                        let view_id = ViewId::from_proto(id.clone())?;
 5369                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5370                            tasks.push(item.view.apply_update_proto(
 5371                                &project,
 5372                                variant.clone(),
 5373                                window,
 5374                                cx,
 5375                            ));
 5376                        }
 5377                    }
 5378                    anyhow::Ok(())
 5379                })??;
 5380                try_join_all(tasks).await.log_err();
 5381            }
 5382        }
 5383        this.update_in(cx, |this, window, cx| {
 5384            this.leader_updated(leader_id, window, cx)
 5385        })?;
 5386        Ok(())
 5387    }
 5388
 5389    async fn add_view_from_leader(
 5390        this: WeakEntity<Self>,
 5391        leader_id: PeerId,
 5392        view: &proto::View,
 5393        cx: &mut AsyncWindowContext,
 5394    ) -> Result<()> {
 5395        let this = this.upgrade().context("workspace dropped")?;
 5396
 5397        let Some(id) = view.id.clone() else {
 5398            anyhow::bail!("no id for view");
 5399        };
 5400        let id = ViewId::from_proto(id)?;
 5401        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5402
 5403        let pane = this.update(cx, |this, _cx| {
 5404            let state = this
 5405                .follower_states
 5406                .get(&leader_id.into())
 5407                .context("stopped following")?;
 5408            anyhow::Ok(state.pane().clone())
 5409        })?;
 5410        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5411            let client = this.read(cx).client().clone();
 5412            pane.items().find_map(|item| {
 5413                let item = item.to_followable_item_handle(cx)?;
 5414                if item.remote_id(&client, window, cx) == Some(id) {
 5415                    Some(item)
 5416                } else {
 5417                    None
 5418                }
 5419            })
 5420        })?;
 5421        let item = if let Some(existing_item) = existing_item {
 5422            existing_item
 5423        } else {
 5424            let variant = view.variant.clone();
 5425            anyhow::ensure!(variant.is_some(), "missing view variant");
 5426
 5427            let task = cx.update(|window, cx| {
 5428                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5429            })?;
 5430
 5431            let Some(task) = task else {
 5432                anyhow::bail!(
 5433                    "failed to construct view from leader (maybe from a different version of zed?)"
 5434                );
 5435            };
 5436
 5437            let mut new_item = task.await?;
 5438            pane.update_in(cx, |pane, window, cx| {
 5439                let mut item_to_remove = None;
 5440                for (ix, item) in pane.items().enumerate() {
 5441                    if let Some(item) = item.to_followable_item_handle(cx) {
 5442                        match new_item.dedup(item.as_ref(), window, cx) {
 5443                            Some(item::Dedup::KeepExisting) => {
 5444                                new_item =
 5445                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5446                                break;
 5447                            }
 5448                            Some(item::Dedup::ReplaceExisting) => {
 5449                                item_to_remove = Some((ix, item.item_id()));
 5450                                break;
 5451                            }
 5452                            None => {}
 5453                        }
 5454                    }
 5455                }
 5456
 5457                if let Some((ix, id)) = item_to_remove {
 5458                    pane.remove_item(id, false, false, window, cx);
 5459                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5460                }
 5461            })?;
 5462
 5463            new_item
 5464        };
 5465
 5466        this.update_in(cx, |this, window, cx| {
 5467            let state = this.follower_states.get_mut(&leader_id.into())?;
 5468            item.set_leader_id(Some(leader_id.into()), window, cx);
 5469            state.items_by_leader_view_id.insert(
 5470                id,
 5471                FollowerView {
 5472                    view: item,
 5473                    location: panel_id,
 5474                },
 5475            );
 5476
 5477            Some(())
 5478        })
 5479        .context("no follower state")?;
 5480
 5481        Ok(())
 5482    }
 5483
 5484    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5485        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5486            return;
 5487        };
 5488
 5489        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5490            let buffer_entity_id = agent_location.buffer.entity_id();
 5491            let view_id = ViewId {
 5492                creator: CollaboratorId::Agent,
 5493                id: buffer_entity_id.as_u64(),
 5494            };
 5495            follower_state.active_view_id = Some(view_id);
 5496
 5497            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5498                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5499                hash_map::Entry::Vacant(entry) => {
 5500                    let existing_view =
 5501                        follower_state
 5502                            .center_pane
 5503                            .read(cx)
 5504                            .items()
 5505                            .find_map(|item| {
 5506                                let item = item.to_followable_item_handle(cx)?;
 5507                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5508                                    && item.project_item_model_ids(cx).as_slice()
 5509                                        == [buffer_entity_id]
 5510                                {
 5511                                    Some(item)
 5512                                } else {
 5513                                    None
 5514                                }
 5515                            });
 5516                    let view = existing_view.or_else(|| {
 5517                        agent_location.buffer.upgrade().and_then(|buffer| {
 5518                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5519                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5520                            })?
 5521                            .to_followable_item_handle(cx)
 5522                        })
 5523                    });
 5524
 5525                    view.map(|view| {
 5526                        entry.insert(FollowerView {
 5527                            view,
 5528                            location: None,
 5529                        })
 5530                    })
 5531                }
 5532            };
 5533
 5534            if let Some(item) = item {
 5535                item.view
 5536                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5537                item.view
 5538                    .update_agent_location(agent_location.position, window, cx);
 5539            }
 5540        } else {
 5541            follower_state.active_view_id = None;
 5542        }
 5543
 5544        self.leader_updated(CollaboratorId::Agent, window, cx);
 5545    }
 5546
 5547    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5548        let mut is_project_item = true;
 5549        let mut update = proto::UpdateActiveView::default();
 5550        if window.is_window_active() {
 5551            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5552
 5553            if let Some(item) = active_item
 5554                && item.item_focus_handle(cx).contains_focused(window, cx)
 5555            {
 5556                let leader_id = self
 5557                    .pane_for(&*item)
 5558                    .and_then(|pane| self.leader_for_pane(&pane));
 5559                let leader_peer_id = match leader_id {
 5560                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5561                    Some(CollaboratorId::Agent) | None => None,
 5562                };
 5563
 5564                if let Some(item) = item.to_followable_item_handle(cx) {
 5565                    let id = item
 5566                        .remote_id(&self.app_state.client, window, cx)
 5567                        .map(|id| id.to_proto());
 5568
 5569                    if let Some(id) = id
 5570                        && let Some(variant) = item.to_state_proto(window, cx)
 5571                    {
 5572                        let view = Some(proto::View {
 5573                            id,
 5574                            leader_id: leader_peer_id,
 5575                            variant: Some(variant),
 5576                            panel_id: panel_id.map(|id| id as i32),
 5577                        });
 5578
 5579                        is_project_item = item.is_project_item(window, cx);
 5580                        update = proto::UpdateActiveView { view };
 5581                    };
 5582                }
 5583            }
 5584        }
 5585
 5586        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5587        if active_view_id != self.last_active_view_id.as_ref() {
 5588            self.last_active_view_id = active_view_id.cloned();
 5589            self.update_followers(
 5590                is_project_item,
 5591                proto::update_followers::Variant::UpdateActiveView(update),
 5592                window,
 5593                cx,
 5594            );
 5595        }
 5596    }
 5597
 5598    fn active_item_for_followers(
 5599        &self,
 5600        window: &mut Window,
 5601        cx: &mut App,
 5602    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5603        let mut active_item = None;
 5604        let mut panel_id = None;
 5605        for dock in self.all_docks() {
 5606            if dock.focus_handle(cx).contains_focused(window, cx)
 5607                && let Some(panel) = dock.read(cx).active_panel()
 5608                && let Some(pane) = panel.pane(cx)
 5609                && let Some(item) = pane.read(cx).active_item()
 5610            {
 5611                active_item = Some(item);
 5612                panel_id = panel.remote_id();
 5613                break;
 5614            }
 5615        }
 5616
 5617        if active_item.is_none() {
 5618            active_item = self.active_pane().read(cx).active_item();
 5619        }
 5620        (active_item, panel_id)
 5621    }
 5622
 5623    fn update_followers(
 5624        &self,
 5625        project_only: bool,
 5626        update: proto::update_followers::Variant,
 5627        _: &mut Window,
 5628        cx: &mut App,
 5629    ) -> Option<()> {
 5630        // If this update only applies to for followers in the current project,
 5631        // then skip it unless this project is shared. If it applies to all
 5632        // followers, regardless of project, then set `project_id` to none,
 5633        // indicating that it goes to all followers.
 5634        let project_id = if project_only {
 5635            Some(self.project.read(cx).remote_id()?)
 5636        } else {
 5637            None
 5638        };
 5639        self.app_state().workspace_store.update(cx, |store, cx| {
 5640            store.update_followers(project_id, update, cx)
 5641        })
 5642    }
 5643
 5644    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5645        self.follower_states.iter().find_map(|(leader_id, state)| {
 5646            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5647                Some(*leader_id)
 5648            } else {
 5649                None
 5650            }
 5651        })
 5652    }
 5653
 5654    fn leader_updated(
 5655        &mut self,
 5656        leader_id: impl Into<CollaboratorId>,
 5657        window: &mut Window,
 5658        cx: &mut Context<Self>,
 5659    ) -> Option<Box<dyn ItemHandle>> {
 5660        cx.notify();
 5661
 5662        let leader_id = leader_id.into();
 5663        let (panel_id, item) = match leader_id {
 5664            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5665            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5666        };
 5667
 5668        let state = self.follower_states.get(&leader_id)?;
 5669        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5670        let pane;
 5671        if let Some(panel_id) = panel_id {
 5672            pane = self
 5673                .activate_panel_for_proto_id(panel_id, window, cx)?
 5674                .pane(cx)?;
 5675            let state = self.follower_states.get_mut(&leader_id)?;
 5676            state.dock_pane = Some(pane.clone());
 5677        } else {
 5678            pane = state.center_pane.clone();
 5679            let state = self.follower_states.get_mut(&leader_id)?;
 5680            if let Some(dock_pane) = state.dock_pane.take() {
 5681                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5682            }
 5683        }
 5684
 5685        pane.update(cx, |pane, cx| {
 5686            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5687            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5688                pane.activate_item(index, false, false, window, cx);
 5689            } else {
 5690                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5691            }
 5692
 5693            if focus_active_item {
 5694                pane.focus_active_item(window, cx)
 5695            }
 5696        });
 5697
 5698        Some(item)
 5699    }
 5700
 5701    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5702        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5703        let active_view_id = state.active_view_id?;
 5704        Some(
 5705            state
 5706                .items_by_leader_view_id
 5707                .get(&active_view_id)?
 5708                .view
 5709                .boxed_clone(),
 5710        )
 5711    }
 5712
 5713    fn active_item_for_peer(
 5714        &self,
 5715        peer_id: PeerId,
 5716        window: &mut Window,
 5717        cx: &mut Context<Self>,
 5718    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5719        let call = self.active_call()?;
 5720        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5721        let leader_in_this_app;
 5722        let leader_in_this_project;
 5723        match participant.location {
 5724            ParticipantLocation::SharedProject { project_id } => {
 5725                leader_in_this_app = true;
 5726                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5727            }
 5728            ParticipantLocation::UnsharedProject => {
 5729                leader_in_this_app = true;
 5730                leader_in_this_project = false;
 5731            }
 5732            ParticipantLocation::External => {
 5733                leader_in_this_app = false;
 5734                leader_in_this_project = false;
 5735            }
 5736        };
 5737        let state = self.follower_states.get(&peer_id.into())?;
 5738        let mut item_to_activate = None;
 5739        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5740            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5741                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5742            {
 5743                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5744            }
 5745        } else if let Some(shared_screen) =
 5746            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5747        {
 5748            item_to_activate = Some((None, Box::new(shared_screen)));
 5749        }
 5750        item_to_activate
 5751    }
 5752
 5753    fn shared_screen_for_peer(
 5754        &self,
 5755        peer_id: PeerId,
 5756        pane: &Entity<Pane>,
 5757        window: &mut Window,
 5758        cx: &mut App,
 5759    ) -> Option<Entity<SharedScreen>> {
 5760        self.active_call()?
 5761            .create_shared_screen(peer_id, pane, window, cx)
 5762    }
 5763
 5764    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5765        if window.is_window_active() {
 5766            self.update_active_view_for_followers(window, cx);
 5767
 5768            if let Some(database_id) = self.database_id {
 5769                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5770                    .detach();
 5771            }
 5772        } else {
 5773            for pane in &self.panes {
 5774                pane.update(cx, |pane, cx| {
 5775                    if let Some(item) = pane.active_item() {
 5776                        item.workspace_deactivated(window, cx);
 5777                    }
 5778                    for item in pane.items() {
 5779                        if matches!(
 5780                            item.workspace_settings(cx).autosave,
 5781                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5782                        ) {
 5783                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5784                                .detach_and_log_err(cx);
 5785                        }
 5786                    }
 5787                });
 5788            }
 5789        }
 5790    }
 5791
 5792    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5793        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5794    }
 5795
 5796    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5797        self.active_call.as_ref().map(|(call, _)| call.clone())
 5798    }
 5799
 5800    fn on_active_call_event(
 5801        &mut self,
 5802        event: &ActiveCallEvent,
 5803        window: &mut Window,
 5804        cx: &mut Context<Self>,
 5805    ) {
 5806        match event {
 5807            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 5808            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 5809                self.leader_updated(participant_id, window, cx);
 5810            }
 5811        }
 5812    }
 5813
 5814    pub fn database_id(&self) -> Option<WorkspaceId> {
 5815        self.database_id
 5816    }
 5817
 5818    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 5819        self.database_id = Some(id);
 5820    }
 5821
 5822    pub fn session_id(&self) -> Option<String> {
 5823        self.session_id.clone()
 5824    }
 5825
 5826    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5827        let Some(display) = window.display(cx) else {
 5828            return Task::ready(());
 5829        };
 5830        let Ok(display_uuid) = display.uuid() else {
 5831            return Task::ready(());
 5832        };
 5833
 5834        let window_bounds = window.inner_window_bounds();
 5835        let database_id = self.database_id;
 5836        let has_paths = !self.root_paths(cx).is_empty();
 5837
 5838        cx.background_executor().spawn(async move {
 5839            if !has_paths {
 5840                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5841                    .await
 5842                    .log_err();
 5843            }
 5844            if let Some(database_id) = database_id {
 5845                DB.set_window_open_status(
 5846                    database_id,
 5847                    SerializedWindowBounds(window_bounds),
 5848                    display_uuid,
 5849                )
 5850                .await
 5851                .log_err();
 5852            } else {
 5853                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5854                    .await
 5855                    .log_err();
 5856            }
 5857        })
 5858    }
 5859
 5860    /// Bypass the 200ms serialization throttle and write workspace state to
 5861    /// the DB immediately. Returns a task the caller can await to ensure the
 5862    /// write completes. Used by the quit handler so the most recent state
 5863    /// isn't lost to a pending throttle timer when the process exits.
 5864    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5865        self._schedule_serialize_workspace.take();
 5866        self._serialize_workspace_task.take();
 5867        self.bounds_save_task_queued.take();
 5868
 5869        let bounds_task = self.save_window_bounds(window, cx);
 5870        let serialize_task = self.serialize_workspace_internal(window, cx);
 5871        cx.spawn(async move |_| {
 5872            bounds_task.await;
 5873            serialize_task.await;
 5874        })
 5875    }
 5876
 5877    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5878        let project = self.project().read(cx);
 5879        project
 5880            .visible_worktrees(cx)
 5881            .map(|worktree| worktree.read(cx).abs_path())
 5882            .collect::<Vec<_>>()
 5883    }
 5884
 5885    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5886        match member {
 5887            Member::Axis(PaneAxis { members, .. }) => {
 5888                for child in members.iter() {
 5889                    self.remove_panes(child.clone(), window, cx)
 5890                }
 5891            }
 5892            Member::Pane(pane) => {
 5893                self.force_remove_pane(&pane, &None, window, cx);
 5894            }
 5895        }
 5896    }
 5897
 5898    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5899        self.session_id.take();
 5900        self.serialize_workspace_internal(window, cx)
 5901    }
 5902
 5903    fn force_remove_pane(
 5904        &mut self,
 5905        pane: &Entity<Pane>,
 5906        focus_on: &Option<Entity<Pane>>,
 5907        window: &mut Window,
 5908        cx: &mut Context<Workspace>,
 5909    ) {
 5910        self.panes.retain(|p| p != pane);
 5911        if let Some(focus_on) = focus_on {
 5912            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5913        } else if self.active_pane() == pane {
 5914            self.panes
 5915                .last()
 5916                .unwrap()
 5917                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5918        }
 5919        if self.last_active_center_pane == Some(pane.downgrade()) {
 5920            self.last_active_center_pane = None;
 5921        }
 5922        cx.notify();
 5923    }
 5924
 5925    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5926        if self._schedule_serialize_workspace.is_none() {
 5927            self._schedule_serialize_workspace =
 5928                Some(cx.spawn_in(window, async move |this, cx| {
 5929                    cx.background_executor()
 5930                        .timer(SERIALIZATION_THROTTLE_TIME)
 5931                        .await;
 5932                    this.update_in(cx, |this, window, cx| {
 5933                        this._serialize_workspace_task =
 5934                            Some(this.serialize_workspace_internal(window, cx));
 5935                        this._schedule_serialize_workspace.take();
 5936                    })
 5937                    .log_err();
 5938                }));
 5939        }
 5940    }
 5941
 5942    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5943        let Some(database_id) = self.database_id() else {
 5944            return Task::ready(());
 5945        };
 5946
 5947        fn serialize_pane_handle(
 5948            pane_handle: &Entity<Pane>,
 5949            window: &mut Window,
 5950            cx: &mut App,
 5951        ) -> SerializedPane {
 5952            let (items, active, pinned_count) = {
 5953                let pane = pane_handle.read(cx);
 5954                let active_item_id = pane.active_item().map(|item| item.item_id());
 5955                (
 5956                    pane.items()
 5957                        .filter_map(|handle| {
 5958                            let handle = handle.to_serializable_item_handle(cx)?;
 5959
 5960                            Some(SerializedItem {
 5961                                kind: Arc::from(handle.serialized_item_kind()),
 5962                                item_id: handle.item_id().as_u64(),
 5963                                active: Some(handle.item_id()) == active_item_id,
 5964                                preview: pane.is_active_preview_item(handle.item_id()),
 5965                            })
 5966                        })
 5967                        .collect::<Vec<_>>(),
 5968                    pane.has_focus(window, cx),
 5969                    pane.pinned_count(),
 5970                )
 5971            };
 5972
 5973            SerializedPane::new(items, active, pinned_count)
 5974        }
 5975
 5976        fn build_serialized_pane_group(
 5977            pane_group: &Member,
 5978            window: &mut Window,
 5979            cx: &mut App,
 5980        ) -> SerializedPaneGroup {
 5981            match pane_group {
 5982                Member::Axis(PaneAxis {
 5983                    axis,
 5984                    members,
 5985                    flexes,
 5986                    bounding_boxes: _,
 5987                }) => SerializedPaneGroup::Group {
 5988                    axis: SerializedAxis(*axis),
 5989                    children: members
 5990                        .iter()
 5991                        .map(|member| build_serialized_pane_group(member, window, cx))
 5992                        .collect::<Vec<_>>(),
 5993                    flexes: Some(flexes.lock().clone()),
 5994                },
 5995                Member::Pane(pane_handle) => {
 5996                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5997                }
 5998            }
 5999        }
 6000
 6001        fn build_serialized_docks(
 6002            this: &Workspace,
 6003            window: &mut Window,
 6004            cx: &mut App,
 6005        ) -> DockStructure {
 6006            let left_dock = this.left_dock.read(cx);
 6007            let left_visible = left_dock.is_open();
 6008            let left_active_panel = left_dock
 6009                .active_panel()
 6010                .map(|panel| panel.persistent_name().to_string());
 6011            let left_dock_zoom = left_dock
 6012                .active_panel()
 6013                .map(|panel| panel.is_zoomed(window, cx))
 6014                .unwrap_or(false);
 6015
 6016            let right_dock = this.right_dock.read(cx);
 6017            let right_visible = right_dock.is_open();
 6018            let right_active_panel = right_dock
 6019                .active_panel()
 6020                .map(|panel| panel.persistent_name().to_string());
 6021            let right_dock_zoom = right_dock
 6022                .active_panel()
 6023                .map(|panel| panel.is_zoomed(window, cx))
 6024                .unwrap_or(false);
 6025
 6026            let bottom_dock = this.bottom_dock.read(cx);
 6027            let bottom_visible = bottom_dock.is_open();
 6028            let bottom_active_panel = bottom_dock
 6029                .active_panel()
 6030                .map(|panel| panel.persistent_name().to_string());
 6031            let bottom_dock_zoom = bottom_dock
 6032                .active_panel()
 6033                .map(|panel| panel.is_zoomed(window, cx))
 6034                .unwrap_or(false);
 6035
 6036            DockStructure {
 6037                left: DockData {
 6038                    visible: left_visible,
 6039                    active_panel: left_active_panel,
 6040                    zoom: left_dock_zoom,
 6041                },
 6042                right: DockData {
 6043                    visible: right_visible,
 6044                    active_panel: right_active_panel,
 6045                    zoom: right_dock_zoom,
 6046                },
 6047                bottom: DockData {
 6048                    visible: bottom_visible,
 6049                    active_panel: bottom_active_panel,
 6050                    zoom: bottom_dock_zoom,
 6051                },
 6052            }
 6053        }
 6054
 6055        match self.workspace_location(cx) {
 6056            WorkspaceLocation::Location(location, paths) => {
 6057                let breakpoints = self.project.update(cx, |project, cx| {
 6058                    project
 6059                        .breakpoint_store()
 6060                        .read(cx)
 6061                        .all_source_breakpoints(cx)
 6062                });
 6063                let user_toolchains = self
 6064                    .project
 6065                    .read(cx)
 6066                    .user_toolchains(cx)
 6067                    .unwrap_or_default();
 6068
 6069                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6070                let docks = build_serialized_docks(self, window, cx);
 6071                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6072
 6073                let serialized_workspace = SerializedWorkspace {
 6074                    id: database_id,
 6075                    location,
 6076                    paths,
 6077                    center_group,
 6078                    window_bounds,
 6079                    display: Default::default(),
 6080                    docks,
 6081                    centered_layout: self.centered_layout,
 6082                    session_id: self.session_id.clone(),
 6083                    breakpoints,
 6084                    window_id: Some(window.window_handle().window_id().as_u64()),
 6085                    user_toolchains,
 6086                };
 6087
 6088                window.spawn(cx, async move |_| {
 6089                    persistence::DB.save_workspace(serialized_workspace).await;
 6090                })
 6091            }
 6092            WorkspaceLocation::DetachFromSession => {
 6093                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6094                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6095                // Save dock state for empty local workspaces
 6096                let docks = build_serialized_docks(self, window, cx);
 6097                window.spawn(cx, async move |_| {
 6098                    persistence::DB
 6099                        .set_window_open_status(
 6100                            database_id,
 6101                            window_bounds,
 6102                            display.unwrap_or_default(),
 6103                        )
 6104                        .await
 6105                        .log_err();
 6106                    persistence::DB
 6107                        .set_session_id(database_id, None)
 6108                        .await
 6109                        .log_err();
 6110                    persistence::write_default_dock_state(docks).await.log_err();
 6111                })
 6112            }
 6113            WorkspaceLocation::None => {
 6114                // Save dock state for empty non-local workspaces
 6115                let docks = build_serialized_docks(self, window, cx);
 6116                window.spawn(cx, async move |_| {
 6117                    persistence::write_default_dock_state(docks).await.log_err();
 6118                })
 6119            }
 6120        }
 6121    }
 6122
 6123    fn has_any_items_open(&self, cx: &App) -> bool {
 6124        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6125    }
 6126
 6127    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6128        let paths = PathList::new(&self.root_paths(cx));
 6129        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6130            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6131        } else if self.project.read(cx).is_local() {
 6132            if !paths.is_empty() || self.has_any_items_open(cx) {
 6133                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6134            } else {
 6135                WorkspaceLocation::DetachFromSession
 6136            }
 6137        } else {
 6138            WorkspaceLocation::None
 6139        }
 6140    }
 6141
 6142    fn update_history(&self, cx: &mut App) {
 6143        let Some(id) = self.database_id() else {
 6144            return;
 6145        };
 6146        if !self.project.read(cx).is_local() {
 6147            return;
 6148        }
 6149        if let Some(manager) = HistoryManager::global(cx) {
 6150            let paths = PathList::new(&self.root_paths(cx));
 6151            manager.update(cx, |this, cx| {
 6152                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6153            });
 6154        }
 6155    }
 6156
 6157    async fn serialize_items(
 6158        this: &WeakEntity<Self>,
 6159        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6160        cx: &mut AsyncWindowContext,
 6161    ) -> Result<()> {
 6162        const CHUNK_SIZE: usize = 200;
 6163
 6164        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6165
 6166        while let Some(items_received) = serializable_items.next().await {
 6167            let unique_items =
 6168                items_received
 6169                    .into_iter()
 6170                    .fold(HashMap::default(), |mut acc, item| {
 6171                        acc.entry(item.item_id()).or_insert(item);
 6172                        acc
 6173                    });
 6174
 6175            // We use into_iter() here so that the references to the items are moved into
 6176            // the tasks and not kept alive while we're sleeping.
 6177            for (_, item) in unique_items.into_iter() {
 6178                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6179                    item.serialize(workspace, false, window, cx)
 6180                }) {
 6181                    cx.background_spawn(async move { task.await.log_err() })
 6182                        .detach();
 6183                }
 6184            }
 6185
 6186            cx.background_executor()
 6187                .timer(SERIALIZATION_THROTTLE_TIME)
 6188                .await;
 6189        }
 6190
 6191        Ok(())
 6192    }
 6193
 6194    pub(crate) fn enqueue_item_serialization(
 6195        &mut self,
 6196        item: Box<dyn SerializableItemHandle>,
 6197    ) -> Result<()> {
 6198        self.serializable_items_tx
 6199            .unbounded_send(item)
 6200            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6201    }
 6202
 6203    pub(crate) fn load_workspace(
 6204        serialized_workspace: SerializedWorkspace,
 6205        paths_to_open: Vec<Option<ProjectPath>>,
 6206        window: &mut Window,
 6207        cx: &mut Context<Workspace>,
 6208    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6209        cx.spawn_in(window, async move |workspace, cx| {
 6210            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6211
 6212            let mut center_group = None;
 6213            let mut center_items = None;
 6214
 6215            // Traverse the splits tree and add to things
 6216            if let Some((group, active_pane, items)) = serialized_workspace
 6217                .center_group
 6218                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6219                .await
 6220            {
 6221                center_items = Some(items);
 6222                center_group = Some((group, active_pane))
 6223            }
 6224
 6225            let mut items_by_project_path = HashMap::default();
 6226            let mut item_ids_by_kind = HashMap::default();
 6227            let mut all_deserialized_items = Vec::default();
 6228            cx.update(|_, cx| {
 6229                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6230                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6231                        item_ids_by_kind
 6232                            .entry(serializable_item_handle.serialized_item_kind())
 6233                            .or_insert(Vec::new())
 6234                            .push(item.item_id().as_u64() as ItemId);
 6235                    }
 6236
 6237                    if let Some(project_path) = item.project_path(cx) {
 6238                        items_by_project_path.insert(project_path, item.clone());
 6239                    }
 6240                    all_deserialized_items.push(item);
 6241                }
 6242            })?;
 6243
 6244            let opened_items = paths_to_open
 6245                .into_iter()
 6246                .map(|path_to_open| {
 6247                    path_to_open
 6248                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6249                })
 6250                .collect::<Vec<_>>();
 6251
 6252            // Remove old panes from workspace panes list
 6253            workspace.update_in(cx, |workspace, window, cx| {
 6254                if let Some((center_group, active_pane)) = center_group {
 6255                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6256
 6257                    // Swap workspace center group
 6258                    workspace.center = PaneGroup::with_root(center_group);
 6259                    workspace.center.set_is_center(true);
 6260                    workspace.center.mark_positions(cx);
 6261
 6262                    if let Some(active_pane) = active_pane {
 6263                        workspace.set_active_pane(&active_pane, window, cx);
 6264                        cx.focus_self(window);
 6265                    } else {
 6266                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6267                    }
 6268                }
 6269
 6270                let docks = serialized_workspace.docks;
 6271
 6272                for (dock, serialized_dock) in [
 6273                    (&mut workspace.right_dock, docks.right),
 6274                    (&mut workspace.left_dock, docks.left),
 6275                    (&mut workspace.bottom_dock, docks.bottom),
 6276                ]
 6277                .iter_mut()
 6278                {
 6279                    dock.update(cx, |dock, cx| {
 6280                        dock.serialized_dock = Some(serialized_dock.clone());
 6281                        dock.restore_state(window, cx);
 6282                    });
 6283                }
 6284
 6285                cx.notify();
 6286            })?;
 6287
 6288            let _ = project
 6289                .update(cx, |project, cx| {
 6290                    project
 6291                        .breakpoint_store()
 6292                        .update(cx, |breakpoint_store, cx| {
 6293                            breakpoint_store
 6294                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6295                        })
 6296                })
 6297                .await;
 6298
 6299            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6300            // after loading the items, we might have different items and in order to avoid
 6301            // the database filling up, we delete items that haven't been loaded now.
 6302            //
 6303            // The items that have been loaded, have been saved after they've been added to the workspace.
 6304            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6305                item_ids_by_kind
 6306                    .into_iter()
 6307                    .map(|(item_kind, loaded_items)| {
 6308                        SerializableItemRegistry::cleanup(
 6309                            item_kind,
 6310                            serialized_workspace.id,
 6311                            loaded_items,
 6312                            window,
 6313                            cx,
 6314                        )
 6315                        .log_err()
 6316                    })
 6317                    .collect::<Vec<_>>()
 6318            })?;
 6319
 6320            futures::future::join_all(clean_up_tasks).await;
 6321
 6322            workspace
 6323                .update_in(cx, |workspace, window, cx| {
 6324                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6325                    workspace.serialize_workspace_internal(window, cx).detach();
 6326
 6327                    // Ensure that we mark the window as edited if we did load dirty items
 6328                    workspace.update_window_edited(window, cx);
 6329                })
 6330                .ok();
 6331
 6332            Ok(opened_items)
 6333        })
 6334    }
 6335
 6336    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6337        self.add_workspace_actions_listeners(div, window, cx)
 6338            .on_action(cx.listener(
 6339                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6340                    for action in &action_sequence.0 {
 6341                        window.dispatch_action(action.boxed_clone(), cx);
 6342                    }
 6343                },
 6344            ))
 6345            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6346            .on_action(cx.listener(Self::close_all_items_and_panes))
 6347            .on_action(cx.listener(Self::close_item_in_all_panes))
 6348            .on_action(cx.listener(Self::save_all))
 6349            .on_action(cx.listener(Self::send_keystrokes))
 6350            .on_action(cx.listener(Self::add_folder_to_project))
 6351            .on_action(cx.listener(Self::follow_next_collaborator))
 6352            .on_action(cx.listener(Self::activate_pane_at_index))
 6353            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6354            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6355            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6356            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6357                let pane = workspace.active_pane().clone();
 6358                workspace.unfollow_in_pane(&pane, window, cx);
 6359            }))
 6360            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6361                workspace
 6362                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6363                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6364            }))
 6365            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6366                workspace
 6367                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6368                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6369            }))
 6370            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6371                workspace
 6372                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6373                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6374            }))
 6375            .on_action(
 6376                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6377                    workspace.activate_previous_pane(window, cx)
 6378                }),
 6379            )
 6380            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6381                workspace.activate_next_pane(window, cx)
 6382            }))
 6383            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6384                workspace.activate_last_pane(window, cx)
 6385            }))
 6386            .on_action(
 6387                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6388                    workspace.activate_next_window(cx)
 6389                }),
 6390            )
 6391            .on_action(
 6392                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6393                    workspace.activate_previous_window(cx)
 6394                }),
 6395            )
 6396            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6397                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6398            }))
 6399            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6400                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6401            }))
 6402            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6403                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6404            }))
 6405            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6406                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6407            }))
 6408            .on_action(cx.listener(
 6409                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6410                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6411                },
 6412            ))
 6413            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6414                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6415            }))
 6416            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6417                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6418            }))
 6419            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6420                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6421            }))
 6422            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6423                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6424            }))
 6425            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6426                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6427                    SplitDirection::Down,
 6428                    SplitDirection::Up,
 6429                    SplitDirection::Right,
 6430                    SplitDirection::Left,
 6431                ];
 6432                for dir in DIRECTION_PRIORITY {
 6433                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6434                        workspace.swap_pane_in_direction(dir, cx);
 6435                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6436                        break;
 6437                    }
 6438                }
 6439            }))
 6440            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6441                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6442            }))
 6443            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6444                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6445            }))
 6446            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6447                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6448            }))
 6449            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6450                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6451            }))
 6452            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6453                this.toggle_dock(DockPosition::Left, window, cx);
 6454            }))
 6455            .on_action(cx.listener(
 6456                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6457                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6458                },
 6459            ))
 6460            .on_action(cx.listener(
 6461                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6462                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6463                },
 6464            ))
 6465            .on_action(cx.listener(
 6466                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6467                    if !workspace.close_active_dock(window, cx) {
 6468                        cx.propagate();
 6469                    }
 6470                },
 6471            ))
 6472            .on_action(
 6473                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6474                    workspace.close_all_docks(window, cx);
 6475                }),
 6476            )
 6477            .on_action(cx.listener(Self::toggle_all_docks))
 6478            .on_action(cx.listener(
 6479                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6480                    workspace.clear_all_notifications(cx);
 6481                },
 6482            ))
 6483            .on_action(cx.listener(
 6484                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6485                    workspace.clear_navigation_history(window, cx);
 6486                },
 6487            ))
 6488            .on_action(cx.listener(
 6489                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6490                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6491                        workspace.suppress_notification(&notification_id, cx);
 6492                    }
 6493                },
 6494            ))
 6495            .on_action(cx.listener(
 6496                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6497                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6498                },
 6499            ))
 6500            .on_action(
 6501                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6502                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6503                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6504                            trusted_worktrees.clear_trusted_paths()
 6505                        });
 6506                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6507                        cx.spawn(async move |_, cx| {
 6508                            if clear_task.await.log_err().is_some() {
 6509                                cx.update(|cx| reload(cx));
 6510                            }
 6511                        })
 6512                        .detach();
 6513                    }
 6514                }),
 6515            )
 6516            .on_action(cx.listener(
 6517                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6518                    workspace.reopen_closed_item(window, cx).detach();
 6519                },
 6520            ))
 6521            .on_action(cx.listener(
 6522                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6523                    for dock in workspace.all_docks() {
 6524                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6525                            let Some(panel) = dock.read(cx).active_panel() else {
 6526                                return;
 6527                            };
 6528
 6529                            // Set to `None`, then the size will fall back to the default.
 6530                            panel.clone().set_size(None, window, cx);
 6531
 6532                            return;
 6533                        }
 6534                    }
 6535                },
 6536            ))
 6537            .on_action(cx.listener(
 6538                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6539                    for dock in workspace.all_docks() {
 6540                        if let Some(panel) = dock.read(cx).visible_panel() {
 6541                            // Set to `None`, then the size will fall back to the default.
 6542                            panel.clone().set_size(None, window, cx);
 6543                        }
 6544                    }
 6545                },
 6546            ))
 6547            .on_action(cx.listener(
 6548                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6549                    adjust_active_dock_size_by_px(
 6550                        px_with_ui_font_fallback(act.px, cx),
 6551                        workspace,
 6552                        window,
 6553                        cx,
 6554                    );
 6555                },
 6556            ))
 6557            .on_action(cx.listener(
 6558                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6559                    adjust_active_dock_size_by_px(
 6560                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6561                        workspace,
 6562                        window,
 6563                        cx,
 6564                    );
 6565                },
 6566            ))
 6567            .on_action(cx.listener(
 6568                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6569                    adjust_open_docks_size_by_px(
 6570                        px_with_ui_font_fallback(act.px, cx),
 6571                        workspace,
 6572                        window,
 6573                        cx,
 6574                    );
 6575                },
 6576            ))
 6577            .on_action(cx.listener(
 6578                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6579                    adjust_open_docks_size_by_px(
 6580                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6581                        workspace,
 6582                        window,
 6583                        cx,
 6584                    );
 6585                },
 6586            ))
 6587            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6588            .on_action(cx.listener(
 6589                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6590                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6591                        let dock = active_dock.read(cx);
 6592                        if let Some(active_panel) = dock.active_panel() {
 6593                            if active_panel.pane(cx).is_none() {
 6594                                let mut recent_pane: Option<Entity<Pane>> = None;
 6595                                let mut recent_timestamp = 0;
 6596                                for pane_handle in workspace.panes() {
 6597                                    let pane = pane_handle.read(cx);
 6598                                    for entry in pane.activation_history() {
 6599                                        if entry.timestamp > recent_timestamp {
 6600                                            recent_timestamp = entry.timestamp;
 6601                                            recent_pane = Some(pane_handle.clone());
 6602                                        }
 6603                                    }
 6604                                }
 6605
 6606                                if let Some(pane) = recent_pane {
 6607                                    pane.update(cx, |pane, cx| {
 6608                                        let current_index = pane.active_item_index();
 6609                                        let items_len = pane.items_len();
 6610                                        if items_len > 0 {
 6611                                            let next_index = if current_index + 1 < items_len {
 6612                                                current_index + 1
 6613                                            } else {
 6614                                                0
 6615                                            };
 6616                                            pane.activate_item(
 6617                                                next_index, false, false, window, cx,
 6618                                            );
 6619                                        }
 6620                                    });
 6621                                    return;
 6622                                }
 6623                            }
 6624                        }
 6625                    }
 6626                    cx.propagate();
 6627                },
 6628            ))
 6629            .on_action(cx.listener(
 6630                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6631                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6632                        let dock = active_dock.read(cx);
 6633                        if let Some(active_panel) = dock.active_panel() {
 6634                            if active_panel.pane(cx).is_none() {
 6635                                let mut recent_pane: Option<Entity<Pane>> = None;
 6636                                let mut recent_timestamp = 0;
 6637                                for pane_handle in workspace.panes() {
 6638                                    let pane = pane_handle.read(cx);
 6639                                    for entry in pane.activation_history() {
 6640                                        if entry.timestamp > recent_timestamp {
 6641                                            recent_timestamp = entry.timestamp;
 6642                                            recent_pane = Some(pane_handle.clone());
 6643                                        }
 6644                                    }
 6645                                }
 6646
 6647                                if let Some(pane) = recent_pane {
 6648                                    pane.update(cx, |pane, cx| {
 6649                                        let current_index = pane.active_item_index();
 6650                                        let items_len = pane.items_len();
 6651                                        if items_len > 0 {
 6652                                            let prev_index = if current_index > 0 {
 6653                                                current_index - 1
 6654                                            } else {
 6655                                                items_len.saturating_sub(1)
 6656                                            };
 6657                                            pane.activate_item(
 6658                                                prev_index, false, false, window, cx,
 6659                                            );
 6660                                        }
 6661                                    });
 6662                                    return;
 6663                                }
 6664                            }
 6665                        }
 6666                    }
 6667                    cx.propagate();
 6668                },
 6669            ))
 6670            .on_action(cx.listener(
 6671                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6672                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6673                        let dock = active_dock.read(cx);
 6674                        if let Some(active_panel) = dock.active_panel() {
 6675                            if active_panel.pane(cx).is_none() {
 6676                                let active_pane = workspace.active_pane().clone();
 6677                                active_pane.update(cx, |pane, cx| {
 6678                                    pane.close_active_item(action, window, cx)
 6679                                        .detach_and_log_err(cx);
 6680                                });
 6681                                return;
 6682                            }
 6683                        }
 6684                    }
 6685                    cx.propagate();
 6686                },
 6687            ))
 6688            .on_action(
 6689                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6690                    let pane = workspace.active_pane().clone();
 6691                    if let Some(item) = pane.read(cx).active_item() {
 6692                        item.toggle_read_only(window, cx);
 6693                    }
 6694                }),
 6695            )
 6696            .on_action(cx.listener(Workspace::cancel))
 6697    }
 6698
 6699    #[cfg(any(test, feature = "test-support"))]
 6700    pub fn set_random_database_id(&mut self) {
 6701        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6702    }
 6703
 6704    #[cfg(any(test, feature = "test-support"))]
 6705    pub(crate) fn test_new(
 6706        project: Entity<Project>,
 6707        window: &mut Window,
 6708        cx: &mut Context<Self>,
 6709    ) -> Self {
 6710        use node_runtime::NodeRuntime;
 6711        use session::Session;
 6712
 6713        let client = project.read(cx).client();
 6714        let user_store = project.read(cx).user_store();
 6715        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6716        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6717        window.activate_window();
 6718        let app_state = Arc::new(AppState {
 6719            languages: project.read(cx).languages().clone(),
 6720            workspace_store,
 6721            client,
 6722            user_store,
 6723            fs: project.read(cx).fs().clone(),
 6724            build_window_options: |_, _| Default::default(),
 6725            node_runtime: NodeRuntime::unavailable(),
 6726            session,
 6727        });
 6728        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6729        workspace
 6730            .active_pane
 6731            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6732        workspace
 6733    }
 6734
 6735    pub fn register_action<A: Action>(
 6736        &mut self,
 6737        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6738    ) -> &mut Self {
 6739        let callback = Arc::new(callback);
 6740
 6741        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6742            let callback = callback.clone();
 6743            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6744                (callback)(workspace, event, window, cx)
 6745            }))
 6746        }));
 6747        self
 6748    }
 6749    pub fn register_action_renderer(
 6750        &mut self,
 6751        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6752    ) -> &mut Self {
 6753        self.workspace_actions.push(Box::new(callback));
 6754        self
 6755    }
 6756
 6757    fn add_workspace_actions_listeners(
 6758        &self,
 6759        mut div: Div,
 6760        window: &mut Window,
 6761        cx: &mut Context<Self>,
 6762    ) -> Div {
 6763        for action in self.workspace_actions.iter() {
 6764            div = (action)(div, self, window, cx)
 6765        }
 6766        div
 6767    }
 6768
 6769    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6770        self.modal_layer.read(cx).has_active_modal()
 6771    }
 6772
 6773    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6774        self.modal_layer.read(cx).active_modal()
 6775    }
 6776
 6777    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6778    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6779    /// If no modal is active, the new modal will be shown.
 6780    ///
 6781    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6782    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6783    /// will not be shown.
 6784    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6785    where
 6786        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6787    {
 6788        self.modal_layer.update(cx, |modal_layer, cx| {
 6789            modal_layer.toggle_modal(window, cx, build)
 6790        })
 6791    }
 6792
 6793    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6794        self.modal_layer
 6795            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6796    }
 6797
 6798    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6799        self.toast_layer
 6800            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6801    }
 6802
 6803    pub fn toggle_centered_layout(
 6804        &mut self,
 6805        _: &ToggleCenteredLayout,
 6806        _: &mut Window,
 6807        cx: &mut Context<Self>,
 6808    ) {
 6809        self.centered_layout = !self.centered_layout;
 6810        if let Some(database_id) = self.database_id() {
 6811            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6812                .detach_and_log_err(cx);
 6813        }
 6814        cx.notify();
 6815    }
 6816
 6817    fn adjust_padding(padding: Option<f32>) -> f32 {
 6818        padding
 6819            .unwrap_or(CenteredPaddingSettings::default().0)
 6820            .clamp(
 6821                CenteredPaddingSettings::MIN_PADDING,
 6822                CenteredPaddingSettings::MAX_PADDING,
 6823            )
 6824    }
 6825
 6826    fn render_dock(
 6827        &self,
 6828        position: DockPosition,
 6829        dock: &Entity<Dock>,
 6830        window: &mut Window,
 6831        cx: &mut App,
 6832    ) -> Option<Div> {
 6833        if self.zoomed_position == Some(position) {
 6834            return None;
 6835        }
 6836
 6837        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6838            let pane = panel.pane(cx)?;
 6839            let follower_states = &self.follower_states;
 6840            leader_border_for_pane(follower_states, &pane, window, cx)
 6841        });
 6842
 6843        Some(
 6844            div()
 6845                .flex()
 6846                .flex_none()
 6847                .overflow_hidden()
 6848                .child(dock.clone())
 6849                .children(leader_border),
 6850        )
 6851    }
 6852
 6853    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 6854        window
 6855            .root::<MultiWorkspace>()
 6856            .flatten()
 6857            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 6858    }
 6859
 6860    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6861        self.zoomed.as_ref()
 6862    }
 6863
 6864    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6865        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6866            return;
 6867        };
 6868        let windows = cx.windows();
 6869        let next_window =
 6870            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6871                || {
 6872                    windows
 6873                        .iter()
 6874                        .cycle()
 6875                        .skip_while(|window| window.window_id() != current_window_id)
 6876                        .nth(1)
 6877                },
 6878            );
 6879
 6880        if let Some(window) = next_window {
 6881            window
 6882                .update(cx, |_, window, _| window.activate_window())
 6883                .ok();
 6884        }
 6885    }
 6886
 6887    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6888        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6889            return;
 6890        };
 6891        let windows = cx.windows();
 6892        let prev_window =
 6893            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6894                || {
 6895                    windows
 6896                        .iter()
 6897                        .rev()
 6898                        .cycle()
 6899                        .skip_while(|window| window.window_id() != current_window_id)
 6900                        .nth(1)
 6901                },
 6902            );
 6903
 6904        if let Some(window) = prev_window {
 6905            window
 6906                .update(cx, |_, window, _| window.activate_window())
 6907                .ok();
 6908        }
 6909    }
 6910
 6911    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6912        if cx.stop_active_drag(window) {
 6913        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6914            dismiss_app_notification(&notification_id, cx);
 6915        } else {
 6916            cx.propagate();
 6917        }
 6918    }
 6919
 6920    fn adjust_dock_size_by_px(
 6921        &mut self,
 6922        panel_size: Pixels,
 6923        dock_pos: DockPosition,
 6924        px: Pixels,
 6925        window: &mut Window,
 6926        cx: &mut Context<Self>,
 6927    ) {
 6928        match dock_pos {
 6929            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6930            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6931            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6932        }
 6933    }
 6934
 6935    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6936        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6937
 6938        self.left_dock.update(cx, |left_dock, cx| {
 6939            if WorkspaceSettings::get_global(cx)
 6940                .resize_all_panels_in_dock
 6941                .contains(&DockPosition::Left)
 6942            {
 6943                left_dock.resize_all_panels(Some(size), window, cx);
 6944            } else {
 6945                left_dock.resize_active_panel(Some(size), window, cx);
 6946            }
 6947        });
 6948    }
 6949
 6950    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6951        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6952        self.left_dock.read_with(cx, |left_dock, cx| {
 6953            let left_dock_size = left_dock
 6954                .active_panel_size(window, cx)
 6955                .unwrap_or(Pixels::ZERO);
 6956            if left_dock_size + size > self.bounds.right() {
 6957                size = self.bounds.right() - left_dock_size
 6958            }
 6959        });
 6960        self.right_dock.update(cx, |right_dock, cx| {
 6961            if WorkspaceSettings::get_global(cx)
 6962                .resize_all_panels_in_dock
 6963                .contains(&DockPosition::Right)
 6964            {
 6965                right_dock.resize_all_panels(Some(size), window, cx);
 6966            } else {
 6967                right_dock.resize_active_panel(Some(size), window, cx);
 6968            }
 6969        });
 6970    }
 6971
 6972    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6973        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6974        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6975            if WorkspaceSettings::get_global(cx)
 6976                .resize_all_panels_in_dock
 6977                .contains(&DockPosition::Bottom)
 6978            {
 6979                bottom_dock.resize_all_panels(Some(size), window, cx);
 6980            } else {
 6981                bottom_dock.resize_active_panel(Some(size), window, cx);
 6982            }
 6983        });
 6984    }
 6985
 6986    fn toggle_edit_predictions_all_files(
 6987        &mut self,
 6988        _: &ToggleEditPrediction,
 6989        _window: &mut Window,
 6990        cx: &mut Context<Self>,
 6991    ) {
 6992        let fs = self.project().read(cx).fs().clone();
 6993        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6994        update_settings_file(fs, cx, move |file, _| {
 6995            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6996        });
 6997    }
 6998
 6999    pub fn show_worktree_trust_security_modal(
 7000        &mut self,
 7001        toggle: bool,
 7002        window: &mut Window,
 7003        cx: &mut Context<Self>,
 7004    ) {
 7005        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7006            if toggle {
 7007                security_modal.update(cx, |security_modal, cx| {
 7008                    security_modal.dismiss(cx);
 7009                })
 7010            } else {
 7011                security_modal.update(cx, |security_modal, cx| {
 7012                    security_modal.refresh_restricted_paths(cx);
 7013                });
 7014            }
 7015        } else {
 7016            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7017                .map(|trusted_worktrees| {
 7018                    trusted_worktrees
 7019                        .read(cx)
 7020                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7021                })
 7022                .unwrap_or(false);
 7023            if has_restricted_worktrees {
 7024                let project = self.project().read(cx);
 7025                let remote_host = project
 7026                    .remote_connection_options(cx)
 7027                    .map(RemoteHostLocation::from);
 7028                let worktree_store = project.worktree_store().downgrade();
 7029                self.toggle_modal(window, cx, |_, cx| {
 7030                    SecurityModal::new(worktree_store, remote_host, cx)
 7031                });
 7032            }
 7033        }
 7034    }
 7035}
 7036
 7037pub trait AnyActiveCall {
 7038    fn entity(&self) -> AnyEntity;
 7039    fn is_in_room(&self, _: &App) -> bool;
 7040    fn room_id(&self, _: &App) -> Option<u64>;
 7041    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7042    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7043    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7044    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7045    fn is_sharing_project(&self, _: &App) -> bool;
 7046    fn has_remote_participants(&self, _: &App) -> bool;
 7047    fn local_participant_is_guest(&self, _: &App) -> bool;
 7048    fn client(&self, _: &App) -> Arc<Client>;
 7049    fn share_on_join(&self, _: &App) -> bool;
 7050    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7051    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7052    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7053    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7054    fn join_project(
 7055        &self,
 7056        _: u64,
 7057        _: Arc<LanguageRegistry>,
 7058        _: Arc<dyn Fs>,
 7059        _: &mut App,
 7060    ) -> Task<Result<Entity<Project>>>;
 7061    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7062    fn subscribe(
 7063        &self,
 7064        _: &mut Window,
 7065        _: &mut Context<Workspace>,
 7066        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7067    ) -> Subscription;
 7068    fn create_shared_screen(
 7069        &self,
 7070        _: PeerId,
 7071        _: &Entity<Pane>,
 7072        _: &mut Window,
 7073        _: &mut App,
 7074    ) -> Option<Entity<SharedScreen>>;
 7075}
 7076
 7077#[derive(Clone)]
 7078pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7079impl Global for GlobalAnyActiveCall {}
 7080
 7081impl GlobalAnyActiveCall {
 7082    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7083        cx.try_global()
 7084    }
 7085
 7086    pub(crate) fn global(cx: &App) -> &Self {
 7087        cx.global()
 7088    }
 7089}
 7090/// Workspace-local view of a remote participant's location.
 7091#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7092pub enum ParticipantLocation {
 7093    SharedProject { project_id: u64 },
 7094    UnsharedProject,
 7095    External,
 7096}
 7097
 7098impl ParticipantLocation {
 7099    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7100        match location
 7101            .and_then(|l| l.variant)
 7102            .context("participant location was not provided")?
 7103        {
 7104            proto::participant_location::Variant::SharedProject(project) => {
 7105                Ok(Self::SharedProject {
 7106                    project_id: project.id,
 7107                })
 7108            }
 7109            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7110            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7111        }
 7112    }
 7113}
 7114/// Workspace-local view of a remote collaborator's state.
 7115/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7116#[derive(Clone)]
 7117pub struct RemoteCollaborator {
 7118    pub user: Arc<User>,
 7119    pub peer_id: PeerId,
 7120    pub location: ParticipantLocation,
 7121    pub participant_index: ParticipantIndex,
 7122}
 7123
 7124pub enum ActiveCallEvent {
 7125    ParticipantLocationChanged { participant_id: PeerId },
 7126    RemoteVideoTracksChanged { participant_id: PeerId },
 7127}
 7128
 7129fn leader_border_for_pane(
 7130    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7131    pane: &Entity<Pane>,
 7132    _: &Window,
 7133    cx: &App,
 7134) -> Option<Div> {
 7135    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7136        if state.pane() == pane {
 7137            Some((*leader_id, state))
 7138        } else {
 7139            None
 7140        }
 7141    })?;
 7142
 7143    let mut leader_color = match leader_id {
 7144        CollaboratorId::PeerId(leader_peer_id) => {
 7145            let leader = GlobalAnyActiveCall::try_global(cx)?
 7146                .0
 7147                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7148
 7149            cx.theme()
 7150                .players()
 7151                .color_for_participant(leader.participant_index.0)
 7152                .cursor
 7153        }
 7154        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7155    };
 7156    leader_color.fade_out(0.3);
 7157    Some(
 7158        div()
 7159            .absolute()
 7160            .size_full()
 7161            .left_0()
 7162            .top_0()
 7163            .border_2()
 7164            .border_color(leader_color),
 7165    )
 7166}
 7167
 7168fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7169    ZED_WINDOW_POSITION
 7170        .zip(*ZED_WINDOW_SIZE)
 7171        .map(|(position, size)| Bounds {
 7172            origin: position,
 7173            size,
 7174        })
 7175}
 7176
 7177fn open_items(
 7178    serialized_workspace: Option<SerializedWorkspace>,
 7179    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7180    window: &mut Window,
 7181    cx: &mut Context<Workspace>,
 7182) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7183    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7184        Workspace::load_workspace(
 7185            serialized_workspace,
 7186            project_paths_to_open
 7187                .iter()
 7188                .map(|(_, project_path)| project_path)
 7189                .cloned()
 7190                .collect(),
 7191            window,
 7192            cx,
 7193        )
 7194    });
 7195
 7196    cx.spawn_in(window, async move |workspace, cx| {
 7197        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7198
 7199        if let Some(restored_items) = restored_items {
 7200            let restored_items = restored_items.await?;
 7201
 7202            let restored_project_paths = restored_items
 7203                .iter()
 7204                .filter_map(|item| {
 7205                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7206                        .ok()
 7207                        .flatten()
 7208                })
 7209                .collect::<HashSet<_>>();
 7210
 7211            for restored_item in restored_items {
 7212                opened_items.push(restored_item.map(Ok));
 7213            }
 7214
 7215            project_paths_to_open
 7216                .iter_mut()
 7217                .for_each(|(_, project_path)| {
 7218                    if let Some(project_path_to_open) = project_path
 7219                        && restored_project_paths.contains(project_path_to_open)
 7220                    {
 7221                        *project_path = None;
 7222                    }
 7223                });
 7224        } else {
 7225            for _ in 0..project_paths_to_open.len() {
 7226                opened_items.push(None);
 7227            }
 7228        }
 7229        assert!(opened_items.len() == project_paths_to_open.len());
 7230
 7231        let tasks =
 7232            project_paths_to_open
 7233                .into_iter()
 7234                .enumerate()
 7235                .map(|(ix, (abs_path, project_path))| {
 7236                    let workspace = workspace.clone();
 7237                    cx.spawn(async move |cx| {
 7238                        let file_project_path = project_path?;
 7239                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7240                            workspace.project().update(cx, |project, cx| {
 7241                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7242                            })
 7243                        });
 7244
 7245                        // We only want to open file paths here. If one of the items
 7246                        // here is a directory, it was already opened further above
 7247                        // with a `find_or_create_worktree`.
 7248                        if let Ok(task) = abs_path_task
 7249                            && task.await.is_none_or(|p| p.is_file())
 7250                        {
 7251                            return Some((
 7252                                ix,
 7253                                workspace
 7254                                    .update_in(cx, |workspace, window, cx| {
 7255                                        workspace.open_path(
 7256                                            file_project_path,
 7257                                            None,
 7258                                            true,
 7259                                            window,
 7260                                            cx,
 7261                                        )
 7262                                    })
 7263                                    .log_err()?
 7264                                    .await,
 7265                            ));
 7266                        }
 7267                        None
 7268                    })
 7269                });
 7270
 7271        let tasks = tasks.collect::<Vec<_>>();
 7272
 7273        let tasks = futures::future::join_all(tasks);
 7274        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7275            opened_items[ix] = Some(path_open_result);
 7276        }
 7277
 7278        Ok(opened_items)
 7279    })
 7280}
 7281
 7282enum ActivateInDirectionTarget {
 7283    Pane(Entity<Pane>),
 7284    Dock(Entity<Dock>),
 7285}
 7286
 7287fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7288    window
 7289        .update(cx, |multi_workspace, _, cx| {
 7290            let workspace = multi_workspace.workspace().clone();
 7291            workspace.update(cx, |workspace, cx| {
 7292                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7293                    struct DatabaseFailedNotification;
 7294
 7295                    workspace.show_notification(
 7296                        NotificationId::unique::<DatabaseFailedNotification>(),
 7297                        cx,
 7298                        |cx| {
 7299                            cx.new(|cx| {
 7300                                MessageNotification::new("Failed to load the database file.", cx)
 7301                                    .primary_message("File an Issue")
 7302                                    .primary_icon(IconName::Plus)
 7303                                    .primary_on_click(|window, cx| {
 7304                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7305                                    })
 7306                            })
 7307                        },
 7308                    );
 7309                }
 7310            });
 7311        })
 7312        .log_err();
 7313}
 7314
 7315fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7316    if val == 0 {
 7317        ThemeSettings::get_global(cx).ui_font_size(cx)
 7318    } else {
 7319        px(val as f32)
 7320    }
 7321}
 7322
 7323fn adjust_active_dock_size_by_px(
 7324    px: Pixels,
 7325    workspace: &mut Workspace,
 7326    window: &mut Window,
 7327    cx: &mut Context<Workspace>,
 7328) {
 7329    let Some(active_dock) = workspace
 7330        .all_docks()
 7331        .into_iter()
 7332        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7333    else {
 7334        return;
 7335    };
 7336    let dock = active_dock.read(cx);
 7337    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7338        return;
 7339    };
 7340    let dock_pos = dock.position();
 7341    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7342}
 7343
 7344fn adjust_open_docks_size_by_px(
 7345    px: Pixels,
 7346    workspace: &mut Workspace,
 7347    window: &mut Window,
 7348    cx: &mut Context<Workspace>,
 7349) {
 7350    let docks = workspace
 7351        .all_docks()
 7352        .into_iter()
 7353        .filter_map(|dock| {
 7354            if dock.read(cx).is_open() {
 7355                let dock = dock.read(cx);
 7356                let panel_size = dock.active_panel_size(window, cx)?;
 7357                let dock_pos = dock.position();
 7358                Some((panel_size, dock_pos, px))
 7359            } else {
 7360                None
 7361            }
 7362        })
 7363        .collect::<Vec<_>>();
 7364
 7365    docks
 7366        .into_iter()
 7367        .for_each(|(panel_size, dock_pos, offset)| {
 7368            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7369        });
 7370}
 7371
 7372impl Focusable for Workspace {
 7373    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7374        self.active_pane.focus_handle(cx)
 7375    }
 7376}
 7377
 7378#[derive(Clone)]
 7379struct DraggedDock(DockPosition);
 7380
 7381impl Render for DraggedDock {
 7382    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7383        gpui::Empty
 7384    }
 7385}
 7386
 7387impl Render for Workspace {
 7388    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7389        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7390        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7391            log::info!("Rendered first frame");
 7392        }
 7393        let mut context = KeyContext::new_with_defaults();
 7394        context.add("Workspace");
 7395        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 7396        if let Some(status) = self
 7397            .debugger_provider
 7398            .as_ref()
 7399            .and_then(|provider| provider.active_thread_state(cx))
 7400        {
 7401            match status {
 7402                ThreadStatus::Running | ThreadStatus::Stepping => {
 7403                    context.add("debugger_running");
 7404                }
 7405                ThreadStatus::Stopped => context.add("debugger_stopped"),
 7406                ThreadStatus::Exited | ThreadStatus::Ended => {}
 7407            }
 7408        }
 7409
 7410        if self.left_dock.read(cx).is_open() {
 7411            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 7412                context.set("left_dock", active_panel.panel_key());
 7413            }
 7414        }
 7415
 7416        if self.right_dock.read(cx).is_open() {
 7417            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 7418                context.set("right_dock", active_panel.panel_key());
 7419            }
 7420        }
 7421
 7422        if self.bottom_dock.read(cx).is_open() {
 7423            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 7424                context.set("bottom_dock", active_panel.panel_key());
 7425            }
 7426        }
 7427
 7428        let centered_layout = self.centered_layout
 7429            && self.center.panes().len() == 1
 7430            && self.active_item(cx).is_some();
 7431        let render_padding = |size| {
 7432            (size > 0.0).then(|| {
 7433                div()
 7434                    .h_full()
 7435                    .w(relative(size))
 7436                    .bg(cx.theme().colors().editor_background)
 7437                    .border_color(cx.theme().colors().pane_group_border)
 7438            })
 7439        };
 7440        let paddings = if centered_layout {
 7441            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7442            (
 7443                render_padding(Self::adjust_padding(
 7444                    settings.left_padding.map(|padding| padding.0),
 7445                )),
 7446                render_padding(Self::adjust_padding(
 7447                    settings.right_padding.map(|padding| padding.0),
 7448                )),
 7449            )
 7450        } else {
 7451            (None, None)
 7452        };
 7453        let ui_font = theme::setup_ui_font(window, cx);
 7454
 7455        let theme = cx.theme().clone();
 7456        let colors = theme.colors();
 7457        let notification_entities = self
 7458            .notifications
 7459            .iter()
 7460            .map(|(_, notification)| notification.entity_id())
 7461            .collect::<Vec<_>>();
 7462        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7463
 7464        self.actions(div(), window, cx)
 7465            .key_context(context)
 7466            .relative()
 7467            .size_full()
 7468            .flex()
 7469            .flex_col()
 7470            .font(ui_font)
 7471            .gap_0()
 7472                .justify_start()
 7473                .items_start()
 7474                .text_color(colors.text)
 7475                .overflow_hidden()
 7476                .children(self.titlebar_item.clone())
 7477                .on_modifiers_changed(move |_, _, cx| {
 7478                    for &id in &notification_entities {
 7479                        cx.notify(id);
 7480                    }
 7481                })
 7482                .child(
 7483                    div()
 7484                        .size_full()
 7485                        .relative()
 7486                        .flex_1()
 7487                        .flex()
 7488                        .flex_col()
 7489                        .child(
 7490                            div()
 7491                                .id("workspace")
 7492                                .bg(colors.background)
 7493                                .relative()
 7494                                .flex_1()
 7495                                .w_full()
 7496                                .flex()
 7497                                .flex_col()
 7498                                .overflow_hidden()
 7499                                .border_t_1()
 7500                                .border_b_1()
 7501                                .border_color(colors.border)
 7502                                .child({
 7503                                    let this = cx.entity();
 7504                                    canvas(
 7505                                        move |bounds, window, cx| {
 7506                                            this.update(cx, |this, cx| {
 7507                                                let bounds_changed = this.bounds != bounds;
 7508                                                this.bounds = bounds;
 7509
 7510                                                if bounds_changed {
 7511                                                    this.left_dock.update(cx, |dock, cx| {
 7512                                                        dock.clamp_panel_size(
 7513                                                            bounds.size.width,
 7514                                                            window,
 7515                                                            cx,
 7516                                                        )
 7517                                                    });
 7518
 7519                                                    this.right_dock.update(cx, |dock, cx| {
 7520                                                        dock.clamp_panel_size(
 7521                                                            bounds.size.width,
 7522                                                            window,
 7523                                                            cx,
 7524                                                        )
 7525                                                    });
 7526
 7527                                                    this.bottom_dock.update(cx, |dock, cx| {
 7528                                                        dock.clamp_panel_size(
 7529                                                            bounds.size.height,
 7530                                                            window,
 7531                                                            cx,
 7532                                                        )
 7533                                                    });
 7534                                                }
 7535                                            })
 7536                                        },
 7537                                        |_, _, _, _| {},
 7538                                    )
 7539                                    .absolute()
 7540                                    .size_full()
 7541                                })
 7542                                .when(self.zoomed.is_none(), |this| {
 7543                                    this.on_drag_move(cx.listener(
 7544                                        move |workspace,
 7545                                              e: &DragMoveEvent<DraggedDock>,
 7546                                              window,
 7547                                              cx| {
 7548                                            if workspace.previous_dock_drag_coordinates
 7549                                                != Some(e.event.position)
 7550                                            {
 7551                                                workspace.previous_dock_drag_coordinates =
 7552                                                    Some(e.event.position);
 7553                                                match e.drag(cx).0 {
 7554                                                    DockPosition::Left => {
 7555                                                        workspace.resize_left_dock(
 7556                                                            e.event.position.x
 7557                                                                - workspace.bounds.left(),
 7558                                                            window,
 7559                                                            cx,
 7560                                                        );
 7561                                                    }
 7562                                                    DockPosition::Right => {
 7563                                                        workspace.resize_right_dock(
 7564                                                            workspace.bounds.right()
 7565                                                                - e.event.position.x,
 7566                                                            window,
 7567                                                            cx,
 7568                                                        );
 7569                                                    }
 7570                                                    DockPosition::Bottom => {
 7571                                                        workspace.resize_bottom_dock(
 7572                                                            workspace.bounds.bottom()
 7573                                                                - e.event.position.y,
 7574                                                            window,
 7575                                                            cx,
 7576                                                        );
 7577                                                    }
 7578                                                };
 7579                                                workspace.serialize_workspace(window, cx);
 7580                                            }
 7581                                        },
 7582                                    ))
 7583
 7584                                })
 7585                                .child({
 7586                                    match bottom_dock_layout {
 7587                                        BottomDockLayout::Full => div()
 7588                                            .flex()
 7589                                            .flex_col()
 7590                                            .h_full()
 7591                                            .child(
 7592                                                div()
 7593                                                    .flex()
 7594                                                    .flex_row()
 7595                                                    .flex_1()
 7596                                                    .overflow_hidden()
 7597                                                    .children(self.render_dock(
 7598                                                        DockPosition::Left,
 7599                                                        &self.left_dock,
 7600                                                        window,
 7601                                                        cx,
 7602                                                    ))
 7603
 7604                                                    .child(
 7605                                                        div()
 7606                                                            .flex()
 7607                                                            .flex_col()
 7608                                                            .flex_1()
 7609                                                            .overflow_hidden()
 7610                                                            .child(
 7611                                                                h_flex()
 7612                                                                    .flex_1()
 7613                                                                    .when_some(
 7614                                                                        paddings.0,
 7615                                                                        |this, p| {
 7616                                                                            this.child(
 7617                                                                                p.border_r_1(),
 7618                                                                            )
 7619                                                                        },
 7620                                                                    )
 7621                                                                    .child(self.center.render(
 7622                                                                        self.zoomed.as_ref(),
 7623                                                                        &PaneRenderContext {
 7624                                                                            follower_states:
 7625                                                                                &self.follower_states,
 7626                                                                            active_call: self.active_call(),
 7627                                                                            active_pane: &self.active_pane,
 7628                                                                            app_state: &self.app_state,
 7629                                                                            project: &self.project,
 7630                                                                            workspace: &self.weak_self,
 7631                                                                        },
 7632                                                                        window,
 7633                                                                        cx,
 7634                                                                    ))
 7635                                                                    .when_some(
 7636                                                                        paddings.1,
 7637                                                                        |this, p| {
 7638                                                                            this.child(
 7639                                                                                p.border_l_1(),
 7640                                                                            )
 7641                                                                        },
 7642                                                                    ),
 7643                                                            ),
 7644                                                    )
 7645
 7646                                                    .children(self.render_dock(
 7647                                                        DockPosition::Right,
 7648                                                        &self.right_dock,
 7649                                                        window,
 7650                                                        cx,
 7651                                                    )),
 7652                                            )
 7653                                            .child(div().w_full().children(self.render_dock(
 7654                                                DockPosition::Bottom,
 7655                                                &self.bottom_dock,
 7656                                                window,
 7657                                                cx
 7658                                            ))),
 7659
 7660                                        BottomDockLayout::LeftAligned => div()
 7661                                            .flex()
 7662                                            .flex_row()
 7663                                            .h_full()
 7664                                            .child(
 7665                                                div()
 7666                                                    .flex()
 7667                                                    .flex_col()
 7668                                                    .flex_1()
 7669                                                    .h_full()
 7670                                                    .child(
 7671                                                        div()
 7672                                                            .flex()
 7673                                                            .flex_row()
 7674                                                            .flex_1()
 7675                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7676
 7677                                                            .child(
 7678                                                                div()
 7679                                                                    .flex()
 7680                                                                    .flex_col()
 7681                                                                    .flex_1()
 7682                                                                    .overflow_hidden()
 7683                                                                    .child(
 7684                                                                        h_flex()
 7685                                                                            .flex_1()
 7686                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7687                                                                            .child(self.center.render(
 7688                                                                                self.zoomed.as_ref(),
 7689                                                                                &PaneRenderContext {
 7690                                                                                    follower_states:
 7691                                                                                        &self.follower_states,
 7692                                                                                    active_call: self.active_call(),
 7693                                                                                    active_pane: &self.active_pane,
 7694                                                                                    app_state: &self.app_state,
 7695                                                                                    project: &self.project,
 7696                                                                                    workspace: &self.weak_self,
 7697                                                                                },
 7698                                                                                window,
 7699                                                                                cx,
 7700                                                                            ))
 7701                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7702                                                                    )
 7703                                                            )
 7704
 7705                                                    )
 7706                                                    .child(
 7707                                                        div()
 7708                                                            .w_full()
 7709                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7710                                                    ),
 7711                                            )
 7712                                            .children(self.render_dock(
 7713                                                DockPosition::Right,
 7714                                                &self.right_dock,
 7715                                                window,
 7716                                                cx,
 7717                                            )),
 7718
 7719                                        BottomDockLayout::RightAligned => div()
 7720                                            .flex()
 7721                                            .flex_row()
 7722                                            .h_full()
 7723                                            .children(self.render_dock(
 7724                                                DockPosition::Left,
 7725                                                &self.left_dock,
 7726                                                window,
 7727                                                cx,
 7728                                            ))
 7729
 7730                                            .child(
 7731                                                div()
 7732                                                    .flex()
 7733                                                    .flex_col()
 7734                                                    .flex_1()
 7735                                                    .h_full()
 7736                                                    .child(
 7737                                                        div()
 7738                                                            .flex()
 7739                                                            .flex_row()
 7740                                                            .flex_1()
 7741                                                            .child(
 7742                                                                div()
 7743                                                                    .flex()
 7744                                                                    .flex_col()
 7745                                                                    .flex_1()
 7746                                                                    .overflow_hidden()
 7747                                                                    .child(
 7748                                                                        h_flex()
 7749                                                                            .flex_1()
 7750                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7751                                                                            .child(self.center.render(
 7752                                                                                self.zoomed.as_ref(),
 7753                                                                                &PaneRenderContext {
 7754                                                                                    follower_states:
 7755                                                                                        &self.follower_states,
 7756                                                                                    active_call: self.active_call(),
 7757                                                                                    active_pane: &self.active_pane,
 7758                                                                                    app_state: &self.app_state,
 7759                                                                                    project: &self.project,
 7760                                                                                    workspace: &self.weak_self,
 7761                                                                                },
 7762                                                                                window,
 7763                                                                                cx,
 7764                                                                            ))
 7765                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7766                                                                    )
 7767                                                            )
 7768
 7769                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7770                                                    )
 7771                                                    .child(
 7772                                                        div()
 7773                                                            .w_full()
 7774                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7775                                                    ),
 7776                                            ),
 7777
 7778                                        BottomDockLayout::Contained => div()
 7779                                            .flex()
 7780                                            .flex_row()
 7781                                            .h_full()
 7782                                            .children(self.render_dock(
 7783                                                DockPosition::Left,
 7784                                                &self.left_dock,
 7785                                                window,
 7786                                                cx,
 7787                                            ))
 7788
 7789                                            .child(
 7790                                                div()
 7791                                                    .flex()
 7792                                                    .flex_col()
 7793                                                    .flex_1()
 7794                                                    .overflow_hidden()
 7795                                                    .child(
 7796                                                        h_flex()
 7797                                                            .flex_1()
 7798                                                            .when_some(paddings.0, |this, p| {
 7799                                                                this.child(p.border_r_1())
 7800                                                            })
 7801                                                            .child(self.center.render(
 7802                                                                self.zoomed.as_ref(),
 7803                                                                &PaneRenderContext {
 7804                                                                    follower_states:
 7805                                                                        &self.follower_states,
 7806                                                                    active_call: self.active_call(),
 7807                                                                    active_pane: &self.active_pane,
 7808                                                                    app_state: &self.app_state,
 7809                                                                    project: &self.project,
 7810                                                                    workspace: &self.weak_self,
 7811                                                                },
 7812                                                                window,
 7813                                                                cx,
 7814                                                            ))
 7815                                                            .when_some(paddings.1, |this, p| {
 7816                                                                this.child(p.border_l_1())
 7817                                                            }),
 7818                                                    )
 7819                                                    .children(self.render_dock(
 7820                                                        DockPosition::Bottom,
 7821                                                        &self.bottom_dock,
 7822                                                        window,
 7823                                                        cx,
 7824                                                    )),
 7825                                            )
 7826
 7827                                            .children(self.render_dock(
 7828                                                DockPosition::Right,
 7829                                                &self.right_dock,
 7830                                                window,
 7831                                                cx,
 7832                                            )),
 7833                                    }
 7834                                })
 7835                                .children(self.zoomed.as_ref().and_then(|view| {
 7836                                    let zoomed_view = view.upgrade()?;
 7837                                    let div = div()
 7838                                        .occlude()
 7839                                        .absolute()
 7840                                        .overflow_hidden()
 7841                                        .border_color(colors.border)
 7842                                        .bg(colors.background)
 7843                                        .child(zoomed_view)
 7844                                        .inset_0()
 7845                                        .shadow_lg();
 7846
 7847                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7848                                       return Some(div);
 7849                                    }
 7850
 7851                                    Some(match self.zoomed_position {
 7852                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7853                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7854                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7855                                        None => {
 7856                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7857                                        }
 7858                                    })
 7859                                }))
 7860                                .children(self.render_notifications(window, cx)),
 7861                        )
 7862                        .when(self.status_bar_visible(cx), |parent| {
 7863                            parent.child(self.status_bar.clone())
 7864                        })
 7865                        .child(self.modal_layer.clone())
 7866                        .child(self.toast_layer.clone()),
 7867                )
 7868    }
 7869}
 7870
 7871impl WorkspaceStore {
 7872    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7873        Self {
 7874            workspaces: Default::default(),
 7875            _subscriptions: vec![
 7876                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7877                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7878            ],
 7879            client,
 7880        }
 7881    }
 7882
 7883    pub fn update_followers(
 7884        &self,
 7885        project_id: Option<u64>,
 7886        update: proto::update_followers::Variant,
 7887        cx: &App,
 7888    ) -> Option<()> {
 7889        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 7890        let room_id = active_call.0.room_id(cx)?;
 7891        self.client
 7892            .send(proto::UpdateFollowers {
 7893                room_id,
 7894                project_id,
 7895                variant: Some(update),
 7896            })
 7897            .log_err()
 7898    }
 7899
 7900    pub async fn handle_follow(
 7901        this: Entity<Self>,
 7902        envelope: TypedEnvelope<proto::Follow>,
 7903        mut cx: AsyncApp,
 7904    ) -> Result<proto::FollowResponse> {
 7905        this.update(&mut cx, |this, cx| {
 7906            let follower = Follower {
 7907                project_id: envelope.payload.project_id,
 7908                peer_id: envelope.original_sender_id()?,
 7909            };
 7910
 7911            let mut response = proto::FollowResponse::default();
 7912
 7913            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7914                let Some(workspace) = weak_workspace.upgrade() else {
 7915                    return false;
 7916                };
 7917                window_handle
 7918                    .update(cx, |_, window, cx| {
 7919                        workspace.update(cx, |workspace, cx| {
 7920                            let handler_response =
 7921                                workspace.handle_follow(follower.project_id, window, cx);
 7922                            if let Some(active_view) = handler_response.active_view
 7923                                && workspace.project.read(cx).remote_id() == follower.project_id
 7924                            {
 7925                                response.active_view = Some(active_view)
 7926                            }
 7927                        });
 7928                    })
 7929                    .is_ok()
 7930            });
 7931
 7932            Ok(response)
 7933        })
 7934    }
 7935
 7936    async fn handle_update_followers(
 7937        this: Entity<Self>,
 7938        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7939        mut cx: AsyncApp,
 7940    ) -> Result<()> {
 7941        let leader_id = envelope.original_sender_id()?;
 7942        let update = envelope.payload;
 7943
 7944        this.update(&mut cx, |this, cx| {
 7945            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7946                let Some(workspace) = weak_workspace.upgrade() else {
 7947                    return false;
 7948                };
 7949                window_handle
 7950                    .update(cx, |_, window, cx| {
 7951                        workspace.update(cx, |workspace, cx| {
 7952                            let project_id = workspace.project.read(cx).remote_id();
 7953                            if update.project_id != project_id && update.project_id.is_some() {
 7954                                return;
 7955                            }
 7956                            workspace.handle_update_followers(
 7957                                leader_id,
 7958                                update.clone(),
 7959                                window,
 7960                                cx,
 7961                            );
 7962                        });
 7963                    })
 7964                    .is_ok()
 7965            });
 7966            Ok(())
 7967        })
 7968    }
 7969
 7970    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 7971        self.workspaces.iter().map(|(_, weak)| weak)
 7972    }
 7973
 7974    pub fn workspaces_with_windows(
 7975        &self,
 7976    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 7977        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 7978    }
 7979}
 7980
 7981impl ViewId {
 7982    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7983        Ok(Self {
 7984            creator: message
 7985                .creator
 7986                .map(CollaboratorId::PeerId)
 7987                .context("creator is missing")?,
 7988            id: message.id,
 7989        })
 7990    }
 7991
 7992    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7993        if let CollaboratorId::PeerId(peer_id) = self.creator {
 7994            Some(proto::ViewId {
 7995                creator: Some(peer_id),
 7996                id: self.id,
 7997            })
 7998        } else {
 7999            None
 8000        }
 8001    }
 8002}
 8003
 8004impl FollowerState {
 8005    fn pane(&self) -> &Entity<Pane> {
 8006        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8007    }
 8008}
 8009
 8010pub trait WorkspaceHandle {
 8011    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8012}
 8013
 8014impl WorkspaceHandle for Entity<Workspace> {
 8015    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8016        self.read(cx)
 8017            .worktrees(cx)
 8018            .flat_map(|worktree| {
 8019                let worktree_id = worktree.read(cx).id();
 8020                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8021                    worktree_id,
 8022                    path: f.path.clone(),
 8023                })
 8024            })
 8025            .collect::<Vec<_>>()
 8026    }
 8027}
 8028
 8029pub async fn last_opened_workspace_location(
 8030    fs: &dyn fs::Fs,
 8031) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8032    DB.last_workspace(fs)
 8033        .await
 8034        .log_err()
 8035        .flatten()
 8036        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8037}
 8038
 8039pub async fn last_session_workspace_locations(
 8040    last_session_id: &str,
 8041    last_session_window_stack: Option<Vec<WindowId>>,
 8042    fs: &dyn fs::Fs,
 8043) -> Option<Vec<SessionWorkspace>> {
 8044    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8045        .await
 8046        .log_err()
 8047}
 8048
 8049pub struct MultiWorkspaceRestoreResult {
 8050    pub window_handle: WindowHandle<MultiWorkspace>,
 8051    pub errors: Vec<anyhow::Error>,
 8052}
 8053
 8054pub async fn restore_multiworkspace(
 8055    multi_workspace: SerializedMultiWorkspace,
 8056    app_state: Arc<AppState>,
 8057    cx: &mut AsyncApp,
 8058) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8059    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8060    let mut group_iter = workspaces.into_iter();
 8061    let first = group_iter
 8062        .next()
 8063        .context("window group must not be empty")?;
 8064
 8065    let window_handle = if first.paths.is_empty() {
 8066        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8067            .await?
 8068    } else {
 8069        let (window, _items) = cx
 8070            .update(|cx| {
 8071                Workspace::new_local(
 8072                    first.paths.paths().to_vec(),
 8073                    app_state.clone(),
 8074                    None,
 8075                    None,
 8076                    None,
 8077                    cx,
 8078                )
 8079            })
 8080            .await?;
 8081        window
 8082    };
 8083
 8084    let mut errors = Vec::new();
 8085
 8086    for session_workspace in group_iter {
 8087        let error = if session_workspace.paths.is_empty() {
 8088            cx.update(|cx| {
 8089                open_workspace_by_id(
 8090                    session_workspace.workspace_id,
 8091                    app_state.clone(),
 8092                    Some(window_handle),
 8093                    cx,
 8094                )
 8095            })
 8096            .await
 8097            .err()
 8098        } else {
 8099            cx.update(|cx| {
 8100                Workspace::new_local(
 8101                    session_workspace.paths.paths().to_vec(),
 8102                    app_state.clone(),
 8103                    Some(window_handle),
 8104                    None,
 8105                    None,
 8106                    cx,
 8107                )
 8108            })
 8109            .await
 8110            .err()
 8111        };
 8112
 8113        if let Some(error) = error {
 8114            errors.push(error);
 8115        }
 8116    }
 8117
 8118    if let Some(target_id) = state.active_workspace_id {
 8119        window_handle
 8120            .update(cx, |multi_workspace, window, cx| {
 8121                let target_index = multi_workspace
 8122                    .workspaces()
 8123                    .iter()
 8124                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8125                if let Some(index) = target_index {
 8126                    multi_workspace.activate_index(index, window, cx);
 8127                } else if !multi_workspace.workspaces().is_empty() {
 8128                    multi_workspace.activate_index(0, window, cx);
 8129                }
 8130            })
 8131            .ok();
 8132    } else {
 8133        window_handle
 8134            .update(cx, |multi_workspace, window, cx| {
 8135                if !multi_workspace.workspaces().is_empty() {
 8136                    multi_workspace.activate_index(0, window, cx);
 8137                }
 8138            })
 8139            .ok();
 8140    }
 8141
 8142    if state.sidebar_open {
 8143        window_handle
 8144            .update(cx, |multi_workspace, _, cx| {
 8145                multi_workspace.open_sidebar(cx);
 8146            })
 8147            .ok();
 8148    }
 8149
 8150    window_handle
 8151        .update(cx, |_, window, _cx| {
 8152            window.activate_window();
 8153        })
 8154        .ok();
 8155
 8156    Ok(MultiWorkspaceRestoreResult {
 8157        window_handle,
 8158        errors,
 8159    })
 8160}
 8161
 8162actions!(
 8163    collab,
 8164    [
 8165        /// Opens the channel notes for the current call.
 8166        ///
 8167        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8168        /// channel in the collab panel.
 8169        ///
 8170        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8171        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8172        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8173        OpenChannelNotes,
 8174        /// Mutes your microphone.
 8175        Mute,
 8176        /// Deafens yourself (mute both microphone and speakers).
 8177        Deafen,
 8178        /// Leaves the current call.
 8179        LeaveCall,
 8180        /// Shares the current project with collaborators.
 8181        ShareProject,
 8182        /// Shares your screen with collaborators.
 8183        ScreenShare,
 8184        /// Copies the current room name and session id for debugging purposes.
 8185        CopyRoomId,
 8186    ]
 8187);
 8188actions!(
 8189    zed,
 8190    [
 8191        /// Opens the Zed log file.
 8192        OpenLog,
 8193        /// Reveals the Zed log file in the system file manager.
 8194        RevealLogInFileManager
 8195    ]
 8196);
 8197
 8198async fn join_channel_internal(
 8199    channel_id: ChannelId,
 8200    app_state: &Arc<AppState>,
 8201    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8202    requesting_workspace: Option<WeakEntity<Workspace>>,
 8203    active_call: &dyn AnyActiveCall,
 8204    cx: &mut AsyncApp,
 8205) -> Result<bool> {
 8206    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8207        if !active_call.is_in_room(cx) {
 8208            return (false, false);
 8209        }
 8210
 8211        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8212        let should_prompt = active_call.is_sharing_project(cx)
 8213            && active_call.has_remote_participants(cx)
 8214            && !already_in_channel;
 8215        (should_prompt, already_in_channel)
 8216    });
 8217
 8218    if already_in_channel {
 8219        let task = cx.update(|cx| {
 8220            if let Some((project, host)) = active_call.most_active_project(cx) {
 8221                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8222            } else {
 8223                None
 8224            }
 8225        });
 8226        if let Some(task) = task {
 8227            task.await?;
 8228        }
 8229        return anyhow::Ok(true);
 8230    }
 8231
 8232    if should_prompt {
 8233        if let Some(multi_workspace) = requesting_window {
 8234            let answer = multi_workspace
 8235                .update(cx, |_, window, cx| {
 8236                    window.prompt(
 8237                        PromptLevel::Warning,
 8238                        "Do you want to switch channels?",
 8239                        Some("Leaving this call will unshare your current project."),
 8240                        &["Yes, Join Channel", "Cancel"],
 8241                        cx,
 8242                    )
 8243                })?
 8244                .await;
 8245
 8246            if answer == Ok(1) {
 8247                return Ok(false);
 8248            }
 8249        } else {
 8250            return Ok(false);
 8251        }
 8252    }
 8253
 8254    let client = cx.update(|cx| active_call.client(cx));
 8255
 8256    let mut client_status = client.status();
 8257
 8258    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8259    'outer: loop {
 8260        let Some(status) = client_status.recv().await else {
 8261            anyhow::bail!("error connecting");
 8262        };
 8263
 8264        match status {
 8265            Status::Connecting
 8266            | Status::Authenticating
 8267            | Status::Authenticated
 8268            | Status::Reconnecting
 8269            | Status::Reauthenticating
 8270            | Status::Reauthenticated => continue,
 8271            Status::Connected { .. } => break 'outer,
 8272            Status::SignedOut | Status::AuthenticationError => {
 8273                return Err(ErrorCode::SignedOut.into());
 8274            }
 8275            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8276            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8277                return Err(ErrorCode::Disconnected.into());
 8278            }
 8279        }
 8280    }
 8281
 8282    let joined = cx
 8283        .update(|cx| active_call.join_channel(channel_id, cx))
 8284        .await?;
 8285
 8286    if !joined {
 8287        return anyhow::Ok(true);
 8288    }
 8289
 8290    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8291
 8292    let task = cx.update(|cx| {
 8293        if let Some((project, host)) = active_call.most_active_project(cx) {
 8294            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8295        }
 8296
 8297        // If you are the first to join a channel, see if you should share your project.
 8298        if !active_call.has_remote_participants(cx)
 8299            && !active_call.local_participant_is_guest(cx)
 8300            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8301        {
 8302            let project = workspace.update(cx, |workspace, cx| {
 8303                let project = workspace.project.read(cx);
 8304
 8305                if !active_call.share_on_join(cx) {
 8306                    return None;
 8307                }
 8308
 8309                if (project.is_local() || project.is_via_remote_server())
 8310                    && project.visible_worktrees(cx).any(|tree| {
 8311                        tree.read(cx)
 8312                            .root_entry()
 8313                            .is_some_and(|entry| entry.is_dir())
 8314                    })
 8315                {
 8316                    Some(workspace.project.clone())
 8317                } else {
 8318                    None
 8319                }
 8320            });
 8321            if let Some(project) = project {
 8322                let share_task = active_call.share_project(project, cx);
 8323                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8324                    share_task.await?;
 8325                    Ok(())
 8326                }));
 8327            }
 8328        }
 8329
 8330        None
 8331    });
 8332    if let Some(task) = task {
 8333        task.await?;
 8334        return anyhow::Ok(true);
 8335    }
 8336    anyhow::Ok(false)
 8337}
 8338
 8339pub fn join_channel(
 8340    channel_id: ChannelId,
 8341    app_state: Arc<AppState>,
 8342    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8343    requesting_workspace: Option<WeakEntity<Workspace>>,
 8344    cx: &mut App,
 8345) -> Task<Result<()>> {
 8346    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8347    cx.spawn(async move |cx| {
 8348        let result = join_channel_internal(
 8349            channel_id,
 8350            &app_state,
 8351            requesting_window,
 8352            requesting_workspace,
 8353            &*active_call.0,
 8354            cx,
 8355        )
 8356        .await;
 8357
 8358        // join channel succeeded, and opened a window
 8359        if matches!(result, Ok(true)) {
 8360            return anyhow::Ok(());
 8361        }
 8362
 8363        // find an existing workspace to focus and show call controls
 8364        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8365        if active_window.is_none() {
 8366            // no open workspaces, make one to show the error in (blergh)
 8367            let (window_handle, _) = cx
 8368                .update(|cx| {
 8369                    Workspace::new_local(
 8370                        vec![],
 8371                        app_state.clone(),
 8372                        requesting_window,
 8373                        None,
 8374                        None,
 8375                        cx,
 8376                    )
 8377                })
 8378                .await?;
 8379
 8380            window_handle
 8381                .update(cx, |_, window, _cx| {
 8382                    window.activate_window();
 8383                })
 8384                .ok();
 8385
 8386            if result.is_ok() {
 8387                cx.update(|cx| {
 8388                    cx.dispatch_action(&OpenChannelNotes);
 8389                });
 8390            }
 8391
 8392            active_window = Some(window_handle);
 8393        }
 8394
 8395        if let Err(err) = result {
 8396            log::error!("failed to join channel: {}", err);
 8397            if let Some(active_window) = active_window {
 8398                active_window
 8399                    .update(cx, |_, window, cx| {
 8400                        let detail: SharedString = match err.error_code() {
 8401                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8402                            ErrorCode::UpgradeRequired => concat!(
 8403                                "Your are running an unsupported version of Zed. ",
 8404                                "Please update to continue."
 8405                            )
 8406                            .into(),
 8407                            ErrorCode::NoSuchChannel => concat!(
 8408                                "No matching channel was found. ",
 8409                                "Please check the link and try again."
 8410                            )
 8411                            .into(),
 8412                            ErrorCode::Forbidden => concat!(
 8413                                "This channel is private, and you do not have access. ",
 8414                                "Please ask someone to add you and try again."
 8415                            )
 8416                            .into(),
 8417                            ErrorCode::Disconnected => {
 8418                                "Please check your internet connection and try again.".into()
 8419                            }
 8420                            _ => format!("{}\n\nPlease try again.", err).into(),
 8421                        };
 8422                        window.prompt(
 8423                            PromptLevel::Critical,
 8424                            "Failed to join channel",
 8425                            Some(&detail),
 8426                            &["Ok"],
 8427                            cx,
 8428                        )
 8429                    })?
 8430                    .await
 8431                    .ok();
 8432            }
 8433        }
 8434
 8435        // return ok, we showed the error to the user.
 8436        anyhow::Ok(())
 8437    })
 8438}
 8439
 8440pub async fn get_any_active_multi_workspace(
 8441    app_state: Arc<AppState>,
 8442    mut cx: AsyncApp,
 8443) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8444    // find an existing workspace to focus and show call controls
 8445    let active_window = activate_any_workspace_window(&mut cx);
 8446    if active_window.is_none() {
 8447        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
 8448            .await?;
 8449    }
 8450    activate_any_workspace_window(&mut cx).context("could not open zed")
 8451}
 8452
 8453fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8454    cx.update(|cx| {
 8455        if let Some(workspace_window) = cx
 8456            .active_window()
 8457            .and_then(|window| window.downcast::<MultiWorkspace>())
 8458        {
 8459            return Some(workspace_window);
 8460        }
 8461
 8462        for window in cx.windows() {
 8463            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8464                workspace_window
 8465                    .update(cx, |_, window, _| window.activate_window())
 8466                    .ok();
 8467                return Some(workspace_window);
 8468            }
 8469        }
 8470        None
 8471    })
 8472}
 8473
 8474pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8475    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8476}
 8477
 8478pub fn workspace_windows_for_location(
 8479    serialized_location: &SerializedWorkspaceLocation,
 8480    cx: &App,
 8481) -> Vec<WindowHandle<MultiWorkspace>> {
 8482    cx.windows()
 8483        .into_iter()
 8484        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8485        .filter(|multi_workspace| {
 8486            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8487                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8488                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8489                }
 8490                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8491                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8492                    a.distro_name == b.distro_name
 8493                }
 8494                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8495                    a.container_id == b.container_id
 8496                }
 8497                #[cfg(any(test, feature = "test-support"))]
 8498                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8499                    a.id == b.id
 8500                }
 8501                _ => false,
 8502            };
 8503
 8504            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8505                multi_workspace.workspaces().iter().any(|workspace| {
 8506                    match workspace.read(cx).workspace_location(cx) {
 8507                        WorkspaceLocation::Location(location, _) => {
 8508                            match (&location, serialized_location) {
 8509                                (
 8510                                    SerializedWorkspaceLocation::Local,
 8511                                    SerializedWorkspaceLocation::Local,
 8512                                ) => true,
 8513                                (
 8514                                    SerializedWorkspaceLocation::Remote(a),
 8515                                    SerializedWorkspaceLocation::Remote(b),
 8516                                ) => same_host(a, b),
 8517                                _ => false,
 8518                            }
 8519                        }
 8520                        _ => false,
 8521                    }
 8522                })
 8523            })
 8524        })
 8525        .collect()
 8526}
 8527
 8528pub async fn find_existing_workspace(
 8529    abs_paths: &[PathBuf],
 8530    open_options: &OpenOptions,
 8531    location: &SerializedWorkspaceLocation,
 8532    cx: &mut AsyncApp,
 8533) -> (
 8534    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8535    OpenVisible,
 8536) {
 8537    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8538    let mut open_visible = OpenVisible::All;
 8539    let mut best_match = None;
 8540
 8541    if open_options.open_new_workspace != Some(true) {
 8542        cx.update(|cx| {
 8543            for window in workspace_windows_for_location(location, cx) {
 8544                if let Ok(multi_workspace) = window.read(cx) {
 8545                    for workspace in multi_workspace.workspaces() {
 8546                        let project = workspace.read(cx).project.read(cx);
 8547                        let m = project.visibility_for_paths(
 8548                            abs_paths,
 8549                            open_options.open_new_workspace == None,
 8550                            cx,
 8551                        );
 8552                        if m > best_match {
 8553                            existing = Some((window, workspace.clone()));
 8554                            best_match = m;
 8555                        } else if best_match.is_none()
 8556                            && open_options.open_new_workspace == Some(false)
 8557                        {
 8558                            existing = Some((window, workspace.clone()))
 8559                        }
 8560                    }
 8561                }
 8562            }
 8563        });
 8564
 8565        let all_paths_are_files = existing
 8566            .as_ref()
 8567            .and_then(|(_, target_workspace)| {
 8568                cx.update(|cx| {
 8569                    let workspace = target_workspace.read(cx);
 8570                    let project = workspace.project.read(cx);
 8571                    let path_style = workspace.path_style(cx);
 8572                    Some(!abs_paths.iter().any(|path| {
 8573                        let path = util::paths::SanitizedPath::new(path);
 8574                        project.worktrees(cx).any(|worktree| {
 8575                            let worktree = worktree.read(cx);
 8576                            let abs_path = worktree.abs_path();
 8577                            path_style
 8578                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8579                                .and_then(|rel| worktree.entry_for_path(&rel))
 8580                                .is_some_and(|e| e.is_dir())
 8581                        })
 8582                    }))
 8583                })
 8584            })
 8585            .unwrap_or(false);
 8586
 8587        if open_options.open_new_workspace.is_none()
 8588            && existing.is_some()
 8589            && open_options.wait
 8590            && all_paths_are_files
 8591        {
 8592            cx.update(|cx| {
 8593                let windows = workspace_windows_for_location(location, cx);
 8594                let window = cx
 8595                    .active_window()
 8596                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8597                    .filter(|window| windows.contains(window))
 8598                    .or_else(|| windows.into_iter().next());
 8599                if let Some(window) = window {
 8600                    if let Ok(multi_workspace) = window.read(cx) {
 8601                        let active_workspace = multi_workspace.workspace().clone();
 8602                        existing = Some((window, active_workspace));
 8603                        open_visible = OpenVisible::None;
 8604                    }
 8605                }
 8606            });
 8607        }
 8608    }
 8609    (existing, open_visible)
 8610}
 8611
 8612#[derive(Default, Clone)]
 8613pub struct OpenOptions {
 8614    pub visible: Option<OpenVisible>,
 8615    pub focus: Option<bool>,
 8616    pub open_new_workspace: Option<bool>,
 8617    pub wait: bool,
 8618    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8619    pub env: Option<HashMap<String, String>>,
 8620}
 8621
 8622/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8623pub fn open_workspace_by_id(
 8624    workspace_id: WorkspaceId,
 8625    app_state: Arc<AppState>,
 8626    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8627    cx: &mut App,
 8628) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8629    let project_handle = Project::local(
 8630        app_state.client.clone(),
 8631        app_state.node_runtime.clone(),
 8632        app_state.user_store.clone(),
 8633        app_state.languages.clone(),
 8634        app_state.fs.clone(),
 8635        None,
 8636        project::LocalProjectFlags {
 8637            init_worktree_trust: true,
 8638            ..project::LocalProjectFlags::default()
 8639        },
 8640        cx,
 8641    );
 8642
 8643    cx.spawn(async move |cx| {
 8644        let serialized_workspace = persistence::DB
 8645            .workspace_for_id(workspace_id)
 8646            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8647
 8648        let centered_layout = serialized_workspace.centered_layout;
 8649
 8650        let (window, workspace) = if let Some(window) = requesting_window {
 8651            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8652                let workspace = cx.new(|cx| {
 8653                    let mut workspace = Workspace::new(
 8654                        Some(workspace_id),
 8655                        project_handle.clone(),
 8656                        app_state.clone(),
 8657                        window,
 8658                        cx,
 8659                    );
 8660                    workspace.centered_layout = centered_layout;
 8661                    workspace
 8662                });
 8663                multi_workspace.add_workspace(workspace.clone(), cx);
 8664                workspace
 8665            })?;
 8666            (window, workspace)
 8667        } else {
 8668            let window_bounds_override = window_bounds_env_override();
 8669
 8670            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8671                (Some(WindowBounds::Windowed(bounds)), None)
 8672            } else if let Some(display) = serialized_workspace.display
 8673                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8674            {
 8675                (Some(bounds.0), Some(display))
 8676            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8677                (Some(bounds), Some(display))
 8678            } else {
 8679                (None, None)
 8680            };
 8681
 8682            let options = cx.update(|cx| {
 8683                let mut options = (app_state.build_window_options)(display, cx);
 8684                options.window_bounds = window_bounds;
 8685                options
 8686            });
 8687
 8688            let window = cx.open_window(options, {
 8689                let app_state = app_state.clone();
 8690                let project_handle = project_handle.clone();
 8691                move |window, cx| {
 8692                    let workspace = cx.new(|cx| {
 8693                        let mut workspace = Workspace::new(
 8694                            Some(workspace_id),
 8695                            project_handle,
 8696                            app_state,
 8697                            window,
 8698                            cx,
 8699                        );
 8700                        workspace.centered_layout = centered_layout;
 8701                        workspace
 8702                    });
 8703                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8704                }
 8705            })?;
 8706
 8707            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8708                multi_workspace.workspace().clone()
 8709            })?;
 8710
 8711            (window, workspace)
 8712        };
 8713
 8714        notify_if_database_failed(window, cx);
 8715
 8716        // Restore items from the serialized workspace
 8717        window
 8718            .update(cx, |_, window, cx| {
 8719                workspace.update(cx, |_workspace, cx| {
 8720                    open_items(Some(serialized_workspace), vec![], window, cx)
 8721                })
 8722            })?
 8723            .await?;
 8724
 8725        window.update(cx, |_, window, cx| {
 8726            workspace.update(cx, |workspace, cx| {
 8727                workspace.serialize_workspace(window, cx);
 8728            });
 8729        })?;
 8730
 8731        Ok(window)
 8732    })
 8733}
 8734
 8735#[allow(clippy::type_complexity)]
 8736pub fn open_paths(
 8737    abs_paths: &[PathBuf],
 8738    app_state: Arc<AppState>,
 8739    open_options: OpenOptions,
 8740    cx: &mut App,
 8741) -> Task<
 8742    anyhow::Result<(
 8743        WindowHandle<MultiWorkspace>,
 8744        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8745    )>,
 8746> {
 8747    let abs_paths = abs_paths.to_vec();
 8748    #[cfg(target_os = "windows")]
 8749    let wsl_path = abs_paths
 8750        .iter()
 8751        .find_map(|p| util::paths::WslPath::from_path(p));
 8752
 8753    cx.spawn(async move |cx| {
 8754        let (mut existing, mut open_visible) = find_existing_workspace(
 8755            &abs_paths,
 8756            &open_options,
 8757            &SerializedWorkspaceLocation::Local,
 8758            cx,
 8759        )
 8760        .await;
 8761
 8762        // Fallback: if no workspace contains the paths and all paths are files,
 8763        // prefer an existing local workspace window (active window first).
 8764        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8765            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8766            let all_metadatas = futures::future::join_all(all_paths)
 8767                .await
 8768                .into_iter()
 8769                .filter_map(|result| result.ok().flatten())
 8770                .collect::<Vec<_>>();
 8771
 8772            if all_metadatas.iter().all(|file| !file.is_dir) {
 8773                cx.update(|cx| {
 8774                    let windows = workspace_windows_for_location(
 8775                        &SerializedWorkspaceLocation::Local,
 8776                        cx,
 8777                    );
 8778                    let window = cx
 8779                        .active_window()
 8780                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8781                        .filter(|window| windows.contains(window))
 8782                        .or_else(|| windows.into_iter().next());
 8783                    if let Some(window) = window {
 8784                        if let Ok(multi_workspace) = window.read(cx) {
 8785                            let active_workspace = multi_workspace.workspace().clone();
 8786                            existing = Some((window, active_workspace));
 8787                            open_visible = OpenVisible::None;
 8788                        }
 8789                    }
 8790                });
 8791            }
 8792        }
 8793
 8794        let result = if let Some((existing, target_workspace)) = existing {
 8795            let open_task = existing
 8796                .update(cx, |multi_workspace, window, cx| {
 8797                    window.activate_window();
 8798                    multi_workspace.activate(target_workspace.clone(), cx);
 8799                    target_workspace.update(cx, |workspace, cx| {
 8800                        workspace.open_paths(
 8801                            abs_paths,
 8802                            OpenOptions {
 8803                                visible: Some(open_visible),
 8804                                ..Default::default()
 8805                            },
 8806                            None,
 8807                            window,
 8808                            cx,
 8809                        )
 8810                    })
 8811                })?
 8812                .await;
 8813
 8814            _ = existing.update(cx, |multi_workspace, _, cx| {
 8815                let workspace = multi_workspace.workspace().clone();
 8816                workspace.update(cx, |workspace, cx| {
 8817                    for item in open_task.iter().flatten() {
 8818                        if let Err(e) = item {
 8819                            workspace.show_error(&e, cx);
 8820                        }
 8821                    }
 8822                });
 8823            });
 8824
 8825            Ok((existing, open_task))
 8826        } else {
 8827            let result = cx
 8828                .update(move |cx| {
 8829                    Workspace::new_local(
 8830                        abs_paths,
 8831                        app_state.clone(),
 8832                        open_options.replace_window,
 8833                        open_options.env,
 8834                        None,
 8835                        cx,
 8836                    )
 8837                })
 8838                .await;
 8839
 8840            if let Ok((ref window_handle, _)) = result {
 8841                window_handle
 8842                    .update(cx, |_, window, _cx| {
 8843                        window.activate_window();
 8844                    })
 8845                    .log_err();
 8846            }
 8847
 8848            result
 8849        };
 8850
 8851        #[cfg(target_os = "windows")]
 8852        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8853            && let Ok((multi_workspace_window, _)) = &result
 8854        {
 8855            multi_workspace_window
 8856                .update(cx, move |multi_workspace, _window, cx| {
 8857                    struct OpenInWsl;
 8858                    let workspace = multi_workspace.workspace().clone();
 8859                    workspace.update(cx, |workspace, cx| {
 8860                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8861                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8862                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8863                            cx.new(move |cx| {
 8864                                MessageNotification::new(msg, cx)
 8865                                    .primary_message("Open in WSL")
 8866                                    .primary_icon(IconName::FolderOpen)
 8867                                    .primary_on_click(move |window, cx| {
 8868                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 8869                                                distro: remote::WslConnectionOptions {
 8870                                                        distro_name: distro.clone(),
 8871                                                    user: None,
 8872                                                },
 8873                                                paths: vec![path.clone().into()],
 8874                                            }), cx)
 8875                                    })
 8876                            })
 8877                        });
 8878                    });
 8879                })
 8880                .unwrap();
 8881        };
 8882        result
 8883    })
 8884}
 8885
 8886pub fn open_new(
 8887    open_options: OpenOptions,
 8888    app_state: Arc<AppState>,
 8889    cx: &mut App,
 8890    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8891) -> Task<anyhow::Result<()>> {
 8892    let task = Workspace::new_local(
 8893        Vec::new(),
 8894        app_state,
 8895        open_options.replace_window,
 8896        open_options.env,
 8897        Some(Box::new(init)),
 8898        cx,
 8899    );
 8900    cx.spawn(async move |cx| {
 8901        let (window, _opened_paths) = task.await?;
 8902        window
 8903            .update(cx, |_, window, _cx| {
 8904                window.activate_window();
 8905            })
 8906            .ok();
 8907        Ok(())
 8908    })
 8909}
 8910
 8911pub fn create_and_open_local_file(
 8912    path: &'static Path,
 8913    window: &mut Window,
 8914    cx: &mut Context<Workspace>,
 8915    default_content: impl 'static + Send + FnOnce() -> Rope,
 8916) -> Task<Result<Box<dyn ItemHandle>>> {
 8917    cx.spawn_in(window, async move |workspace, cx| {
 8918        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8919        if !fs.is_file(path).await {
 8920            fs.create_file(path, Default::default()).await?;
 8921            fs.save(path, &default_content(), Default::default())
 8922                .await?;
 8923        }
 8924
 8925        workspace
 8926            .update_in(cx, |workspace, window, cx| {
 8927                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 8928                    let path = workspace
 8929                        .project
 8930                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 8931                    cx.spawn_in(window, async move |workspace, cx| {
 8932                        let path = path.await?;
 8933                        let mut items = workspace
 8934                            .update_in(cx, |workspace, window, cx| {
 8935                                workspace.open_paths(
 8936                                    vec![path.to_path_buf()],
 8937                                    OpenOptions {
 8938                                        visible: Some(OpenVisible::None),
 8939                                        ..Default::default()
 8940                                    },
 8941                                    None,
 8942                                    window,
 8943                                    cx,
 8944                                )
 8945                            })?
 8946                            .await;
 8947                        let item = items.pop().flatten();
 8948                        item.with_context(|| format!("path {path:?} is not a file"))?
 8949                    })
 8950                })
 8951            })?
 8952            .await?
 8953            .await
 8954    })
 8955}
 8956
 8957pub fn open_remote_project_with_new_connection(
 8958    window: WindowHandle<MultiWorkspace>,
 8959    remote_connection: Arc<dyn RemoteConnection>,
 8960    cancel_rx: oneshot::Receiver<()>,
 8961    delegate: Arc<dyn RemoteClientDelegate>,
 8962    app_state: Arc<AppState>,
 8963    paths: Vec<PathBuf>,
 8964    cx: &mut App,
 8965) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8966    cx.spawn(async move |cx| {
 8967        let (workspace_id, serialized_workspace) =
 8968            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8969                .await?;
 8970
 8971        let session = match cx
 8972            .update(|cx| {
 8973                remote::RemoteClient::new(
 8974                    ConnectionIdentifier::Workspace(workspace_id.0),
 8975                    remote_connection,
 8976                    cancel_rx,
 8977                    delegate,
 8978                    cx,
 8979                )
 8980            })
 8981            .await?
 8982        {
 8983            Some(result) => result,
 8984            None => return Ok(Vec::new()),
 8985        };
 8986
 8987        let project = cx.update(|cx| {
 8988            project::Project::remote(
 8989                session,
 8990                app_state.client.clone(),
 8991                app_state.node_runtime.clone(),
 8992                app_state.user_store.clone(),
 8993                app_state.languages.clone(),
 8994                app_state.fs.clone(),
 8995                true,
 8996                cx,
 8997            )
 8998        });
 8999
 9000        open_remote_project_inner(
 9001            project,
 9002            paths,
 9003            workspace_id,
 9004            serialized_workspace,
 9005            app_state,
 9006            window,
 9007            cx,
 9008        )
 9009        .await
 9010    })
 9011}
 9012
 9013pub fn open_remote_project_with_existing_connection(
 9014    connection_options: RemoteConnectionOptions,
 9015    project: Entity<Project>,
 9016    paths: Vec<PathBuf>,
 9017    app_state: Arc<AppState>,
 9018    window: WindowHandle<MultiWorkspace>,
 9019    cx: &mut AsyncApp,
 9020) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9021    cx.spawn(async move |cx| {
 9022        let (workspace_id, serialized_workspace) =
 9023            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9024
 9025        open_remote_project_inner(
 9026            project,
 9027            paths,
 9028            workspace_id,
 9029            serialized_workspace,
 9030            app_state,
 9031            window,
 9032            cx,
 9033        )
 9034        .await
 9035    })
 9036}
 9037
 9038async fn open_remote_project_inner(
 9039    project: Entity<Project>,
 9040    paths: Vec<PathBuf>,
 9041    workspace_id: WorkspaceId,
 9042    serialized_workspace: Option<SerializedWorkspace>,
 9043    app_state: Arc<AppState>,
 9044    window: WindowHandle<MultiWorkspace>,
 9045    cx: &mut AsyncApp,
 9046) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9047    let toolchains = DB.toolchains(workspace_id).await?;
 9048    for (toolchain, worktree_path, path) in toolchains {
 9049        project
 9050            .update(cx, |this, cx| {
 9051                let Some(worktree_id) =
 9052                    this.find_worktree(&worktree_path, cx)
 9053                        .and_then(|(worktree, rel_path)| {
 9054                            if rel_path.is_empty() {
 9055                                Some(worktree.read(cx).id())
 9056                            } else {
 9057                                None
 9058                            }
 9059                        })
 9060                else {
 9061                    return Task::ready(None);
 9062                };
 9063
 9064                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9065            })
 9066            .await;
 9067    }
 9068    let mut project_paths_to_open = vec![];
 9069    let mut project_path_errors = vec![];
 9070
 9071    for path in paths {
 9072        let result = cx
 9073            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9074            .await;
 9075        match result {
 9076            Ok((_, project_path)) => {
 9077                project_paths_to_open.push((path.clone(), Some(project_path)));
 9078            }
 9079            Err(error) => {
 9080                project_path_errors.push(error);
 9081            }
 9082        };
 9083    }
 9084
 9085    if project_paths_to_open.is_empty() {
 9086        return Err(project_path_errors.pop().context("no paths given")?);
 9087    }
 9088
 9089    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9090        telemetry::event!("SSH Project Opened");
 9091
 9092        let new_workspace = cx.new(|cx| {
 9093            let mut workspace =
 9094                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9095            workspace.update_history(cx);
 9096
 9097            if let Some(ref serialized) = serialized_workspace {
 9098                workspace.centered_layout = serialized.centered_layout;
 9099            }
 9100
 9101            workspace
 9102        });
 9103
 9104        multi_workspace.activate(new_workspace.clone(), cx);
 9105        new_workspace
 9106    })?;
 9107
 9108    let items = window
 9109        .update(cx, |_, window, cx| {
 9110            window.activate_window();
 9111            workspace.update(cx, |_workspace, cx| {
 9112                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9113            })
 9114        })?
 9115        .await?;
 9116
 9117    workspace.update(cx, |workspace, cx| {
 9118        for error in project_path_errors {
 9119            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9120                if let Some(path) = error.error_tag("path") {
 9121                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9122                }
 9123            } else {
 9124                workspace.show_error(&error, cx)
 9125            }
 9126        }
 9127    });
 9128
 9129    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9130}
 9131
 9132fn deserialize_remote_project(
 9133    connection_options: RemoteConnectionOptions,
 9134    paths: Vec<PathBuf>,
 9135    cx: &AsyncApp,
 9136) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9137    cx.background_spawn(async move {
 9138        let remote_connection_id = persistence::DB
 9139            .get_or_create_remote_connection(connection_options)
 9140            .await?;
 9141
 9142        let serialized_workspace =
 9143            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9144
 9145        let workspace_id = if let Some(workspace_id) =
 9146            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9147        {
 9148            workspace_id
 9149        } else {
 9150            persistence::DB.next_id().await?
 9151        };
 9152
 9153        Ok((workspace_id, serialized_workspace))
 9154    })
 9155}
 9156
 9157pub fn join_in_room_project(
 9158    project_id: u64,
 9159    follow_user_id: u64,
 9160    app_state: Arc<AppState>,
 9161    cx: &mut App,
 9162) -> Task<Result<()>> {
 9163    let windows = cx.windows();
 9164    cx.spawn(async move |cx| {
 9165        let existing_window_and_workspace: Option<(
 9166            WindowHandle<MultiWorkspace>,
 9167            Entity<Workspace>,
 9168        )> = windows.into_iter().find_map(|window_handle| {
 9169            window_handle
 9170                .downcast::<MultiWorkspace>()
 9171                .and_then(|window_handle| {
 9172                    window_handle
 9173                        .update(cx, |multi_workspace, _window, cx| {
 9174                            for workspace in multi_workspace.workspaces() {
 9175                                if workspace.read(cx).project().read(cx).remote_id()
 9176                                    == Some(project_id)
 9177                                {
 9178                                    return Some((window_handle, workspace.clone()));
 9179                                }
 9180                            }
 9181                            None
 9182                        })
 9183                        .unwrap_or(None)
 9184                })
 9185        });
 9186
 9187        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9188            existing_window_and_workspace
 9189        {
 9190            existing_window
 9191                .update(cx, |multi_workspace, _, cx| {
 9192                    multi_workspace.activate(target_workspace, cx);
 9193                })
 9194                .ok();
 9195            existing_window
 9196        } else {
 9197            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9198            let project = cx
 9199                .update(|cx| {
 9200                    active_call.0.join_project(
 9201                        project_id,
 9202                        app_state.languages.clone(),
 9203                        app_state.fs.clone(),
 9204                        cx,
 9205                    )
 9206                })
 9207                .await?;
 9208
 9209            let window_bounds_override = window_bounds_env_override();
 9210            cx.update(|cx| {
 9211                let mut options = (app_state.build_window_options)(None, cx);
 9212                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9213                cx.open_window(options, |window, cx| {
 9214                    let workspace = cx.new(|cx| {
 9215                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9216                    });
 9217                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9218                })
 9219            })?
 9220        };
 9221
 9222        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9223            cx.activate(true);
 9224            window.activate_window();
 9225
 9226            // We set the active workspace above, so this is the correct workspace.
 9227            let workspace = multi_workspace.workspace().clone();
 9228            workspace.update(cx, |workspace, cx| {
 9229                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9230                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9231                    .or_else(|| {
 9232                        // If we couldn't follow the given user, follow the host instead.
 9233                        let collaborator = workspace
 9234                            .project()
 9235                            .read(cx)
 9236                            .collaborators()
 9237                            .values()
 9238                            .find(|collaborator| collaborator.is_host)?;
 9239                        Some(collaborator.peer_id)
 9240                    });
 9241
 9242                if let Some(follow_peer_id) = follow_peer_id {
 9243                    workspace.follow(follow_peer_id, window, cx);
 9244                }
 9245            });
 9246        })?;
 9247
 9248        anyhow::Ok(())
 9249    })
 9250}
 9251
 9252pub fn reload(cx: &mut App) {
 9253    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9254    let mut workspace_windows = cx
 9255        .windows()
 9256        .into_iter()
 9257        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9258        .collect::<Vec<_>>();
 9259
 9260    // If multiple windows have unsaved changes, and need a save prompt,
 9261    // prompt in the active window before switching to a different window.
 9262    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9263
 9264    let mut prompt = None;
 9265    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9266        prompt = window
 9267            .update(cx, |_, window, cx| {
 9268                window.prompt(
 9269                    PromptLevel::Info,
 9270                    "Are you sure you want to restart?",
 9271                    None,
 9272                    &["Restart", "Cancel"],
 9273                    cx,
 9274                )
 9275            })
 9276            .ok();
 9277    }
 9278
 9279    cx.spawn(async move |cx| {
 9280        if let Some(prompt) = prompt {
 9281            let answer = prompt.await?;
 9282            if answer != 0 {
 9283                return anyhow::Ok(());
 9284            }
 9285        }
 9286
 9287        // If the user cancels any save prompt, then keep the app open.
 9288        for window in workspace_windows {
 9289            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9290                let workspace = multi_workspace.workspace().clone();
 9291                workspace.update(cx, |workspace, cx| {
 9292                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9293                })
 9294            }) && !should_close.await?
 9295            {
 9296                return anyhow::Ok(());
 9297            }
 9298        }
 9299        cx.update(|cx| cx.restart());
 9300        anyhow::Ok(())
 9301    })
 9302    .detach_and_log_err(cx);
 9303}
 9304
 9305fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9306    let mut parts = value.split(',');
 9307    let x: usize = parts.next()?.parse().ok()?;
 9308    let y: usize = parts.next()?.parse().ok()?;
 9309    Some(point(px(x as f32), px(y as f32)))
 9310}
 9311
 9312fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9313    let mut parts = value.split(',');
 9314    let width: usize = parts.next()?.parse().ok()?;
 9315    let height: usize = parts.next()?.parse().ok()?;
 9316    Some(size(px(width as f32), px(height as f32)))
 9317}
 9318
 9319/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9320/// appropriate.
 9321///
 9322/// The `border_radius_tiling` parameter allows overriding which corners get
 9323/// rounded, independently of the actual window tiling state. This is used
 9324/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9325/// we want square corners on the left (so the sidebar appears flush with the
 9326/// window edge) but we still need the shadow padding for proper visual
 9327/// appearance. Unlike actual window tiling, this only affects border radius -
 9328/// not padding or shadows.
 9329pub fn client_side_decorations(
 9330    element: impl IntoElement,
 9331    window: &mut Window,
 9332    cx: &mut App,
 9333    border_radius_tiling: Tiling,
 9334) -> Stateful<Div> {
 9335    const BORDER_SIZE: Pixels = px(1.0);
 9336    let decorations = window.window_decorations();
 9337    let tiling = match decorations {
 9338        Decorations::Server => Tiling::default(),
 9339        Decorations::Client { tiling } => tiling,
 9340    };
 9341
 9342    match decorations {
 9343        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9344        Decorations::Server => window.set_client_inset(px(0.0)),
 9345    }
 9346
 9347    struct GlobalResizeEdge(ResizeEdge);
 9348    impl Global for GlobalResizeEdge {}
 9349
 9350    div()
 9351        .id("window-backdrop")
 9352        .bg(transparent_black())
 9353        .map(|div| match decorations {
 9354            Decorations::Server => div,
 9355            Decorations::Client { .. } => div
 9356                .when(
 9357                    !(tiling.top
 9358                        || tiling.right
 9359                        || border_radius_tiling.top
 9360                        || border_radius_tiling.right),
 9361                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9362                )
 9363                .when(
 9364                    !(tiling.top
 9365                        || tiling.left
 9366                        || border_radius_tiling.top
 9367                        || border_radius_tiling.left),
 9368                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9369                )
 9370                .when(
 9371                    !(tiling.bottom
 9372                        || tiling.right
 9373                        || border_radius_tiling.bottom
 9374                        || border_radius_tiling.right),
 9375                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9376                )
 9377                .when(
 9378                    !(tiling.bottom
 9379                        || tiling.left
 9380                        || border_radius_tiling.bottom
 9381                        || border_radius_tiling.left),
 9382                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9383                )
 9384                .when(!tiling.top, |div| {
 9385                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9386                })
 9387                .when(!tiling.bottom, |div| {
 9388                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9389                })
 9390                .when(!tiling.left, |div| {
 9391                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9392                })
 9393                .when(!tiling.right, |div| {
 9394                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9395                })
 9396                .on_mouse_move(move |e, window, cx| {
 9397                    let size = window.window_bounds().get_bounds().size;
 9398                    let pos = e.position;
 9399
 9400                    let new_edge =
 9401                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9402
 9403                    let edge = cx.try_global::<GlobalResizeEdge>();
 9404                    if new_edge != edge.map(|edge| edge.0) {
 9405                        window
 9406                            .window_handle()
 9407                            .update(cx, |workspace, _, cx| {
 9408                                cx.notify(workspace.entity_id());
 9409                            })
 9410                            .ok();
 9411                    }
 9412                })
 9413                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9414                    let size = window.window_bounds().get_bounds().size;
 9415                    let pos = e.position;
 9416
 9417                    let edge = match resize_edge(
 9418                        pos,
 9419                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9420                        size,
 9421                        tiling,
 9422                    ) {
 9423                        Some(value) => value,
 9424                        None => return,
 9425                    };
 9426
 9427                    window.start_window_resize(edge);
 9428                }),
 9429        })
 9430        .size_full()
 9431        .child(
 9432            div()
 9433                .cursor(CursorStyle::Arrow)
 9434                .map(|div| match decorations {
 9435                    Decorations::Server => div,
 9436                    Decorations::Client { .. } => div
 9437                        .border_color(cx.theme().colors().border)
 9438                        .when(
 9439                            !(tiling.top
 9440                                || tiling.right
 9441                                || border_radius_tiling.top
 9442                                || border_radius_tiling.right),
 9443                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9444                        )
 9445                        .when(
 9446                            !(tiling.top
 9447                                || tiling.left
 9448                                || border_radius_tiling.top
 9449                                || border_radius_tiling.left),
 9450                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9451                        )
 9452                        .when(
 9453                            !(tiling.bottom
 9454                                || tiling.right
 9455                                || border_radius_tiling.bottom
 9456                                || border_radius_tiling.right),
 9457                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9458                        )
 9459                        .when(
 9460                            !(tiling.bottom
 9461                                || tiling.left
 9462                                || border_radius_tiling.bottom
 9463                                || border_radius_tiling.left),
 9464                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9465                        )
 9466                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9467                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9468                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9469                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9470                        .when(!tiling.is_tiled(), |div| {
 9471                            div.shadow(vec![gpui::BoxShadow {
 9472                                color: Hsla {
 9473                                    h: 0.,
 9474                                    s: 0.,
 9475                                    l: 0.,
 9476                                    a: 0.4,
 9477                                },
 9478                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9479                                spread_radius: px(0.),
 9480                                offset: point(px(0.0), px(0.0)),
 9481                            }])
 9482                        }),
 9483                })
 9484                .on_mouse_move(|_e, _, cx| {
 9485                    cx.stop_propagation();
 9486                })
 9487                .size_full()
 9488                .child(element),
 9489        )
 9490        .map(|div| match decorations {
 9491            Decorations::Server => div,
 9492            Decorations::Client { tiling, .. } => div.child(
 9493                canvas(
 9494                    |_bounds, window, _| {
 9495                        window.insert_hitbox(
 9496                            Bounds::new(
 9497                                point(px(0.0), px(0.0)),
 9498                                window.window_bounds().get_bounds().size,
 9499                            ),
 9500                            HitboxBehavior::Normal,
 9501                        )
 9502                    },
 9503                    move |_bounds, hitbox, window, cx| {
 9504                        let mouse = window.mouse_position();
 9505                        let size = window.window_bounds().get_bounds().size;
 9506                        let Some(edge) =
 9507                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9508                        else {
 9509                            return;
 9510                        };
 9511                        cx.set_global(GlobalResizeEdge(edge));
 9512                        window.set_cursor_style(
 9513                            match edge {
 9514                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9515                                ResizeEdge::Left | ResizeEdge::Right => {
 9516                                    CursorStyle::ResizeLeftRight
 9517                                }
 9518                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9519                                    CursorStyle::ResizeUpLeftDownRight
 9520                                }
 9521                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9522                                    CursorStyle::ResizeUpRightDownLeft
 9523                                }
 9524                            },
 9525                            &hitbox,
 9526                        );
 9527                    },
 9528                )
 9529                .size_full()
 9530                .absolute(),
 9531            ),
 9532        })
 9533}
 9534
 9535fn resize_edge(
 9536    pos: Point<Pixels>,
 9537    shadow_size: Pixels,
 9538    window_size: Size<Pixels>,
 9539    tiling: Tiling,
 9540) -> Option<ResizeEdge> {
 9541    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9542    if bounds.contains(&pos) {
 9543        return None;
 9544    }
 9545
 9546    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9547    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9548    if !tiling.top && top_left_bounds.contains(&pos) {
 9549        return Some(ResizeEdge::TopLeft);
 9550    }
 9551
 9552    let top_right_bounds = Bounds::new(
 9553        Point::new(window_size.width - corner_size.width, px(0.)),
 9554        corner_size,
 9555    );
 9556    if !tiling.top && top_right_bounds.contains(&pos) {
 9557        return Some(ResizeEdge::TopRight);
 9558    }
 9559
 9560    let bottom_left_bounds = Bounds::new(
 9561        Point::new(px(0.), window_size.height - corner_size.height),
 9562        corner_size,
 9563    );
 9564    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9565        return Some(ResizeEdge::BottomLeft);
 9566    }
 9567
 9568    let bottom_right_bounds = Bounds::new(
 9569        Point::new(
 9570            window_size.width - corner_size.width,
 9571            window_size.height - corner_size.height,
 9572        ),
 9573        corner_size,
 9574    );
 9575    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9576        return Some(ResizeEdge::BottomRight);
 9577    }
 9578
 9579    if !tiling.top && pos.y < shadow_size {
 9580        Some(ResizeEdge::Top)
 9581    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9582        Some(ResizeEdge::Bottom)
 9583    } else if !tiling.left && pos.x < shadow_size {
 9584        Some(ResizeEdge::Left)
 9585    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9586        Some(ResizeEdge::Right)
 9587    } else {
 9588        None
 9589    }
 9590}
 9591
 9592fn join_pane_into_active(
 9593    active_pane: &Entity<Pane>,
 9594    pane: &Entity<Pane>,
 9595    window: &mut Window,
 9596    cx: &mut App,
 9597) {
 9598    if pane == active_pane {
 9599    } else if pane.read(cx).items_len() == 0 {
 9600        pane.update(cx, |_, cx| {
 9601            cx.emit(pane::Event::Remove {
 9602                focus_on_pane: None,
 9603            });
 9604        })
 9605    } else {
 9606        move_all_items(pane, active_pane, window, cx);
 9607    }
 9608}
 9609
 9610fn move_all_items(
 9611    from_pane: &Entity<Pane>,
 9612    to_pane: &Entity<Pane>,
 9613    window: &mut Window,
 9614    cx: &mut App,
 9615) {
 9616    let destination_is_different = from_pane != to_pane;
 9617    let mut moved_items = 0;
 9618    for (item_ix, item_handle) in from_pane
 9619        .read(cx)
 9620        .items()
 9621        .enumerate()
 9622        .map(|(ix, item)| (ix, item.clone()))
 9623        .collect::<Vec<_>>()
 9624    {
 9625        let ix = item_ix - moved_items;
 9626        if destination_is_different {
 9627            // Close item from previous pane
 9628            from_pane.update(cx, |source, cx| {
 9629                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9630            });
 9631            moved_items += 1;
 9632        }
 9633
 9634        // This automatically removes duplicate items in the pane
 9635        to_pane.update(cx, |destination, cx| {
 9636            destination.add_item(item_handle, true, true, None, window, cx);
 9637            window.focus(&destination.focus_handle(cx), cx)
 9638        });
 9639    }
 9640}
 9641
 9642pub fn move_item(
 9643    source: &Entity<Pane>,
 9644    destination: &Entity<Pane>,
 9645    item_id_to_move: EntityId,
 9646    destination_index: usize,
 9647    activate: bool,
 9648    window: &mut Window,
 9649    cx: &mut App,
 9650) {
 9651    let Some((item_ix, item_handle)) = source
 9652        .read(cx)
 9653        .items()
 9654        .enumerate()
 9655        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9656        .map(|(ix, item)| (ix, item.clone()))
 9657    else {
 9658        // Tab was closed during drag
 9659        return;
 9660    };
 9661
 9662    if source != destination {
 9663        // Close item from previous pane
 9664        source.update(cx, |source, cx| {
 9665            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9666        });
 9667    }
 9668
 9669    // This automatically removes duplicate items in the pane
 9670    destination.update(cx, |destination, cx| {
 9671        destination.add_item_inner(
 9672            item_handle,
 9673            activate,
 9674            activate,
 9675            activate,
 9676            Some(destination_index),
 9677            window,
 9678            cx,
 9679        );
 9680        if activate {
 9681            window.focus(&destination.focus_handle(cx), cx)
 9682        }
 9683    });
 9684}
 9685
 9686pub fn move_active_item(
 9687    source: &Entity<Pane>,
 9688    destination: &Entity<Pane>,
 9689    focus_destination: bool,
 9690    close_if_empty: bool,
 9691    window: &mut Window,
 9692    cx: &mut App,
 9693) {
 9694    if source == destination {
 9695        return;
 9696    }
 9697    let Some(active_item) = source.read(cx).active_item() else {
 9698        return;
 9699    };
 9700    source.update(cx, |source_pane, cx| {
 9701        let item_id = active_item.item_id();
 9702        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9703        destination.update(cx, |target_pane, cx| {
 9704            target_pane.add_item(
 9705                active_item,
 9706                focus_destination,
 9707                focus_destination,
 9708                Some(target_pane.items_len()),
 9709                window,
 9710                cx,
 9711            );
 9712        });
 9713    });
 9714}
 9715
 9716pub fn clone_active_item(
 9717    workspace_id: Option<WorkspaceId>,
 9718    source: &Entity<Pane>,
 9719    destination: &Entity<Pane>,
 9720    focus_destination: bool,
 9721    window: &mut Window,
 9722    cx: &mut App,
 9723) {
 9724    if source == destination {
 9725        return;
 9726    }
 9727    let Some(active_item) = source.read(cx).active_item() else {
 9728        return;
 9729    };
 9730    if !active_item.can_split(cx) {
 9731        return;
 9732    }
 9733    let destination = destination.downgrade();
 9734    let task = active_item.clone_on_split(workspace_id, window, cx);
 9735    window
 9736        .spawn(cx, async move |cx| {
 9737            let Some(clone) = task.await else {
 9738                return;
 9739            };
 9740            destination
 9741                .update_in(cx, |target_pane, window, cx| {
 9742                    target_pane.add_item(
 9743                        clone,
 9744                        focus_destination,
 9745                        focus_destination,
 9746                        Some(target_pane.items_len()),
 9747                        window,
 9748                        cx,
 9749                    );
 9750                })
 9751                .log_err();
 9752        })
 9753        .detach();
 9754}
 9755
 9756#[derive(Debug)]
 9757pub struct WorkspacePosition {
 9758    pub window_bounds: Option<WindowBounds>,
 9759    pub display: Option<Uuid>,
 9760    pub centered_layout: bool,
 9761}
 9762
 9763pub fn remote_workspace_position_from_db(
 9764    connection_options: RemoteConnectionOptions,
 9765    paths_to_open: &[PathBuf],
 9766    cx: &App,
 9767) -> Task<Result<WorkspacePosition>> {
 9768    let paths = paths_to_open.to_vec();
 9769
 9770    cx.background_spawn(async move {
 9771        let remote_connection_id = persistence::DB
 9772            .get_or_create_remote_connection(connection_options)
 9773            .await
 9774            .context("fetching serialized ssh project")?;
 9775        let serialized_workspace =
 9776            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9777
 9778        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9779            (Some(WindowBounds::Windowed(bounds)), None)
 9780        } else {
 9781            let restorable_bounds = serialized_workspace
 9782                .as_ref()
 9783                .and_then(|workspace| {
 9784                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9785                })
 9786                .or_else(|| persistence::read_default_window_bounds());
 9787
 9788            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9789                (Some(serialized_bounds), Some(serialized_display))
 9790            } else {
 9791                (None, None)
 9792            }
 9793        };
 9794
 9795        let centered_layout = serialized_workspace
 9796            .as_ref()
 9797            .map(|w| w.centered_layout)
 9798            .unwrap_or(false);
 9799
 9800        Ok(WorkspacePosition {
 9801            window_bounds,
 9802            display,
 9803            centered_layout,
 9804        })
 9805    })
 9806}
 9807
 9808pub fn with_active_or_new_workspace(
 9809    cx: &mut App,
 9810    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9811) {
 9812    match cx
 9813        .active_window()
 9814        .and_then(|w| w.downcast::<MultiWorkspace>())
 9815    {
 9816        Some(multi_workspace) => {
 9817            cx.defer(move |cx| {
 9818                multi_workspace
 9819                    .update(cx, |multi_workspace, window, cx| {
 9820                        let workspace = multi_workspace.workspace().clone();
 9821                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9822                    })
 9823                    .log_err();
 9824            });
 9825        }
 9826        None => {
 9827            let app_state = AppState::global(cx);
 9828            if let Some(app_state) = app_state.upgrade() {
 9829                open_new(
 9830                    OpenOptions::default(),
 9831                    app_state,
 9832                    cx,
 9833                    move |workspace, window, cx| f(workspace, window, cx),
 9834                )
 9835                .detach_and_log_err(cx);
 9836            }
 9837        }
 9838    }
 9839}
 9840
 9841#[cfg(test)]
 9842mod tests {
 9843    use std::{cell::RefCell, rc::Rc};
 9844
 9845    use super::*;
 9846    use crate::{
 9847        dock::{PanelEvent, test::TestPanel},
 9848        item::{
 9849            ItemBufferKind, ItemEvent,
 9850            test::{TestItem, TestProjectItem},
 9851        },
 9852    };
 9853    use fs::FakeFs;
 9854    use gpui::{
 9855        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9856        UpdateGlobal, VisualTestContext, px,
 9857    };
 9858    use project::{Project, ProjectEntryId};
 9859    use serde_json::json;
 9860    use settings::SettingsStore;
 9861    use util::rel_path::rel_path;
 9862
 9863    #[gpui::test]
 9864    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9865        init_test(cx);
 9866
 9867        let fs = FakeFs::new(cx.executor());
 9868        let project = Project::test(fs, [], cx).await;
 9869        let (workspace, cx) =
 9870            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9871
 9872        // Adding an item with no ambiguity renders the tab without detail.
 9873        let item1 = cx.new(|cx| {
 9874            let mut item = TestItem::new(cx);
 9875            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9876            item
 9877        });
 9878        workspace.update_in(cx, |workspace, window, cx| {
 9879            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9880        });
 9881        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9882
 9883        // Adding an item that creates ambiguity increases the level of detail on
 9884        // both tabs.
 9885        let item2 = cx.new_window_entity(|_window, cx| {
 9886            let mut item = TestItem::new(cx);
 9887            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9888            item
 9889        });
 9890        workspace.update_in(cx, |workspace, window, cx| {
 9891            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9892        });
 9893        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9894        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9895
 9896        // Adding an item that creates ambiguity increases the level of detail only
 9897        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9898        // we stop at the highest detail available.
 9899        let item3 = cx.new(|cx| {
 9900            let mut item = TestItem::new(cx);
 9901            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9902            item
 9903        });
 9904        workspace.update_in(cx, |workspace, window, cx| {
 9905            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9906        });
 9907        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9908        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9909        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9910    }
 9911
 9912    #[gpui::test]
 9913    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9914        init_test(cx);
 9915
 9916        let fs = FakeFs::new(cx.executor());
 9917        fs.insert_tree(
 9918            "/root1",
 9919            json!({
 9920                "one.txt": "",
 9921                "two.txt": "",
 9922            }),
 9923        )
 9924        .await;
 9925        fs.insert_tree(
 9926            "/root2",
 9927            json!({
 9928                "three.txt": "",
 9929            }),
 9930        )
 9931        .await;
 9932
 9933        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9934        let (workspace, cx) =
 9935            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9936        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9937        let worktree_id = project.update(cx, |project, cx| {
 9938            project.worktrees(cx).next().unwrap().read(cx).id()
 9939        });
 9940
 9941        let item1 = cx.new(|cx| {
 9942            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9943        });
 9944        let item2 = cx.new(|cx| {
 9945            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9946        });
 9947
 9948        // Add an item to an empty pane
 9949        workspace.update_in(cx, |workspace, window, cx| {
 9950            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9951        });
 9952        project.update(cx, |project, cx| {
 9953            assert_eq!(
 9954                project.active_entry(),
 9955                project
 9956                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9957                    .map(|e| e.id)
 9958            );
 9959        });
 9960        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9961
 9962        // Add a second item to a non-empty pane
 9963        workspace.update_in(cx, |workspace, window, cx| {
 9964            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9965        });
 9966        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9967        project.update(cx, |project, cx| {
 9968            assert_eq!(
 9969                project.active_entry(),
 9970                project
 9971                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9972                    .map(|e| e.id)
 9973            );
 9974        });
 9975
 9976        // Close the active item
 9977        pane.update_in(cx, |pane, window, cx| {
 9978            pane.close_active_item(&Default::default(), window, cx)
 9979        })
 9980        .await
 9981        .unwrap();
 9982        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9983        project.update(cx, |project, cx| {
 9984            assert_eq!(
 9985                project.active_entry(),
 9986                project
 9987                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9988                    .map(|e| e.id)
 9989            );
 9990        });
 9991
 9992        // Add a project folder
 9993        project
 9994            .update(cx, |project, cx| {
 9995                project.find_or_create_worktree("root2", true, cx)
 9996            })
 9997            .await
 9998            .unwrap();
 9999        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10000
10001        // Remove a project folder
10002        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10003        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10004    }
10005
10006    #[gpui::test]
10007    async fn test_close_window(cx: &mut TestAppContext) {
10008        init_test(cx);
10009
10010        let fs = FakeFs::new(cx.executor());
10011        fs.insert_tree("/root", json!({ "one": "" })).await;
10012
10013        let project = Project::test(fs, ["root".as_ref()], cx).await;
10014        let (workspace, cx) =
10015            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10016
10017        // When there are no dirty items, there's nothing to do.
10018        let item1 = cx.new(TestItem::new);
10019        workspace.update_in(cx, |w, window, cx| {
10020            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10021        });
10022        let task = workspace.update_in(cx, |w, window, cx| {
10023            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10024        });
10025        assert!(task.await.unwrap());
10026
10027        // When there are dirty untitled items, prompt to save each one. If the user
10028        // cancels any prompt, then abort.
10029        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10030        let item3 = cx.new(|cx| {
10031            TestItem::new(cx)
10032                .with_dirty(true)
10033                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10034        });
10035        workspace.update_in(cx, |w, window, cx| {
10036            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10037            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10038        });
10039        let task = workspace.update_in(cx, |w, window, cx| {
10040            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10041        });
10042        cx.executor().run_until_parked();
10043        cx.simulate_prompt_answer("Cancel"); // cancel save all
10044        cx.executor().run_until_parked();
10045        assert!(!cx.has_pending_prompt());
10046        assert!(!task.await.unwrap());
10047    }
10048
10049    #[gpui::test]
10050    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10051        init_test(cx);
10052
10053        let fs = FakeFs::new(cx.executor());
10054        fs.insert_tree("/root", json!({ "one": "" })).await;
10055
10056        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10057        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10058        let multi_workspace_handle =
10059            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10060
10061        let workspace_a = multi_workspace_handle
10062            .read_with(cx, |mw, _| mw.workspace().clone())
10063            .unwrap();
10064
10065        let workspace_b = multi_workspace_handle
10066            .update(cx, |mw, window, cx| {
10067                mw.test_add_workspace(project_b, window, cx)
10068            })
10069            .unwrap();
10070
10071        // Activate workspace A
10072        multi_workspace_handle
10073            .update(cx, |mw, window, cx| {
10074                mw.activate_index(0, window, cx);
10075            })
10076            .unwrap();
10077
10078        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10079
10080        // Workspace A has a clean item
10081        let item_a = cx.new(TestItem::new);
10082        workspace_a.update_in(cx, |w, window, cx| {
10083            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10084        });
10085
10086        // Workspace B has a dirty item
10087        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10088        workspace_b.update_in(cx, |w, window, cx| {
10089            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10090        });
10091
10092        // Verify workspace A is active
10093        multi_workspace_handle
10094            .read_with(cx, |mw, _| {
10095                assert_eq!(mw.active_workspace_index(), 0);
10096            })
10097            .unwrap();
10098
10099        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10100        multi_workspace_handle
10101            .update(cx, |mw, window, cx| {
10102                mw.close_window(&CloseWindow, window, cx);
10103            })
10104            .unwrap();
10105        cx.run_until_parked();
10106
10107        // Workspace B should now be active since it has dirty items that need attention
10108        multi_workspace_handle
10109            .read_with(cx, |mw, _| {
10110                assert_eq!(
10111                    mw.active_workspace_index(),
10112                    1,
10113                    "workspace B should be activated when it prompts"
10114                );
10115            })
10116            .unwrap();
10117
10118        // User cancels the save prompt from workspace B
10119        cx.simulate_prompt_answer("Cancel");
10120        cx.run_until_parked();
10121
10122        // Window should still exist because workspace B's close was cancelled
10123        assert!(
10124            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10125            "window should still exist after cancelling one workspace's close"
10126        );
10127    }
10128
10129    #[gpui::test]
10130    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10131        init_test(cx);
10132
10133        // Register TestItem as a serializable item
10134        cx.update(|cx| {
10135            register_serializable_item::<TestItem>(cx);
10136        });
10137
10138        let fs = FakeFs::new(cx.executor());
10139        fs.insert_tree("/root", json!({ "one": "" })).await;
10140
10141        let project = Project::test(fs, ["root".as_ref()], cx).await;
10142        let (workspace, cx) =
10143            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10144
10145        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10146        let item1 = cx.new(|cx| {
10147            TestItem::new(cx)
10148                .with_dirty(true)
10149                .with_serialize(|| Some(Task::ready(Ok(()))))
10150        });
10151        let item2 = cx.new(|cx| {
10152            TestItem::new(cx)
10153                .with_dirty(true)
10154                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10155                .with_serialize(|| Some(Task::ready(Ok(()))))
10156        });
10157        workspace.update_in(cx, |w, window, cx| {
10158            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10159            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10160        });
10161        let task = workspace.update_in(cx, |w, window, cx| {
10162            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10163        });
10164        assert!(task.await.unwrap());
10165    }
10166
10167    #[gpui::test]
10168    async fn test_close_pane_items(cx: &mut TestAppContext) {
10169        init_test(cx);
10170
10171        let fs = FakeFs::new(cx.executor());
10172
10173        let project = Project::test(fs, None, cx).await;
10174        let (workspace, cx) =
10175            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10176
10177        let item1 = cx.new(|cx| {
10178            TestItem::new(cx)
10179                .with_dirty(true)
10180                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10181        });
10182        let item2 = cx.new(|cx| {
10183            TestItem::new(cx)
10184                .with_dirty(true)
10185                .with_conflict(true)
10186                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10187        });
10188        let item3 = cx.new(|cx| {
10189            TestItem::new(cx)
10190                .with_dirty(true)
10191                .with_conflict(true)
10192                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10193        });
10194        let item4 = cx.new(|cx| {
10195            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10196                let project_item = TestProjectItem::new_untitled(cx);
10197                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10198                project_item
10199            }])
10200        });
10201        let pane = workspace.update_in(cx, |workspace, window, cx| {
10202            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10203            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10204            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10205            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10206            workspace.active_pane().clone()
10207        });
10208
10209        let close_items = pane.update_in(cx, |pane, window, cx| {
10210            pane.activate_item(1, true, true, window, cx);
10211            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10212            let item1_id = item1.item_id();
10213            let item3_id = item3.item_id();
10214            let item4_id = item4.item_id();
10215            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10216                [item1_id, item3_id, item4_id].contains(&id)
10217            })
10218        });
10219        cx.executor().run_until_parked();
10220
10221        assert!(cx.has_pending_prompt());
10222        cx.simulate_prompt_answer("Save all");
10223
10224        cx.executor().run_until_parked();
10225
10226        // Item 1 is saved. There's a prompt to save item 3.
10227        pane.update(cx, |pane, cx| {
10228            assert_eq!(item1.read(cx).save_count, 1);
10229            assert_eq!(item1.read(cx).save_as_count, 0);
10230            assert_eq!(item1.read(cx).reload_count, 0);
10231            assert_eq!(pane.items_len(), 3);
10232            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10233        });
10234        assert!(cx.has_pending_prompt());
10235
10236        // Cancel saving item 3.
10237        cx.simulate_prompt_answer("Discard");
10238        cx.executor().run_until_parked();
10239
10240        // Item 3 is reloaded. There's a prompt to save item 4.
10241        pane.update(cx, |pane, cx| {
10242            assert_eq!(item3.read(cx).save_count, 0);
10243            assert_eq!(item3.read(cx).save_as_count, 0);
10244            assert_eq!(item3.read(cx).reload_count, 1);
10245            assert_eq!(pane.items_len(), 2);
10246            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10247        });
10248
10249        // There's a prompt for a path for item 4.
10250        cx.simulate_new_path_selection(|_| Some(Default::default()));
10251        close_items.await.unwrap();
10252
10253        // The requested items are closed.
10254        pane.update(cx, |pane, cx| {
10255            assert_eq!(item4.read(cx).save_count, 0);
10256            assert_eq!(item4.read(cx).save_as_count, 1);
10257            assert_eq!(item4.read(cx).reload_count, 0);
10258            assert_eq!(pane.items_len(), 1);
10259            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10260        });
10261    }
10262
10263    #[gpui::test]
10264    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10265        init_test(cx);
10266
10267        let fs = FakeFs::new(cx.executor());
10268        let project = Project::test(fs, [], cx).await;
10269        let (workspace, cx) =
10270            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10271
10272        // Create several workspace items with single project entries, and two
10273        // workspace items with multiple project entries.
10274        let single_entry_items = (0..=4)
10275            .map(|project_entry_id| {
10276                cx.new(|cx| {
10277                    TestItem::new(cx)
10278                        .with_dirty(true)
10279                        .with_project_items(&[dirty_project_item(
10280                            project_entry_id,
10281                            &format!("{project_entry_id}.txt"),
10282                            cx,
10283                        )])
10284                })
10285            })
10286            .collect::<Vec<_>>();
10287        let item_2_3 = cx.new(|cx| {
10288            TestItem::new(cx)
10289                .with_dirty(true)
10290                .with_buffer_kind(ItemBufferKind::Multibuffer)
10291                .with_project_items(&[
10292                    single_entry_items[2].read(cx).project_items[0].clone(),
10293                    single_entry_items[3].read(cx).project_items[0].clone(),
10294                ])
10295        });
10296        let item_3_4 = cx.new(|cx| {
10297            TestItem::new(cx)
10298                .with_dirty(true)
10299                .with_buffer_kind(ItemBufferKind::Multibuffer)
10300                .with_project_items(&[
10301                    single_entry_items[3].read(cx).project_items[0].clone(),
10302                    single_entry_items[4].read(cx).project_items[0].clone(),
10303                ])
10304        });
10305
10306        // Create two panes that contain the following project entries:
10307        //   left pane:
10308        //     multi-entry items:   (2, 3)
10309        //     single-entry items:  0, 2, 3, 4
10310        //   right pane:
10311        //     single-entry items:  4, 1
10312        //     multi-entry items:   (3, 4)
10313        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10314            let left_pane = workspace.active_pane().clone();
10315            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10316            workspace.add_item_to_active_pane(
10317                single_entry_items[0].boxed_clone(),
10318                None,
10319                true,
10320                window,
10321                cx,
10322            );
10323            workspace.add_item_to_active_pane(
10324                single_entry_items[2].boxed_clone(),
10325                None,
10326                true,
10327                window,
10328                cx,
10329            );
10330            workspace.add_item_to_active_pane(
10331                single_entry_items[3].boxed_clone(),
10332                None,
10333                true,
10334                window,
10335                cx,
10336            );
10337            workspace.add_item_to_active_pane(
10338                single_entry_items[4].boxed_clone(),
10339                None,
10340                true,
10341                window,
10342                cx,
10343            );
10344
10345            let right_pane =
10346                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10347
10348            let boxed_clone = single_entry_items[1].boxed_clone();
10349            let right_pane = window.spawn(cx, async move |cx| {
10350                right_pane.await.inspect(|right_pane| {
10351                    right_pane
10352                        .update_in(cx, |pane, window, cx| {
10353                            pane.add_item(boxed_clone, true, true, None, window, cx);
10354                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10355                        })
10356                        .unwrap();
10357                })
10358            });
10359
10360            (left_pane, right_pane)
10361        });
10362        let right_pane = right_pane.await.unwrap();
10363        cx.focus(&right_pane);
10364
10365        let close = right_pane.update_in(cx, |pane, window, cx| {
10366            pane.close_all_items(&CloseAllItems::default(), window, cx)
10367                .unwrap()
10368        });
10369        cx.executor().run_until_parked();
10370
10371        let msg = cx.pending_prompt().unwrap().0;
10372        assert!(msg.contains("1.txt"));
10373        assert!(!msg.contains("2.txt"));
10374        assert!(!msg.contains("3.txt"));
10375        assert!(!msg.contains("4.txt"));
10376
10377        // With best-effort close, cancelling item 1 keeps it open but items 4
10378        // and (3,4) still close since their entries exist in left pane.
10379        cx.simulate_prompt_answer("Cancel");
10380        close.await;
10381
10382        right_pane.read_with(cx, |pane, _| {
10383            assert_eq!(pane.items_len(), 1);
10384        });
10385
10386        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10387        left_pane
10388            .update_in(cx, |left_pane, window, cx| {
10389                left_pane.close_item_by_id(
10390                    single_entry_items[3].entity_id(),
10391                    SaveIntent::Skip,
10392                    window,
10393                    cx,
10394                )
10395            })
10396            .await
10397            .unwrap();
10398
10399        let close = left_pane.update_in(cx, |pane, window, cx| {
10400            pane.close_all_items(&CloseAllItems::default(), window, cx)
10401                .unwrap()
10402        });
10403        cx.executor().run_until_parked();
10404
10405        let details = cx.pending_prompt().unwrap().1;
10406        assert!(details.contains("0.txt"));
10407        assert!(details.contains("3.txt"));
10408        assert!(details.contains("4.txt"));
10409        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10410        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10411        // assert!(!details.contains("2.txt"));
10412
10413        cx.simulate_prompt_answer("Save all");
10414        cx.executor().run_until_parked();
10415        close.await;
10416
10417        left_pane.read_with(cx, |pane, _| {
10418            assert_eq!(pane.items_len(), 0);
10419        });
10420    }
10421
10422    #[gpui::test]
10423    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10424        init_test(cx);
10425
10426        let fs = FakeFs::new(cx.executor());
10427        let project = Project::test(fs, [], cx).await;
10428        let (workspace, cx) =
10429            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10430        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10431
10432        let item = cx.new(|cx| {
10433            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10434        });
10435        let item_id = item.entity_id();
10436        workspace.update_in(cx, |workspace, window, cx| {
10437            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10438        });
10439
10440        // Autosave on window change.
10441        item.update(cx, |item, cx| {
10442            SettingsStore::update_global(cx, |settings, cx| {
10443                settings.update_user_settings(cx, |settings| {
10444                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10445                })
10446            });
10447            item.is_dirty = true;
10448        });
10449
10450        // Deactivating the window saves the file.
10451        cx.deactivate_window();
10452        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10453
10454        // Re-activating the window doesn't save the file.
10455        cx.update(|window, _| window.activate_window());
10456        cx.executor().run_until_parked();
10457        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10458
10459        // Autosave on focus change.
10460        item.update_in(cx, |item, window, cx| {
10461            cx.focus_self(window);
10462            SettingsStore::update_global(cx, |settings, cx| {
10463                settings.update_user_settings(cx, |settings| {
10464                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10465                })
10466            });
10467            item.is_dirty = true;
10468        });
10469        // Blurring the item saves the file.
10470        item.update_in(cx, |_, window, _| window.blur());
10471        cx.executor().run_until_parked();
10472        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10473
10474        // Deactivating the window still saves the file.
10475        item.update_in(cx, |item, window, cx| {
10476            cx.focus_self(window);
10477            item.is_dirty = true;
10478        });
10479        cx.deactivate_window();
10480        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10481
10482        // Autosave after delay.
10483        item.update(cx, |item, cx| {
10484            SettingsStore::update_global(cx, |settings, cx| {
10485                settings.update_user_settings(cx, |settings| {
10486                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10487                        milliseconds: 500.into(),
10488                    });
10489                })
10490            });
10491            item.is_dirty = true;
10492            cx.emit(ItemEvent::Edit);
10493        });
10494
10495        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10496        cx.executor().advance_clock(Duration::from_millis(250));
10497        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10498
10499        // After delay expires, the file is saved.
10500        cx.executor().advance_clock(Duration::from_millis(250));
10501        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10502
10503        // Autosave after delay, should save earlier than delay if tab is closed
10504        item.update(cx, |item, cx| {
10505            item.is_dirty = true;
10506            cx.emit(ItemEvent::Edit);
10507        });
10508        cx.executor().advance_clock(Duration::from_millis(250));
10509        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10510
10511        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10512        pane.update_in(cx, |pane, window, cx| {
10513            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10514        })
10515        .await
10516        .unwrap();
10517        assert!(!cx.has_pending_prompt());
10518        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10519
10520        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10521        workspace.update_in(cx, |workspace, window, cx| {
10522            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10523        });
10524        item.update_in(cx, |item, _window, cx| {
10525            item.is_dirty = true;
10526            for project_item in &mut item.project_items {
10527                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10528            }
10529        });
10530        cx.run_until_parked();
10531        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10532
10533        // Autosave on focus change, ensuring closing the tab counts as such.
10534        item.update(cx, |item, cx| {
10535            SettingsStore::update_global(cx, |settings, cx| {
10536                settings.update_user_settings(cx, |settings| {
10537                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10538                })
10539            });
10540            item.is_dirty = true;
10541            for project_item in &mut item.project_items {
10542                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10543            }
10544        });
10545
10546        pane.update_in(cx, |pane, window, cx| {
10547            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10548        })
10549        .await
10550        .unwrap();
10551        assert!(!cx.has_pending_prompt());
10552        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10553
10554        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10555        workspace.update_in(cx, |workspace, window, cx| {
10556            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10557        });
10558        item.update_in(cx, |item, window, cx| {
10559            item.project_items[0].update(cx, |item, _| {
10560                item.entry_id = None;
10561            });
10562            item.is_dirty = true;
10563            window.blur();
10564        });
10565        cx.run_until_parked();
10566        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10567
10568        // Ensure autosave is prevented for deleted files also when closing the buffer.
10569        let _close_items = pane.update_in(cx, |pane, window, cx| {
10570            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10571        });
10572        cx.run_until_parked();
10573        assert!(cx.has_pending_prompt());
10574        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10575    }
10576
10577    #[gpui::test]
10578    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10579        init_test(cx);
10580
10581        let fs = FakeFs::new(cx.executor());
10582
10583        let project = Project::test(fs, [], cx).await;
10584        let (workspace, cx) =
10585            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10586
10587        let item = cx.new(|cx| {
10588            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10589        });
10590        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10591        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10592        let toolbar_notify_count = Rc::new(RefCell::new(0));
10593
10594        workspace.update_in(cx, |workspace, window, cx| {
10595            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10596            let toolbar_notification_count = toolbar_notify_count.clone();
10597            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10598                *toolbar_notification_count.borrow_mut() += 1
10599            })
10600            .detach();
10601        });
10602
10603        pane.read_with(cx, |pane, _| {
10604            assert!(!pane.can_navigate_backward());
10605            assert!(!pane.can_navigate_forward());
10606        });
10607
10608        item.update_in(cx, |item, _, cx| {
10609            item.set_state("one".to_string(), cx);
10610        });
10611
10612        // Toolbar must be notified to re-render the navigation buttons
10613        assert_eq!(*toolbar_notify_count.borrow(), 1);
10614
10615        pane.read_with(cx, |pane, _| {
10616            assert!(pane.can_navigate_backward());
10617            assert!(!pane.can_navigate_forward());
10618        });
10619
10620        workspace
10621            .update_in(cx, |workspace, window, cx| {
10622                workspace.go_back(pane.downgrade(), window, cx)
10623            })
10624            .await
10625            .unwrap();
10626
10627        assert_eq!(*toolbar_notify_count.borrow(), 2);
10628        pane.read_with(cx, |pane, _| {
10629            assert!(!pane.can_navigate_backward());
10630            assert!(pane.can_navigate_forward());
10631        });
10632    }
10633
10634    #[gpui::test]
10635    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10636        init_test(cx);
10637        let fs = FakeFs::new(cx.executor());
10638        let project = Project::test(fs, [], cx).await;
10639        let (workspace, cx) =
10640            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10641
10642        workspace.update_in(cx, |workspace, window, cx| {
10643            let first_item = cx.new(|cx| {
10644                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10645            });
10646            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10647            workspace.split_pane(
10648                workspace.active_pane().clone(),
10649                SplitDirection::Right,
10650                window,
10651                cx,
10652            );
10653            workspace.split_pane(
10654                workspace.active_pane().clone(),
10655                SplitDirection::Right,
10656                window,
10657                cx,
10658            );
10659        });
10660
10661        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10662            let panes = workspace.center.panes();
10663            assert!(panes.len() >= 2);
10664            (
10665                panes.first().expect("at least one pane").entity_id(),
10666                panes.last().expect("at least one pane").entity_id(),
10667            )
10668        });
10669
10670        workspace.update_in(cx, |workspace, window, cx| {
10671            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10672        });
10673        workspace.update(cx, |workspace, _| {
10674            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10675            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10676        });
10677
10678        cx.dispatch_action(ActivateLastPane);
10679
10680        workspace.update(cx, |workspace, _| {
10681            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10682        });
10683    }
10684
10685    #[gpui::test]
10686    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10687        init_test(cx);
10688        let fs = FakeFs::new(cx.executor());
10689
10690        let project = Project::test(fs, [], cx).await;
10691        let (workspace, cx) =
10692            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10693
10694        let panel = workspace.update_in(cx, |workspace, window, cx| {
10695            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10696            workspace.add_panel(panel.clone(), window, cx);
10697
10698            workspace
10699                .right_dock()
10700                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10701
10702            panel
10703        });
10704
10705        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10706        pane.update_in(cx, |pane, window, cx| {
10707            let item = cx.new(TestItem::new);
10708            pane.add_item(Box::new(item), true, true, None, window, cx);
10709        });
10710
10711        // Transfer focus from center to panel
10712        workspace.update_in(cx, |workspace, window, cx| {
10713            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10714        });
10715
10716        workspace.update_in(cx, |workspace, window, cx| {
10717            assert!(workspace.right_dock().read(cx).is_open());
10718            assert!(!panel.is_zoomed(window, cx));
10719            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10720        });
10721
10722        // Transfer focus from panel to center
10723        workspace.update_in(cx, |workspace, window, cx| {
10724            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10725        });
10726
10727        workspace.update_in(cx, |workspace, window, cx| {
10728            assert!(workspace.right_dock().read(cx).is_open());
10729            assert!(!panel.is_zoomed(window, cx));
10730            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10731        });
10732
10733        // Close the dock
10734        workspace.update_in(cx, |workspace, window, cx| {
10735            workspace.toggle_dock(DockPosition::Right, window, cx);
10736        });
10737
10738        workspace.update_in(cx, |workspace, window, cx| {
10739            assert!(!workspace.right_dock().read(cx).is_open());
10740            assert!(!panel.is_zoomed(window, cx));
10741            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10742        });
10743
10744        // Open the dock
10745        workspace.update_in(cx, |workspace, window, cx| {
10746            workspace.toggle_dock(DockPosition::Right, window, cx);
10747        });
10748
10749        workspace.update_in(cx, |workspace, window, cx| {
10750            assert!(workspace.right_dock().read(cx).is_open());
10751            assert!(!panel.is_zoomed(window, cx));
10752            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10753        });
10754
10755        // Focus and zoom panel
10756        panel.update_in(cx, |panel, window, cx| {
10757            cx.focus_self(window);
10758            panel.set_zoomed(true, window, cx)
10759        });
10760
10761        workspace.update_in(cx, |workspace, window, cx| {
10762            assert!(workspace.right_dock().read(cx).is_open());
10763            assert!(panel.is_zoomed(window, cx));
10764            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10765        });
10766
10767        // Transfer focus to the center closes the dock
10768        workspace.update_in(cx, |workspace, window, cx| {
10769            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10770        });
10771
10772        workspace.update_in(cx, |workspace, window, cx| {
10773            assert!(!workspace.right_dock().read(cx).is_open());
10774            assert!(panel.is_zoomed(window, cx));
10775            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10776        });
10777
10778        // Transferring focus back to the panel keeps it zoomed
10779        workspace.update_in(cx, |workspace, window, cx| {
10780            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10781        });
10782
10783        workspace.update_in(cx, |workspace, window, cx| {
10784            assert!(workspace.right_dock().read(cx).is_open());
10785            assert!(panel.is_zoomed(window, cx));
10786            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10787        });
10788
10789        // Close the dock while it is zoomed
10790        workspace.update_in(cx, |workspace, window, cx| {
10791            workspace.toggle_dock(DockPosition::Right, window, cx)
10792        });
10793
10794        workspace.update_in(cx, |workspace, window, cx| {
10795            assert!(!workspace.right_dock().read(cx).is_open());
10796            assert!(panel.is_zoomed(window, cx));
10797            assert!(workspace.zoomed.is_none());
10798            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10799        });
10800
10801        // Opening the dock, when it's zoomed, retains focus
10802        workspace.update_in(cx, |workspace, window, cx| {
10803            workspace.toggle_dock(DockPosition::Right, window, cx)
10804        });
10805
10806        workspace.update_in(cx, |workspace, window, cx| {
10807            assert!(workspace.right_dock().read(cx).is_open());
10808            assert!(panel.is_zoomed(window, cx));
10809            assert!(workspace.zoomed.is_some());
10810            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10811        });
10812
10813        // Unzoom and close the panel, zoom the active pane.
10814        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10815        workspace.update_in(cx, |workspace, window, cx| {
10816            workspace.toggle_dock(DockPosition::Right, window, cx)
10817        });
10818        pane.update_in(cx, |pane, window, cx| {
10819            pane.toggle_zoom(&Default::default(), window, cx)
10820        });
10821
10822        // Opening a dock unzooms the pane.
10823        workspace.update_in(cx, |workspace, window, cx| {
10824            workspace.toggle_dock(DockPosition::Right, window, cx)
10825        });
10826        workspace.update_in(cx, |workspace, window, cx| {
10827            let pane = pane.read(cx);
10828            assert!(!pane.is_zoomed());
10829            assert!(!pane.focus_handle(cx).is_focused(window));
10830            assert!(workspace.right_dock().read(cx).is_open());
10831            assert!(workspace.zoomed.is_none());
10832        });
10833    }
10834
10835    #[gpui::test]
10836    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10837        init_test(cx);
10838        let fs = FakeFs::new(cx.executor());
10839
10840        let project = Project::test(fs, [], cx).await;
10841        let (workspace, cx) =
10842            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10843
10844        let panel = workspace.update_in(cx, |workspace, window, cx| {
10845            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10846            workspace.add_panel(panel.clone(), window, cx);
10847            panel
10848        });
10849
10850        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10851        pane.update_in(cx, |pane, window, cx| {
10852            let item = cx.new(TestItem::new);
10853            pane.add_item(Box::new(item), true, true, None, window, cx);
10854        });
10855
10856        // Enable close_panel_on_toggle
10857        cx.update_global(|store: &mut SettingsStore, cx| {
10858            store.update_user_settings(cx, |settings| {
10859                settings.workspace.close_panel_on_toggle = Some(true);
10860            });
10861        });
10862
10863        // Panel starts closed. Toggling should open and focus it.
10864        workspace.update_in(cx, |workspace, window, cx| {
10865            assert!(!workspace.right_dock().read(cx).is_open());
10866            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10867        });
10868
10869        workspace.update_in(cx, |workspace, window, cx| {
10870            assert!(
10871                workspace.right_dock().read(cx).is_open(),
10872                "Dock should be open after toggling from center"
10873            );
10874            assert!(
10875                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10876                "Panel should be focused after toggling from center"
10877            );
10878        });
10879
10880        // Panel is open and focused. Toggling should close the panel and
10881        // return focus to the center.
10882        workspace.update_in(cx, |workspace, window, cx| {
10883            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10884        });
10885
10886        workspace.update_in(cx, |workspace, window, cx| {
10887            assert!(
10888                !workspace.right_dock().read(cx).is_open(),
10889                "Dock should be closed after toggling from focused panel"
10890            );
10891            assert!(
10892                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10893                "Panel should not be focused after toggling from focused panel"
10894            );
10895        });
10896
10897        // Open the dock and focus something else so the panel is open but not
10898        // focused. Toggling should focus the panel (not close it).
10899        workspace.update_in(cx, |workspace, window, cx| {
10900            workspace
10901                .right_dock()
10902                .update(cx, |dock, cx| dock.set_open(true, window, cx));
10903            window.focus(&pane.read(cx).focus_handle(cx), cx);
10904        });
10905
10906        workspace.update_in(cx, |workspace, window, cx| {
10907            assert!(workspace.right_dock().read(cx).is_open());
10908            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10909            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10910        });
10911
10912        workspace.update_in(cx, |workspace, window, cx| {
10913            assert!(
10914                workspace.right_dock().read(cx).is_open(),
10915                "Dock should remain open when toggling focuses an open-but-unfocused panel"
10916            );
10917            assert!(
10918                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10919                "Panel should be focused after toggling an open-but-unfocused panel"
10920            );
10921        });
10922
10923        // Now disable the setting and verify the original behavior: toggling
10924        // from a focused panel moves focus to center but leaves the dock open.
10925        cx.update_global(|store: &mut SettingsStore, cx| {
10926            store.update_user_settings(cx, |settings| {
10927                settings.workspace.close_panel_on_toggle = Some(false);
10928            });
10929        });
10930
10931        workspace.update_in(cx, |workspace, window, cx| {
10932            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10933        });
10934
10935        workspace.update_in(cx, |workspace, window, cx| {
10936            assert!(
10937                workspace.right_dock().read(cx).is_open(),
10938                "Dock should remain open when setting is disabled"
10939            );
10940            assert!(
10941                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10942                "Panel should not be focused after toggling with setting disabled"
10943            );
10944        });
10945    }
10946
10947    #[gpui::test]
10948    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10949        init_test(cx);
10950        let fs = FakeFs::new(cx.executor());
10951
10952        let project = Project::test(fs, [], cx).await;
10953        let (workspace, cx) =
10954            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10955
10956        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10957            workspace.active_pane().clone()
10958        });
10959
10960        // Add an item to the pane so it can be zoomed
10961        workspace.update_in(cx, |workspace, window, cx| {
10962            let item = cx.new(TestItem::new);
10963            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10964        });
10965
10966        // Initially not zoomed
10967        workspace.update_in(cx, |workspace, _window, cx| {
10968            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10969            assert!(
10970                workspace.zoomed.is_none(),
10971                "Workspace should track no zoomed pane"
10972            );
10973            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10974        });
10975
10976        // Zoom In
10977        pane.update_in(cx, |pane, window, cx| {
10978            pane.zoom_in(&crate::ZoomIn, window, cx);
10979        });
10980
10981        workspace.update_in(cx, |workspace, window, cx| {
10982            assert!(
10983                pane.read(cx).is_zoomed(),
10984                "Pane should be zoomed after ZoomIn"
10985            );
10986            assert!(
10987                workspace.zoomed.is_some(),
10988                "Workspace should track the zoomed pane"
10989            );
10990            assert!(
10991                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10992                "ZoomIn should focus the pane"
10993            );
10994        });
10995
10996        // Zoom In again is a no-op
10997        pane.update_in(cx, |pane, window, cx| {
10998            pane.zoom_in(&crate::ZoomIn, window, cx);
10999        });
11000
11001        workspace.update_in(cx, |workspace, window, cx| {
11002            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11003            assert!(
11004                workspace.zoomed.is_some(),
11005                "Workspace still tracks zoomed pane"
11006            );
11007            assert!(
11008                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11009                "Pane remains focused after repeated ZoomIn"
11010            );
11011        });
11012
11013        // Zoom Out
11014        pane.update_in(cx, |pane, window, cx| {
11015            pane.zoom_out(&crate::ZoomOut, window, cx);
11016        });
11017
11018        workspace.update_in(cx, |workspace, _window, cx| {
11019            assert!(
11020                !pane.read(cx).is_zoomed(),
11021                "Pane should unzoom after ZoomOut"
11022            );
11023            assert!(
11024                workspace.zoomed.is_none(),
11025                "Workspace clears zoom tracking after ZoomOut"
11026            );
11027        });
11028
11029        // Zoom Out again is a no-op
11030        pane.update_in(cx, |pane, window, cx| {
11031            pane.zoom_out(&crate::ZoomOut, window, cx);
11032        });
11033
11034        workspace.update_in(cx, |workspace, _window, cx| {
11035            assert!(
11036                !pane.read(cx).is_zoomed(),
11037                "Second ZoomOut keeps pane unzoomed"
11038            );
11039            assert!(
11040                workspace.zoomed.is_none(),
11041                "Workspace remains without zoomed pane"
11042            );
11043        });
11044    }
11045
11046    #[gpui::test]
11047    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11048        init_test(cx);
11049        let fs = FakeFs::new(cx.executor());
11050
11051        let project = Project::test(fs, [], cx).await;
11052        let (workspace, cx) =
11053            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11054        workspace.update_in(cx, |workspace, window, cx| {
11055            // Open two docks
11056            let left_dock = workspace.dock_at_position(DockPosition::Left);
11057            let right_dock = workspace.dock_at_position(DockPosition::Right);
11058
11059            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11060            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11061
11062            assert!(left_dock.read(cx).is_open());
11063            assert!(right_dock.read(cx).is_open());
11064        });
11065
11066        workspace.update_in(cx, |workspace, window, cx| {
11067            // Toggle all docks - should close both
11068            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11069
11070            let left_dock = workspace.dock_at_position(DockPosition::Left);
11071            let right_dock = workspace.dock_at_position(DockPosition::Right);
11072            assert!(!left_dock.read(cx).is_open());
11073            assert!(!right_dock.read(cx).is_open());
11074        });
11075
11076        workspace.update_in(cx, |workspace, window, cx| {
11077            // Toggle again - should reopen both
11078            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11079
11080            let left_dock = workspace.dock_at_position(DockPosition::Left);
11081            let right_dock = workspace.dock_at_position(DockPosition::Right);
11082            assert!(left_dock.read(cx).is_open());
11083            assert!(right_dock.read(cx).is_open());
11084        });
11085    }
11086
11087    #[gpui::test]
11088    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11089        init_test(cx);
11090        let fs = FakeFs::new(cx.executor());
11091
11092        let project = Project::test(fs, [], cx).await;
11093        let (workspace, cx) =
11094            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11095        workspace.update_in(cx, |workspace, window, cx| {
11096            // Open two docks
11097            let left_dock = workspace.dock_at_position(DockPosition::Left);
11098            let right_dock = workspace.dock_at_position(DockPosition::Right);
11099
11100            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11101            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11102
11103            assert!(left_dock.read(cx).is_open());
11104            assert!(right_dock.read(cx).is_open());
11105        });
11106
11107        workspace.update_in(cx, |workspace, window, cx| {
11108            // Close them manually
11109            workspace.toggle_dock(DockPosition::Left, window, cx);
11110            workspace.toggle_dock(DockPosition::Right, window, cx);
11111
11112            let left_dock = workspace.dock_at_position(DockPosition::Left);
11113            let right_dock = workspace.dock_at_position(DockPosition::Right);
11114            assert!(!left_dock.read(cx).is_open());
11115            assert!(!right_dock.read(cx).is_open());
11116        });
11117
11118        workspace.update_in(cx, |workspace, window, cx| {
11119            // Toggle all docks - only last closed (right dock) should reopen
11120            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11121
11122            let left_dock = workspace.dock_at_position(DockPosition::Left);
11123            let right_dock = workspace.dock_at_position(DockPosition::Right);
11124            assert!(!left_dock.read(cx).is_open());
11125            assert!(right_dock.read(cx).is_open());
11126        });
11127    }
11128
11129    #[gpui::test]
11130    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11131        init_test(cx);
11132        let fs = FakeFs::new(cx.executor());
11133        let project = Project::test(fs, [], cx).await;
11134        let (workspace, cx) =
11135            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11136
11137        // Open two docks (left and right) with one panel each
11138        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11139            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11140            workspace.add_panel(left_panel.clone(), window, cx);
11141
11142            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11143            workspace.add_panel(right_panel.clone(), window, cx);
11144
11145            workspace.toggle_dock(DockPosition::Left, window, cx);
11146            workspace.toggle_dock(DockPosition::Right, window, cx);
11147
11148            // Verify initial state
11149            assert!(
11150                workspace.left_dock().read(cx).is_open(),
11151                "Left dock should be open"
11152            );
11153            assert_eq!(
11154                workspace
11155                    .left_dock()
11156                    .read(cx)
11157                    .visible_panel()
11158                    .unwrap()
11159                    .panel_id(),
11160                left_panel.panel_id(),
11161                "Left panel should be visible in left dock"
11162            );
11163            assert!(
11164                workspace.right_dock().read(cx).is_open(),
11165                "Right dock should be open"
11166            );
11167            assert_eq!(
11168                workspace
11169                    .right_dock()
11170                    .read(cx)
11171                    .visible_panel()
11172                    .unwrap()
11173                    .panel_id(),
11174                right_panel.panel_id(),
11175                "Right panel should be visible in right dock"
11176            );
11177            assert!(
11178                !workspace.bottom_dock().read(cx).is_open(),
11179                "Bottom dock should be closed"
11180            );
11181
11182            (left_panel, right_panel)
11183        });
11184
11185        // Focus the left panel and move it to the next position (bottom dock)
11186        workspace.update_in(cx, |workspace, window, cx| {
11187            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11188            assert!(
11189                left_panel.read(cx).focus_handle(cx).is_focused(window),
11190                "Left panel should be focused"
11191            );
11192        });
11193
11194        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11195
11196        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11197        workspace.update(cx, |workspace, cx| {
11198            assert!(
11199                !workspace.left_dock().read(cx).is_open(),
11200                "Left dock should be closed"
11201            );
11202            assert!(
11203                workspace.bottom_dock().read(cx).is_open(),
11204                "Bottom dock should now be open"
11205            );
11206            assert_eq!(
11207                left_panel.read(cx).position,
11208                DockPosition::Bottom,
11209                "Left panel should now be in the bottom dock"
11210            );
11211            assert_eq!(
11212                workspace
11213                    .bottom_dock()
11214                    .read(cx)
11215                    .visible_panel()
11216                    .unwrap()
11217                    .panel_id(),
11218                left_panel.panel_id(),
11219                "Left panel should be the visible panel in the bottom dock"
11220            );
11221        });
11222
11223        // Toggle all docks off
11224        workspace.update_in(cx, |workspace, window, cx| {
11225            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11226            assert!(
11227                !workspace.left_dock().read(cx).is_open(),
11228                "Left dock should be closed"
11229            );
11230            assert!(
11231                !workspace.right_dock().read(cx).is_open(),
11232                "Right dock should be closed"
11233            );
11234            assert!(
11235                !workspace.bottom_dock().read(cx).is_open(),
11236                "Bottom dock should be closed"
11237            );
11238        });
11239
11240        // Toggle all docks back on and verify positions are restored
11241        workspace.update_in(cx, |workspace, window, cx| {
11242            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11243            assert!(
11244                !workspace.left_dock().read(cx).is_open(),
11245                "Left dock should remain closed"
11246            );
11247            assert!(
11248                workspace.right_dock().read(cx).is_open(),
11249                "Right dock should remain open"
11250            );
11251            assert!(
11252                workspace.bottom_dock().read(cx).is_open(),
11253                "Bottom dock should remain open"
11254            );
11255            assert_eq!(
11256                left_panel.read(cx).position,
11257                DockPosition::Bottom,
11258                "Left panel should remain in the bottom dock"
11259            );
11260            assert_eq!(
11261                right_panel.read(cx).position,
11262                DockPosition::Right,
11263                "Right panel should remain in the right dock"
11264            );
11265            assert_eq!(
11266                workspace
11267                    .bottom_dock()
11268                    .read(cx)
11269                    .visible_panel()
11270                    .unwrap()
11271                    .panel_id(),
11272                left_panel.panel_id(),
11273                "Left panel should be the visible panel in the right dock"
11274            );
11275        });
11276    }
11277
11278    #[gpui::test]
11279    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11280        init_test(cx);
11281
11282        let fs = FakeFs::new(cx.executor());
11283
11284        let project = Project::test(fs, None, cx).await;
11285        let (workspace, cx) =
11286            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11287
11288        // Let's arrange the panes like this:
11289        //
11290        // +-----------------------+
11291        // |         top           |
11292        // +------+--------+-------+
11293        // | left | center | right |
11294        // +------+--------+-------+
11295        // |        bottom         |
11296        // +-----------------------+
11297
11298        let top_item = cx.new(|cx| {
11299            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11300        });
11301        let bottom_item = cx.new(|cx| {
11302            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11303        });
11304        let left_item = cx.new(|cx| {
11305            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11306        });
11307        let right_item = cx.new(|cx| {
11308            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11309        });
11310        let center_item = cx.new(|cx| {
11311            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11312        });
11313
11314        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11315            let top_pane_id = workspace.active_pane().entity_id();
11316            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11317            workspace.split_pane(
11318                workspace.active_pane().clone(),
11319                SplitDirection::Down,
11320                window,
11321                cx,
11322            );
11323            top_pane_id
11324        });
11325        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11326            let bottom_pane_id = workspace.active_pane().entity_id();
11327            workspace.add_item_to_active_pane(
11328                Box::new(bottom_item.clone()),
11329                None,
11330                false,
11331                window,
11332                cx,
11333            );
11334            workspace.split_pane(
11335                workspace.active_pane().clone(),
11336                SplitDirection::Up,
11337                window,
11338                cx,
11339            );
11340            bottom_pane_id
11341        });
11342        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11343            let left_pane_id = workspace.active_pane().entity_id();
11344            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11345            workspace.split_pane(
11346                workspace.active_pane().clone(),
11347                SplitDirection::Right,
11348                window,
11349                cx,
11350            );
11351            left_pane_id
11352        });
11353        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11354            let right_pane_id = workspace.active_pane().entity_id();
11355            workspace.add_item_to_active_pane(
11356                Box::new(right_item.clone()),
11357                None,
11358                false,
11359                window,
11360                cx,
11361            );
11362            workspace.split_pane(
11363                workspace.active_pane().clone(),
11364                SplitDirection::Left,
11365                window,
11366                cx,
11367            );
11368            right_pane_id
11369        });
11370        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11371            let center_pane_id = workspace.active_pane().entity_id();
11372            workspace.add_item_to_active_pane(
11373                Box::new(center_item.clone()),
11374                None,
11375                false,
11376                window,
11377                cx,
11378            );
11379            center_pane_id
11380        });
11381        cx.executor().run_until_parked();
11382
11383        workspace.update_in(cx, |workspace, window, cx| {
11384            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11385
11386            // Join into next from center pane into right
11387            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11388        });
11389
11390        workspace.update_in(cx, |workspace, window, cx| {
11391            let active_pane = workspace.active_pane();
11392            assert_eq!(right_pane_id, active_pane.entity_id());
11393            assert_eq!(2, active_pane.read(cx).items_len());
11394            let item_ids_in_pane =
11395                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11396            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11397            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11398
11399            // Join into next from right pane into bottom
11400            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11401        });
11402
11403        workspace.update_in(cx, |workspace, window, cx| {
11404            let active_pane = workspace.active_pane();
11405            assert_eq!(bottom_pane_id, active_pane.entity_id());
11406            assert_eq!(3, active_pane.read(cx).items_len());
11407            let item_ids_in_pane =
11408                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11409            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11410            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11411            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11412
11413            // Join into next from bottom pane into left
11414            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11415        });
11416
11417        workspace.update_in(cx, |workspace, window, cx| {
11418            let active_pane = workspace.active_pane();
11419            assert_eq!(left_pane_id, active_pane.entity_id());
11420            assert_eq!(4, active_pane.read(cx).items_len());
11421            let item_ids_in_pane =
11422                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11423            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11424            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11425            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11426            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11427
11428            // Join into next from left pane into top
11429            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11430        });
11431
11432        workspace.update_in(cx, |workspace, window, cx| {
11433            let active_pane = workspace.active_pane();
11434            assert_eq!(top_pane_id, active_pane.entity_id());
11435            assert_eq!(5, active_pane.read(cx).items_len());
11436            let item_ids_in_pane =
11437                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11438            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11439            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11440            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11441            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11442            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11443
11444            // Single pane left: no-op
11445            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11446        });
11447
11448        workspace.update(cx, |workspace, _cx| {
11449            let active_pane = workspace.active_pane();
11450            assert_eq!(top_pane_id, active_pane.entity_id());
11451        });
11452    }
11453
11454    fn add_an_item_to_active_pane(
11455        cx: &mut VisualTestContext,
11456        workspace: &Entity<Workspace>,
11457        item_id: u64,
11458    ) -> Entity<TestItem> {
11459        let item = cx.new(|cx| {
11460            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11461                item_id,
11462                "item{item_id}.txt",
11463                cx,
11464            )])
11465        });
11466        workspace.update_in(cx, |workspace, window, cx| {
11467            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11468        });
11469        item
11470    }
11471
11472    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11473        workspace.update_in(cx, |workspace, window, cx| {
11474            workspace.split_pane(
11475                workspace.active_pane().clone(),
11476                SplitDirection::Right,
11477                window,
11478                cx,
11479            )
11480        })
11481    }
11482
11483    #[gpui::test]
11484    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11485        init_test(cx);
11486        let fs = FakeFs::new(cx.executor());
11487        let project = Project::test(fs, None, cx).await;
11488        let (workspace, cx) =
11489            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11490
11491        add_an_item_to_active_pane(cx, &workspace, 1);
11492        split_pane(cx, &workspace);
11493        add_an_item_to_active_pane(cx, &workspace, 2);
11494        split_pane(cx, &workspace); // empty pane
11495        split_pane(cx, &workspace);
11496        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11497
11498        cx.executor().run_until_parked();
11499
11500        workspace.update(cx, |workspace, cx| {
11501            let num_panes = workspace.panes().len();
11502            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11503            let active_item = workspace
11504                .active_pane()
11505                .read(cx)
11506                .active_item()
11507                .expect("item is in focus");
11508
11509            assert_eq!(num_panes, 4);
11510            assert_eq!(num_items_in_current_pane, 1);
11511            assert_eq!(active_item.item_id(), last_item.item_id());
11512        });
11513
11514        workspace.update_in(cx, |workspace, window, cx| {
11515            workspace.join_all_panes(window, cx);
11516        });
11517
11518        workspace.update(cx, |workspace, cx| {
11519            let num_panes = workspace.panes().len();
11520            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11521            let active_item = workspace
11522                .active_pane()
11523                .read(cx)
11524                .active_item()
11525                .expect("item is in focus");
11526
11527            assert_eq!(num_panes, 1);
11528            assert_eq!(num_items_in_current_pane, 3);
11529            assert_eq!(active_item.item_id(), last_item.item_id());
11530        });
11531    }
11532    struct TestModal(FocusHandle);
11533
11534    impl TestModal {
11535        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11536            Self(cx.focus_handle())
11537        }
11538    }
11539
11540    impl EventEmitter<DismissEvent> for TestModal {}
11541
11542    impl Focusable for TestModal {
11543        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11544            self.0.clone()
11545        }
11546    }
11547
11548    impl ModalView for TestModal {}
11549
11550    impl Render for TestModal {
11551        fn render(
11552            &mut self,
11553            _window: &mut Window,
11554            _cx: &mut Context<TestModal>,
11555        ) -> impl IntoElement {
11556            div().track_focus(&self.0)
11557        }
11558    }
11559
11560    #[gpui::test]
11561    async fn test_panels(cx: &mut gpui::TestAppContext) {
11562        init_test(cx);
11563        let fs = FakeFs::new(cx.executor());
11564
11565        let project = Project::test(fs, [], cx).await;
11566        let (workspace, cx) =
11567            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11568
11569        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11570            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11571            workspace.add_panel(panel_1.clone(), window, cx);
11572            workspace.toggle_dock(DockPosition::Left, window, cx);
11573            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11574            workspace.add_panel(panel_2.clone(), window, cx);
11575            workspace.toggle_dock(DockPosition::Right, window, cx);
11576
11577            let left_dock = workspace.left_dock();
11578            assert_eq!(
11579                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11580                panel_1.panel_id()
11581            );
11582            assert_eq!(
11583                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11584                panel_1.size(window, cx)
11585            );
11586
11587            left_dock.update(cx, |left_dock, cx| {
11588                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11589            });
11590            assert_eq!(
11591                workspace
11592                    .right_dock()
11593                    .read(cx)
11594                    .visible_panel()
11595                    .unwrap()
11596                    .panel_id(),
11597                panel_2.panel_id(),
11598            );
11599
11600            (panel_1, panel_2)
11601        });
11602
11603        // Move panel_1 to the right
11604        panel_1.update_in(cx, |panel_1, window, cx| {
11605            panel_1.set_position(DockPosition::Right, window, cx)
11606        });
11607
11608        workspace.update_in(cx, |workspace, window, cx| {
11609            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11610            // Since it was the only panel on the left, the left dock should now be closed.
11611            assert!(!workspace.left_dock().read(cx).is_open());
11612            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11613            let right_dock = workspace.right_dock();
11614            assert_eq!(
11615                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11616                panel_1.panel_id()
11617            );
11618            assert_eq!(
11619                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11620                px(1337.)
11621            );
11622
11623            // Now we move panel_2 to the left
11624            panel_2.set_position(DockPosition::Left, window, cx);
11625        });
11626
11627        workspace.update(cx, |workspace, cx| {
11628            // Since panel_2 was not visible on the right, we don't open the left dock.
11629            assert!(!workspace.left_dock().read(cx).is_open());
11630            // And the right dock is unaffected in its displaying of panel_1
11631            assert!(workspace.right_dock().read(cx).is_open());
11632            assert_eq!(
11633                workspace
11634                    .right_dock()
11635                    .read(cx)
11636                    .visible_panel()
11637                    .unwrap()
11638                    .panel_id(),
11639                panel_1.panel_id(),
11640            );
11641        });
11642
11643        // Move panel_1 back to the left
11644        panel_1.update_in(cx, |panel_1, window, cx| {
11645            panel_1.set_position(DockPosition::Left, window, cx)
11646        });
11647
11648        workspace.update_in(cx, |workspace, window, cx| {
11649            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11650            let left_dock = workspace.left_dock();
11651            assert!(left_dock.read(cx).is_open());
11652            assert_eq!(
11653                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11654                panel_1.panel_id()
11655            );
11656            assert_eq!(
11657                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11658                px(1337.)
11659            );
11660            // And the right dock should be closed as it no longer has any panels.
11661            assert!(!workspace.right_dock().read(cx).is_open());
11662
11663            // Now we move panel_1 to the bottom
11664            panel_1.set_position(DockPosition::Bottom, window, cx);
11665        });
11666
11667        workspace.update_in(cx, |workspace, window, cx| {
11668            // Since panel_1 was visible on the left, we close the left dock.
11669            assert!(!workspace.left_dock().read(cx).is_open());
11670            // The bottom dock is sized based on the panel's default size,
11671            // since the panel orientation changed from vertical to horizontal.
11672            let bottom_dock = workspace.bottom_dock();
11673            assert_eq!(
11674                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11675                panel_1.size(window, cx),
11676            );
11677            // Close bottom dock and move panel_1 back to the left.
11678            bottom_dock.update(cx, |bottom_dock, cx| {
11679                bottom_dock.set_open(false, window, cx)
11680            });
11681            panel_1.set_position(DockPosition::Left, window, cx);
11682        });
11683
11684        // Emit activated event on panel 1
11685        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11686
11687        // Now the left dock is open and panel_1 is active and focused.
11688        workspace.update_in(cx, |workspace, window, cx| {
11689            let left_dock = workspace.left_dock();
11690            assert!(left_dock.read(cx).is_open());
11691            assert_eq!(
11692                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11693                panel_1.panel_id(),
11694            );
11695            assert!(panel_1.focus_handle(cx).is_focused(window));
11696        });
11697
11698        // Emit closed event on panel 2, which is not active
11699        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11700
11701        // Wo don't close the left dock, because panel_2 wasn't the active panel
11702        workspace.update(cx, |workspace, cx| {
11703            let left_dock = workspace.left_dock();
11704            assert!(left_dock.read(cx).is_open());
11705            assert_eq!(
11706                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11707                panel_1.panel_id(),
11708            );
11709        });
11710
11711        // Emitting a ZoomIn event shows the panel as zoomed.
11712        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11713        workspace.read_with(cx, |workspace, _| {
11714            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11715            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11716        });
11717
11718        // Move panel to another dock while it is zoomed
11719        panel_1.update_in(cx, |panel, window, cx| {
11720            panel.set_position(DockPosition::Right, window, cx)
11721        });
11722        workspace.read_with(cx, |workspace, _| {
11723            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11724
11725            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11726        });
11727
11728        // This is a helper for getting a:
11729        // - valid focus on an element,
11730        // - that isn't a part of the panes and panels system of the Workspace,
11731        // - and doesn't trigger the 'on_focus_lost' API.
11732        let focus_other_view = {
11733            let workspace = workspace.clone();
11734            move |cx: &mut VisualTestContext| {
11735                workspace.update_in(cx, |workspace, window, cx| {
11736                    if workspace.active_modal::<TestModal>(cx).is_some() {
11737                        workspace.toggle_modal(window, cx, TestModal::new);
11738                        workspace.toggle_modal(window, cx, TestModal::new);
11739                    } else {
11740                        workspace.toggle_modal(window, cx, TestModal::new);
11741                    }
11742                })
11743            }
11744        };
11745
11746        // If focus is transferred to another view that's not a panel or another pane, we still show
11747        // the panel as zoomed.
11748        focus_other_view(cx);
11749        workspace.read_with(cx, |workspace, _| {
11750            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11751            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11752        });
11753
11754        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11755        workspace.update_in(cx, |_workspace, window, cx| {
11756            cx.focus_self(window);
11757        });
11758        workspace.read_with(cx, |workspace, _| {
11759            assert_eq!(workspace.zoomed, None);
11760            assert_eq!(workspace.zoomed_position, None);
11761        });
11762
11763        // If focus is transferred again to another view that's not a panel or a pane, we won't
11764        // show the panel as zoomed because it wasn't zoomed before.
11765        focus_other_view(cx);
11766        workspace.read_with(cx, |workspace, _| {
11767            assert_eq!(workspace.zoomed, None);
11768            assert_eq!(workspace.zoomed_position, None);
11769        });
11770
11771        // When the panel is activated, it is zoomed again.
11772        cx.dispatch_action(ToggleRightDock);
11773        workspace.read_with(cx, |workspace, _| {
11774            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11775            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11776        });
11777
11778        // Emitting a ZoomOut event unzooms the panel.
11779        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11780        workspace.read_with(cx, |workspace, _| {
11781            assert_eq!(workspace.zoomed, None);
11782            assert_eq!(workspace.zoomed_position, None);
11783        });
11784
11785        // Emit closed event on panel 1, which is active
11786        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11787
11788        // Now the left dock is closed, because panel_1 was the active panel
11789        workspace.update(cx, |workspace, cx| {
11790            let right_dock = workspace.right_dock();
11791            assert!(!right_dock.read(cx).is_open());
11792        });
11793    }
11794
11795    #[gpui::test]
11796    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11797        init_test(cx);
11798
11799        let fs = FakeFs::new(cx.background_executor.clone());
11800        let project = Project::test(fs, [], cx).await;
11801        let (workspace, cx) =
11802            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11803        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11804
11805        let dirty_regular_buffer = cx.new(|cx| {
11806            TestItem::new(cx)
11807                .with_dirty(true)
11808                .with_label("1.txt")
11809                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11810        });
11811        let dirty_regular_buffer_2 = cx.new(|cx| {
11812            TestItem::new(cx)
11813                .with_dirty(true)
11814                .with_label("2.txt")
11815                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11816        });
11817        let dirty_multi_buffer_with_both = cx.new(|cx| {
11818            TestItem::new(cx)
11819                .with_dirty(true)
11820                .with_buffer_kind(ItemBufferKind::Multibuffer)
11821                .with_label("Fake Project Search")
11822                .with_project_items(&[
11823                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11824                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11825                ])
11826        });
11827        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11828        workspace.update_in(cx, |workspace, window, cx| {
11829            workspace.add_item(
11830                pane.clone(),
11831                Box::new(dirty_regular_buffer.clone()),
11832                None,
11833                false,
11834                false,
11835                window,
11836                cx,
11837            );
11838            workspace.add_item(
11839                pane.clone(),
11840                Box::new(dirty_regular_buffer_2.clone()),
11841                None,
11842                false,
11843                false,
11844                window,
11845                cx,
11846            );
11847            workspace.add_item(
11848                pane.clone(),
11849                Box::new(dirty_multi_buffer_with_both.clone()),
11850                None,
11851                false,
11852                false,
11853                window,
11854                cx,
11855            );
11856        });
11857
11858        pane.update_in(cx, |pane, window, cx| {
11859            pane.activate_item(2, true, true, window, cx);
11860            assert_eq!(
11861                pane.active_item().unwrap().item_id(),
11862                multi_buffer_with_both_files_id,
11863                "Should select the multi buffer in the pane"
11864            );
11865        });
11866        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11867            pane.close_other_items(
11868                &CloseOtherItems {
11869                    save_intent: Some(SaveIntent::Save),
11870                    close_pinned: true,
11871                },
11872                None,
11873                window,
11874                cx,
11875            )
11876        });
11877        cx.background_executor.run_until_parked();
11878        assert!(!cx.has_pending_prompt());
11879        close_all_but_multi_buffer_task
11880            .await
11881            .expect("Closing all buffers but the multi buffer failed");
11882        pane.update(cx, |pane, cx| {
11883            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11884            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11885            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11886            assert_eq!(pane.items_len(), 1);
11887            assert_eq!(
11888                pane.active_item().unwrap().item_id(),
11889                multi_buffer_with_both_files_id,
11890                "Should have only the multi buffer left in the pane"
11891            );
11892            assert!(
11893                dirty_multi_buffer_with_both.read(cx).is_dirty,
11894                "The multi buffer containing the unsaved buffer should still be dirty"
11895            );
11896        });
11897
11898        dirty_regular_buffer.update(cx, |buffer, cx| {
11899            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11900        });
11901
11902        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11903            pane.close_active_item(
11904                &CloseActiveItem {
11905                    save_intent: Some(SaveIntent::Close),
11906                    close_pinned: false,
11907                },
11908                window,
11909                cx,
11910            )
11911        });
11912        cx.background_executor.run_until_parked();
11913        assert!(
11914            cx.has_pending_prompt(),
11915            "Dirty multi buffer should prompt a save dialog"
11916        );
11917        cx.simulate_prompt_answer("Save");
11918        cx.background_executor.run_until_parked();
11919        close_multi_buffer_task
11920            .await
11921            .expect("Closing the multi buffer failed");
11922        pane.update(cx, |pane, cx| {
11923            assert_eq!(
11924                dirty_multi_buffer_with_both.read(cx).save_count,
11925                1,
11926                "Multi buffer item should get be saved"
11927            );
11928            // Test impl does not save inner items, so we do not assert them
11929            assert_eq!(
11930                pane.items_len(),
11931                0,
11932                "No more items should be left in the pane"
11933            );
11934            assert!(pane.active_item().is_none());
11935        });
11936    }
11937
11938    #[gpui::test]
11939    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11940        cx: &mut TestAppContext,
11941    ) {
11942        init_test(cx);
11943
11944        let fs = FakeFs::new(cx.background_executor.clone());
11945        let project = Project::test(fs, [], cx).await;
11946        let (workspace, cx) =
11947            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11948        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11949
11950        let dirty_regular_buffer = cx.new(|cx| {
11951            TestItem::new(cx)
11952                .with_dirty(true)
11953                .with_label("1.txt")
11954                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11955        });
11956        let dirty_regular_buffer_2 = cx.new(|cx| {
11957            TestItem::new(cx)
11958                .with_dirty(true)
11959                .with_label("2.txt")
11960                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11961        });
11962        let clear_regular_buffer = cx.new(|cx| {
11963            TestItem::new(cx)
11964                .with_label("3.txt")
11965                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11966        });
11967
11968        let dirty_multi_buffer_with_both = cx.new(|cx| {
11969            TestItem::new(cx)
11970                .with_dirty(true)
11971                .with_buffer_kind(ItemBufferKind::Multibuffer)
11972                .with_label("Fake Project Search")
11973                .with_project_items(&[
11974                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11975                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11976                    clear_regular_buffer.read(cx).project_items[0].clone(),
11977                ])
11978        });
11979        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11980        workspace.update_in(cx, |workspace, window, cx| {
11981            workspace.add_item(
11982                pane.clone(),
11983                Box::new(dirty_regular_buffer.clone()),
11984                None,
11985                false,
11986                false,
11987                window,
11988                cx,
11989            );
11990            workspace.add_item(
11991                pane.clone(),
11992                Box::new(dirty_multi_buffer_with_both.clone()),
11993                None,
11994                false,
11995                false,
11996                window,
11997                cx,
11998            );
11999        });
12000
12001        pane.update_in(cx, |pane, window, cx| {
12002            pane.activate_item(1, true, true, window, cx);
12003            assert_eq!(
12004                pane.active_item().unwrap().item_id(),
12005                multi_buffer_with_both_files_id,
12006                "Should select the multi buffer in the pane"
12007            );
12008        });
12009        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12010            pane.close_active_item(
12011                &CloseActiveItem {
12012                    save_intent: None,
12013                    close_pinned: false,
12014                },
12015                window,
12016                cx,
12017            )
12018        });
12019        cx.background_executor.run_until_parked();
12020        assert!(
12021            cx.has_pending_prompt(),
12022            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12023        );
12024    }
12025
12026    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12027    /// closed when they are deleted from disk.
12028    #[gpui::test]
12029    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12030        init_test(cx);
12031
12032        // Enable the close_on_disk_deletion setting
12033        cx.update_global(|store: &mut SettingsStore, cx| {
12034            store.update_user_settings(cx, |settings| {
12035                settings.workspace.close_on_file_delete = Some(true);
12036            });
12037        });
12038
12039        let fs = FakeFs::new(cx.background_executor.clone());
12040        let project = Project::test(fs, [], cx).await;
12041        let (workspace, cx) =
12042            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12043        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12044
12045        // Create a test item that simulates a file
12046        let item = cx.new(|cx| {
12047            TestItem::new(cx)
12048                .with_label("test.txt")
12049                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12050        });
12051
12052        // Add item to workspace
12053        workspace.update_in(cx, |workspace, window, cx| {
12054            workspace.add_item(
12055                pane.clone(),
12056                Box::new(item.clone()),
12057                None,
12058                false,
12059                false,
12060                window,
12061                cx,
12062            );
12063        });
12064
12065        // Verify the item is in the pane
12066        pane.read_with(cx, |pane, _| {
12067            assert_eq!(pane.items().count(), 1);
12068        });
12069
12070        // Simulate file deletion by setting the item's deleted state
12071        item.update(cx, |item, _| {
12072            item.set_has_deleted_file(true);
12073        });
12074
12075        // Emit UpdateTab event to trigger the close behavior
12076        cx.run_until_parked();
12077        item.update(cx, |_, cx| {
12078            cx.emit(ItemEvent::UpdateTab);
12079        });
12080
12081        // Allow the close operation to complete
12082        cx.run_until_parked();
12083
12084        // Verify the item was automatically closed
12085        pane.read_with(cx, |pane, _| {
12086            assert_eq!(
12087                pane.items().count(),
12088                0,
12089                "Item should be automatically closed when file is deleted"
12090            );
12091        });
12092    }
12093
12094    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12095    /// open with a strikethrough when they are deleted from disk.
12096    #[gpui::test]
12097    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12098        init_test(cx);
12099
12100        // Ensure close_on_disk_deletion is disabled (default)
12101        cx.update_global(|store: &mut SettingsStore, cx| {
12102            store.update_user_settings(cx, |settings| {
12103                settings.workspace.close_on_file_delete = Some(false);
12104            });
12105        });
12106
12107        let fs = FakeFs::new(cx.background_executor.clone());
12108        let project = Project::test(fs, [], cx).await;
12109        let (workspace, cx) =
12110            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12111        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12112
12113        // Create a test item that simulates a file
12114        let item = cx.new(|cx| {
12115            TestItem::new(cx)
12116                .with_label("test.txt")
12117                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12118        });
12119
12120        // Add item to workspace
12121        workspace.update_in(cx, |workspace, window, cx| {
12122            workspace.add_item(
12123                pane.clone(),
12124                Box::new(item.clone()),
12125                None,
12126                false,
12127                false,
12128                window,
12129                cx,
12130            );
12131        });
12132
12133        // Verify the item is in the pane
12134        pane.read_with(cx, |pane, _| {
12135            assert_eq!(pane.items().count(), 1);
12136        });
12137
12138        // Simulate file deletion
12139        item.update(cx, |item, _| {
12140            item.set_has_deleted_file(true);
12141        });
12142
12143        // Emit UpdateTab event
12144        cx.run_until_parked();
12145        item.update(cx, |_, cx| {
12146            cx.emit(ItemEvent::UpdateTab);
12147        });
12148
12149        // Allow any potential close operation to complete
12150        cx.run_until_parked();
12151
12152        // Verify the item remains open (with strikethrough)
12153        pane.read_with(cx, |pane, _| {
12154            assert_eq!(
12155                pane.items().count(),
12156                1,
12157                "Item should remain open when close_on_disk_deletion is disabled"
12158            );
12159        });
12160
12161        // Verify the item shows as deleted
12162        item.read_with(cx, |item, _| {
12163            assert!(
12164                item.has_deleted_file,
12165                "Item should be marked as having deleted file"
12166            );
12167        });
12168    }
12169
12170    /// Tests that dirty files are not automatically closed when deleted from disk,
12171    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12172    /// unsaved changes without being prompted.
12173    #[gpui::test]
12174    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12175        init_test(cx);
12176
12177        // Enable the close_on_file_delete setting
12178        cx.update_global(|store: &mut SettingsStore, cx| {
12179            store.update_user_settings(cx, |settings| {
12180                settings.workspace.close_on_file_delete = Some(true);
12181            });
12182        });
12183
12184        let fs = FakeFs::new(cx.background_executor.clone());
12185        let project = Project::test(fs, [], cx).await;
12186        let (workspace, cx) =
12187            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12188        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12189
12190        // Create a dirty test item
12191        let item = cx.new(|cx| {
12192            TestItem::new(cx)
12193                .with_dirty(true)
12194                .with_label("test.txt")
12195                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12196        });
12197
12198        // Add item to workspace
12199        workspace.update_in(cx, |workspace, window, cx| {
12200            workspace.add_item(
12201                pane.clone(),
12202                Box::new(item.clone()),
12203                None,
12204                false,
12205                false,
12206                window,
12207                cx,
12208            );
12209        });
12210
12211        // Simulate file deletion
12212        item.update(cx, |item, _| {
12213            item.set_has_deleted_file(true);
12214        });
12215
12216        // Emit UpdateTab event to trigger the close behavior
12217        cx.run_until_parked();
12218        item.update(cx, |_, cx| {
12219            cx.emit(ItemEvent::UpdateTab);
12220        });
12221
12222        // Allow any potential close operation to complete
12223        cx.run_until_parked();
12224
12225        // Verify the item remains open (dirty files are not auto-closed)
12226        pane.read_with(cx, |pane, _| {
12227            assert_eq!(
12228                pane.items().count(),
12229                1,
12230                "Dirty items should not be automatically closed even when file is deleted"
12231            );
12232        });
12233
12234        // Verify the item is marked as deleted and still dirty
12235        item.read_with(cx, |item, _| {
12236            assert!(
12237                item.has_deleted_file,
12238                "Item should be marked as having deleted file"
12239            );
12240            assert!(item.is_dirty, "Item should still be dirty");
12241        });
12242    }
12243
12244    /// Tests that navigation history is cleaned up when files are auto-closed
12245    /// due to deletion from disk.
12246    #[gpui::test]
12247    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12248        init_test(cx);
12249
12250        // Enable the close_on_file_delete setting
12251        cx.update_global(|store: &mut SettingsStore, cx| {
12252            store.update_user_settings(cx, |settings| {
12253                settings.workspace.close_on_file_delete = Some(true);
12254            });
12255        });
12256
12257        let fs = FakeFs::new(cx.background_executor.clone());
12258        let project = Project::test(fs, [], cx).await;
12259        let (workspace, cx) =
12260            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12261        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12262
12263        // Create test items
12264        let item1 = cx.new(|cx| {
12265            TestItem::new(cx)
12266                .with_label("test1.txt")
12267                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12268        });
12269        let item1_id = item1.item_id();
12270
12271        let item2 = cx.new(|cx| {
12272            TestItem::new(cx)
12273                .with_label("test2.txt")
12274                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12275        });
12276
12277        // Add items to workspace
12278        workspace.update_in(cx, |workspace, window, cx| {
12279            workspace.add_item(
12280                pane.clone(),
12281                Box::new(item1.clone()),
12282                None,
12283                false,
12284                false,
12285                window,
12286                cx,
12287            );
12288            workspace.add_item(
12289                pane.clone(),
12290                Box::new(item2.clone()),
12291                None,
12292                false,
12293                false,
12294                window,
12295                cx,
12296            );
12297        });
12298
12299        // Activate item1 to ensure it gets navigation entries
12300        pane.update_in(cx, |pane, window, cx| {
12301            pane.activate_item(0, true, true, window, cx);
12302        });
12303
12304        // Switch to item2 and back to create navigation history
12305        pane.update_in(cx, |pane, window, cx| {
12306            pane.activate_item(1, true, true, window, cx);
12307        });
12308        cx.run_until_parked();
12309
12310        pane.update_in(cx, |pane, window, cx| {
12311            pane.activate_item(0, true, true, window, cx);
12312        });
12313        cx.run_until_parked();
12314
12315        // Simulate file deletion for item1
12316        item1.update(cx, |item, _| {
12317            item.set_has_deleted_file(true);
12318        });
12319
12320        // Emit UpdateTab event to trigger the close behavior
12321        item1.update(cx, |_, cx| {
12322            cx.emit(ItemEvent::UpdateTab);
12323        });
12324        cx.run_until_parked();
12325
12326        // Verify item1 was closed
12327        pane.read_with(cx, |pane, _| {
12328            assert_eq!(
12329                pane.items().count(),
12330                1,
12331                "Should have 1 item remaining after auto-close"
12332            );
12333        });
12334
12335        // Check navigation history after close
12336        let has_item = pane.read_with(cx, |pane, cx| {
12337            let mut has_item = false;
12338            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12339                if entry.item.id() == item1_id {
12340                    has_item = true;
12341                }
12342            });
12343            has_item
12344        });
12345
12346        assert!(
12347            !has_item,
12348            "Navigation history should not contain closed item entries"
12349        );
12350    }
12351
12352    #[gpui::test]
12353    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12354        cx: &mut TestAppContext,
12355    ) {
12356        init_test(cx);
12357
12358        let fs = FakeFs::new(cx.background_executor.clone());
12359        let project = Project::test(fs, [], cx).await;
12360        let (workspace, cx) =
12361            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12362        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12363
12364        let dirty_regular_buffer = cx.new(|cx| {
12365            TestItem::new(cx)
12366                .with_dirty(true)
12367                .with_label("1.txt")
12368                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12369        });
12370        let dirty_regular_buffer_2 = cx.new(|cx| {
12371            TestItem::new(cx)
12372                .with_dirty(true)
12373                .with_label("2.txt")
12374                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12375        });
12376        let clear_regular_buffer = cx.new(|cx| {
12377            TestItem::new(cx)
12378                .with_label("3.txt")
12379                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12380        });
12381
12382        let dirty_multi_buffer = cx.new(|cx| {
12383            TestItem::new(cx)
12384                .with_dirty(true)
12385                .with_buffer_kind(ItemBufferKind::Multibuffer)
12386                .with_label("Fake Project Search")
12387                .with_project_items(&[
12388                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12389                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12390                    clear_regular_buffer.read(cx).project_items[0].clone(),
12391                ])
12392        });
12393        workspace.update_in(cx, |workspace, window, cx| {
12394            workspace.add_item(
12395                pane.clone(),
12396                Box::new(dirty_regular_buffer.clone()),
12397                None,
12398                false,
12399                false,
12400                window,
12401                cx,
12402            );
12403            workspace.add_item(
12404                pane.clone(),
12405                Box::new(dirty_regular_buffer_2.clone()),
12406                None,
12407                false,
12408                false,
12409                window,
12410                cx,
12411            );
12412            workspace.add_item(
12413                pane.clone(),
12414                Box::new(dirty_multi_buffer.clone()),
12415                None,
12416                false,
12417                false,
12418                window,
12419                cx,
12420            );
12421        });
12422
12423        pane.update_in(cx, |pane, window, cx| {
12424            pane.activate_item(2, true, true, window, cx);
12425            assert_eq!(
12426                pane.active_item().unwrap().item_id(),
12427                dirty_multi_buffer.item_id(),
12428                "Should select the multi buffer in the pane"
12429            );
12430        });
12431        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12432            pane.close_active_item(
12433                &CloseActiveItem {
12434                    save_intent: None,
12435                    close_pinned: false,
12436                },
12437                window,
12438                cx,
12439            )
12440        });
12441        cx.background_executor.run_until_parked();
12442        assert!(
12443            !cx.has_pending_prompt(),
12444            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12445        );
12446        close_multi_buffer_task
12447            .await
12448            .expect("Closing multi buffer failed");
12449        pane.update(cx, |pane, cx| {
12450            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12451            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12452            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12453            assert_eq!(
12454                pane.items()
12455                    .map(|item| item.item_id())
12456                    .sorted()
12457                    .collect::<Vec<_>>(),
12458                vec![
12459                    dirty_regular_buffer.item_id(),
12460                    dirty_regular_buffer_2.item_id(),
12461                ],
12462                "Should have no multi buffer left in the pane"
12463            );
12464            assert!(dirty_regular_buffer.read(cx).is_dirty);
12465            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12466        });
12467    }
12468
12469    #[gpui::test]
12470    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12471        init_test(cx);
12472        let fs = FakeFs::new(cx.executor());
12473        let project = Project::test(fs, [], cx).await;
12474        let (workspace, cx) =
12475            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12476
12477        // Add a new panel to the right dock, opening the dock and setting the
12478        // focus to the new panel.
12479        let panel = workspace.update_in(cx, |workspace, window, cx| {
12480            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12481            workspace.add_panel(panel.clone(), window, cx);
12482
12483            workspace
12484                .right_dock()
12485                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12486
12487            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12488
12489            panel
12490        });
12491
12492        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12493        // panel to the next valid position which, in this case, is the left
12494        // dock.
12495        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12496        workspace.update(cx, |workspace, cx| {
12497            assert!(workspace.left_dock().read(cx).is_open());
12498            assert_eq!(panel.read(cx).position, DockPosition::Left);
12499        });
12500
12501        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12502        // panel to the next valid position which, in this case, is the bottom
12503        // dock.
12504        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12505        workspace.update(cx, |workspace, cx| {
12506            assert!(workspace.bottom_dock().read(cx).is_open());
12507            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12508        });
12509
12510        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12511        // around moving the panel to its initial position, the right dock.
12512        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12513        workspace.update(cx, |workspace, cx| {
12514            assert!(workspace.right_dock().read(cx).is_open());
12515            assert_eq!(panel.read(cx).position, DockPosition::Right);
12516        });
12517
12518        // Remove focus from the panel, ensuring that, if the panel is not
12519        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12520        // the panel's position, so the panel is still in the right dock.
12521        workspace.update_in(cx, |workspace, window, cx| {
12522            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12523        });
12524
12525        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12526        workspace.update(cx, |workspace, cx| {
12527            assert!(workspace.right_dock().read(cx).is_open());
12528            assert_eq!(panel.read(cx).position, DockPosition::Right);
12529        });
12530    }
12531
12532    #[gpui::test]
12533    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12534        init_test(cx);
12535
12536        let fs = FakeFs::new(cx.executor());
12537        let project = Project::test(fs, [], cx).await;
12538        let (workspace, cx) =
12539            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12540
12541        let item_1 = cx.new(|cx| {
12542            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12543        });
12544        workspace.update_in(cx, |workspace, window, cx| {
12545            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12546            workspace.move_item_to_pane_in_direction(
12547                &MoveItemToPaneInDirection {
12548                    direction: SplitDirection::Right,
12549                    focus: true,
12550                    clone: false,
12551                },
12552                window,
12553                cx,
12554            );
12555            workspace.move_item_to_pane_at_index(
12556                &MoveItemToPane {
12557                    destination: 3,
12558                    focus: true,
12559                    clone: false,
12560                },
12561                window,
12562                cx,
12563            );
12564
12565            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12566            assert_eq!(
12567                pane_items_paths(&workspace.active_pane, cx),
12568                vec!["first.txt".to_string()],
12569                "Single item was not moved anywhere"
12570            );
12571        });
12572
12573        let item_2 = cx.new(|cx| {
12574            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12575        });
12576        workspace.update_in(cx, |workspace, window, cx| {
12577            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12578            assert_eq!(
12579                pane_items_paths(&workspace.panes[0], cx),
12580                vec!["first.txt".to_string(), "second.txt".to_string()],
12581            );
12582            workspace.move_item_to_pane_in_direction(
12583                &MoveItemToPaneInDirection {
12584                    direction: SplitDirection::Right,
12585                    focus: true,
12586                    clone: false,
12587                },
12588                window,
12589                cx,
12590            );
12591
12592            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12593            assert_eq!(
12594                pane_items_paths(&workspace.panes[0], cx),
12595                vec!["first.txt".to_string()],
12596                "After moving, one item should be left in the original pane"
12597            );
12598            assert_eq!(
12599                pane_items_paths(&workspace.panes[1], cx),
12600                vec!["second.txt".to_string()],
12601                "New item should have been moved to the new pane"
12602            );
12603        });
12604
12605        let item_3 = cx.new(|cx| {
12606            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12607        });
12608        workspace.update_in(cx, |workspace, window, cx| {
12609            let original_pane = workspace.panes[0].clone();
12610            workspace.set_active_pane(&original_pane, window, cx);
12611            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12612            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12613            assert_eq!(
12614                pane_items_paths(&workspace.active_pane, cx),
12615                vec!["first.txt".to_string(), "third.txt".to_string()],
12616                "New pane should be ready to move one item out"
12617            );
12618
12619            workspace.move_item_to_pane_at_index(
12620                &MoveItemToPane {
12621                    destination: 3,
12622                    focus: true,
12623                    clone: false,
12624                },
12625                window,
12626                cx,
12627            );
12628            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12629            assert_eq!(
12630                pane_items_paths(&workspace.active_pane, cx),
12631                vec!["first.txt".to_string()],
12632                "After moving, one item should be left in the original pane"
12633            );
12634            assert_eq!(
12635                pane_items_paths(&workspace.panes[1], cx),
12636                vec!["second.txt".to_string()],
12637                "Previously created pane should be unchanged"
12638            );
12639            assert_eq!(
12640                pane_items_paths(&workspace.panes[2], cx),
12641                vec!["third.txt".to_string()],
12642                "New item should have been moved to the new pane"
12643            );
12644        });
12645    }
12646
12647    #[gpui::test]
12648    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12649        init_test(cx);
12650
12651        let fs = FakeFs::new(cx.executor());
12652        let project = Project::test(fs, [], cx).await;
12653        let (workspace, cx) =
12654            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12655
12656        let item_1 = cx.new(|cx| {
12657            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12658        });
12659        workspace.update_in(cx, |workspace, window, cx| {
12660            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12661            workspace.move_item_to_pane_in_direction(
12662                &MoveItemToPaneInDirection {
12663                    direction: SplitDirection::Right,
12664                    focus: true,
12665                    clone: true,
12666                },
12667                window,
12668                cx,
12669            );
12670        });
12671        cx.run_until_parked();
12672        workspace.update_in(cx, |workspace, window, cx| {
12673            workspace.move_item_to_pane_at_index(
12674                &MoveItemToPane {
12675                    destination: 3,
12676                    focus: true,
12677                    clone: true,
12678                },
12679                window,
12680                cx,
12681            );
12682        });
12683        cx.run_until_parked();
12684
12685        workspace.update(cx, |workspace, cx| {
12686            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12687            for pane in workspace.panes() {
12688                assert_eq!(
12689                    pane_items_paths(pane, cx),
12690                    vec!["first.txt".to_string()],
12691                    "Single item exists in all panes"
12692                );
12693            }
12694        });
12695
12696        // verify that the active pane has been updated after waiting for the
12697        // pane focus event to fire and resolve
12698        workspace.read_with(cx, |workspace, _app| {
12699            assert_eq!(
12700                workspace.active_pane(),
12701                &workspace.panes[2],
12702                "The third pane should be the active one: {:?}",
12703                workspace.panes
12704            );
12705        })
12706    }
12707
12708    #[gpui::test]
12709    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12710        init_test(cx);
12711
12712        let fs = FakeFs::new(cx.executor());
12713        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12714
12715        let project = Project::test(fs, ["root".as_ref()], cx).await;
12716        let (workspace, cx) =
12717            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12718
12719        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12720        // Add item to pane A with project path
12721        let item_a = cx.new(|cx| {
12722            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12723        });
12724        workspace.update_in(cx, |workspace, window, cx| {
12725            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12726        });
12727
12728        // Split to create pane B
12729        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12730            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12731        });
12732
12733        // Add item with SAME project path to pane B, and pin it
12734        let item_b = cx.new(|cx| {
12735            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12736        });
12737        pane_b.update_in(cx, |pane, window, cx| {
12738            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12739            pane.set_pinned_count(1);
12740        });
12741
12742        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12743        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12744
12745        // close_pinned: false should only close the unpinned copy
12746        workspace.update_in(cx, |workspace, window, cx| {
12747            workspace.close_item_in_all_panes(
12748                &CloseItemInAllPanes {
12749                    save_intent: Some(SaveIntent::Close),
12750                    close_pinned: false,
12751                },
12752                window,
12753                cx,
12754            )
12755        });
12756        cx.executor().run_until_parked();
12757
12758        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12759        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12760        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12761        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12762
12763        // Split again, seeing as closing the previous item also closed its
12764        // pane, so only pane remains, which does not allow us to properly test
12765        // that both items close when `close_pinned: true`.
12766        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12767            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12768        });
12769
12770        // Add an item with the same project path to pane C so that
12771        // close_item_in_all_panes can determine what to close across all panes
12772        // (it reads the active item from the active pane, and split_pane
12773        // creates an empty pane).
12774        let item_c = cx.new(|cx| {
12775            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12776        });
12777        pane_c.update_in(cx, |pane, window, cx| {
12778            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12779        });
12780
12781        // close_pinned: true should close the pinned copy too
12782        workspace.update_in(cx, |workspace, window, cx| {
12783            let panes_count = workspace.panes().len();
12784            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12785
12786            workspace.close_item_in_all_panes(
12787                &CloseItemInAllPanes {
12788                    save_intent: Some(SaveIntent::Close),
12789                    close_pinned: true,
12790                },
12791                window,
12792                cx,
12793            )
12794        });
12795        cx.executor().run_until_parked();
12796
12797        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12798        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12799        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12800        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12801    }
12802
12803    mod register_project_item_tests {
12804
12805        use super::*;
12806
12807        // View
12808        struct TestPngItemView {
12809            focus_handle: FocusHandle,
12810        }
12811        // Model
12812        struct TestPngItem {}
12813
12814        impl project::ProjectItem for TestPngItem {
12815            fn try_open(
12816                _project: &Entity<Project>,
12817                path: &ProjectPath,
12818                cx: &mut App,
12819            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12820                if path.path.extension().unwrap() == "png" {
12821                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12822                } else {
12823                    None
12824                }
12825            }
12826
12827            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12828                None
12829            }
12830
12831            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12832                None
12833            }
12834
12835            fn is_dirty(&self) -> bool {
12836                false
12837            }
12838        }
12839
12840        impl Item for TestPngItemView {
12841            type Event = ();
12842            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12843                "".into()
12844            }
12845        }
12846        impl EventEmitter<()> for TestPngItemView {}
12847        impl Focusable for TestPngItemView {
12848            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12849                self.focus_handle.clone()
12850            }
12851        }
12852
12853        impl Render for TestPngItemView {
12854            fn render(
12855                &mut self,
12856                _window: &mut Window,
12857                _cx: &mut Context<Self>,
12858            ) -> impl IntoElement {
12859                Empty
12860            }
12861        }
12862
12863        impl ProjectItem for TestPngItemView {
12864            type Item = TestPngItem;
12865
12866            fn for_project_item(
12867                _project: Entity<Project>,
12868                _pane: Option<&Pane>,
12869                _item: Entity<Self::Item>,
12870                _: &mut Window,
12871                cx: &mut Context<Self>,
12872            ) -> Self
12873            where
12874                Self: Sized,
12875            {
12876                Self {
12877                    focus_handle: cx.focus_handle(),
12878                }
12879            }
12880        }
12881
12882        // View
12883        struct TestIpynbItemView {
12884            focus_handle: FocusHandle,
12885        }
12886        // Model
12887        struct TestIpynbItem {}
12888
12889        impl project::ProjectItem for TestIpynbItem {
12890            fn try_open(
12891                _project: &Entity<Project>,
12892                path: &ProjectPath,
12893                cx: &mut App,
12894            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12895                if path.path.extension().unwrap() == "ipynb" {
12896                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12897                } else {
12898                    None
12899                }
12900            }
12901
12902            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12903                None
12904            }
12905
12906            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12907                None
12908            }
12909
12910            fn is_dirty(&self) -> bool {
12911                false
12912            }
12913        }
12914
12915        impl Item for TestIpynbItemView {
12916            type Event = ();
12917            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12918                "".into()
12919            }
12920        }
12921        impl EventEmitter<()> for TestIpynbItemView {}
12922        impl Focusable for TestIpynbItemView {
12923            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12924                self.focus_handle.clone()
12925            }
12926        }
12927
12928        impl Render for TestIpynbItemView {
12929            fn render(
12930                &mut self,
12931                _window: &mut Window,
12932                _cx: &mut Context<Self>,
12933            ) -> impl IntoElement {
12934                Empty
12935            }
12936        }
12937
12938        impl ProjectItem for TestIpynbItemView {
12939            type Item = TestIpynbItem;
12940
12941            fn for_project_item(
12942                _project: Entity<Project>,
12943                _pane: Option<&Pane>,
12944                _item: Entity<Self::Item>,
12945                _: &mut Window,
12946                cx: &mut Context<Self>,
12947            ) -> Self
12948            where
12949                Self: Sized,
12950            {
12951                Self {
12952                    focus_handle: cx.focus_handle(),
12953                }
12954            }
12955        }
12956
12957        struct TestAlternatePngItemView {
12958            focus_handle: FocusHandle,
12959        }
12960
12961        impl Item for TestAlternatePngItemView {
12962            type Event = ();
12963            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12964                "".into()
12965            }
12966        }
12967
12968        impl EventEmitter<()> for TestAlternatePngItemView {}
12969        impl Focusable for TestAlternatePngItemView {
12970            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12971                self.focus_handle.clone()
12972            }
12973        }
12974
12975        impl Render for TestAlternatePngItemView {
12976            fn render(
12977                &mut self,
12978                _window: &mut Window,
12979                _cx: &mut Context<Self>,
12980            ) -> impl IntoElement {
12981                Empty
12982            }
12983        }
12984
12985        impl ProjectItem for TestAlternatePngItemView {
12986            type Item = TestPngItem;
12987
12988            fn for_project_item(
12989                _project: Entity<Project>,
12990                _pane: Option<&Pane>,
12991                _item: Entity<Self::Item>,
12992                _: &mut Window,
12993                cx: &mut Context<Self>,
12994            ) -> Self
12995            where
12996                Self: Sized,
12997            {
12998                Self {
12999                    focus_handle: cx.focus_handle(),
13000                }
13001            }
13002        }
13003
13004        #[gpui::test]
13005        async fn test_register_project_item(cx: &mut TestAppContext) {
13006            init_test(cx);
13007
13008            cx.update(|cx| {
13009                register_project_item::<TestPngItemView>(cx);
13010                register_project_item::<TestIpynbItemView>(cx);
13011            });
13012
13013            let fs = FakeFs::new(cx.executor());
13014            fs.insert_tree(
13015                "/root1",
13016                json!({
13017                    "one.png": "BINARYDATAHERE",
13018                    "two.ipynb": "{ totally a notebook }",
13019                    "three.txt": "editing text, sure why not?"
13020                }),
13021            )
13022            .await;
13023
13024            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13025            let (workspace, cx) =
13026                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13027
13028            let worktree_id = project.update(cx, |project, cx| {
13029                project.worktrees(cx).next().unwrap().read(cx).id()
13030            });
13031
13032            let handle = workspace
13033                .update_in(cx, |workspace, window, cx| {
13034                    let project_path = (worktree_id, rel_path("one.png"));
13035                    workspace.open_path(project_path, None, true, window, cx)
13036                })
13037                .await
13038                .unwrap();
13039
13040            // Now we can check if the handle we got back errored or not
13041            assert_eq!(
13042                handle.to_any_view().entity_type(),
13043                TypeId::of::<TestPngItemView>()
13044            );
13045
13046            let handle = workspace
13047                .update_in(cx, |workspace, window, cx| {
13048                    let project_path = (worktree_id, rel_path("two.ipynb"));
13049                    workspace.open_path(project_path, None, true, window, cx)
13050                })
13051                .await
13052                .unwrap();
13053
13054            assert_eq!(
13055                handle.to_any_view().entity_type(),
13056                TypeId::of::<TestIpynbItemView>()
13057            );
13058
13059            let handle = workspace
13060                .update_in(cx, |workspace, window, cx| {
13061                    let project_path = (worktree_id, rel_path("three.txt"));
13062                    workspace.open_path(project_path, None, true, window, cx)
13063                })
13064                .await;
13065            assert!(handle.is_err());
13066        }
13067
13068        #[gpui::test]
13069        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13070            init_test(cx);
13071
13072            cx.update(|cx| {
13073                register_project_item::<TestPngItemView>(cx);
13074                register_project_item::<TestAlternatePngItemView>(cx);
13075            });
13076
13077            let fs = FakeFs::new(cx.executor());
13078            fs.insert_tree(
13079                "/root1",
13080                json!({
13081                    "one.png": "BINARYDATAHERE",
13082                    "two.ipynb": "{ totally a notebook }",
13083                    "three.txt": "editing text, sure why not?"
13084                }),
13085            )
13086            .await;
13087            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13088            let (workspace, cx) =
13089                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13090            let worktree_id = project.update(cx, |project, cx| {
13091                project.worktrees(cx).next().unwrap().read(cx).id()
13092            });
13093
13094            let handle = workspace
13095                .update_in(cx, |workspace, window, cx| {
13096                    let project_path = (worktree_id, rel_path("one.png"));
13097                    workspace.open_path(project_path, None, true, window, cx)
13098                })
13099                .await
13100                .unwrap();
13101
13102            // This _must_ be the second item registered
13103            assert_eq!(
13104                handle.to_any_view().entity_type(),
13105                TypeId::of::<TestAlternatePngItemView>()
13106            );
13107
13108            let handle = workspace
13109                .update_in(cx, |workspace, window, cx| {
13110                    let project_path = (worktree_id, rel_path("three.txt"));
13111                    workspace.open_path(project_path, None, true, window, cx)
13112                })
13113                .await;
13114            assert!(handle.is_err());
13115        }
13116    }
13117
13118    #[gpui::test]
13119    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13120        init_test(cx);
13121
13122        let fs = FakeFs::new(cx.executor());
13123        let project = Project::test(fs, [], cx).await;
13124        let (workspace, _cx) =
13125            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13126
13127        // Test with status bar shown (default)
13128        workspace.read_with(cx, |workspace, cx| {
13129            let visible = workspace.status_bar_visible(cx);
13130            assert!(visible, "Status bar should be visible by default");
13131        });
13132
13133        // Test with status bar hidden
13134        cx.update_global(|store: &mut SettingsStore, cx| {
13135            store.update_user_settings(cx, |settings| {
13136                settings.status_bar.get_or_insert_default().show = Some(false);
13137            });
13138        });
13139
13140        workspace.read_with(cx, |workspace, cx| {
13141            let visible = workspace.status_bar_visible(cx);
13142            assert!(!visible, "Status bar should be hidden when show is false");
13143        });
13144
13145        // Test with status bar shown explicitly
13146        cx.update_global(|store: &mut SettingsStore, cx| {
13147            store.update_user_settings(cx, |settings| {
13148                settings.status_bar.get_or_insert_default().show = Some(true);
13149            });
13150        });
13151
13152        workspace.read_with(cx, |workspace, cx| {
13153            let visible = workspace.status_bar_visible(cx);
13154            assert!(visible, "Status bar should be visible when show is true");
13155        });
13156    }
13157
13158    #[gpui::test]
13159    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13160        init_test(cx);
13161
13162        let fs = FakeFs::new(cx.executor());
13163        let project = Project::test(fs, [], cx).await;
13164        let (workspace, cx) =
13165            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13166        let panel = workspace.update_in(cx, |workspace, window, cx| {
13167            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13168            workspace.add_panel(panel.clone(), window, cx);
13169
13170            workspace
13171                .right_dock()
13172                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13173
13174            panel
13175        });
13176
13177        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13178        let item_a = cx.new(TestItem::new);
13179        let item_b = cx.new(TestItem::new);
13180        let item_a_id = item_a.entity_id();
13181        let item_b_id = item_b.entity_id();
13182
13183        pane.update_in(cx, |pane, window, cx| {
13184            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13185            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13186        });
13187
13188        pane.read_with(cx, |pane, _| {
13189            assert_eq!(pane.items_len(), 2);
13190            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13191        });
13192
13193        workspace.update_in(cx, |workspace, window, cx| {
13194            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13195        });
13196
13197        workspace.update_in(cx, |_, window, cx| {
13198            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13199        });
13200
13201        // Assert that the `pane::CloseActiveItem` action is handled at the
13202        // workspace level when one of the dock panels is focused and, in that
13203        // case, the center pane's active item is closed but the focus is not
13204        // moved.
13205        cx.dispatch_action(pane::CloseActiveItem::default());
13206        cx.run_until_parked();
13207
13208        pane.read_with(cx, |pane, _| {
13209            assert_eq!(pane.items_len(), 1);
13210            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13211        });
13212
13213        workspace.update_in(cx, |workspace, window, cx| {
13214            assert!(workspace.right_dock().read(cx).is_open());
13215            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13216        });
13217    }
13218
13219    #[gpui::test]
13220    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13221        init_test(cx);
13222        let fs = FakeFs::new(cx.executor());
13223
13224        let project_a = Project::test(fs.clone(), [], cx).await;
13225        let project_b = Project::test(fs, [], cx).await;
13226
13227        let multi_workspace_handle =
13228            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13229
13230        let workspace_a = multi_workspace_handle
13231            .read_with(cx, |mw, _| mw.workspace().clone())
13232            .unwrap();
13233
13234        let _workspace_b = multi_workspace_handle
13235            .update(cx, |mw, window, cx| {
13236                mw.test_add_workspace(project_b, window, cx)
13237            })
13238            .unwrap();
13239
13240        // Switch to workspace A
13241        multi_workspace_handle
13242            .update(cx, |mw, window, cx| {
13243                mw.activate_index(0, window, cx);
13244            })
13245            .unwrap();
13246
13247        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13248
13249        // Add a panel to workspace A's right dock and open the dock
13250        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13251            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13252            workspace.add_panel(panel.clone(), window, cx);
13253            workspace
13254                .right_dock()
13255                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13256            panel
13257        });
13258
13259        // Focus the panel through the workspace (matching existing test pattern)
13260        workspace_a.update_in(cx, |workspace, window, cx| {
13261            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13262        });
13263
13264        // Zoom the panel
13265        panel.update_in(cx, |panel, window, cx| {
13266            panel.set_zoomed(true, window, cx);
13267        });
13268
13269        // Verify the panel is zoomed and the dock is open
13270        workspace_a.update_in(cx, |workspace, window, cx| {
13271            assert!(
13272                workspace.right_dock().read(cx).is_open(),
13273                "dock should be open before switch"
13274            );
13275            assert!(
13276                panel.is_zoomed(window, cx),
13277                "panel should be zoomed before switch"
13278            );
13279            assert!(
13280                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13281                "panel should be focused before switch"
13282            );
13283        });
13284
13285        // Switch to workspace B
13286        multi_workspace_handle
13287            .update(cx, |mw, window, cx| {
13288                mw.activate_index(1, window, cx);
13289            })
13290            .unwrap();
13291        cx.run_until_parked();
13292
13293        // Switch back to workspace A
13294        multi_workspace_handle
13295            .update(cx, |mw, window, cx| {
13296                mw.activate_index(0, window, cx);
13297            })
13298            .unwrap();
13299        cx.run_until_parked();
13300
13301        // Verify the panel is still zoomed and the dock is still open
13302        workspace_a.update_in(cx, |workspace, window, cx| {
13303            assert!(
13304                workspace.right_dock().read(cx).is_open(),
13305                "dock should still be open after switching back"
13306            );
13307            assert!(
13308                panel.is_zoomed(window, cx),
13309                "panel should still be zoomed after switching back"
13310            );
13311        });
13312    }
13313
13314    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13315        pane.read(cx)
13316            .items()
13317            .flat_map(|item| {
13318                item.project_paths(cx)
13319                    .into_iter()
13320                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13321            })
13322            .collect()
13323    }
13324
13325    pub fn init_test(cx: &mut TestAppContext) {
13326        cx.update(|cx| {
13327            let settings_store = SettingsStore::test(cx);
13328            cx.set_global(settings_store);
13329            theme::init(theme::LoadThemes::JustBase, cx);
13330        });
13331    }
13332
13333    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13334        let item = TestProjectItem::new(id, path, cx);
13335        item.update(cx, |item, _| {
13336            item.is_dirty = true;
13337        });
13338        item
13339    }
13340
13341    #[gpui::test]
13342    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13343        cx: &mut gpui::TestAppContext,
13344    ) {
13345        init_test(cx);
13346        let fs = FakeFs::new(cx.executor());
13347
13348        let project = Project::test(fs, [], cx).await;
13349        let (workspace, cx) =
13350            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13351
13352        let panel = workspace.update_in(cx, |workspace, window, cx| {
13353            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13354            workspace.add_panel(panel.clone(), window, cx);
13355            workspace
13356                .right_dock()
13357                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13358            panel
13359        });
13360
13361        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13362        pane.update_in(cx, |pane, window, cx| {
13363            let item = cx.new(TestItem::new);
13364            pane.add_item(Box::new(item), true, true, None, window, cx);
13365        });
13366
13367        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13368        // mirrors the real-world flow and avoids side effects from directly
13369        // focusing the panel while the center pane is active.
13370        workspace.update_in(cx, |workspace, window, cx| {
13371            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13372        });
13373
13374        panel.update_in(cx, |panel, window, cx| {
13375            panel.set_zoomed(true, window, cx);
13376        });
13377
13378        workspace.update_in(cx, |workspace, window, cx| {
13379            assert!(workspace.right_dock().read(cx).is_open());
13380            assert!(panel.is_zoomed(window, cx));
13381            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13382        });
13383
13384        // Simulate a spurious pane::Event::Focus on the center pane while the
13385        // panel still has focus. This mirrors what happens during macOS window
13386        // activation: the center pane fires a focus event even though actual
13387        // focus remains on the dock panel.
13388        pane.update_in(cx, |_, _, cx| {
13389            cx.emit(pane::Event::Focus);
13390        });
13391
13392        // The dock must remain open because the panel had focus at the time the
13393        // event was processed. Before the fix, dock_to_preserve was None for
13394        // panels that don't implement pane(), causing the dock to close.
13395        workspace.update_in(cx, |workspace, window, cx| {
13396            assert!(
13397                workspace.right_dock().read(cx).is_open(),
13398                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13399            );
13400            assert!(panel.is_zoomed(window, cx));
13401        });
13402    }
13403}