workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6pub mod notifications;
    7pub mod pane;
    8pub mod pane_group;
    9mod path_list;
   10mod persistence;
   11pub mod searchable;
   12mod security_modal;
   13pub mod shared_screen;
   14mod status_bar;
   15pub mod tasks;
   16mod theme_preview;
   17mod toast_layer;
   18mod toolbar;
   19pub mod utility_pane;
   20pub mod welcome;
   21mod workspace_settings;
   22
   23pub use crate::notifications::NotificationFrame;
   24pub use dock::Panel;
   25pub use path_list::PathList;
   26pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   27
   28use anyhow::{Context as _, Result, anyhow};
   29use call::{ActiveCall, call_settings::CallSettings};
   30use client::{
   31    ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
   32    proto::{self, ErrorCode, PanelId, PeerId},
   33};
   34use collections::{HashMap, HashSet, hash_map};
   35use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   36use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   37use futures::{
   38    Future, FutureExt, StreamExt,
   39    channel::{
   40        mpsc::{self, UnboundedReceiver, UnboundedSender},
   41        oneshot,
   42    },
   43    future::{Shared, try_join_all},
   44};
   45use gpui::{
   46    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   47    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   48    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   49    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   50    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   51    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   52};
   53pub use history_manager::*;
   54pub use item::{
   55    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   56    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   57};
   58use itertools::Itertools;
   59use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   60pub use modal_layer::*;
   61use node_runtime::NodeRuntime;
   62use notifications::{
   63    DetachAndPromptErr, Notifications, dismiss_app_notification,
   64    simple_message_notification::MessageNotification,
   65};
   66pub use pane::*;
   67pub use pane_group::{
   68    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   69    SplitDirection,
   70};
   71use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   72pub use persistence::{
   73    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   74    model::{ItemId, SerializedWorkspaceLocation},
   75};
   76use postage::stream::Stream;
   77use project::{
   78    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   79    WorktreeSettings,
   80    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   81    project_settings::ProjectSettings,
   82    toolchain_store::ToolchainStoreEvent,
   83    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   84};
   85use remote::{
   86    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   87    remote_client::ConnectionIdentifier,
   88};
   89use schemars::JsonSchema;
   90use serde::Deserialize;
   91use session::AppSession;
   92use settings::{
   93    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
   94};
   95use shared_screen::SharedScreen;
   96use sqlez::{
   97    bindable::{Bind, Column, StaticColumnCount},
   98    statement::Statement,
   99};
  100use status_bar::StatusBar;
  101pub use status_bar::StatusItemView;
  102use std::{
  103    any::TypeId,
  104    borrow::Cow,
  105    cell::RefCell,
  106    cmp,
  107    collections::{VecDeque, hash_map::DefaultHasher},
  108    env,
  109    hash::{Hash, Hasher},
  110    path::{Path, PathBuf},
  111    process::ExitStatus,
  112    rc::Rc,
  113    sync::{
  114        Arc, LazyLock, Weak,
  115        atomic::{AtomicBool, AtomicUsize},
  116    },
  117    time::Duration,
  118};
  119use task::{DebugScenario, SpawnInTerminal, TaskContext};
  120use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  121pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
  122pub use ui;
  123use ui::{Window, prelude::*};
  124use util::{
  125    ResultExt, TryFutureExt,
  126    paths::{PathStyle, SanitizedPath},
  127    rel_path::RelPath,
  128    serde::default_true,
  129};
  130use uuid::Uuid;
  131pub use workspace_settings::{
  132    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  133    WorkspaceSettings,
  134};
  135use zed_actions::{Spawn, feedback::FileBugReport};
  136
  137use crate::{
  138    item::ItemBufferKind,
  139    notifications::NotificationId,
  140    utility_pane::{UTILITY_PANE_MIN_WIDTH, utility_slot_for_dock_position},
  141};
  142use crate::{
  143    persistence::{
  144        SerializedAxis,
  145        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  146    },
  147    security_modal::SecurityModal,
  148    utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
  149};
  150
  151pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  152
  153static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  154    env::var("ZED_WINDOW_SIZE")
  155        .ok()
  156        .as_deref()
  157        .and_then(parse_pixel_size_env_var)
  158});
  159
  160static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  161    env::var("ZED_WINDOW_POSITION")
  162        .ok()
  163        .as_deref()
  164        .and_then(parse_pixel_position_env_var)
  165});
  166
  167pub trait TerminalProvider {
  168    fn spawn(
  169        &self,
  170        task: SpawnInTerminal,
  171        window: &mut Window,
  172        cx: &mut App,
  173    ) -> Task<Option<Result<ExitStatus>>>;
  174}
  175
  176pub trait DebuggerProvider {
  177    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  178    fn start_session(
  179        &self,
  180        definition: DebugScenario,
  181        task_context: TaskContext,
  182        active_buffer: Option<Entity<Buffer>>,
  183        worktree_id: Option<WorktreeId>,
  184        window: &mut Window,
  185        cx: &mut App,
  186    );
  187
  188    fn spawn_task_or_modal(
  189        &self,
  190        workspace: &mut Workspace,
  191        action: &Spawn,
  192        window: &mut Window,
  193        cx: &mut Context<Workspace>,
  194    );
  195
  196    fn task_scheduled(&self, cx: &mut App);
  197    fn debug_scenario_scheduled(&self, cx: &mut App);
  198    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  199
  200    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  201}
  202
  203actions!(
  204    workspace,
  205    [
  206        /// Activates the next pane in the workspace.
  207        ActivateNextPane,
  208        /// Activates the previous pane in the workspace.
  209        ActivatePreviousPane,
  210        /// Switches to the next window.
  211        ActivateNextWindow,
  212        /// Switches to the previous window.
  213        ActivatePreviousWindow,
  214        /// Adds a folder to the current project.
  215        AddFolderToProject,
  216        /// Opens the project switcher dropdown (only visible when multiple folders are open).
  217        SwitchProject,
  218        /// Clears all notifications.
  219        ClearAllNotifications,
  220        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  221        ClearNavigationHistory,
  222        /// Closes the active dock.
  223        CloseActiveDock,
  224        /// Closes all docks.
  225        CloseAllDocks,
  226        /// Toggles all docks.
  227        ToggleAllDocks,
  228        /// Closes the current window.
  229        CloseWindow,
  230        /// Opens the feedback dialog.
  231        Feedback,
  232        /// Follows the next collaborator in the session.
  233        FollowNextCollaborator,
  234        /// Moves the focused panel to the next position.
  235        MoveFocusedPanelToNextPosition,
  236        /// Creates a new file.
  237        NewFile,
  238        /// Creates a new file in a vertical split.
  239        NewFileSplitVertical,
  240        /// Creates a new file in a horizontal split.
  241        NewFileSplitHorizontal,
  242        /// Opens a new search.
  243        NewSearch,
  244        /// Opens a new window.
  245        NewWindow,
  246        /// Opens a file or directory.
  247        Open,
  248        /// Opens multiple files.
  249        OpenFiles,
  250        /// Opens the current location in terminal.
  251        OpenInTerminal,
  252        /// Opens the component preview.
  253        OpenComponentPreview,
  254        /// Reloads the active item.
  255        ReloadActiveItem,
  256        /// Resets the active dock to its default size.
  257        ResetActiveDockSize,
  258        /// Resets all open docks to their default sizes.
  259        ResetOpenDocksSize,
  260        /// Reloads the application
  261        Reload,
  262        /// Saves the current file with a new name.
  263        SaveAs,
  264        /// Saves without formatting.
  265        SaveWithoutFormat,
  266        /// Shuts down all debug adapters.
  267        ShutdownDebugAdapters,
  268        /// Suppresses the current notification.
  269        SuppressNotification,
  270        /// Toggles the bottom dock.
  271        ToggleBottomDock,
  272        /// Toggles centered layout mode.
  273        ToggleCenteredLayout,
  274        /// Toggles edit prediction feature globally for all files.
  275        ToggleEditPrediction,
  276        /// Toggles the left dock.
  277        ToggleLeftDock,
  278        /// Toggles the right dock.
  279        ToggleRightDock,
  280        /// Toggles zoom on the active pane.
  281        ToggleZoom,
  282        /// Toggles read-only mode for the active item (if supported by that item).
  283        ToggleReadOnlyFile,
  284        /// Zooms in on the active pane.
  285        ZoomIn,
  286        /// Zooms out of the active pane.
  287        ZoomOut,
  288        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  289        /// If the modal is shown already, closes it without trusting any worktree.
  290        ToggleWorktreeSecurity,
  291        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  292        /// Requires restart to take effect on already opened projects.
  293        ClearTrustedWorktrees,
  294        /// Stops following a collaborator.
  295        Unfollow,
  296        /// Restores the banner.
  297        RestoreBanner,
  298        /// Toggles expansion of the selected item.
  299        ToggleExpandItem,
  300    ]
  301);
  302
  303/// Activates a specific pane by its index.
  304#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  305#[action(namespace = workspace)]
  306pub struct ActivatePane(pub usize);
  307
  308/// Moves an item to a specific pane by index.
  309#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  310#[action(namespace = workspace)]
  311#[serde(deny_unknown_fields)]
  312pub struct MoveItemToPane {
  313    #[serde(default = "default_1")]
  314    pub destination: usize,
  315    #[serde(default = "default_true")]
  316    pub focus: bool,
  317    #[serde(default)]
  318    pub clone: bool,
  319}
  320
  321fn default_1() -> usize {
  322    1
  323}
  324
  325/// Moves an item to a pane in the specified direction.
  326#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  327#[action(namespace = workspace)]
  328#[serde(deny_unknown_fields)]
  329pub struct MoveItemToPaneInDirection {
  330    #[serde(default = "default_right")]
  331    pub direction: SplitDirection,
  332    #[serde(default = "default_true")]
  333    pub focus: bool,
  334    #[serde(default)]
  335    pub clone: bool,
  336}
  337
  338/// Creates a new file in a split of the desired direction.
  339#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  340#[action(namespace = workspace)]
  341#[serde(deny_unknown_fields)]
  342pub struct NewFileSplit(pub SplitDirection);
  343
  344fn default_right() -> SplitDirection {
  345    SplitDirection::Right
  346}
  347
  348/// Saves all open files in the workspace.
  349#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  350#[action(namespace = workspace)]
  351#[serde(deny_unknown_fields)]
  352pub struct SaveAll {
  353    #[serde(default)]
  354    pub save_intent: Option<SaveIntent>,
  355}
  356
  357/// Saves the current file with the specified options.
  358#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  359#[action(namespace = workspace)]
  360#[serde(deny_unknown_fields)]
  361pub struct Save {
  362    #[serde(default)]
  363    pub save_intent: Option<SaveIntent>,
  364}
  365
  366/// Closes all items and panes in the workspace.
  367#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  368#[action(namespace = workspace)]
  369#[serde(deny_unknown_fields)]
  370pub struct CloseAllItemsAndPanes {
  371    #[serde(default)]
  372    pub save_intent: Option<SaveIntent>,
  373}
  374
  375/// Closes all inactive tabs and panes in the workspace.
  376#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  377#[action(namespace = workspace)]
  378#[serde(deny_unknown_fields)]
  379pub struct CloseInactiveTabsAndPanes {
  380    #[serde(default)]
  381    pub save_intent: Option<SaveIntent>,
  382}
  383
  384/// Sends a sequence of keystrokes to the active element.
  385#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  386#[action(namespace = workspace)]
  387pub struct SendKeystrokes(pub String);
  388
  389actions!(
  390    project_symbols,
  391    [
  392        /// Toggles the project symbols search.
  393        #[action(name = "Toggle")]
  394        ToggleProjectSymbols
  395    ]
  396);
  397
  398/// Toggles the file finder interface.
  399#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  400#[action(namespace = file_finder, name = "Toggle")]
  401#[serde(deny_unknown_fields)]
  402pub struct ToggleFileFinder {
  403    #[serde(default)]
  404    pub separate_history: bool,
  405}
  406
  407/// Opens a new terminal in the center.
  408#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  409#[action(namespace = workspace)]
  410#[serde(deny_unknown_fields)]
  411pub struct NewCenterTerminal {
  412    /// If true, creates a local terminal even in remote projects.
  413    #[serde(default)]
  414    pub local: bool,
  415}
  416
  417/// Opens a new terminal.
  418#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  419#[action(namespace = workspace)]
  420#[serde(deny_unknown_fields)]
  421pub struct NewTerminal {
  422    /// If true, creates a local terminal even in remote projects.
  423    #[serde(default)]
  424    pub local: bool,
  425}
  426
  427/// Increases size of a currently focused dock by a given amount of pixels.
  428#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  429#[action(namespace = workspace)]
  430#[serde(deny_unknown_fields)]
  431pub struct IncreaseActiveDockSize {
  432    /// For 0px parameter, uses UI font size value.
  433    #[serde(default)]
  434    pub px: u32,
  435}
  436
  437/// Decreases size of a currently focused dock by a given amount of pixels.
  438#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  439#[action(namespace = workspace)]
  440#[serde(deny_unknown_fields)]
  441pub struct DecreaseActiveDockSize {
  442    /// For 0px parameter, uses UI font size value.
  443    #[serde(default)]
  444    pub px: u32,
  445}
  446
  447/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  448#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  449#[action(namespace = workspace)]
  450#[serde(deny_unknown_fields)]
  451pub struct IncreaseOpenDocksSize {
  452    /// For 0px parameter, uses UI font size value.
  453    #[serde(default)]
  454    pub px: u32,
  455}
  456
  457/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  458#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  459#[action(namespace = workspace)]
  460#[serde(deny_unknown_fields)]
  461pub struct DecreaseOpenDocksSize {
  462    /// For 0px parameter, uses UI font size value.
  463    #[serde(default)]
  464    pub px: u32,
  465}
  466
  467actions!(
  468    workspace,
  469    [
  470        /// Activates the pane to the left.
  471        ActivatePaneLeft,
  472        /// Activates the pane to the right.
  473        ActivatePaneRight,
  474        /// Activates the pane above.
  475        ActivatePaneUp,
  476        /// Activates the pane below.
  477        ActivatePaneDown,
  478        /// Swaps the current pane with the one to the left.
  479        SwapPaneLeft,
  480        /// Swaps the current pane with the one to the right.
  481        SwapPaneRight,
  482        /// Swaps the current pane with the one above.
  483        SwapPaneUp,
  484        /// Swaps the current pane with the one below.
  485        SwapPaneDown,
  486        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  487        SwapPaneAdjacent,
  488        /// Move the current pane to be at the far left.
  489        MovePaneLeft,
  490        /// Move the current pane to be at the far right.
  491        MovePaneRight,
  492        /// Move the current pane to be at the very top.
  493        MovePaneUp,
  494        /// Move the current pane to be at the very bottom.
  495        MovePaneDown,
  496    ]
  497);
  498
  499#[derive(PartialEq, Eq, Debug)]
  500pub enum CloseIntent {
  501    /// Quit the program entirely.
  502    Quit,
  503    /// Close a window.
  504    CloseWindow,
  505    /// Replace the workspace in an existing window.
  506    ReplaceWindow,
  507}
  508
  509#[derive(Clone)]
  510pub struct Toast {
  511    id: NotificationId,
  512    msg: Cow<'static, str>,
  513    autohide: bool,
  514    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  515}
  516
  517impl Toast {
  518    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  519        Toast {
  520            id,
  521            msg: msg.into(),
  522            on_click: None,
  523            autohide: false,
  524        }
  525    }
  526
  527    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  528    where
  529        M: Into<Cow<'static, str>>,
  530        F: Fn(&mut Window, &mut App) + 'static,
  531    {
  532        self.on_click = Some((message.into(), Arc::new(on_click)));
  533        self
  534    }
  535
  536    pub fn autohide(mut self) -> Self {
  537        self.autohide = true;
  538        self
  539    }
  540}
  541
  542impl PartialEq for Toast {
  543    fn eq(&self, other: &Self) -> bool {
  544        self.id == other.id
  545            && self.msg == other.msg
  546            && self.on_click.is_some() == other.on_click.is_some()
  547    }
  548}
  549
  550/// Opens a new terminal with the specified working directory.
  551#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  552#[action(namespace = workspace)]
  553#[serde(deny_unknown_fields)]
  554pub struct OpenTerminal {
  555    pub working_directory: PathBuf,
  556    /// If true, creates a local terminal even in remote projects.
  557    #[serde(default)]
  558    pub local: bool,
  559}
  560
  561#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
  562pub struct WorkspaceId(i64);
  563
  564impl StaticColumnCount for WorkspaceId {}
  565impl Bind for WorkspaceId {
  566    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  567        self.0.bind(statement, start_index)
  568    }
  569}
  570impl Column for WorkspaceId {
  571    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  572        i64::column(statement, start_index)
  573            .map(|(i, next_index)| (Self(i), next_index))
  574            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  575    }
  576}
  577impl From<WorkspaceId> for i64 {
  578    fn from(val: WorkspaceId) -> Self {
  579        val.0
  580    }
  581}
  582
  583fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  584    let paths = cx.prompt_for_paths(options);
  585    cx.spawn(
  586        async move |cx| match paths.await.anyhow().and_then(|res| res) {
  587            Ok(Some(paths)) => {
  588                cx.update(|cx| {
  589                    open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
  590                });
  591            }
  592            Ok(None) => {}
  593            Err(err) => {
  594                util::log_err(&err);
  595                cx.update(|cx| {
  596                    if let Some(workspace_window) = cx
  597                        .active_window()
  598                        .and_then(|window| window.downcast::<Workspace>())
  599                    {
  600                        workspace_window
  601                            .update(cx, |workspace, _, cx| {
  602                                workspace.show_portal_error(err.to_string(), cx);
  603                            })
  604                            .ok();
  605                    }
  606                });
  607            }
  608        },
  609    )
  610    .detach();
  611}
  612
  613pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  614    component::init();
  615    theme_preview::init(cx);
  616    toast_layer::init(cx);
  617    history_manager::init(cx);
  618
  619    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  620        .on_action(|_: &Reload, cx| reload(cx))
  621        .on_action({
  622            let app_state = Arc::downgrade(&app_state);
  623            move |_: &Open, cx: &mut App| {
  624                if let Some(app_state) = app_state.upgrade() {
  625                    prompt_and_open_paths(
  626                        app_state,
  627                        PathPromptOptions {
  628                            files: true,
  629                            directories: true,
  630                            multiple: true,
  631                            prompt: None,
  632                        },
  633                        cx,
  634                    );
  635                }
  636            }
  637        })
  638        .on_action({
  639            let app_state = Arc::downgrade(&app_state);
  640            move |_: &OpenFiles, cx: &mut App| {
  641                let directories = cx.can_select_mixed_files_and_dirs();
  642                if let Some(app_state) = app_state.upgrade() {
  643                    prompt_and_open_paths(
  644                        app_state,
  645                        PathPromptOptions {
  646                            files: true,
  647                            directories,
  648                            multiple: true,
  649                            prompt: None,
  650                        },
  651                        cx,
  652                    );
  653                }
  654            }
  655        });
  656}
  657
  658type BuildProjectItemFn =
  659    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  660
  661type BuildProjectItemForPathFn =
  662    fn(
  663        &Entity<Project>,
  664        &ProjectPath,
  665        &mut Window,
  666        &mut App,
  667    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  668
  669#[derive(Clone, Default)]
  670struct ProjectItemRegistry {
  671    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  672    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  673}
  674
  675impl ProjectItemRegistry {
  676    fn register<T: ProjectItem>(&mut self) {
  677        self.build_project_item_fns_by_type.insert(
  678            TypeId::of::<T::Item>(),
  679            |item, project, pane, window, cx| {
  680                let item = item.downcast().unwrap();
  681                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  682                    as Box<dyn ItemHandle>
  683            },
  684        );
  685        self.build_project_item_for_path_fns
  686            .push(|project, project_path, window, cx| {
  687                let project_path = project_path.clone();
  688                let is_file = project
  689                    .read(cx)
  690                    .entry_for_path(&project_path, cx)
  691                    .is_some_and(|entry| entry.is_file());
  692                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  693                let is_local = project.read(cx).is_local();
  694                let project_item =
  695                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  696                let project = project.clone();
  697                Some(window.spawn(cx, async move |cx| {
  698                    match project_item.await.with_context(|| {
  699                        format!(
  700                            "opening project path {:?}",
  701                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  702                        )
  703                    }) {
  704                        Ok(project_item) => {
  705                            let project_item = project_item;
  706                            let project_entry_id: Option<ProjectEntryId> =
  707                                project_item.read_with(cx, project::ProjectItem::entry_id);
  708                            let build_workspace_item = Box::new(
  709                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  710                                    Box::new(cx.new(|cx| {
  711                                        T::for_project_item(
  712                                            project,
  713                                            Some(pane),
  714                                            project_item,
  715                                            window,
  716                                            cx,
  717                                        )
  718                                    })) as Box<dyn ItemHandle>
  719                                },
  720                            ) as Box<_>;
  721                            Ok((project_entry_id, build_workspace_item))
  722                        }
  723                        Err(e) => {
  724                            log::warn!("Failed to open a project item: {e:#}");
  725                            if e.error_code() == ErrorCode::Internal {
  726                                if let Some(abs_path) =
  727                                    entry_abs_path.as_deref().filter(|_| is_file)
  728                                {
  729                                    if let Some(broken_project_item_view) =
  730                                        cx.update(|window, cx| {
  731                                            T::for_broken_project_item(
  732                                                abs_path, is_local, &e, window, cx,
  733                                            )
  734                                        })?
  735                                    {
  736                                        let build_workspace_item = Box::new(
  737                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  738                                                cx.new(|_| broken_project_item_view).boxed_clone()
  739                                            },
  740                                        )
  741                                        as Box<_>;
  742                                        return Ok((None, build_workspace_item));
  743                                    }
  744                                }
  745                            }
  746                            Err(e)
  747                        }
  748                    }
  749                }))
  750            });
  751    }
  752
  753    fn open_path(
  754        &self,
  755        project: &Entity<Project>,
  756        path: &ProjectPath,
  757        window: &mut Window,
  758        cx: &mut App,
  759    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  760        let Some(open_project_item) = self
  761            .build_project_item_for_path_fns
  762            .iter()
  763            .rev()
  764            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  765        else {
  766            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  767        };
  768        open_project_item
  769    }
  770
  771    fn build_item<T: project::ProjectItem>(
  772        &self,
  773        item: Entity<T>,
  774        project: Entity<Project>,
  775        pane: Option<&Pane>,
  776        window: &mut Window,
  777        cx: &mut App,
  778    ) -> Option<Box<dyn ItemHandle>> {
  779        let build = self
  780            .build_project_item_fns_by_type
  781            .get(&TypeId::of::<T>())?;
  782        Some(build(item.into_any(), project, pane, window, cx))
  783    }
  784}
  785
  786type WorkspaceItemBuilder =
  787    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  788
  789impl Global for ProjectItemRegistry {}
  790
  791/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  792/// items will get a chance to open the file, starting from the project item that
  793/// was added last.
  794pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  795    cx.default_global::<ProjectItemRegistry>().register::<I>();
  796}
  797
  798#[derive(Default)]
  799pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  800
  801struct FollowableViewDescriptor {
  802    from_state_proto: fn(
  803        Entity<Workspace>,
  804        ViewId,
  805        &mut Option<proto::view::Variant>,
  806        &mut Window,
  807        &mut App,
  808    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  809    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  810}
  811
  812impl Global for FollowableViewRegistry {}
  813
  814impl FollowableViewRegistry {
  815    pub fn register<I: FollowableItem>(cx: &mut App) {
  816        cx.default_global::<Self>().0.insert(
  817            TypeId::of::<I>(),
  818            FollowableViewDescriptor {
  819                from_state_proto: |workspace, id, state, window, cx| {
  820                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  821                        cx.foreground_executor()
  822                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  823                    })
  824                },
  825                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  826            },
  827        );
  828    }
  829
  830    pub fn from_state_proto(
  831        workspace: Entity<Workspace>,
  832        view_id: ViewId,
  833        mut state: Option<proto::view::Variant>,
  834        window: &mut Window,
  835        cx: &mut App,
  836    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  837        cx.update_default_global(|this: &mut Self, cx| {
  838            this.0.values().find_map(|descriptor| {
  839                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  840            })
  841        })
  842    }
  843
  844    pub fn to_followable_view(
  845        view: impl Into<AnyView>,
  846        cx: &App,
  847    ) -> Option<Box<dyn FollowableItemHandle>> {
  848        let this = cx.try_global::<Self>()?;
  849        let view = view.into();
  850        let descriptor = this.0.get(&view.entity_type())?;
  851        Some((descriptor.to_followable_view)(&view))
  852    }
  853}
  854
  855#[derive(Copy, Clone)]
  856struct SerializableItemDescriptor {
  857    deserialize: fn(
  858        Entity<Project>,
  859        WeakEntity<Workspace>,
  860        WorkspaceId,
  861        ItemId,
  862        &mut Window,
  863        &mut Context<Pane>,
  864    ) -> Task<Result<Box<dyn ItemHandle>>>,
  865    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  866    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  867}
  868
  869#[derive(Default)]
  870struct SerializableItemRegistry {
  871    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  872    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  873}
  874
  875impl Global for SerializableItemRegistry {}
  876
  877impl SerializableItemRegistry {
  878    fn deserialize(
  879        item_kind: &str,
  880        project: Entity<Project>,
  881        workspace: WeakEntity<Workspace>,
  882        workspace_id: WorkspaceId,
  883        item_item: ItemId,
  884        window: &mut Window,
  885        cx: &mut Context<Pane>,
  886    ) -> Task<Result<Box<dyn ItemHandle>>> {
  887        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  888            return Task::ready(Err(anyhow!(
  889                "cannot deserialize {}, descriptor not found",
  890                item_kind
  891            )));
  892        };
  893
  894        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  895    }
  896
  897    fn cleanup(
  898        item_kind: &str,
  899        workspace_id: WorkspaceId,
  900        loaded_items: Vec<ItemId>,
  901        window: &mut Window,
  902        cx: &mut App,
  903    ) -> Task<Result<()>> {
  904        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  905            return Task::ready(Err(anyhow!(
  906                "cannot cleanup {}, descriptor not found",
  907                item_kind
  908            )));
  909        };
  910
  911        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  912    }
  913
  914    fn view_to_serializable_item_handle(
  915        view: AnyView,
  916        cx: &App,
  917    ) -> Option<Box<dyn SerializableItemHandle>> {
  918        let this = cx.try_global::<Self>()?;
  919        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  920        Some((descriptor.view_to_serializable_item)(view))
  921    }
  922
  923    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  924        let this = cx.try_global::<Self>()?;
  925        this.descriptors_by_kind.get(item_kind).copied()
  926    }
  927}
  928
  929pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  930    let serialized_item_kind = I::serialized_item_kind();
  931
  932    let registry = cx.default_global::<SerializableItemRegistry>();
  933    let descriptor = SerializableItemDescriptor {
  934        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  935            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  936            cx.foreground_executor()
  937                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
  938        },
  939        cleanup: |workspace_id, loaded_items, window, cx| {
  940            I::cleanup(workspace_id, loaded_items, window, cx)
  941        },
  942        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
  943    };
  944    registry
  945        .descriptors_by_kind
  946        .insert(Arc::from(serialized_item_kind), descriptor);
  947    registry
  948        .descriptors_by_type
  949        .insert(TypeId::of::<I>(), descriptor);
  950}
  951
  952pub struct AppState {
  953    pub languages: Arc<LanguageRegistry>,
  954    pub client: Arc<Client>,
  955    pub user_store: Entity<UserStore>,
  956    pub workspace_store: Entity<WorkspaceStore>,
  957    pub fs: Arc<dyn fs::Fs>,
  958    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
  959    pub node_runtime: NodeRuntime,
  960    pub session: Entity<AppSession>,
  961}
  962
  963struct GlobalAppState(Weak<AppState>);
  964
  965impl Global for GlobalAppState {}
  966
  967pub struct WorkspaceStore {
  968    workspaces: HashSet<WindowHandle<Workspace>>,
  969    client: Arc<Client>,
  970    _subscriptions: Vec<client::Subscription>,
  971}
  972
  973#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
  974pub enum CollaboratorId {
  975    PeerId(PeerId),
  976    Agent,
  977}
  978
  979impl From<PeerId> for CollaboratorId {
  980    fn from(peer_id: PeerId) -> Self {
  981        CollaboratorId::PeerId(peer_id)
  982    }
  983}
  984
  985impl From<&PeerId> for CollaboratorId {
  986    fn from(peer_id: &PeerId) -> Self {
  987        CollaboratorId::PeerId(*peer_id)
  988    }
  989}
  990
  991#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
  992struct Follower {
  993    project_id: Option<u64>,
  994    peer_id: PeerId,
  995}
  996
  997impl AppState {
  998    #[track_caller]
  999    pub fn global(cx: &App) -> Weak<Self> {
 1000        cx.global::<GlobalAppState>().0.clone()
 1001    }
 1002    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1003        cx.try_global::<GlobalAppState>()
 1004            .map(|state| state.0.clone())
 1005    }
 1006    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1007        cx.set_global(GlobalAppState(state));
 1008    }
 1009
 1010    #[cfg(any(test, feature = "test-support"))]
 1011    pub fn test(cx: &mut App) -> Arc<Self> {
 1012        use fs::Fs;
 1013        use node_runtime::NodeRuntime;
 1014        use session::Session;
 1015        use settings::SettingsStore;
 1016
 1017        if !cx.has_global::<SettingsStore>() {
 1018            let settings_store = SettingsStore::test(cx);
 1019            cx.set_global(settings_store);
 1020        }
 1021
 1022        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1023        <dyn Fs>::set_global(fs.clone(), cx);
 1024        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1025        let clock = Arc::new(clock::FakeSystemClock::new());
 1026        let http_client = http_client::FakeHttpClient::with_404_response();
 1027        let client = Client::new(clock, http_client, cx);
 1028        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1029        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1030        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1031
 1032        theme::init(theme::LoadThemes::JustBase, cx);
 1033        client::init(&client, cx);
 1034
 1035        Arc::new(Self {
 1036            client,
 1037            fs,
 1038            languages,
 1039            user_store,
 1040            workspace_store,
 1041            node_runtime: NodeRuntime::unavailable(),
 1042            build_window_options: |_, _| Default::default(),
 1043            session,
 1044        })
 1045    }
 1046}
 1047
 1048struct DelayedDebouncedEditAction {
 1049    task: Option<Task<()>>,
 1050    cancel_channel: Option<oneshot::Sender<()>>,
 1051}
 1052
 1053impl DelayedDebouncedEditAction {
 1054    fn new() -> DelayedDebouncedEditAction {
 1055        DelayedDebouncedEditAction {
 1056            task: None,
 1057            cancel_channel: None,
 1058        }
 1059    }
 1060
 1061    fn fire_new<F>(
 1062        &mut self,
 1063        delay: Duration,
 1064        window: &mut Window,
 1065        cx: &mut Context<Workspace>,
 1066        func: F,
 1067    ) where
 1068        F: 'static
 1069            + Send
 1070            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1071    {
 1072        if let Some(channel) = self.cancel_channel.take() {
 1073            _ = channel.send(());
 1074        }
 1075
 1076        let (sender, mut receiver) = oneshot::channel::<()>();
 1077        self.cancel_channel = Some(sender);
 1078
 1079        let previous_task = self.task.take();
 1080        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1081            let mut timer = cx.background_executor().timer(delay).fuse();
 1082            if let Some(previous_task) = previous_task {
 1083                previous_task.await;
 1084            }
 1085
 1086            futures::select_biased! {
 1087                _ = receiver => return,
 1088                    _ = timer => {}
 1089            }
 1090
 1091            if let Some(result) = workspace
 1092                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1093                .log_err()
 1094            {
 1095                result.await.log_err();
 1096            }
 1097        }));
 1098    }
 1099}
 1100
 1101pub enum Event {
 1102    PaneAdded(Entity<Pane>),
 1103    PaneRemoved,
 1104    ItemAdded {
 1105        item: Box<dyn ItemHandle>,
 1106    },
 1107    ActiveItemChanged,
 1108    ItemRemoved {
 1109        item_id: EntityId,
 1110    },
 1111    UserSavedItem {
 1112        pane: WeakEntity<Pane>,
 1113        item: Box<dyn WeakItemHandle>,
 1114        save_intent: SaveIntent,
 1115    },
 1116    ContactRequestedJoin(u64),
 1117    WorkspaceCreated(WeakEntity<Workspace>),
 1118    OpenBundledFile {
 1119        text: Cow<'static, str>,
 1120        title: &'static str,
 1121        language: &'static str,
 1122    },
 1123    ZoomChanged,
 1124    ModalOpened,
 1125}
 1126
 1127#[derive(Debug)]
 1128pub enum OpenVisible {
 1129    All,
 1130    None,
 1131    OnlyFiles,
 1132    OnlyDirectories,
 1133}
 1134
 1135enum WorkspaceLocation {
 1136    // Valid local paths or SSH project to serialize
 1137    Location(SerializedWorkspaceLocation, PathList),
 1138    // No valid location found hence clear session id
 1139    DetachFromSession,
 1140    // No valid location found to serialize
 1141    None,
 1142}
 1143
 1144type PromptForNewPath = Box<
 1145    dyn Fn(
 1146        &mut Workspace,
 1147        DirectoryLister,
 1148        &mut Window,
 1149        &mut Context<Workspace>,
 1150    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1151>;
 1152
 1153type PromptForOpenPath = Box<
 1154    dyn Fn(
 1155        &mut Workspace,
 1156        DirectoryLister,
 1157        &mut Window,
 1158        &mut Context<Workspace>,
 1159    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1160>;
 1161
 1162#[derive(Default)]
 1163struct DispatchingKeystrokes {
 1164    dispatched: HashSet<Vec<Keystroke>>,
 1165    queue: VecDeque<Keystroke>,
 1166    task: Option<Shared<Task<()>>>,
 1167}
 1168
 1169/// Collects everything project-related for a certain window opened.
 1170/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1171///
 1172/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1173/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1174/// that can be used to register a global action to be triggered from any place in the window.
 1175pub struct Workspace {
 1176    weak_self: WeakEntity<Self>,
 1177    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1178    zoomed: Option<AnyWeakView>,
 1179    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1180    zoomed_position: Option<DockPosition>,
 1181    center: PaneGroup,
 1182    left_dock: Entity<Dock>,
 1183    bottom_dock: Entity<Dock>,
 1184    right_dock: Entity<Dock>,
 1185    panes: Vec<Entity<Pane>>,
 1186    active_worktree_override: Option<WorktreeId>,
 1187    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1188    active_pane: Entity<Pane>,
 1189    last_active_center_pane: Option<WeakEntity<Pane>>,
 1190    last_active_view_id: Option<proto::ViewId>,
 1191    status_bar: Entity<StatusBar>,
 1192    modal_layer: Entity<ModalLayer>,
 1193    toast_layer: Entity<ToastLayer>,
 1194    titlebar_item: Option<AnyView>,
 1195    notifications: Notifications,
 1196    suppressed_notifications: HashSet<NotificationId>,
 1197    project: Entity<Project>,
 1198    follower_states: HashMap<CollaboratorId, FollowerState>,
 1199    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1200    window_edited: bool,
 1201    last_window_title: Option<String>,
 1202    dirty_items: HashMap<EntityId, Subscription>,
 1203    active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
 1204    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1205    database_id: Option<WorkspaceId>,
 1206    app_state: Arc<AppState>,
 1207    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1208    _subscriptions: Vec<Subscription>,
 1209    _apply_leader_updates: Task<Result<()>>,
 1210    _observe_current_user: Task<Result<()>>,
 1211    _schedule_serialize_workspace: Option<Task<()>>,
 1212    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1213    pane_history_timestamp: Arc<AtomicUsize>,
 1214    bounds: Bounds<Pixels>,
 1215    pub centered_layout: bool,
 1216    bounds_save_task_queued: Option<Task<()>>,
 1217    on_prompt_for_new_path: Option<PromptForNewPath>,
 1218    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1219    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1220    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1221    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1222    _items_serializer: Task<Result<()>>,
 1223    session_id: Option<String>,
 1224    scheduled_tasks: Vec<Task<()>>,
 1225    last_open_dock_positions: Vec<DockPosition>,
 1226    removing: bool,
 1227    utility_panes: UtilityPaneState,
 1228}
 1229
 1230impl EventEmitter<Event> for Workspace {}
 1231
 1232#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1233pub struct ViewId {
 1234    pub creator: CollaboratorId,
 1235    pub id: u64,
 1236}
 1237
 1238pub struct FollowerState {
 1239    center_pane: Entity<Pane>,
 1240    dock_pane: Option<Entity<Pane>>,
 1241    active_view_id: Option<ViewId>,
 1242    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1243}
 1244
 1245struct FollowerView {
 1246    view: Box<dyn FollowableItemHandle>,
 1247    location: Option<proto::PanelId>,
 1248}
 1249
 1250impl Workspace {
 1251    pub fn new(
 1252        workspace_id: Option<WorkspaceId>,
 1253        project: Entity<Project>,
 1254        app_state: Arc<AppState>,
 1255        window: &mut Window,
 1256        cx: &mut Context<Self>,
 1257    ) -> Self {
 1258        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1259            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1260                if let TrustedWorktreesEvent::Trusted(..) = e {
 1261                    // Do not persist auto trusted worktrees
 1262                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1263                        worktrees_store.update(cx, |worktrees_store, cx| {
 1264                            worktrees_store.schedule_serialization(
 1265                                cx,
 1266                                |new_trusted_worktrees, cx| {
 1267                                    let timeout =
 1268                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1269                                    cx.background_spawn(async move {
 1270                                        timeout.await;
 1271                                        persistence::DB
 1272                                            .save_trusted_worktrees(new_trusted_worktrees)
 1273                                            .await
 1274                                            .log_err();
 1275                                    })
 1276                                },
 1277                            )
 1278                        });
 1279                    }
 1280                }
 1281            })
 1282            .detach();
 1283
 1284            cx.observe_global::<SettingsStore>(|_, cx| {
 1285                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1286                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1287                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1288                            trusted_worktrees.auto_trust_all(cx);
 1289                        })
 1290                    }
 1291                }
 1292            })
 1293            .detach();
 1294        }
 1295
 1296        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1297            match event {
 1298                project::Event::RemoteIdChanged(_) => {
 1299                    this.update_window_title(window, cx);
 1300                }
 1301
 1302                project::Event::CollaboratorLeft(peer_id) => {
 1303                    this.collaborator_left(*peer_id, window, cx);
 1304                }
 1305
 1306                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(..) => {
 1307                    this.update_window_title(window, cx);
 1308                    this.serialize_workspace(window, cx);
 1309                    this.update_history(cx);
 1310                }
 1311
 1312                project::Event::WorktreeUpdatedEntries(..) => {
 1313                    this.update_window_title(window, cx);
 1314                    this.serialize_workspace(window, cx);
 1315                }
 1316
 1317                project::Event::DisconnectedFromHost => {
 1318                    this.update_window_edited(window, cx);
 1319                    let leaders_to_unfollow =
 1320                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1321                    for leader_id in leaders_to_unfollow {
 1322                        this.unfollow(leader_id, window, cx);
 1323                    }
 1324                }
 1325
 1326                project::Event::DisconnectedFromRemote => {
 1327                    this.update_window_edited(window, cx);
 1328                }
 1329
 1330                project::Event::Closed => {
 1331                    window.remove_window();
 1332                }
 1333
 1334                project::Event::DeletedEntry(_, entry_id) => {
 1335                    for pane in this.panes.iter() {
 1336                        pane.update(cx, |pane, cx| {
 1337                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1338                        });
 1339                    }
 1340                }
 1341
 1342                project::Event::Toast {
 1343                    notification_id,
 1344                    message,
 1345                } => this.show_notification(
 1346                    NotificationId::named(notification_id.clone()),
 1347                    cx,
 1348                    |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
 1349                ),
 1350
 1351                project::Event::HideToast { notification_id } => {
 1352                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1353                }
 1354
 1355                project::Event::LanguageServerPrompt(request) => {
 1356                    struct LanguageServerPrompt;
 1357
 1358                    let mut hasher = DefaultHasher::new();
 1359                    request.lsp_name.as_str().hash(&mut hasher);
 1360                    let id = hasher.finish();
 1361
 1362                    this.show_notification(
 1363                        NotificationId::composite::<LanguageServerPrompt>(id as usize),
 1364                        cx,
 1365                        |cx| {
 1366                            cx.new(|cx| {
 1367                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1368                            })
 1369                        },
 1370                    );
 1371                }
 1372
 1373                project::Event::AgentLocationChanged => {
 1374                    this.handle_agent_location_changed(window, cx)
 1375                }
 1376
 1377                _ => {}
 1378            }
 1379            cx.notify()
 1380        })
 1381        .detach();
 1382
 1383        cx.subscribe_in(
 1384            &project.read(cx).breakpoint_store(),
 1385            window,
 1386            |workspace, _, event, window, cx| match event {
 1387                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1388                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1389                    workspace.serialize_workspace(window, cx);
 1390                }
 1391                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1392            },
 1393        )
 1394        .detach();
 1395        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1396            cx.subscribe_in(
 1397                &toolchain_store,
 1398                window,
 1399                |workspace, _, event, window, cx| match event {
 1400                    ToolchainStoreEvent::CustomToolchainsModified => {
 1401                        workspace.serialize_workspace(window, cx);
 1402                    }
 1403                    _ => {}
 1404                },
 1405            )
 1406            .detach();
 1407        }
 1408
 1409        cx.on_focus_lost(window, |this, window, cx| {
 1410            let focus_handle = this.focus_handle(cx);
 1411            window.focus(&focus_handle, cx);
 1412        })
 1413        .detach();
 1414
 1415        let weak_handle = cx.entity().downgrade();
 1416        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1417
 1418        let center_pane = cx.new(|cx| {
 1419            let mut center_pane = Pane::new(
 1420                weak_handle.clone(),
 1421                project.clone(),
 1422                pane_history_timestamp.clone(),
 1423                None,
 1424                NewFile.boxed_clone(),
 1425                true,
 1426                window,
 1427                cx,
 1428            );
 1429            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1430            center_pane
 1431        });
 1432        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1433            .detach();
 1434
 1435        window.focus(&center_pane.focus_handle(cx), cx);
 1436
 1437        cx.emit(Event::PaneAdded(center_pane.clone()));
 1438
 1439        let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
 1440        app_state.workspace_store.update(cx, |store, _| {
 1441            store.workspaces.insert(window_handle);
 1442        });
 1443
 1444        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1445        let mut connection_status = app_state.client.status();
 1446        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1447            current_user.next().await;
 1448            connection_status.next().await;
 1449            let mut stream =
 1450                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1451
 1452            while stream.recv().await.is_some() {
 1453                this.update(cx, |_, cx| cx.notify())?;
 1454            }
 1455            anyhow::Ok(())
 1456        });
 1457
 1458        // All leader updates are enqueued and then processed in a single task, so
 1459        // that each asynchronous operation can be run in order.
 1460        let (leader_updates_tx, mut leader_updates_rx) =
 1461            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1462        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1463            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1464                Self::process_leader_update(&this, leader_id, update, cx)
 1465                    .await
 1466                    .log_err();
 1467            }
 1468
 1469            Ok(())
 1470        });
 1471
 1472        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1473        let modal_layer = cx.new(|_| ModalLayer::new());
 1474        let toast_layer = cx.new(|_| ToastLayer::new());
 1475        cx.subscribe(
 1476            &modal_layer,
 1477            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1478                cx.emit(Event::ModalOpened);
 1479            },
 1480        )
 1481        .detach();
 1482
 1483        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1484        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1485        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1486        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1487        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1488        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1489        let status_bar = cx.new(|cx| {
 1490            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1491            status_bar.add_left_item(left_dock_buttons, window, cx);
 1492            status_bar.add_right_item(right_dock_buttons, window, cx);
 1493            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1494            status_bar
 1495        });
 1496
 1497        let session_id = app_state.session.read(cx).id().to_owned();
 1498
 1499        let mut active_call = None;
 1500        if let Some(call) = ActiveCall::try_global(cx) {
 1501            let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
 1502            active_call = Some((call, subscriptions));
 1503        }
 1504
 1505        let (serializable_items_tx, serializable_items_rx) =
 1506            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1507        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1508            Self::serialize_items(&this, serializable_items_rx, cx).await
 1509        });
 1510
 1511        let subscriptions = vec![
 1512            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1513            cx.observe_window_bounds(window, move |this, window, cx| {
 1514                if this.bounds_save_task_queued.is_some() {
 1515                    return;
 1516                }
 1517                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1518                    cx.background_executor()
 1519                        .timer(Duration::from_millis(100))
 1520                        .await;
 1521                    this.update_in(cx, |this, window, cx| {
 1522                        if let Some(display) = window.display(cx)
 1523                            && let Ok(display_uuid) = display.uuid()
 1524                        {
 1525                            let window_bounds = window.inner_window_bounds();
 1526                            let has_paths = !this.root_paths(cx).is_empty();
 1527                            if !has_paths {
 1528                                cx.background_executor()
 1529                                    .spawn(persistence::write_default_window_bounds(
 1530                                        window_bounds,
 1531                                        display_uuid,
 1532                                    ))
 1533                                    .detach_and_log_err(cx);
 1534                            }
 1535                            if let Some(database_id) = workspace_id {
 1536                                cx.background_executor()
 1537                                    .spawn(DB.set_window_open_status(
 1538                                        database_id,
 1539                                        SerializedWindowBounds(window_bounds),
 1540                                        display_uuid,
 1541                                    ))
 1542                                    .detach_and_log_err(cx);
 1543                            } else {
 1544                                cx.background_executor()
 1545                                    .spawn(persistence::write_default_window_bounds(
 1546                                        window_bounds,
 1547                                        display_uuid,
 1548                                    ))
 1549                                    .detach_and_log_err(cx);
 1550                            }
 1551                        }
 1552                        this.bounds_save_task_queued.take();
 1553                    })
 1554                    .ok();
 1555                }));
 1556                cx.notify();
 1557            }),
 1558            cx.observe_window_appearance(window, |_, window, cx| {
 1559                let window_appearance = window.appearance();
 1560
 1561                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1562
 1563                GlobalTheme::reload_theme(cx);
 1564                GlobalTheme::reload_icon_theme(cx);
 1565            }),
 1566            cx.on_release(move |this, cx| {
 1567                this.app_state.workspace_store.update(cx, move |store, _| {
 1568                    store.workspaces.remove(&window_handle);
 1569                })
 1570            }),
 1571        ];
 1572
 1573        cx.defer_in(window, move |this, window, cx| {
 1574            this.update_window_title(window, cx);
 1575            this.show_initial_notifications(cx);
 1576        });
 1577
 1578        let mut center = PaneGroup::new(center_pane.clone());
 1579        center.set_is_center(true);
 1580        center.mark_positions(cx);
 1581
 1582        Workspace {
 1583            weak_self: weak_handle.clone(),
 1584            zoomed: None,
 1585            zoomed_position: None,
 1586            previous_dock_drag_coordinates: None,
 1587            center,
 1588            panes: vec![center_pane.clone()],
 1589            panes_by_item: Default::default(),
 1590            active_pane: center_pane.clone(),
 1591            last_active_center_pane: Some(center_pane.downgrade()),
 1592            last_active_view_id: None,
 1593            status_bar,
 1594            modal_layer,
 1595            toast_layer,
 1596            titlebar_item: None,
 1597            active_worktree_override: None,
 1598            notifications: Notifications::default(),
 1599            suppressed_notifications: HashSet::default(),
 1600            left_dock,
 1601            bottom_dock,
 1602            right_dock,
 1603            project: project.clone(),
 1604            follower_states: Default::default(),
 1605            last_leaders_by_pane: Default::default(),
 1606            dispatching_keystrokes: Default::default(),
 1607            window_edited: false,
 1608            last_window_title: None,
 1609            dirty_items: Default::default(),
 1610            active_call,
 1611            database_id: workspace_id,
 1612            app_state,
 1613            _observe_current_user,
 1614            _apply_leader_updates,
 1615            _schedule_serialize_workspace: None,
 1616            _schedule_serialize_ssh_paths: None,
 1617            leader_updates_tx,
 1618            _subscriptions: subscriptions,
 1619            pane_history_timestamp,
 1620            workspace_actions: Default::default(),
 1621            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1622            bounds: Default::default(),
 1623            centered_layout: false,
 1624            bounds_save_task_queued: None,
 1625            on_prompt_for_new_path: None,
 1626            on_prompt_for_open_path: None,
 1627            terminal_provider: None,
 1628            debugger_provider: None,
 1629            serializable_items_tx,
 1630            _items_serializer,
 1631            session_id: Some(session_id),
 1632
 1633            scheduled_tasks: Vec::new(),
 1634            last_open_dock_positions: Vec::new(),
 1635            removing: false,
 1636            utility_panes: UtilityPaneState::default(),
 1637        }
 1638    }
 1639
 1640    pub fn new_local(
 1641        abs_paths: Vec<PathBuf>,
 1642        app_state: Arc<AppState>,
 1643        requesting_window: Option<WindowHandle<Workspace>>,
 1644        env: Option<HashMap<String, String>>,
 1645        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1646        cx: &mut App,
 1647    ) -> Task<
 1648        anyhow::Result<(
 1649            WindowHandle<Workspace>,
 1650            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1651        )>,
 1652    > {
 1653        let project_handle = Project::local(
 1654            app_state.client.clone(),
 1655            app_state.node_runtime.clone(),
 1656            app_state.user_store.clone(),
 1657            app_state.languages.clone(),
 1658            app_state.fs.clone(),
 1659            env,
 1660            true,
 1661            cx,
 1662        );
 1663
 1664        cx.spawn(async move |cx| {
 1665            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1666            for path in abs_paths.into_iter() {
 1667                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1668                    paths_to_open.push(canonical)
 1669                } else {
 1670                    paths_to_open.push(path)
 1671                }
 1672            }
 1673
 1674            let serialized_workspace =
 1675                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1676
 1677            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1678                paths_to_open = paths.ordered_paths().cloned().collect();
 1679                if !paths.is_lexicographically_ordered() {
 1680                    project_handle.update(cx, |project, cx| {
 1681                        project.set_worktrees_reordered(true, cx);
 1682                    });
 1683                }
 1684            }
 1685
 1686            // Get project paths for all of the abs_paths
 1687            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1688                Vec::with_capacity(paths_to_open.len());
 1689
 1690            for path in paths_to_open.into_iter() {
 1691                if let Some((_, project_entry)) = cx
 1692                    .update(|cx| {
 1693                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1694                    })
 1695                    .await
 1696                    .log_err()
 1697                {
 1698                    project_paths.push((path, Some(project_entry)));
 1699                } else {
 1700                    project_paths.push((path, None));
 1701                }
 1702            }
 1703
 1704            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1705                serialized_workspace.id
 1706            } else {
 1707                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1708            };
 1709
 1710            let toolchains = DB.toolchains(workspace_id).await?;
 1711
 1712            for (toolchain, worktree_path, path) in toolchains {
 1713                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1714                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1715                    this.find_worktree(&worktree_path, cx)
 1716                        .and_then(|(worktree, rel_path)| {
 1717                            if rel_path.is_empty() {
 1718                                Some(worktree.read(cx).id())
 1719                            } else {
 1720                                None
 1721                            }
 1722                        })
 1723                }) else {
 1724                    // We did not find a worktree with a given path, but that's whatever.
 1725                    continue;
 1726                };
 1727                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1728                    continue;
 1729                }
 1730
 1731                project_handle
 1732                    .update(cx, |this, cx| {
 1733                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1734                    })
 1735                    .await;
 1736            }
 1737            if let Some(workspace) = serialized_workspace.as_ref() {
 1738                project_handle.update(cx, |this, cx| {
 1739                    for (scope, toolchains) in &workspace.user_toolchains {
 1740                        for toolchain in toolchains {
 1741                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1742                        }
 1743                    }
 1744                });
 1745            }
 1746
 1747            let window = if let Some(window) = requesting_window {
 1748                let centered_layout = serialized_workspace
 1749                    .as_ref()
 1750                    .map(|w| w.centered_layout)
 1751                    .unwrap_or(false);
 1752
 1753                cx.update_window(window.into(), |_, window, cx| {
 1754                    window.replace_root(cx, |window, cx| {
 1755                        let mut workspace = Workspace::new(
 1756                            Some(workspace_id),
 1757                            project_handle.clone(),
 1758                            app_state.clone(),
 1759                            window,
 1760                            cx,
 1761                        );
 1762
 1763                        workspace.centered_layout = centered_layout;
 1764
 1765                        // Call init callback to add items before window renders
 1766                        if let Some(init) = init {
 1767                            init(&mut workspace, window, cx);
 1768                        }
 1769
 1770                        workspace
 1771                    });
 1772                })?;
 1773                window
 1774            } else {
 1775                let window_bounds_override = window_bounds_env_override();
 1776
 1777                let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1778                    (Some(WindowBounds::Windowed(bounds)), None)
 1779                } else if let Some(workspace) = serialized_workspace.as_ref()
 1780                    && let Some(display) = workspace.display
 1781                    && let Some(bounds) = workspace.window_bounds.as_ref()
 1782                {
 1783                    // Reopening an existing workspace - restore its saved bounds
 1784                    (Some(bounds.0), Some(display))
 1785                } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 1786                    // New or empty workspace - use the last known window bounds
 1787                    (Some(bounds), Some(display))
 1788                } else {
 1789                    // New window - let GPUI's default_bounds() handle cascading
 1790                    (None, None)
 1791                };
 1792
 1793                // Use the serialized workspace to construct the new window
 1794                let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1795                options.window_bounds = window_bounds;
 1796                let centered_layout = serialized_workspace
 1797                    .as_ref()
 1798                    .map(|w| w.centered_layout)
 1799                    .unwrap_or(false);
 1800                cx.open_window(options, {
 1801                    let app_state = app_state.clone();
 1802                    let project_handle = project_handle.clone();
 1803                    move |window, cx| {
 1804                        cx.new(|cx| {
 1805                            let mut workspace = Workspace::new(
 1806                                Some(workspace_id),
 1807                                project_handle,
 1808                                app_state,
 1809                                window,
 1810                                cx,
 1811                            );
 1812                            workspace.centered_layout = centered_layout;
 1813
 1814                            // Call init callback to add items before window renders
 1815                            if let Some(init) = init {
 1816                                init(&mut workspace, window, cx);
 1817                            }
 1818
 1819                            workspace
 1820                        })
 1821                    }
 1822                })?
 1823            };
 1824
 1825            notify_if_database_failed(window, cx);
 1826            let opened_items = window
 1827                .update(cx, |_workspace, window, cx| {
 1828                    open_items(serialized_workspace, project_paths, window, cx)
 1829                })?
 1830                .await
 1831                .unwrap_or_default();
 1832
 1833            window
 1834                .update(cx, |workspace, window, cx| {
 1835                    window.activate_window();
 1836                    workspace.update_history(cx);
 1837                })
 1838                .log_err();
 1839            Ok((window, opened_items))
 1840        })
 1841    }
 1842
 1843    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1844        self.weak_self.clone()
 1845    }
 1846
 1847    pub fn left_dock(&self) -> &Entity<Dock> {
 1848        &self.left_dock
 1849    }
 1850
 1851    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1852        &self.bottom_dock
 1853    }
 1854
 1855    pub fn set_bottom_dock_layout(
 1856        &mut self,
 1857        layout: BottomDockLayout,
 1858        window: &mut Window,
 1859        cx: &mut Context<Self>,
 1860    ) {
 1861        let fs = self.project().read(cx).fs();
 1862        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1863            content.workspace.bottom_dock_layout = Some(layout);
 1864        });
 1865
 1866        cx.notify();
 1867        self.serialize_workspace(window, cx);
 1868    }
 1869
 1870    pub fn right_dock(&self) -> &Entity<Dock> {
 1871        &self.right_dock
 1872    }
 1873
 1874    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1875        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1876    }
 1877
 1878    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1879        match position {
 1880            DockPosition::Left => &self.left_dock,
 1881            DockPosition::Bottom => &self.bottom_dock,
 1882            DockPosition::Right => &self.right_dock,
 1883        }
 1884    }
 1885
 1886    pub fn is_edited(&self) -> bool {
 1887        self.window_edited
 1888    }
 1889
 1890    pub fn add_panel<T: Panel>(
 1891        &mut self,
 1892        panel: Entity<T>,
 1893        window: &mut Window,
 1894        cx: &mut Context<Self>,
 1895    ) {
 1896        let focus_handle = panel.panel_focus_handle(cx);
 1897        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 1898            .detach();
 1899
 1900        let dock_position = panel.position(window, cx);
 1901        let dock = self.dock_at_position(dock_position);
 1902
 1903        dock.update(cx, |dock, cx| {
 1904            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 1905        });
 1906    }
 1907
 1908    pub fn remove_panel<T: Panel>(
 1909        &mut self,
 1910        panel: &Entity<T>,
 1911        window: &mut Window,
 1912        cx: &mut Context<Self>,
 1913    ) {
 1914        let mut found_in_dock = None;
 1915        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 1916            let found = dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 1917
 1918            if found {
 1919                found_in_dock = Some(dock.clone());
 1920            }
 1921        }
 1922        if let Some(found_in_dock) = found_in_dock {
 1923            let position = found_in_dock.read(cx).position();
 1924            let slot = utility_slot_for_dock_position(position);
 1925            self.clear_utility_pane_if_provider(slot, Entity::entity_id(panel), cx);
 1926        }
 1927    }
 1928
 1929    pub fn status_bar(&self) -> &Entity<StatusBar> {
 1930        &self.status_bar
 1931    }
 1932
 1933    pub fn status_bar_visible(&self, cx: &App) -> bool {
 1934        StatusBarSettings::get_global(cx).show
 1935    }
 1936
 1937    pub fn app_state(&self) -> &Arc<AppState> {
 1938        &self.app_state
 1939    }
 1940
 1941    pub fn user_store(&self) -> &Entity<UserStore> {
 1942        &self.app_state.user_store
 1943    }
 1944
 1945    pub fn project(&self) -> &Entity<Project> {
 1946        &self.project
 1947    }
 1948
 1949    pub fn path_style(&self, cx: &App) -> PathStyle {
 1950        self.project.read(cx).path_style(cx)
 1951    }
 1952
 1953    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 1954        let mut history: HashMap<EntityId, usize> = HashMap::default();
 1955
 1956        for pane_handle in &self.panes {
 1957            let pane = pane_handle.read(cx);
 1958
 1959            for entry in pane.activation_history() {
 1960                history.insert(
 1961                    entry.entity_id,
 1962                    history
 1963                        .get(&entry.entity_id)
 1964                        .cloned()
 1965                        .unwrap_or(0)
 1966                        .max(entry.timestamp),
 1967                );
 1968            }
 1969        }
 1970
 1971        history
 1972    }
 1973
 1974    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 1975        let mut recent_item: Option<Entity<T>> = None;
 1976        let mut recent_timestamp = 0;
 1977        for pane_handle in &self.panes {
 1978            let pane = pane_handle.read(cx);
 1979            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 1980                pane.items().map(|item| (item.item_id(), item)).collect();
 1981            for entry in pane.activation_history() {
 1982                if entry.timestamp > recent_timestamp
 1983                    && let Some(&item) = item_map.get(&entry.entity_id)
 1984                    && let Some(typed_item) = item.act_as::<T>(cx)
 1985                {
 1986                    recent_timestamp = entry.timestamp;
 1987                    recent_item = Some(typed_item);
 1988                }
 1989            }
 1990        }
 1991        recent_item
 1992    }
 1993
 1994    pub fn recent_navigation_history_iter(
 1995        &self,
 1996        cx: &App,
 1997    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 1998        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 1999        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2000
 2001        for pane in &self.panes {
 2002            let pane = pane.read(cx);
 2003
 2004            pane.nav_history()
 2005                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 2006                    if let Some(fs_path) = &fs_path {
 2007                        abs_paths_opened
 2008                            .entry(fs_path.clone())
 2009                            .or_default()
 2010                            .insert(project_path.clone());
 2011                    }
 2012                    let timestamp = entry.timestamp;
 2013                    match history.entry(project_path) {
 2014                        hash_map::Entry::Occupied(mut entry) => {
 2015                            let (_, old_timestamp) = entry.get();
 2016                            if &timestamp > old_timestamp {
 2017                                entry.insert((fs_path, timestamp));
 2018                            }
 2019                        }
 2020                        hash_map::Entry::Vacant(entry) => {
 2021                            entry.insert((fs_path, timestamp));
 2022                        }
 2023                    }
 2024                });
 2025
 2026            if let Some(item) = pane.active_item()
 2027                && let Some(project_path) = item.project_path(cx)
 2028            {
 2029                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2030
 2031                if let Some(fs_path) = &fs_path {
 2032                    abs_paths_opened
 2033                        .entry(fs_path.clone())
 2034                        .or_default()
 2035                        .insert(project_path.clone());
 2036                }
 2037
 2038                history.insert(project_path, (fs_path, std::usize::MAX));
 2039            }
 2040        }
 2041
 2042        history
 2043            .into_iter()
 2044            .sorted_by_key(|(_, (_, order))| *order)
 2045            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2046            .rev()
 2047            .filter(move |(history_path, abs_path)| {
 2048                let latest_project_path_opened = abs_path
 2049                    .as_ref()
 2050                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2051                    .and_then(|project_paths| {
 2052                        project_paths
 2053                            .iter()
 2054                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2055                    });
 2056
 2057                latest_project_path_opened.is_none_or(|path| path == history_path)
 2058            })
 2059    }
 2060
 2061    pub fn recent_navigation_history(
 2062        &self,
 2063        limit: Option<usize>,
 2064        cx: &App,
 2065    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2066        self.recent_navigation_history_iter(cx)
 2067            .take(limit.unwrap_or(usize::MAX))
 2068            .collect()
 2069    }
 2070
 2071    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2072        for pane in &self.panes {
 2073            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2074        }
 2075    }
 2076
 2077    fn navigate_history(
 2078        &mut self,
 2079        pane: WeakEntity<Pane>,
 2080        mode: NavigationMode,
 2081        window: &mut Window,
 2082        cx: &mut Context<Workspace>,
 2083    ) -> Task<Result<()>> {
 2084        self.navigate_history_impl(pane, mode, window, |history, cx| history.pop(mode, cx), cx)
 2085    }
 2086
 2087    fn navigate_tag_history(
 2088        &mut self,
 2089        pane: WeakEntity<Pane>,
 2090        mode: TagNavigationMode,
 2091        window: &mut Window,
 2092        cx: &mut Context<Workspace>,
 2093    ) -> Task<Result<()>> {
 2094        self.navigate_history_impl(
 2095            pane,
 2096            NavigationMode::Normal,
 2097            window,
 2098            |history, _cx| history.pop_tag(mode),
 2099            cx,
 2100        )
 2101    }
 2102
 2103    fn navigate_history_impl(
 2104        &mut self,
 2105        pane: WeakEntity<Pane>,
 2106        mode: NavigationMode,
 2107        window: &mut Window,
 2108        mut cb: impl FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2109        cx: &mut Context<Workspace>,
 2110    ) -> Task<Result<()>> {
 2111        let to_load = if let Some(pane) = pane.upgrade() {
 2112            pane.update(cx, |pane, cx| {
 2113                window.focus(&pane.focus_handle(cx), cx);
 2114                loop {
 2115                    // Retrieve the weak item handle from the history.
 2116                    let entry = cb(pane.nav_history_mut(), cx)?;
 2117
 2118                    // If the item is still present in this pane, then activate it.
 2119                    if let Some(index) = entry
 2120                        .item
 2121                        .upgrade()
 2122                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2123                    {
 2124                        let prev_active_item_index = pane.active_item_index();
 2125                        pane.nav_history_mut().set_mode(mode);
 2126                        pane.activate_item(index, true, true, window, cx);
 2127                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2128
 2129                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2130                        if let Some(data) = entry.data {
 2131                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2132                        }
 2133
 2134                        if navigated {
 2135                            break None;
 2136                        }
 2137                    } else {
 2138                        // If the item is no longer present in this pane, then retrieve its
 2139                        // path info in order to reopen it.
 2140                        break pane
 2141                            .nav_history()
 2142                            .path_for_item(entry.item.id())
 2143                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2144                    }
 2145                }
 2146            })
 2147        } else {
 2148            None
 2149        };
 2150
 2151        if let Some((project_path, abs_path, entry)) = to_load {
 2152            // If the item was no longer present, then load it again from its previous path, first try the local path
 2153            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2154
 2155            cx.spawn_in(window, async move  |workspace, cx| {
 2156                let open_by_project_path = open_by_project_path.await;
 2157                let mut navigated = false;
 2158                match open_by_project_path
 2159                    .with_context(|| format!("Navigating to {project_path:?}"))
 2160                {
 2161                    Ok((project_entry_id, build_item)) => {
 2162                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2163                            pane.nav_history_mut().set_mode(mode);
 2164                            pane.active_item().map(|p| p.item_id())
 2165                        })?;
 2166
 2167                        pane.update_in(cx, |pane, window, cx| {
 2168                            let item = pane.open_item(
 2169                                project_entry_id,
 2170                                project_path,
 2171                                true,
 2172                                entry.is_preview,
 2173                                true,
 2174                                None,
 2175                                window, cx,
 2176                                build_item,
 2177                            );
 2178                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2179                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2180                            if let Some(data) = entry.data {
 2181                                navigated |= item.navigate(data, window, cx);
 2182                            }
 2183                        })?;
 2184                    }
 2185                    Err(open_by_project_path_e) => {
 2186                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2187                        // and its worktree is now dropped
 2188                        if let Some(abs_path) = abs_path {
 2189                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2190                                pane.nav_history_mut().set_mode(mode);
 2191                                pane.active_item().map(|p| p.item_id())
 2192                            })?;
 2193                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2194                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2195                            })?;
 2196                            match open_by_abs_path
 2197                                .await
 2198                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2199                            {
 2200                                Ok(item) => {
 2201                                    pane.update_in(cx, |pane, window, cx| {
 2202                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2203                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2204                                        if let Some(data) = entry.data {
 2205                                            navigated |= item.navigate(data, window, cx);
 2206                                        }
 2207                                    })?;
 2208                                }
 2209                                Err(open_by_abs_path_e) => {
 2210                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2211                                }
 2212                            }
 2213                        }
 2214                    }
 2215                }
 2216
 2217                if !navigated {
 2218                    workspace
 2219                        .update_in(cx, |workspace, window, cx| {
 2220                            Self::navigate_history(workspace, pane, mode, window, cx)
 2221                        })?
 2222                        .await?;
 2223                }
 2224
 2225                Ok(())
 2226            })
 2227        } else {
 2228            Task::ready(Ok(()))
 2229        }
 2230    }
 2231
 2232    pub fn go_back(
 2233        &mut self,
 2234        pane: WeakEntity<Pane>,
 2235        window: &mut Window,
 2236        cx: &mut Context<Workspace>,
 2237    ) -> Task<Result<()>> {
 2238        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2239    }
 2240
 2241    pub fn go_forward(
 2242        &mut self,
 2243        pane: WeakEntity<Pane>,
 2244        window: &mut Window,
 2245        cx: &mut Context<Workspace>,
 2246    ) -> Task<Result<()>> {
 2247        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2248    }
 2249
 2250    pub fn reopen_closed_item(
 2251        &mut self,
 2252        window: &mut Window,
 2253        cx: &mut Context<Workspace>,
 2254    ) -> Task<Result<()>> {
 2255        self.navigate_history(
 2256            self.active_pane().downgrade(),
 2257            NavigationMode::ReopeningClosedItem,
 2258            window,
 2259            cx,
 2260        )
 2261    }
 2262
 2263    pub fn client(&self) -> &Arc<Client> {
 2264        &self.app_state.client
 2265    }
 2266
 2267    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2268        self.titlebar_item = Some(item);
 2269        cx.notify();
 2270    }
 2271
 2272    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2273        self.on_prompt_for_new_path = Some(prompt)
 2274    }
 2275
 2276    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2277        self.on_prompt_for_open_path = Some(prompt)
 2278    }
 2279
 2280    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2281        self.terminal_provider = Some(Box::new(provider));
 2282    }
 2283
 2284    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2285        self.debugger_provider = Some(Arc::new(provider));
 2286    }
 2287
 2288    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2289        self.debugger_provider.clone()
 2290    }
 2291
 2292    pub fn prompt_for_open_path(
 2293        &mut self,
 2294        path_prompt_options: PathPromptOptions,
 2295        lister: DirectoryLister,
 2296        window: &mut Window,
 2297        cx: &mut Context<Self>,
 2298    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2299        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2300            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2301            let rx = prompt(self, lister, window, cx);
 2302            self.on_prompt_for_open_path = Some(prompt);
 2303            rx
 2304        } else {
 2305            let (tx, rx) = oneshot::channel();
 2306            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2307
 2308            cx.spawn_in(window, async move |workspace, cx| {
 2309                let Ok(result) = abs_path.await else {
 2310                    return Ok(());
 2311                };
 2312
 2313                match result {
 2314                    Ok(result) => {
 2315                        tx.send(result).ok();
 2316                    }
 2317                    Err(err) => {
 2318                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2319                            workspace.show_portal_error(err.to_string(), cx);
 2320                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2321                            let rx = prompt(workspace, lister, window, cx);
 2322                            workspace.on_prompt_for_open_path = Some(prompt);
 2323                            rx
 2324                        })?;
 2325                        if let Ok(path) = rx.await {
 2326                            tx.send(path).ok();
 2327                        }
 2328                    }
 2329                };
 2330                anyhow::Ok(())
 2331            })
 2332            .detach();
 2333
 2334            rx
 2335        }
 2336    }
 2337
 2338    pub fn prompt_for_new_path(
 2339        &mut self,
 2340        lister: DirectoryLister,
 2341        suggested_name: Option<String>,
 2342        window: &mut Window,
 2343        cx: &mut Context<Self>,
 2344    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2345        if self.project.read(cx).is_via_collab()
 2346            || self.project.read(cx).is_via_remote_server()
 2347            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2348        {
 2349            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2350            let rx = prompt(self, lister, window, cx);
 2351            self.on_prompt_for_new_path = Some(prompt);
 2352            return rx;
 2353        }
 2354
 2355        let (tx, rx) = oneshot::channel();
 2356        cx.spawn_in(window, async move |workspace, cx| {
 2357            let abs_path = workspace.update(cx, |workspace, cx| {
 2358                let relative_to = workspace
 2359                    .most_recent_active_path(cx)
 2360                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2361                    .or_else(|| {
 2362                        let project = workspace.project.read(cx);
 2363                        project.visible_worktrees(cx).find_map(|worktree| {
 2364                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2365                        })
 2366                    })
 2367                    .or_else(std::env::home_dir)
 2368                    .unwrap_or_else(|| PathBuf::from(""));
 2369                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2370            })?;
 2371            let abs_path = match abs_path.await? {
 2372                Ok(path) => path,
 2373                Err(err) => {
 2374                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2375                        workspace.show_portal_error(err.to_string(), cx);
 2376
 2377                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2378                        let rx = prompt(workspace, lister, window, cx);
 2379                        workspace.on_prompt_for_new_path = Some(prompt);
 2380                        rx
 2381                    })?;
 2382                    if let Ok(path) = rx.await {
 2383                        tx.send(path).ok();
 2384                    }
 2385                    return anyhow::Ok(());
 2386                }
 2387            };
 2388
 2389            tx.send(abs_path.map(|path| vec![path])).ok();
 2390            anyhow::Ok(())
 2391        })
 2392        .detach();
 2393
 2394        rx
 2395    }
 2396
 2397    pub fn titlebar_item(&self) -> Option<AnyView> {
 2398        self.titlebar_item.clone()
 2399    }
 2400
 2401    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2402    /// When set, git-related operations should use this worktree instead of deriving
 2403    /// the active worktree from the focused file.
 2404    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2405        self.active_worktree_override
 2406    }
 2407
 2408    pub fn set_active_worktree_override(
 2409        &mut self,
 2410        worktree_id: Option<WorktreeId>,
 2411        cx: &mut Context<Self>,
 2412    ) {
 2413        self.active_worktree_override = worktree_id;
 2414        cx.notify();
 2415    }
 2416
 2417    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2418        self.active_worktree_override = None;
 2419        cx.notify();
 2420    }
 2421
 2422    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2423    ///
 2424    /// If the given workspace has a local project, then it will be passed
 2425    /// to the callback. Otherwise, a new empty window will be created.
 2426    pub fn with_local_workspace<T, F>(
 2427        &mut self,
 2428        window: &mut Window,
 2429        cx: &mut Context<Self>,
 2430        callback: F,
 2431    ) -> Task<Result<T>>
 2432    where
 2433        T: 'static,
 2434        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2435    {
 2436        if self.project.read(cx).is_local() {
 2437            Task::ready(Ok(callback(self, window, cx)))
 2438        } else {
 2439            let env = self.project.read(cx).cli_environment(cx);
 2440            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2441            cx.spawn_in(window, async move |_vh, cx| {
 2442                let (workspace, _) = task.await?;
 2443                workspace.update(cx, callback)
 2444            })
 2445        }
 2446    }
 2447
 2448    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2449    ///
 2450    /// If the given workspace has a local project, then it will be passed
 2451    /// to the callback. Otherwise, a new empty window will be created.
 2452    pub fn with_local_or_wsl_workspace<T, F>(
 2453        &mut self,
 2454        window: &mut Window,
 2455        cx: &mut Context<Self>,
 2456        callback: F,
 2457    ) -> Task<Result<T>>
 2458    where
 2459        T: 'static,
 2460        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2461    {
 2462        let project = self.project.read(cx);
 2463        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2464            Task::ready(Ok(callback(self, window, cx)))
 2465        } else {
 2466            let env = self.project.read(cx).cli_environment(cx);
 2467            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2468            cx.spawn_in(window, async move |_vh, cx| {
 2469                let (workspace, _) = task.await?;
 2470                workspace.update(cx, callback)
 2471            })
 2472        }
 2473    }
 2474
 2475    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2476        self.project.read(cx).worktrees(cx)
 2477    }
 2478
 2479    pub fn visible_worktrees<'a>(
 2480        &self,
 2481        cx: &'a App,
 2482    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2483        self.project.read(cx).visible_worktrees(cx)
 2484    }
 2485
 2486    #[cfg(any(test, feature = "test-support"))]
 2487    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2488        let futures = self
 2489            .worktrees(cx)
 2490            .filter_map(|worktree| worktree.read(cx).as_local())
 2491            .map(|worktree| worktree.scan_complete())
 2492            .collect::<Vec<_>>();
 2493        async move {
 2494            for future in futures {
 2495                future.await;
 2496            }
 2497        }
 2498    }
 2499
 2500    pub fn close_global(cx: &mut App) {
 2501        cx.defer(|cx| {
 2502            cx.windows().iter().find(|window| {
 2503                window
 2504                    .update(cx, |_, window, _| {
 2505                        if window.is_window_active() {
 2506                            //This can only get called when the window's project connection has been lost
 2507                            //so we don't need to prompt the user for anything and instead just close the window
 2508                            window.remove_window();
 2509                            true
 2510                        } else {
 2511                            false
 2512                        }
 2513                    })
 2514                    .unwrap_or(false)
 2515            });
 2516        });
 2517    }
 2518
 2519    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2520        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2521        cx.spawn_in(window, async move |_, cx| {
 2522            if prepare.await? {
 2523                cx.update(|window, _cx| window.remove_window())?;
 2524            }
 2525            anyhow::Ok(())
 2526        })
 2527        .detach_and_log_err(cx)
 2528    }
 2529
 2530    pub fn move_focused_panel_to_next_position(
 2531        &mut self,
 2532        _: &MoveFocusedPanelToNextPosition,
 2533        window: &mut Window,
 2534        cx: &mut Context<Self>,
 2535    ) {
 2536        let docks = self.all_docks();
 2537        let active_dock = docks
 2538            .into_iter()
 2539            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2540
 2541        if let Some(dock) = active_dock {
 2542            dock.update(cx, |dock, cx| {
 2543                let active_panel = dock
 2544                    .active_panel()
 2545                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2546
 2547                if let Some(panel) = active_panel {
 2548                    panel.move_to_next_position(window, cx);
 2549                }
 2550            })
 2551        }
 2552    }
 2553
 2554    pub fn prepare_to_close(
 2555        &mut self,
 2556        close_intent: CloseIntent,
 2557        window: &mut Window,
 2558        cx: &mut Context<Self>,
 2559    ) -> Task<Result<bool>> {
 2560        let active_call = self.active_call().cloned();
 2561
 2562        cx.spawn_in(window, async move |this, cx| {
 2563            this.update(cx, |this, _| {
 2564                if close_intent == CloseIntent::CloseWindow {
 2565                    this.removing = true;
 2566                }
 2567            })?;
 2568
 2569            let workspace_count = cx.update(|_window, cx| {
 2570                cx.windows()
 2571                    .iter()
 2572                    .filter(|window| window.downcast::<Workspace>().is_some())
 2573                    .count()
 2574            })?;
 2575
 2576            #[cfg(target_os = "macos")]
 2577            let save_last_workspace = false;
 2578
 2579            // On Linux and Windows, closing the last window should restore the last workspace.
 2580            #[cfg(not(target_os = "macos"))]
 2581            let save_last_workspace = {
 2582                let remaining_workspaces = cx.update(|_window, cx| {
 2583                    cx.windows()
 2584                        .iter()
 2585                        .filter_map(|window| window.downcast::<Workspace>())
 2586                        .filter_map(|workspace| {
 2587                            workspace
 2588                                .update(cx, |workspace, _, _| workspace.removing)
 2589                                .ok()
 2590                        })
 2591                        .filter(|removing| !removing)
 2592                        .count()
 2593                })?;
 2594
 2595                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2596            };
 2597
 2598            if let Some(active_call) = active_call
 2599                && workspace_count == 1
 2600                && active_call.read_with(cx, |call, _| call.room().is_some())
 2601            {
 2602                if close_intent == CloseIntent::CloseWindow {
 2603                    let answer = cx.update(|window, cx| {
 2604                        window.prompt(
 2605                            PromptLevel::Warning,
 2606                            "Do you want to leave the current call?",
 2607                            None,
 2608                            &["Close window and hang up", "Cancel"],
 2609                            cx,
 2610                        )
 2611                    })?;
 2612
 2613                    if answer.await.log_err() == Some(1) {
 2614                        return anyhow::Ok(false);
 2615                    } else {
 2616                        active_call
 2617                            .update(cx, |call, cx| call.hang_up(cx))
 2618                            .await
 2619                            .log_err();
 2620                    }
 2621                }
 2622                if close_intent == CloseIntent::ReplaceWindow {
 2623                    _ = active_call.update(cx, |this, cx| {
 2624                        let workspace = cx
 2625                            .windows()
 2626                            .iter()
 2627                            .filter_map(|window| window.downcast::<Workspace>())
 2628                            .next()
 2629                            .unwrap();
 2630                        let project = workspace.read(cx)?.project.clone();
 2631                        if project.read(cx).is_shared() {
 2632                            this.unshare_project(project, cx)?;
 2633                        }
 2634                        Ok::<_, anyhow::Error>(())
 2635                    })?;
 2636                }
 2637            }
 2638
 2639            let save_result = this
 2640                .update_in(cx, |this, window, cx| {
 2641                    this.save_all_internal(SaveIntent::Close, window, cx)
 2642                })?
 2643                .await;
 2644
 2645            // If we're not quitting, but closing, we remove the workspace from
 2646            // the current session.
 2647            if close_intent != CloseIntent::Quit
 2648                && !save_last_workspace
 2649                && save_result.as_ref().is_ok_and(|&res| res)
 2650            {
 2651                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2652                    .await;
 2653            }
 2654
 2655            save_result
 2656        })
 2657    }
 2658
 2659    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2660        self.save_all_internal(
 2661            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2662            window,
 2663            cx,
 2664        )
 2665        .detach_and_log_err(cx);
 2666    }
 2667
 2668    fn send_keystrokes(
 2669        &mut self,
 2670        action: &SendKeystrokes,
 2671        window: &mut Window,
 2672        cx: &mut Context<Self>,
 2673    ) {
 2674        let keystrokes: Vec<Keystroke> = action
 2675            .0
 2676            .split(' ')
 2677            .flat_map(|k| Keystroke::parse(k).log_err())
 2678            .map(|k| {
 2679                cx.keyboard_mapper()
 2680                    .map_key_equivalent(k, true)
 2681                    .inner()
 2682                    .clone()
 2683            })
 2684            .collect();
 2685        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2686    }
 2687
 2688    pub fn send_keystrokes_impl(
 2689        &mut self,
 2690        keystrokes: Vec<Keystroke>,
 2691        window: &mut Window,
 2692        cx: &mut Context<Self>,
 2693    ) -> Shared<Task<()>> {
 2694        let mut state = self.dispatching_keystrokes.borrow_mut();
 2695        if !state.dispatched.insert(keystrokes.clone()) {
 2696            cx.propagate();
 2697            return state.task.clone().unwrap();
 2698        }
 2699
 2700        state.queue.extend(keystrokes);
 2701
 2702        let keystrokes = self.dispatching_keystrokes.clone();
 2703        if state.task.is_none() {
 2704            state.task = Some(
 2705                window
 2706                    .spawn(cx, async move |cx| {
 2707                        // limit to 100 keystrokes to avoid infinite recursion.
 2708                        for _ in 0..100 {
 2709                            let mut state = keystrokes.borrow_mut();
 2710                            let Some(keystroke) = state.queue.pop_front() else {
 2711                                state.dispatched.clear();
 2712                                state.task.take();
 2713                                return;
 2714                            };
 2715                            drop(state);
 2716                            cx.update(|window, cx| {
 2717                                let focused = window.focused(cx);
 2718                                window.dispatch_keystroke(keystroke.clone(), cx);
 2719                                if window.focused(cx) != focused {
 2720                                    // dispatch_keystroke may cause the focus to change.
 2721                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2722                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2723                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2724                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2725                                    // )
 2726                                    window.draw(cx).clear();
 2727                                }
 2728                            })
 2729                            .ok();
 2730                        }
 2731
 2732                        *keystrokes.borrow_mut() = Default::default();
 2733                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2734                    })
 2735                    .shared(),
 2736            );
 2737        }
 2738        state.task.clone().unwrap()
 2739    }
 2740
 2741    fn save_all_internal(
 2742        &mut self,
 2743        mut save_intent: SaveIntent,
 2744        window: &mut Window,
 2745        cx: &mut Context<Self>,
 2746    ) -> Task<Result<bool>> {
 2747        if self.project.read(cx).is_disconnected(cx) {
 2748            return Task::ready(Ok(true));
 2749        }
 2750        let dirty_items = self
 2751            .panes
 2752            .iter()
 2753            .flat_map(|pane| {
 2754                pane.read(cx).items().filter_map(|item| {
 2755                    if item.is_dirty(cx) {
 2756                        item.tab_content_text(0, cx);
 2757                        Some((pane.downgrade(), item.boxed_clone()))
 2758                    } else {
 2759                        None
 2760                    }
 2761                })
 2762            })
 2763            .collect::<Vec<_>>();
 2764
 2765        let project = self.project.clone();
 2766        cx.spawn_in(window, async move |workspace, cx| {
 2767            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2768                let (serialize_tasks, remaining_dirty_items) =
 2769                    workspace.update_in(cx, |workspace, window, cx| {
 2770                        let mut remaining_dirty_items = Vec::new();
 2771                        let mut serialize_tasks = Vec::new();
 2772                        for (pane, item) in dirty_items {
 2773                            if let Some(task) = item
 2774                                .to_serializable_item_handle(cx)
 2775                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2776                            {
 2777                                serialize_tasks.push(task);
 2778                            } else {
 2779                                remaining_dirty_items.push((pane, item));
 2780                            }
 2781                        }
 2782                        (serialize_tasks, remaining_dirty_items)
 2783                    })?;
 2784
 2785                futures::future::try_join_all(serialize_tasks).await?;
 2786
 2787                if remaining_dirty_items.len() > 1 {
 2788                    let answer = workspace.update_in(cx, |_, window, cx| {
 2789                        let detail = Pane::file_names_for_prompt(
 2790                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2791                            cx,
 2792                        );
 2793                        window.prompt(
 2794                            PromptLevel::Warning,
 2795                            "Do you want to save all changes in the following files?",
 2796                            Some(&detail),
 2797                            &["Save all", "Discard all", "Cancel"],
 2798                            cx,
 2799                        )
 2800                    })?;
 2801                    match answer.await.log_err() {
 2802                        Some(0) => save_intent = SaveIntent::SaveAll,
 2803                        Some(1) => save_intent = SaveIntent::Skip,
 2804                        Some(2) => return Ok(false),
 2805                        _ => {}
 2806                    }
 2807                }
 2808
 2809                remaining_dirty_items
 2810            } else {
 2811                dirty_items
 2812            };
 2813
 2814            for (pane, item) in dirty_items {
 2815                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2816                    (
 2817                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2818                        item.project_entry_ids(cx),
 2819                    )
 2820                })?;
 2821                if (singleton || !project_entry_ids.is_empty())
 2822                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2823                {
 2824                    return Ok(false);
 2825                }
 2826            }
 2827            Ok(true)
 2828        })
 2829    }
 2830
 2831    pub fn open_workspace_for_paths(
 2832        &mut self,
 2833        replace_current_window: bool,
 2834        paths: Vec<PathBuf>,
 2835        window: &mut Window,
 2836        cx: &mut Context<Self>,
 2837    ) -> Task<Result<()>> {
 2838        let window_handle = window.window_handle().downcast::<Self>();
 2839        let is_remote = self.project.read(cx).is_via_collab();
 2840        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2841        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2842
 2843        let window_to_replace = if replace_current_window {
 2844            window_handle
 2845        } else if is_remote || has_worktree || has_dirty_items {
 2846            None
 2847        } else {
 2848            window_handle
 2849        };
 2850        let app_state = self.app_state.clone();
 2851
 2852        cx.spawn(async move |_, cx| {
 2853            cx.update(|cx| {
 2854                open_paths(
 2855                    &paths,
 2856                    app_state,
 2857                    OpenOptions {
 2858                        replace_window: window_to_replace,
 2859                        ..Default::default()
 2860                    },
 2861                    cx,
 2862                )
 2863            })
 2864            .await?;
 2865            Ok(())
 2866        })
 2867    }
 2868
 2869    #[allow(clippy::type_complexity)]
 2870    pub fn open_paths(
 2871        &mut self,
 2872        mut abs_paths: Vec<PathBuf>,
 2873        options: OpenOptions,
 2874        pane: Option<WeakEntity<Pane>>,
 2875        window: &mut Window,
 2876        cx: &mut Context<Self>,
 2877    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2878        let fs = self.app_state.fs.clone();
 2879
 2880        let caller_ordered_abs_paths = abs_paths.clone();
 2881
 2882        // Sort the paths to ensure we add worktrees for parents before their children.
 2883        abs_paths.sort_unstable();
 2884        cx.spawn_in(window, async move |this, cx| {
 2885            let mut tasks = Vec::with_capacity(abs_paths.len());
 2886
 2887            for abs_path in &abs_paths {
 2888                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2889                    OpenVisible::All => Some(true),
 2890                    OpenVisible::None => Some(false),
 2891                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 2892                        Some(Some(metadata)) => Some(!metadata.is_dir),
 2893                        Some(None) => Some(true),
 2894                        None => None,
 2895                    },
 2896                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 2897                        Some(Some(metadata)) => Some(metadata.is_dir),
 2898                        Some(None) => Some(false),
 2899                        None => None,
 2900                    },
 2901                };
 2902                let project_path = match visible {
 2903                    Some(visible) => match this
 2904                        .update(cx, |this, cx| {
 2905                            Workspace::project_path_for_path(
 2906                                this.project.clone(),
 2907                                abs_path,
 2908                                visible,
 2909                                cx,
 2910                            )
 2911                        })
 2912                        .log_err()
 2913                    {
 2914                        Some(project_path) => project_path.await.log_err(),
 2915                        None => None,
 2916                    },
 2917                    None => None,
 2918                };
 2919
 2920                let this = this.clone();
 2921                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 2922                let fs = fs.clone();
 2923                let pane = pane.clone();
 2924                let task = cx.spawn(async move |cx| {
 2925                    let (_worktree, project_path) = project_path?;
 2926                    if fs.is_dir(&abs_path).await {
 2927                        // Opening a directory should not race to update the active entry.
 2928                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 2929                        None
 2930                    } else {
 2931                        Some(
 2932                            this.update_in(cx, |this, window, cx| {
 2933                                this.open_path(
 2934                                    project_path,
 2935                                    pane,
 2936                                    options.focus.unwrap_or(true),
 2937                                    window,
 2938                                    cx,
 2939                                )
 2940                            })
 2941                            .ok()?
 2942                            .await,
 2943                        )
 2944                    }
 2945                });
 2946                tasks.push(task);
 2947            }
 2948
 2949            let results = futures::future::join_all(tasks).await;
 2950
 2951            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 2952            let mut winner: Option<(PathBuf, bool)> = None;
 2953            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 2954                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 2955                    if !metadata.is_dir {
 2956                        winner = Some((abs_path, false));
 2957                        break;
 2958                    }
 2959                    if winner.is_none() {
 2960                        winner = Some((abs_path, true));
 2961                    }
 2962                } else if winner.is_none() {
 2963                    winner = Some((abs_path, false));
 2964                }
 2965            }
 2966
 2967            // Compute the winner entry id on the foreground thread and emit once, after all
 2968            // paths finish opening. This avoids races between concurrently-opening paths
 2969            // (directories in particular) and makes the resulting project panel selection
 2970            // deterministic.
 2971            if let Some((winner_abs_path, winner_is_dir)) = winner {
 2972                'emit_winner: {
 2973                    let winner_abs_path: Arc<Path> =
 2974                        SanitizedPath::new(&winner_abs_path).as_path().into();
 2975
 2976                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2977                        OpenVisible::All => true,
 2978                        OpenVisible::None => false,
 2979                        OpenVisible::OnlyFiles => !winner_is_dir,
 2980                        OpenVisible::OnlyDirectories => winner_is_dir,
 2981                    };
 2982
 2983                    let Some(worktree_task) = this
 2984                        .update(cx, |workspace, cx| {
 2985                            workspace.project.update(cx, |project, cx| {
 2986                                project.find_or_create_worktree(
 2987                                    winner_abs_path.as_ref(),
 2988                                    visible,
 2989                                    cx,
 2990                                )
 2991                            })
 2992                        })
 2993                        .ok()
 2994                    else {
 2995                        break 'emit_winner;
 2996                    };
 2997
 2998                    let Ok((worktree, _)) = worktree_task.await else {
 2999                        break 'emit_winner;
 3000                    };
 3001
 3002                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3003                        let worktree = worktree.read(cx);
 3004                        let worktree_abs_path = worktree.abs_path();
 3005                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3006                            worktree.root_entry()
 3007                        } else {
 3008                            winner_abs_path
 3009                                .strip_prefix(worktree_abs_path.as_ref())
 3010                                .ok()
 3011                                .and_then(|relative_path| {
 3012                                    let relative_path =
 3013                                        RelPath::new(relative_path, PathStyle::local())
 3014                                            .log_err()?;
 3015                                    worktree.entry_for_path(&relative_path)
 3016                                })
 3017                        }?;
 3018                        Some(entry.id)
 3019                    }) else {
 3020                        break 'emit_winner;
 3021                    };
 3022
 3023                    this.update(cx, |workspace, cx| {
 3024                        workspace.project.update(cx, |_, cx| {
 3025                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3026                        });
 3027                    })
 3028                    .ok();
 3029                }
 3030            }
 3031
 3032            results
 3033        })
 3034    }
 3035
 3036    pub fn open_resolved_path(
 3037        &mut self,
 3038        path: ResolvedPath,
 3039        window: &mut Window,
 3040        cx: &mut Context<Self>,
 3041    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3042        match path {
 3043            ResolvedPath::ProjectPath { project_path, .. } => {
 3044                self.open_path(project_path, None, true, window, cx)
 3045            }
 3046            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3047                PathBuf::from(path),
 3048                OpenOptions {
 3049                    visible: Some(OpenVisible::None),
 3050                    ..Default::default()
 3051                },
 3052                window,
 3053                cx,
 3054            ),
 3055        }
 3056    }
 3057
 3058    pub fn absolute_path_of_worktree(
 3059        &self,
 3060        worktree_id: WorktreeId,
 3061        cx: &mut Context<Self>,
 3062    ) -> Option<PathBuf> {
 3063        self.project
 3064            .read(cx)
 3065            .worktree_for_id(worktree_id, cx)
 3066            // TODO: use `abs_path` or `root_dir`
 3067            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3068    }
 3069
 3070    fn add_folder_to_project(
 3071        &mut self,
 3072        _: &AddFolderToProject,
 3073        window: &mut Window,
 3074        cx: &mut Context<Self>,
 3075    ) {
 3076        let project = self.project.read(cx);
 3077        if project.is_via_collab() {
 3078            self.show_error(
 3079                &anyhow!("You cannot add folders to someone else's project"),
 3080                cx,
 3081            );
 3082            return;
 3083        }
 3084        let paths = self.prompt_for_open_path(
 3085            PathPromptOptions {
 3086                files: false,
 3087                directories: true,
 3088                multiple: true,
 3089                prompt: None,
 3090            },
 3091            DirectoryLister::Project(self.project.clone()),
 3092            window,
 3093            cx,
 3094        );
 3095        cx.spawn_in(window, async move |this, cx| {
 3096            if let Some(paths) = paths.await.log_err().flatten() {
 3097                let results = this
 3098                    .update_in(cx, |this, window, cx| {
 3099                        this.open_paths(
 3100                            paths,
 3101                            OpenOptions {
 3102                                visible: Some(OpenVisible::All),
 3103                                ..Default::default()
 3104                            },
 3105                            None,
 3106                            window,
 3107                            cx,
 3108                        )
 3109                    })?
 3110                    .await;
 3111                for result in results.into_iter().flatten() {
 3112                    result.log_err();
 3113                }
 3114            }
 3115            anyhow::Ok(())
 3116        })
 3117        .detach_and_log_err(cx);
 3118    }
 3119
 3120    pub fn project_path_for_path(
 3121        project: Entity<Project>,
 3122        abs_path: &Path,
 3123        visible: bool,
 3124        cx: &mut App,
 3125    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3126        let entry = project.update(cx, |project, cx| {
 3127            project.find_or_create_worktree(abs_path, visible, cx)
 3128        });
 3129        cx.spawn(async move |cx| {
 3130            let (worktree, path) = entry.await?;
 3131            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3132            Ok((worktree, ProjectPath { worktree_id, path }))
 3133        })
 3134    }
 3135
 3136    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3137        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3138    }
 3139
 3140    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3141        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3142    }
 3143
 3144    pub fn items_of_type<'a, T: Item>(
 3145        &'a self,
 3146        cx: &'a App,
 3147    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3148        self.panes
 3149            .iter()
 3150            .flat_map(|pane| pane.read(cx).items_of_type())
 3151    }
 3152
 3153    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3154        self.active_pane().read(cx).active_item()
 3155    }
 3156
 3157    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3158        let item = self.active_item(cx)?;
 3159        item.to_any_view().downcast::<I>().ok()
 3160    }
 3161
 3162    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3163        self.active_item(cx).and_then(|item| item.project_path(cx))
 3164    }
 3165
 3166    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3167        self.recent_navigation_history_iter(cx)
 3168            .filter_map(|(path, abs_path)| {
 3169                let worktree = self
 3170                    .project
 3171                    .read(cx)
 3172                    .worktree_for_id(path.worktree_id, cx)?;
 3173                if worktree.read(cx).is_visible() {
 3174                    abs_path
 3175                } else {
 3176                    None
 3177                }
 3178            })
 3179            .next()
 3180    }
 3181
 3182    pub fn save_active_item(
 3183        &mut self,
 3184        save_intent: SaveIntent,
 3185        window: &mut Window,
 3186        cx: &mut App,
 3187    ) -> Task<Result<()>> {
 3188        let project = self.project.clone();
 3189        let pane = self.active_pane();
 3190        let item = pane.read(cx).active_item();
 3191        let pane = pane.downgrade();
 3192
 3193        window.spawn(cx, async move |cx| {
 3194            if let Some(item) = item {
 3195                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3196                    .await
 3197                    .map(|_| ())
 3198            } else {
 3199                Ok(())
 3200            }
 3201        })
 3202    }
 3203
 3204    pub fn close_inactive_items_and_panes(
 3205        &mut self,
 3206        action: &CloseInactiveTabsAndPanes,
 3207        window: &mut Window,
 3208        cx: &mut Context<Self>,
 3209    ) {
 3210        if let Some(task) = self.close_all_internal(
 3211            true,
 3212            action.save_intent.unwrap_or(SaveIntent::Close),
 3213            window,
 3214            cx,
 3215        ) {
 3216            task.detach_and_log_err(cx)
 3217        }
 3218    }
 3219
 3220    pub fn close_all_items_and_panes(
 3221        &mut self,
 3222        action: &CloseAllItemsAndPanes,
 3223        window: &mut Window,
 3224        cx: &mut Context<Self>,
 3225    ) {
 3226        if let Some(task) = self.close_all_internal(
 3227            false,
 3228            action.save_intent.unwrap_or(SaveIntent::Close),
 3229            window,
 3230            cx,
 3231        ) {
 3232            task.detach_and_log_err(cx)
 3233        }
 3234    }
 3235
 3236    fn close_all_internal(
 3237        &mut self,
 3238        retain_active_pane: bool,
 3239        save_intent: SaveIntent,
 3240        window: &mut Window,
 3241        cx: &mut Context<Self>,
 3242    ) -> Option<Task<Result<()>>> {
 3243        let current_pane = self.active_pane();
 3244
 3245        let mut tasks = Vec::new();
 3246
 3247        if retain_active_pane {
 3248            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3249                pane.close_other_items(
 3250                    &CloseOtherItems {
 3251                        save_intent: None,
 3252                        close_pinned: false,
 3253                    },
 3254                    None,
 3255                    window,
 3256                    cx,
 3257                )
 3258            });
 3259
 3260            tasks.push(current_pane_close);
 3261        }
 3262
 3263        for pane in self.panes() {
 3264            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3265                continue;
 3266            }
 3267
 3268            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3269                pane.close_all_items(
 3270                    &CloseAllItems {
 3271                        save_intent: Some(save_intent),
 3272                        close_pinned: false,
 3273                    },
 3274                    window,
 3275                    cx,
 3276                )
 3277            });
 3278
 3279            tasks.push(close_pane_items)
 3280        }
 3281
 3282        if tasks.is_empty() {
 3283            None
 3284        } else {
 3285            Some(cx.spawn_in(window, async move |_, _| {
 3286                for task in tasks {
 3287                    task.await?
 3288                }
 3289                Ok(())
 3290            }))
 3291        }
 3292    }
 3293
 3294    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3295        self.dock_at_position(position).read(cx).is_open()
 3296    }
 3297
 3298    pub fn toggle_dock(
 3299        &mut self,
 3300        dock_side: DockPosition,
 3301        window: &mut Window,
 3302        cx: &mut Context<Self>,
 3303    ) {
 3304        let mut focus_center = false;
 3305        let mut reveal_dock = false;
 3306
 3307        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3308        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3309
 3310        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3311            telemetry::event!(
 3312                "Panel Button Clicked",
 3313                name = panel.persistent_name(),
 3314                toggle_state = !was_visible
 3315            );
 3316        }
 3317        if was_visible {
 3318            self.save_open_dock_positions(cx);
 3319        }
 3320
 3321        let dock = self.dock_at_position(dock_side);
 3322        dock.update(cx, |dock, cx| {
 3323            dock.set_open(!was_visible, window, cx);
 3324
 3325            if dock.active_panel().is_none() {
 3326                let Some(panel_ix) = dock
 3327                    .first_enabled_panel_idx(cx)
 3328                    .log_with_level(log::Level::Info)
 3329                else {
 3330                    return;
 3331                };
 3332                dock.activate_panel(panel_ix, window, cx);
 3333            }
 3334
 3335            if let Some(active_panel) = dock.active_panel() {
 3336                if was_visible {
 3337                    if active_panel
 3338                        .panel_focus_handle(cx)
 3339                        .contains_focused(window, cx)
 3340                    {
 3341                        focus_center = true;
 3342                    }
 3343                } else {
 3344                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3345                    window.focus(focus_handle, cx);
 3346                    reveal_dock = true;
 3347                }
 3348            }
 3349        });
 3350
 3351        if reveal_dock {
 3352            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3353        }
 3354
 3355        if focus_center {
 3356            self.active_pane
 3357                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3358        }
 3359
 3360        cx.notify();
 3361        self.serialize_workspace(window, cx);
 3362    }
 3363
 3364    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3365        self.all_docks().into_iter().find(|&dock| {
 3366            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3367        })
 3368    }
 3369
 3370    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3371        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3372            self.save_open_dock_positions(cx);
 3373            dock.update(cx, |dock, cx| {
 3374                dock.set_open(false, window, cx);
 3375            });
 3376            return true;
 3377        }
 3378        false
 3379    }
 3380
 3381    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3382        self.save_open_dock_positions(cx);
 3383        for dock in self.all_docks() {
 3384            dock.update(cx, |dock, cx| {
 3385                dock.set_open(false, window, cx);
 3386            });
 3387        }
 3388
 3389        cx.focus_self(window);
 3390        cx.notify();
 3391        self.serialize_workspace(window, cx);
 3392    }
 3393
 3394    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3395        self.all_docks()
 3396            .into_iter()
 3397            .filter_map(|dock| {
 3398                let dock_ref = dock.read(cx);
 3399                if dock_ref.is_open() {
 3400                    Some(dock_ref.position())
 3401                } else {
 3402                    None
 3403                }
 3404            })
 3405            .collect()
 3406    }
 3407
 3408    /// Saves the positions of currently open docks.
 3409    ///
 3410    /// Updates `last_open_dock_positions` with positions of all currently open
 3411    /// docks, to later be restored by the 'Toggle All Docks' action.
 3412    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3413        let open_dock_positions = self.get_open_dock_positions(cx);
 3414        if !open_dock_positions.is_empty() {
 3415            self.last_open_dock_positions = open_dock_positions;
 3416        }
 3417    }
 3418
 3419    /// Toggles all docks between open and closed states.
 3420    ///
 3421    /// If any docks are open, closes all and remembers their positions. If all
 3422    /// docks are closed, restores the last remembered dock configuration.
 3423    fn toggle_all_docks(
 3424        &mut self,
 3425        _: &ToggleAllDocks,
 3426        window: &mut Window,
 3427        cx: &mut Context<Self>,
 3428    ) {
 3429        let open_dock_positions = self.get_open_dock_positions(cx);
 3430
 3431        if !open_dock_positions.is_empty() {
 3432            self.close_all_docks(window, cx);
 3433        } else if !self.last_open_dock_positions.is_empty() {
 3434            self.restore_last_open_docks(window, cx);
 3435        }
 3436    }
 3437
 3438    /// Reopens docks from the most recently remembered configuration.
 3439    ///
 3440    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3441    /// and clears the stored positions.
 3442    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3443        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3444
 3445        for position in positions_to_open {
 3446            let dock = self.dock_at_position(position);
 3447            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3448        }
 3449
 3450        cx.focus_self(window);
 3451        cx.notify();
 3452        self.serialize_workspace(window, cx);
 3453    }
 3454
 3455    /// Transfer focus to the panel of the given type.
 3456    pub fn focus_panel<T: Panel>(
 3457        &mut self,
 3458        window: &mut Window,
 3459        cx: &mut Context<Self>,
 3460    ) -> Option<Entity<T>> {
 3461        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 3462        panel.to_any().downcast().ok()
 3463    }
 3464
 3465    /// Focus the panel of the given type if it isn't already focused. If it is
 3466    /// already focused, then transfer focus back to the workspace center.
 3467    pub fn toggle_panel_focus<T: Panel>(
 3468        &mut self,
 3469        window: &mut Window,
 3470        cx: &mut Context<Self>,
 3471    ) -> bool {
 3472        let mut did_focus_panel = false;
 3473        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 3474            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3475            did_focus_panel
 3476        });
 3477
 3478        telemetry::event!(
 3479            "Panel Button Clicked",
 3480            name = T::persistent_name(),
 3481            toggle_state = did_focus_panel
 3482        );
 3483
 3484        did_focus_panel
 3485    }
 3486
 3487    pub fn activate_panel_for_proto_id(
 3488        &mut self,
 3489        panel_id: PanelId,
 3490        window: &mut Window,
 3491        cx: &mut Context<Self>,
 3492    ) -> Option<Arc<dyn PanelHandle>> {
 3493        let mut panel = None;
 3494        for dock in self.all_docks() {
 3495            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3496                panel = dock.update(cx, |dock, cx| {
 3497                    dock.activate_panel(panel_index, window, cx);
 3498                    dock.set_open(true, window, cx);
 3499                    dock.active_panel().cloned()
 3500                });
 3501                break;
 3502            }
 3503        }
 3504
 3505        if panel.is_some() {
 3506            cx.notify();
 3507            self.serialize_workspace(window, cx);
 3508        }
 3509
 3510        panel
 3511    }
 3512
 3513    /// Focus or unfocus the given panel type, depending on the given callback.
 3514    fn focus_or_unfocus_panel<T: Panel>(
 3515        &mut self,
 3516        window: &mut Window,
 3517        cx: &mut Context<Self>,
 3518        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3519    ) -> Option<Arc<dyn PanelHandle>> {
 3520        let mut result_panel = None;
 3521        let mut serialize = false;
 3522        for dock in self.all_docks() {
 3523            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3524                let mut focus_center = false;
 3525                let panel = dock.update(cx, |dock, cx| {
 3526                    dock.activate_panel(panel_index, window, cx);
 3527
 3528                    let panel = dock.active_panel().cloned();
 3529                    if let Some(panel) = panel.as_ref() {
 3530                        if should_focus(&**panel, window, cx) {
 3531                            dock.set_open(true, window, cx);
 3532                            panel.panel_focus_handle(cx).focus(window, cx);
 3533                        } else {
 3534                            focus_center = true;
 3535                        }
 3536                    }
 3537                    panel
 3538                });
 3539
 3540                if focus_center {
 3541                    self.active_pane
 3542                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3543                }
 3544
 3545                result_panel = panel;
 3546                serialize = true;
 3547                break;
 3548            }
 3549        }
 3550
 3551        if serialize {
 3552            self.serialize_workspace(window, cx);
 3553        }
 3554
 3555        cx.notify();
 3556        result_panel
 3557    }
 3558
 3559    /// Open the panel of the given type
 3560    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3561        for dock in self.all_docks() {
 3562            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3563                dock.update(cx, |dock, cx| {
 3564                    dock.activate_panel(panel_index, window, cx);
 3565                    dock.set_open(true, window, cx);
 3566                });
 3567            }
 3568        }
 3569    }
 3570
 3571    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3572        for dock in self.all_docks().iter() {
 3573            dock.update(cx, |dock, cx| {
 3574                if dock.panel::<T>().is_some() {
 3575                    dock.set_open(false, window, cx)
 3576                }
 3577            })
 3578        }
 3579    }
 3580
 3581    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3582        self.all_docks()
 3583            .iter()
 3584            .find_map(|dock| dock.read(cx).panel::<T>())
 3585    }
 3586
 3587    fn dismiss_zoomed_items_to_reveal(
 3588        &mut self,
 3589        dock_to_reveal: Option<DockPosition>,
 3590        window: &mut Window,
 3591        cx: &mut Context<Self>,
 3592    ) {
 3593        // If a center pane is zoomed, unzoom it.
 3594        for pane in &self.panes {
 3595            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3596                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3597            }
 3598        }
 3599
 3600        // If another dock is zoomed, hide it.
 3601        let mut focus_center = false;
 3602        for dock in self.all_docks() {
 3603            dock.update(cx, |dock, cx| {
 3604                if Some(dock.position()) != dock_to_reveal
 3605                    && let Some(panel) = dock.active_panel()
 3606                    && panel.is_zoomed(window, cx)
 3607                {
 3608                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3609                    dock.set_open(false, window, cx);
 3610                }
 3611            });
 3612        }
 3613
 3614        if focus_center {
 3615            self.active_pane
 3616                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3617        }
 3618
 3619        if self.zoomed_position != dock_to_reveal {
 3620            self.zoomed = None;
 3621            self.zoomed_position = None;
 3622            cx.emit(Event::ZoomChanged);
 3623        }
 3624
 3625        cx.notify();
 3626    }
 3627
 3628    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3629        let pane = cx.new(|cx| {
 3630            let mut pane = Pane::new(
 3631                self.weak_handle(),
 3632                self.project.clone(),
 3633                self.pane_history_timestamp.clone(),
 3634                None,
 3635                NewFile.boxed_clone(),
 3636                true,
 3637                window,
 3638                cx,
 3639            );
 3640            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3641            pane
 3642        });
 3643        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3644            .detach();
 3645        self.panes.push(pane.clone());
 3646
 3647        window.focus(&pane.focus_handle(cx), cx);
 3648
 3649        cx.emit(Event::PaneAdded(pane.clone()));
 3650        pane
 3651    }
 3652
 3653    pub fn add_item_to_center(
 3654        &mut self,
 3655        item: Box<dyn ItemHandle>,
 3656        window: &mut Window,
 3657        cx: &mut Context<Self>,
 3658    ) -> bool {
 3659        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3660            if let Some(center_pane) = center_pane.upgrade() {
 3661                center_pane.update(cx, |pane, cx| {
 3662                    pane.add_item(item, true, true, None, window, cx)
 3663                });
 3664                true
 3665            } else {
 3666                false
 3667            }
 3668        } else {
 3669            false
 3670        }
 3671    }
 3672
 3673    pub fn add_item_to_active_pane(
 3674        &mut self,
 3675        item: Box<dyn ItemHandle>,
 3676        destination_index: Option<usize>,
 3677        focus_item: bool,
 3678        window: &mut Window,
 3679        cx: &mut App,
 3680    ) {
 3681        self.add_item(
 3682            self.active_pane.clone(),
 3683            item,
 3684            destination_index,
 3685            false,
 3686            focus_item,
 3687            window,
 3688            cx,
 3689        )
 3690    }
 3691
 3692    pub fn add_item(
 3693        &mut self,
 3694        pane: Entity<Pane>,
 3695        item: Box<dyn ItemHandle>,
 3696        destination_index: Option<usize>,
 3697        activate_pane: bool,
 3698        focus_item: bool,
 3699        window: &mut Window,
 3700        cx: &mut App,
 3701    ) {
 3702        pane.update(cx, |pane, cx| {
 3703            pane.add_item(
 3704                item,
 3705                activate_pane,
 3706                focus_item,
 3707                destination_index,
 3708                window,
 3709                cx,
 3710            )
 3711        });
 3712    }
 3713
 3714    pub fn split_item(
 3715        &mut self,
 3716        split_direction: SplitDirection,
 3717        item: Box<dyn ItemHandle>,
 3718        window: &mut Window,
 3719        cx: &mut Context<Self>,
 3720    ) {
 3721        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3722        self.add_item(new_pane, item, None, true, true, window, cx);
 3723    }
 3724
 3725    pub fn open_abs_path(
 3726        &mut self,
 3727        abs_path: PathBuf,
 3728        options: OpenOptions,
 3729        window: &mut Window,
 3730        cx: &mut Context<Self>,
 3731    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3732        cx.spawn_in(window, async move |workspace, cx| {
 3733            let open_paths_task_result = workspace
 3734                .update_in(cx, |workspace, window, cx| {
 3735                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3736                })
 3737                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3738                .await;
 3739            anyhow::ensure!(
 3740                open_paths_task_result.len() == 1,
 3741                "open abs path {abs_path:?} task returned incorrect number of results"
 3742            );
 3743            match open_paths_task_result
 3744                .into_iter()
 3745                .next()
 3746                .expect("ensured single task result")
 3747            {
 3748                Some(open_result) => {
 3749                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3750                }
 3751                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3752            }
 3753        })
 3754    }
 3755
 3756    pub fn split_abs_path(
 3757        &mut self,
 3758        abs_path: PathBuf,
 3759        visible: bool,
 3760        window: &mut Window,
 3761        cx: &mut Context<Self>,
 3762    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3763        let project_path_task =
 3764            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3765        cx.spawn_in(window, async move |this, cx| {
 3766            let (_, path) = project_path_task.await?;
 3767            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3768                .await
 3769        })
 3770    }
 3771
 3772    pub fn open_path(
 3773        &mut self,
 3774        path: impl Into<ProjectPath>,
 3775        pane: Option<WeakEntity<Pane>>,
 3776        focus_item: bool,
 3777        window: &mut Window,
 3778        cx: &mut App,
 3779    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3780        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3781    }
 3782
 3783    pub fn open_path_preview(
 3784        &mut self,
 3785        path: impl Into<ProjectPath>,
 3786        pane: Option<WeakEntity<Pane>>,
 3787        focus_item: bool,
 3788        allow_preview: bool,
 3789        activate: bool,
 3790        window: &mut Window,
 3791        cx: &mut App,
 3792    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3793        let pane = pane.unwrap_or_else(|| {
 3794            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3795                self.panes
 3796                    .first()
 3797                    .expect("There must be an active pane")
 3798                    .downgrade()
 3799            })
 3800        });
 3801
 3802        let project_path = path.into();
 3803        let task = self.load_path(project_path.clone(), window, cx);
 3804        window.spawn(cx, async move |cx| {
 3805            let (project_entry_id, build_item) = task.await?;
 3806
 3807            pane.update_in(cx, |pane, window, cx| {
 3808                pane.open_item(
 3809                    project_entry_id,
 3810                    project_path,
 3811                    focus_item,
 3812                    allow_preview,
 3813                    activate,
 3814                    None,
 3815                    window,
 3816                    cx,
 3817                    build_item,
 3818                )
 3819            })
 3820        })
 3821    }
 3822
 3823    pub fn split_path(
 3824        &mut self,
 3825        path: impl Into<ProjectPath>,
 3826        window: &mut Window,
 3827        cx: &mut Context<Self>,
 3828    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3829        self.split_path_preview(path, false, None, window, cx)
 3830    }
 3831
 3832    pub fn split_path_preview(
 3833        &mut self,
 3834        path: impl Into<ProjectPath>,
 3835        allow_preview: bool,
 3836        split_direction: Option<SplitDirection>,
 3837        window: &mut Window,
 3838        cx: &mut Context<Self>,
 3839    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3840        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3841            self.panes
 3842                .first()
 3843                .expect("There must be an active pane")
 3844                .downgrade()
 3845        });
 3846
 3847        if let Member::Pane(center_pane) = &self.center.root
 3848            && center_pane.read(cx).items_len() == 0
 3849        {
 3850            return self.open_path(path, Some(pane), true, window, cx);
 3851        }
 3852
 3853        let project_path = path.into();
 3854        let task = self.load_path(project_path.clone(), window, cx);
 3855        cx.spawn_in(window, async move |this, cx| {
 3856            let (project_entry_id, build_item) = task.await?;
 3857            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3858                let pane = pane.upgrade()?;
 3859                let new_pane = this.split_pane(
 3860                    pane,
 3861                    split_direction.unwrap_or(SplitDirection::Right),
 3862                    window,
 3863                    cx,
 3864                );
 3865                new_pane.update(cx, |new_pane, cx| {
 3866                    Some(new_pane.open_item(
 3867                        project_entry_id,
 3868                        project_path,
 3869                        true,
 3870                        allow_preview,
 3871                        true,
 3872                        None,
 3873                        window,
 3874                        cx,
 3875                        build_item,
 3876                    ))
 3877                })
 3878            })
 3879            .map(|option| option.context("pane was dropped"))?
 3880        })
 3881    }
 3882
 3883    fn load_path(
 3884        &mut self,
 3885        path: ProjectPath,
 3886        window: &mut Window,
 3887        cx: &mut App,
 3888    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3889        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3890        registry.open_path(self.project(), &path, window, cx)
 3891    }
 3892
 3893    pub fn find_project_item<T>(
 3894        &self,
 3895        pane: &Entity<Pane>,
 3896        project_item: &Entity<T::Item>,
 3897        cx: &App,
 3898    ) -> Option<Entity<T>>
 3899    where
 3900        T: ProjectItem,
 3901    {
 3902        use project::ProjectItem as _;
 3903        let project_item = project_item.read(cx);
 3904        let entry_id = project_item.entry_id(cx);
 3905        let project_path = project_item.project_path(cx);
 3906
 3907        let mut item = None;
 3908        if let Some(entry_id) = entry_id {
 3909            item = pane.read(cx).item_for_entry(entry_id, cx);
 3910        }
 3911        if item.is_none()
 3912            && let Some(project_path) = project_path
 3913        {
 3914            item = pane.read(cx).item_for_path(project_path, cx);
 3915        }
 3916
 3917        item.and_then(|item| item.downcast::<T>())
 3918    }
 3919
 3920    pub fn is_project_item_open<T>(
 3921        &self,
 3922        pane: &Entity<Pane>,
 3923        project_item: &Entity<T::Item>,
 3924        cx: &App,
 3925    ) -> bool
 3926    where
 3927        T: ProjectItem,
 3928    {
 3929        self.find_project_item::<T>(pane, project_item, cx)
 3930            .is_some()
 3931    }
 3932
 3933    pub fn open_project_item<T>(
 3934        &mut self,
 3935        pane: Entity<Pane>,
 3936        project_item: Entity<T::Item>,
 3937        activate_pane: bool,
 3938        focus_item: bool,
 3939        keep_old_preview: bool,
 3940        allow_new_preview: bool,
 3941        window: &mut Window,
 3942        cx: &mut Context<Self>,
 3943    ) -> Entity<T>
 3944    where
 3945        T: ProjectItem,
 3946    {
 3947        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 3948
 3949        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 3950            if !keep_old_preview
 3951                && let Some(old_id) = old_item_id
 3952                && old_id != item.item_id()
 3953            {
 3954                // switching to a different item, so unpreview old active item
 3955                pane.update(cx, |pane, _| {
 3956                    pane.unpreview_item_if_preview(old_id);
 3957                });
 3958            }
 3959
 3960            self.activate_item(&item, activate_pane, focus_item, window, cx);
 3961            if !allow_new_preview {
 3962                pane.update(cx, |pane, _| {
 3963                    pane.unpreview_item_if_preview(item.item_id());
 3964                });
 3965            }
 3966            return item;
 3967        }
 3968
 3969        let item = pane.update(cx, |pane, cx| {
 3970            cx.new(|cx| {
 3971                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 3972            })
 3973        });
 3974        let mut destination_index = None;
 3975        pane.update(cx, |pane, cx| {
 3976            if !keep_old_preview && let Some(old_id) = old_item_id {
 3977                pane.unpreview_item_if_preview(old_id);
 3978            }
 3979            if allow_new_preview {
 3980                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 3981            }
 3982        });
 3983
 3984        self.add_item(
 3985            pane,
 3986            Box::new(item.clone()),
 3987            destination_index,
 3988            activate_pane,
 3989            focus_item,
 3990            window,
 3991            cx,
 3992        );
 3993        item
 3994    }
 3995
 3996    pub fn open_shared_screen(
 3997        &mut self,
 3998        peer_id: PeerId,
 3999        window: &mut Window,
 4000        cx: &mut Context<Self>,
 4001    ) {
 4002        if let Some(shared_screen) =
 4003            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4004        {
 4005            self.active_pane.update(cx, |pane, cx| {
 4006                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4007            });
 4008        }
 4009    }
 4010
 4011    pub fn activate_item(
 4012        &mut self,
 4013        item: &dyn ItemHandle,
 4014        activate_pane: bool,
 4015        focus_item: bool,
 4016        window: &mut Window,
 4017        cx: &mut App,
 4018    ) -> bool {
 4019        let result = self.panes.iter().find_map(|pane| {
 4020            pane.read(cx)
 4021                .index_for_item(item)
 4022                .map(|ix| (pane.clone(), ix))
 4023        });
 4024        if let Some((pane, ix)) = result {
 4025            pane.update(cx, |pane, cx| {
 4026                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4027            });
 4028            true
 4029        } else {
 4030            false
 4031        }
 4032    }
 4033
 4034    fn activate_pane_at_index(
 4035        &mut self,
 4036        action: &ActivatePane,
 4037        window: &mut Window,
 4038        cx: &mut Context<Self>,
 4039    ) {
 4040        let panes = self.center.panes();
 4041        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4042            window.focus(&pane.focus_handle(cx), cx);
 4043        } else {
 4044            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4045                .detach();
 4046        }
 4047    }
 4048
 4049    fn move_item_to_pane_at_index(
 4050        &mut self,
 4051        action: &MoveItemToPane,
 4052        window: &mut Window,
 4053        cx: &mut Context<Self>,
 4054    ) {
 4055        let panes = self.center.panes();
 4056        let destination = match panes.get(action.destination) {
 4057            Some(&destination) => destination.clone(),
 4058            None => {
 4059                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4060                    return;
 4061                }
 4062                let direction = SplitDirection::Right;
 4063                let split_off_pane = self
 4064                    .find_pane_in_direction(direction, cx)
 4065                    .unwrap_or_else(|| self.active_pane.clone());
 4066                let new_pane = self.add_pane(window, cx);
 4067                if self
 4068                    .center
 4069                    .split(&split_off_pane, &new_pane, direction, cx)
 4070                    .log_err()
 4071                    .is_none()
 4072                {
 4073                    return;
 4074                };
 4075                new_pane
 4076            }
 4077        };
 4078
 4079        if action.clone {
 4080            if self
 4081                .active_pane
 4082                .read(cx)
 4083                .active_item()
 4084                .is_some_and(|item| item.can_split(cx))
 4085            {
 4086                clone_active_item(
 4087                    self.database_id(),
 4088                    &self.active_pane,
 4089                    &destination,
 4090                    action.focus,
 4091                    window,
 4092                    cx,
 4093                );
 4094                return;
 4095            }
 4096        }
 4097        move_active_item(
 4098            &self.active_pane,
 4099            &destination,
 4100            action.focus,
 4101            true,
 4102            window,
 4103            cx,
 4104        )
 4105    }
 4106
 4107    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4108        let panes = self.center.panes();
 4109        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4110            let next_ix = (ix + 1) % panes.len();
 4111            let next_pane = panes[next_ix].clone();
 4112            window.focus(&next_pane.focus_handle(cx), cx);
 4113        }
 4114    }
 4115
 4116    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4117        let panes = self.center.panes();
 4118        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4119            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4120            let prev_pane = panes[prev_ix].clone();
 4121            window.focus(&prev_pane.focus_handle(cx), cx);
 4122        }
 4123    }
 4124
 4125    pub fn activate_pane_in_direction(
 4126        &mut self,
 4127        direction: SplitDirection,
 4128        window: &mut Window,
 4129        cx: &mut App,
 4130    ) {
 4131        use ActivateInDirectionTarget as Target;
 4132        enum Origin {
 4133            LeftDock,
 4134            RightDock,
 4135            BottomDock,
 4136            Center,
 4137        }
 4138
 4139        let origin: Origin = [
 4140            (&self.left_dock, Origin::LeftDock),
 4141            (&self.right_dock, Origin::RightDock),
 4142            (&self.bottom_dock, Origin::BottomDock),
 4143        ]
 4144        .into_iter()
 4145        .find_map(|(dock, origin)| {
 4146            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4147                Some(origin)
 4148            } else {
 4149                None
 4150            }
 4151        })
 4152        .unwrap_or(Origin::Center);
 4153
 4154        let get_last_active_pane = || {
 4155            let pane = self
 4156                .last_active_center_pane
 4157                .clone()
 4158                .unwrap_or_else(|| {
 4159                    self.panes
 4160                        .first()
 4161                        .expect("There must be an active pane")
 4162                        .downgrade()
 4163                })
 4164                .upgrade()?;
 4165            (pane.read(cx).items_len() != 0).then_some(pane)
 4166        };
 4167
 4168        let try_dock =
 4169            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4170
 4171        let target = match (origin, direction) {
 4172            // We're in the center, so we first try to go to a different pane,
 4173            // otherwise try to go to a dock.
 4174            (Origin::Center, direction) => {
 4175                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4176                    Some(Target::Pane(pane))
 4177                } else {
 4178                    match direction {
 4179                        SplitDirection::Up => None,
 4180                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4181                        SplitDirection::Left => try_dock(&self.left_dock),
 4182                        SplitDirection::Right => try_dock(&self.right_dock),
 4183                    }
 4184                }
 4185            }
 4186
 4187            (Origin::LeftDock, SplitDirection::Right) => {
 4188                if let Some(last_active_pane) = get_last_active_pane() {
 4189                    Some(Target::Pane(last_active_pane))
 4190                } else {
 4191                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4192                }
 4193            }
 4194
 4195            (Origin::LeftDock, SplitDirection::Down)
 4196            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4197
 4198            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4199            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4200            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4201
 4202            (Origin::RightDock, SplitDirection::Left) => {
 4203                if let Some(last_active_pane) = get_last_active_pane() {
 4204                    Some(Target::Pane(last_active_pane))
 4205                } else {
 4206                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4207                }
 4208            }
 4209
 4210            _ => None,
 4211        };
 4212
 4213        match target {
 4214            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4215                let pane = pane.read(cx);
 4216                if let Some(item) = pane.active_item() {
 4217                    item.item_focus_handle(cx).focus(window, cx);
 4218                } else {
 4219                    log::error!(
 4220                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4221                    );
 4222                }
 4223            }
 4224            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4225                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4226                window.defer(cx, move |window, cx| {
 4227                    let dock = dock.read(cx);
 4228                    if let Some(panel) = dock.active_panel() {
 4229                        panel.panel_focus_handle(cx).focus(window, cx);
 4230                    } else {
 4231                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4232                    }
 4233                })
 4234            }
 4235            None => {}
 4236        }
 4237    }
 4238
 4239    pub fn move_item_to_pane_in_direction(
 4240        &mut self,
 4241        action: &MoveItemToPaneInDirection,
 4242        window: &mut Window,
 4243        cx: &mut Context<Self>,
 4244    ) {
 4245        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4246            Some(destination) => destination,
 4247            None => {
 4248                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4249                    return;
 4250                }
 4251                let new_pane = self.add_pane(window, cx);
 4252                if self
 4253                    .center
 4254                    .split(&self.active_pane, &new_pane, action.direction, cx)
 4255                    .log_err()
 4256                    .is_none()
 4257                {
 4258                    return;
 4259                };
 4260                new_pane
 4261            }
 4262        };
 4263
 4264        if action.clone {
 4265            if self
 4266                .active_pane
 4267                .read(cx)
 4268                .active_item()
 4269                .is_some_and(|item| item.can_split(cx))
 4270            {
 4271                clone_active_item(
 4272                    self.database_id(),
 4273                    &self.active_pane,
 4274                    &destination,
 4275                    action.focus,
 4276                    window,
 4277                    cx,
 4278                );
 4279                return;
 4280            }
 4281        }
 4282        move_active_item(
 4283            &self.active_pane,
 4284            &destination,
 4285            action.focus,
 4286            true,
 4287            window,
 4288            cx,
 4289        );
 4290    }
 4291
 4292    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4293        self.center.bounding_box_for_pane(pane)
 4294    }
 4295
 4296    pub fn find_pane_in_direction(
 4297        &mut self,
 4298        direction: SplitDirection,
 4299        cx: &App,
 4300    ) -> Option<Entity<Pane>> {
 4301        self.center
 4302            .find_pane_in_direction(&self.active_pane, direction, cx)
 4303            .cloned()
 4304    }
 4305
 4306    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4307        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4308            self.center.swap(&self.active_pane, &to, cx);
 4309            cx.notify();
 4310        }
 4311    }
 4312
 4313    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4314        if self
 4315            .center
 4316            .move_to_border(&self.active_pane, direction, cx)
 4317            .unwrap()
 4318        {
 4319            cx.notify();
 4320        }
 4321    }
 4322
 4323    pub fn resize_pane(
 4324        &mut self,
 4325        axis: gpui::Axis,
 4326        amount: Pixels,
 4327        window: &mut Window,
 4328        cx: &mut Context<Self>,
 4329    ) {
 4330        let docks = self.all_docks();
 4331        let active_dock = docks
 4332            .into_iter()
 4333            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4334
 4335        if let Some(dock) = active_dock {
 4336            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4337                return;
 4338            };
 4339            match dock.read(cx).position() {
 4340                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4341                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4342                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4343            }
 4344        } else {
 4345            self.center
 4346                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4347        }
 4348        cx.notify();
 4349    }
 4350
 4351    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4352        self.center.reset_pane_sizes(cx);
 4353        cx.notify();
 4354    }
 4355
 4356    fn handle_pane_focused(
 4357        &mut self,
 4358        pane: Entity<Pane>,
 4359        window: &mut Window,
 4360        cx: &mut Context<Self>,
 4361    ) {
 4362        // This is explicitly hoisted out of the following check for pane identity as
 4363        // terminal panel panes are not registered as a center panes.
 4364        self.status_bar.update(cx, |status_bar, cx| {
 4365            status_bar.set_active_pane(&pane, window, cx);
 4366        });
 4367        if self.active_pane != pane {
 4368            self.set_active_pane(&pane, window, cx);
 4369        }
 4370
 4371        if self.last_active_center_pane.is_none() {
 4372            self.last_active_center_pane = Some(pane.downgrade());
 4373        }
 4374
 4375        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4376        // This prevents the dock from closing when focus events fire during window activation.
 4377        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4378            let dock_read = dock.read(cx);
 4379            if let Some(panel) = dock_read.active_panel()
 4380                && let Some(dock_pane) = panel.pane(cx)
 4381                && dock_pane == pane
 4382            {
 4383                Some(dock_read.position())
 4384            } else {
 4385                None
 4386            }
 4387        });
 4388
 4389        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4390        if pane.read(cx).is_zoomed() {
 4391            self.zoomed = Some(pane.downgrade().into());
 4392        } else {
 4393            self.zoomed = None;
 4394        }
 4395        self.zoomed_position = None;
 4396        cx.emit(Event::ZoomChanged);
 4397        self.update_active_view_for_followers(window, cx);
 4398        pane.update(cx, |pane, _| {
 4399            pane.track_alternate_file_items();
 4400        });
 4401
 4402        cx.notify();
 4403    }
 4404
 4405    fn set_active_pane(
 4406        &mut self,
 4407        pane: &Entity<Pane>,
 4408        window: &mut Window,
 4409        cx: &mut Context<Self>,
 4410    ) {
 4411        self.active_pane = pane.clone();
 4412        self.active_item_path_changed(true, window, cx);
 4413        self.last_active_center_pane = Some(pane.downgrade());
 4414    }
 4415
 4416    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4417        self.update_active_view_for_followers(window, cx);
 4418    }
 4419
 4420    fn handle_pane_event(
 4421        &mut self,
 4422        pane: &Entity<Pane>,
 4423        event: &pane::Event,
 4424        window: &mut Window,
 4425        cx: &mut Context<Self>,
 4426    ) {
 4427        let mut serialize_workspace = true;
 4428        match event {
 4429            pane::Event::AddItem { item } => {
 4430                item.added_to_pane(self, pane.clone(), window, cx);
 4431                cx.emit(Event::ItemAdded {
 4432                    item: item.boxed_clone(),
 4433                });
 4434            }
 4435            pane::Event::Split { direction, mode } => {
 4436                match mode {
 4437                    SplitMode::ClonePane => {
 4438                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4439                            .detach();
 4440                    }
 4441                    SplitMode::EmptyPane => {
 4442                        self.split_pane(pane.clone(), *direction, window, cx);
 4443                    }
 4444                    SplitMode::MovePane => {
 4445                        self.split_and_move(pane.clone(), *direction, window, cx);
 4446                    }
 4447                };
 4448            }
 4449            pane::Event::JoinIntoNext => {
 4450                self.join_pane_into_next(pane.clone(), window, cx);
 4451            }
 4452            pane::Event::JoinAll => {
 4453                self.join_all_panes(window, cx);
 4454            }
 4455            pane::Event::Remove { focus_on_pane } => {
 4456                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4457            }
 4458            pane::Event::ActivateItem {
 4459                local,
 4460                focus_changed,
 4461            } => {
 4462                window.invalidate_character_coordinates();
 4463
 4464                pane.update(cx, |pane, _| {
 4465                    pane.track_alternate_file_items();
 4466                });
 4467                if *local {
 4468                    self.unfollow_in_pane(pane, window, cx);
 4469                }
 4470                serialize_workspace = *focus_changed || pane != self.active_pane();
 4471                if pane == self.active_pane() {
 4472                    self.active_item_path_changed(*focus_changed, window, cx);
 4473                    self.update_active_view_for_followers(window, cx);
 4474                } else if *local {
 4475                    self.set_active_pane(pane, window, cx);
 4476                }
 4477            }
 4478            pane::Event::UserSavedItem { item, save_intent } => {
 4479                cx.emit(Event::UserSavedItem {
 4480                    pane: pane.downgrade(),
 4481                    item: item.boxed_clone(),
 4482                    save_intent: *save_intent,
 4483                });
 4484                serialize_workspace = false;
 4485            }
 4486            pane::Event::ChangeItemTitle => {
 4487                if *pane == self.active_pane {
 4488                    self.active_item_path_changed(false, window, cx);
 4489                }
 4490                serialize_workspace = false;
 4491            }
 4492            pane::Event::RemovedItem { item } => {
 4493                cx.emit(Event::ActiveItemChanged);
 4494                self.update_window_edited(window, cx);
 4495                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4496                    && entry.get().entity_id() == pane.entity_id()
 4497                {
 4498                    entry.remove();
 4499                }
 4500                cx.emit(Event::ItemRemoved {
 4501                    item_id: item.item_id(),
 4502                });
 4503            }
 4504            pane::Event::Focus => {
 4505                window.invalidate_character_coordinates();
 4506                self.handle_pane_focused(pane.clone(), window, cx);
 4507            }
 4508            pane::Event::ZoomIn => {
 4509                if *pane == self.active_pane {
 4510                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4511                    if pane.read(cx).has_focus(window, cx) {
 4512                        self.zoomed = Some(pane.downgrade().into());
 4513                        self.zoomed_position = None;
 4514                        cx.emit(Event::ZoomChanged);
 4515                    }
 4516                    cx.notify();
 4517                }
 4518            }
 4519            pane::Event::ZoomOut => {
 4520                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4521                if self.zoomed_position.is_none() {
 4522                    self.zoomed = None;
 4523                    cx.emit(Event::ZoomChanged);
 4524                }
 4525                cx.notify();
 4526            }
 4527            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4528        }
 4529
 4530        if serialize_workspace {
 4531            self.serialize_workspace(window, cx);
 4532        }
 4533    }
 4534
 4535    pub fn unfollow_in_pane(
 4536        &mut self,
 4537        pane: &Entity<Pane>,
 4538        window: &mut Window,
 4539        cx: &mut Context<Workspace>,
 4540    ) -> Option<CollaboratorId> {
 4541        let leader_id = self.leader_for_pane(pane)?;
 4542        self.unfollow(leader_id, window, cx);
 4543        Some(leader_id)
 4544    }
 4545
 4546    pub fn split_pane(
 4547        &mut self,
 4548        pane_to_split: Entity<Pane>,
 4549        split_direction: SplitDirection,
 4550        window: &mut Window,
 4551        cx: &mut Context<Self>,
 4552    ) -> Entity<Pane> {
 4553        let new_pane = self.add_pane(window, cx);
 4554        self.center
 4555            .split(&pane_to_split, &new_pane, split_direction, cx)
 4556            .unwrap();
 4557        cx.notify();
 4558        new_pane
 4559    }
 4560
 4561    pub fn split_and_move(
 4562        &mut self,
 4563        pane: Entity<Pane>,
 4564        direction: SplitDirection,
 4565        window: &mut Window,
 4566        cx: &mut Context<Self>,
 4567    ) {
 4568        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4569            return;
 4570        };
 4571        let new_pane = self.add_pane(window, cx);
 4572        new_pane.update(cx, |pane, cx| {
 4573            pane.add_item(item, true, true, None, window, cx)
 4574        });
 4575        self.center.split(&pane, &new_pane, direction, cx).unwrap();
 4576        cx.notify();
 4577    }
 4578
 4579    pub fn split_and_clone(
 4580        &mut self,
 4581        pane: Entity<Pane>,
 4582        direction: SplitDirection,
 4583        window: &mut Window,
 4584        cx: &mut Context<Self>,
 4585    ) -> Task<Option<Entity<Pane>>> {
 4586        let Some(item) = pane.read(cx).active_item() else {
 4587            return Task::ready(None);
 4588        };
 4589        if !item.can_split(cx) {
 4590            return Task::ready(None);
 4591        }
 4592        let task = item.clone_on_split(self.database_id(), window, cx);
 4593        cx.spawn_in(window, async move |this, cx| {
 4594            if let Some(clone) = task.await {
 4595                this.update_in(cx, |this, window, cx| {
 4596                    let new_pane = this.add_pane(window, cx);
 4597                    let nav_history = pane.read(cx).fork_nav_history();
 4598                    new_pane.update(cx, |pane, cx| {
 4599                        pane.set_nav_history(nav_history, cx);
 4600                        pane.add_item(clone, true, true, None, window, cx)
 4601                    });
 4602                    this.center.split(&pane, &new_pane, direction, cx).unwrap();
 4603                    cx.notify();
 4604                    new_pane
 4605                })
 4606                .ok()
 4607            } else {
 4608                None
 4609            }
 4610        })
 4611    }
 4612
 4613    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4614        let active_item = self.active_pane.read(cx).active_item();
 4615        for pane in &self.panes {
 4616            join_pane_into_active(&self.active_pane, pane, window, cx);
 4617        }
 4618        if let Some(active_item) = active_item {
 4619            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4620        }
 4621        cx.notify();
 4622    }
 4623
 4624    pub fn join_pane_into_next(
 4625        &mut self,
 4626        pane: Entity<Pane>,
 4627        window: &mut Window,
 4628        cx: &mut Context<Self>,
 4629    ) {
 4630        let next_pane = self
 4631            .find_pane_in_direction(SplitDirection::Right, cx)
 4632            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4633            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4634            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4635        let Some(next_pane) = next_pane else {
 4636            return;
 4637        };
 4638        move_all_items(&pane, &next_pane, window, cx);
 4639        cx.notify();
 4640    }
 4641
 4642    fn remove_pane(
 4643        &mut self,
 4644        pane: Entity<Pane>,
 4645        focus_on: Option<Entity<Pane>>,
 4646        window: &mut Window,
 4647        cx: &mut Context<Self>,
 4648    ) {
 4649        if self.center.remove(&pane, cx).unwrap() {
 4650            self.force_remove_pane(&pane, &focus_on, window, cx);
 4651            self.unfollow_in_pane(&pane, window, cx);
 4652            self.last_leaders_by_pane.remove(&pane.downgrade());
 4653            for removed_item in pane.read(cx).items() {
 4654                self.panes_by_item.remove(&removed_item.item_id());
 4655            }
 4656
 4657            cx.notify();
 4658        } else {
 4659            self.active_item_path_changed(true, window, cx);
 4660        }
 4661        cx.emit(Event::PaneRemoved);
 4662    }
 4663
 4664    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4665        &mut self.panes
 4666    }
 4667
 4668    pub fn panes(&self) -> &[Entity<Pane>] {
 4669        &self.panes
 4670    }
 4671
 4672    pub fn active_pane(&self) -> &Entity<Pane> {
 4673        &self.active_pane
 4674    }
 4675
 4676    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4677        for dock in self.all_docks() {
 4678            if dock.focus_handle(cx).contains_focused(window, cx)
 4679                && let Some(pane) = dock
 4680                    .read(cx)
 4681                    .active_panel()
 4682                    .and_then(|panel| panel.pane(cx))
 4683            {
 4684                return pane;
 4685            }
 4686        }
 4687        self.active_pane().clone()
 4688    }
 4689
 4690    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4691        self.find_pane_in_direction(SplitDirection::Right, cx)
 4692            .unwrap_or_else(|| {
 4693                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4694            })
 4695    }
 4696
 4697    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4698        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4699        weak_pane.upgrade()
 4700    }
 4701
 4702    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4703        self.follower_states.retain(|leader_id, state| {
 4704            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4705                for item in state.items_by_leader_view_id.values() {
 4706                    item.view.set_leader_id(None, window, cx);
 4707                }
 4708                false
 4709            } else {
 4710                true
 4711            }
 4712        });
 4713        cx.notify();
 4714    }
 4715
 4716    pub fn start_following(
 4717        &mut self,
 4718        leader_id: impl Into<CollaboratorId>,
 4719        window: &mut Window,
 4720        cx: &mut Context<Self>,
 4721    ) -> Option<Task<Result<()>>> {
 4722        let leader_id = leader_id.into();
 4723        let pane = self.active_pane().clone();
 4724
 4725        self.last_leaders_by_pane
 4726            .insert(pane.downgrade(), leader_id);
 4727        self.unfollow(leader_id, window, cx);
 4728        self.unfollow_in_pane(&pane, window, cx);
 4729        self.follower_states.insert(
 4730            leader_id,
 4731            FollowerState {
 4732                center_pane: pane.clone(),
 4733                dock_pane: None,
 4734                active_view_id: None,
 4735                items_by_leader_view_id: Default::default(),
 4736            },
 4737        );
 4738        cx.notify();
 4739
 4740        match leader_id {
 4741            CollaboratorId::PeerId(leader_peer_id) => {
 4742                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4743                let project_id = self.project.read(cx).remote_id();
 4744                let request = self.app_state.client.request(proto::Follow {
 4745                    room_id,
 4746                    project_id,
 4747                    leader_id: Some(leader_peer_id),
 4748                });
 4749
 4750                Some(cx.spawn_in(window, async move |this, cx| {
 4751                    let response = request.await?;
 4752                    this.update(cx, |this, _| {
 4753                        let state = this
 4754                            .follower_states
 4755                            .get_mut(&leader_id)
 4756                            .context("following interrupted")?;
 4757                        state.active_view_id = response
 4758                            .active_view
 4759                            .as_ref()
 4760                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4761                        anyhow::Ok(())
 4762                    })??;
 4763                    if let Some(view) = response.active_view {
 4764                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4765                    }
 4766                    this.update_in(cx, |this, window, cx| {
 4767                        this.leader_updated(leader_id, window, cx)
 4768                    })?;
 4769                    Ok(())
 4770                }))
 4771            }
 4772            CollaboratorId::Agent => {
 4773                self.leader_updated(leader_id, window, cx)?;
 4774                Some(Task::ready(Ok(())))
 4775            }
 4776        }
 4777    }
 4778
 4779    pub fn follow_next_collaborator(
 4780        &mut self,
 4781        _: &FollowNextCollaborator,
 4782        window: &mut Window,
 4783        cx: &mut Context<Self>,
 4784    ) {
 4785        let collaborators = self.project.read(cx).collaborators();
 4786        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4787            let mut collaborators = collaborators.keys().copied();
 4788            for peer_id in collaborators.by_ref() {
 4789                if CollaboratorId::PeerId(peer_id) == leader_id {
 4790                    break;
 4791                }
 4792            }
 4793            collaborators.next().map(CollaboratorId::PeerId)
 4794        } else if let Some(last_leader_id) =
 4795            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4796        {
 4797            match last_leader_id {
 4798                CollaboratorId::PeerId(peer_id) => {
 4799                    if collaborators.contains_key(peer_id) {
 4800                        Some(*last_leader_id)
 4801                    } else {
 4802                        None
 4803                    }
 4804                }
 4805                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4806            }
 4807        } else {
 4808            None
 4809        };
 4810
 4811        let pane = self.active_pane.clone();
 4812        let Some(leader_id) = next_leader_id.or_else(|| {
 4813            Some(CollaboratorId::PeerId(
 4814                collaborators.keys().copied().next()?,
 4815            ))
 4816        }) else {
 4817            return;
 4818        };
 4819        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4820            return;
 4821        }
 4822        if let Some(task) = self.start_following(leader_id, window, cx) {
 4823            task.detach_and_log_err(cx)
 4824        }
 4825    }
 4826
 4827    pub fn follow(
 4828        &mut self,
 4829        leader_id: impl Into<CollaboratorId>,
 4830        window: &mut Window,
 4831        cx: &mut Context<Self>,
 4832    ) {
 4833        let leader_id = leader_id.into();
 4834
 4835        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4836            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4837                return;
 4838            };
 4839            let room = room.read(cx);
 4840            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4841                return;
 4842            };
 4843
 4844            let project = self.project.read(cx);
 4845
 4846            let other_project_id = match remote_participant.location {
 4847                call::ParticipantLocation::External => None,
 4848                call::ParticipantLocation::UnsharedProject => None,
 4849                call::ParticipantLocation::SharedProject { project_id } => {
 4850                    if Some(project_id) == project.remote_id() {
 4851                        None
 4852                    } else {
 4853                        Some(project_id)
 4854                    }
 4855                }
 4856            };
 4857
 4858            // if they are active in another project, follow there.
 4859            if let Some(project_id) = other_project_id {
 4860                let app_state = self.app_state.clone();
 4861                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4862                    .detach_and_log_err(cx);
 4863            }
 4864        }
 4865
 4866        // if you're already following, find the right pane and focus it.
 4867        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4868            window.focus(&follower_state.pane().focus_handle(cx), cx);
 4869
 4870            return;
 4871        }
 4872
 4873        // Otherwise, follow.
 4874        if let Some(task) = self.start_following(leader_id, window, cx) {
 4875            task.detach_and_log_err(cx)
 4876        }
 4877    }
 4878
 4879    pub fn unfollow(
 4880        &mut self,
 4881        leader_id: impl Into<CollaboratorId>,
 4882        window: &mut Window,
 4883        cx: &mut Context<Self>,
 4884    ) -> Option<()> {
 4885        cx.notify();
 4886
 4887        let leader_id = leader_id.into();
 4888        let state = self.follower_states.remove(&leader_id)?;
 4889        for (_, item) in state.items_by_leader_view_id {
 4890            item.view.set_leader_id(None, window, cx);
 4891        }
 4892
 4893        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 4894            let project_id = self.project.read(cx).remote_id();
 4895            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4896            self.app_state
 4897                .client
 4898                .send(proto::Unfollow {
 4899                    room_id,
 4900                    project_id,
 4901                    leader_id: Some(leader_peer_id),
 4902                })
 4903                .log_err();
 4904        }
 4905
 4906        Some(())
 4907    }
 4908
 4909    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 4910        self.follower_states.contains_key(&id.into())
 4911    }
 4912
 4913    fn active_item_path_changed(
 4914        &mut self,
 4915        focus_changed: bool,
 4916        window: &mut Window,
 4917        cx: &mut Context<Self>,
 4918    ) {
 4919        cx.emit(Event::ActiveItemChanged);
 4920        let active_entry = self.active_project_path(cx);
 4921        self.project.update(cx, |project, cx| {
 4922            project.set_active_path(active_entry.clone(), cx)
 4923        });
 4924
 4925        if focus_changed && let Some(project_path) = &active_entry {
 4926            let git_store_entity = self.project.read(cx).git_store().clone();
 4927            git_store_entity.update(cx, |git_store, cx| {
 4928                git_store.set_active_repo_for_path(project_path, cx);
 4929            });
 4930        }
 4931
 4932        self.update_window_title(window, cx);
 4933    }
 4934
 4935    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 4936        let project = self.project().read(cx);
 4937        let mut title = String::new();
 4938
 4939        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 4940            let name = {
 4941                let settings_location = SettingsLocation {
 4942                    worktree_id: worktree.read(cx).id(),
 4943                    path: RelPath::empty(),
 4944                };
 4945
 4946                let settings = WorktreeSettings::get(Some(settings_location), cx);
 4947                match &settings.project_name {
 4948                    Some(name) => name.as_str(),
 4949                    None => worktree.read(cx).root_name_str(),
 4950                }
 4951            };
 4952            if i > 0 {
 4953                title.push_str(", ");
 4954            }
 4955            title.push_str(name);
 4956        }
 4957
 4958        if title.is_empty() {
 4959            title = "empty project".to_string();
 4960        }
 4961
 4962        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 4963            let filename = path.path.file_name().or_else(|| {
 4964                Some(
 4965                    project
 4966                        .worktree_for_id(path.worktree_id, cx)?
 4967                        .read(cx)
 4968                        .root_name_str(),
 4969                )
 4970            });
 4971
 4972            if let Some(filename) = filename {
 4973                title.push_str("");
 4974                title.push_str(filename.as_ref());
 4975            }
 4976        }
 4977
 4978        if project.is_via_collab() {
 4979            title.push_str("");
 4980        } else if project.is_shared() {
 4981            title.push_str("");
 4982        }
 4983
 4984        if let Some(last_title) = self.last_window_title.as_ref()
 4985            && &title == last_title
 4986        {
 4987            return;
 4988        }
 4989        window.set_window_title(&title);
 4990        SystemWindowTabController::update_tab_title(
 4991            cx,
 4992            window.window_handle().window_id(),
 4993            SharedString::from(&title),
 4994        );
 4995        self.last_window_title = Some(title);
 4996    }
 4997
 4998    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4999        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5000        if is_edited != self.window_edited {
 5001            self.window_edited = is_edited;
 5002            window.set_window_edited(self.window_edited)
 5003        }
 5004    }
 5005
 5006    fn update_item_dirty_state(
 5007        &mut self,
 5008        item: &dyn ItemHandle,
 5009        window: &mut Window,
 5010        cx: &mut App,
 5011    ) {
 5012        let is_dirty = item.is_dirty(cx);
 5013        let item_id = item.item_id();
 5014        let was_dirty = self.dirty_items.contains_key(&item_id);
 5015        if is_dirty == was_dirty {
 5016            return;
 5017        }
 5018        if was_dirty {
 5019            self.dirty_items.remove(&item_id);
 5020            self.update_window_edited(window, cx);
 5021            return;
 5022        }
 5023        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 5024            let s = item.on_release(
 5025                cx,
 5026                Box::new(move |cx| {
 5027                    window_handle
 5028                        .update(cx, |this, window, cx| {
 5029                            this.dirty_items.remove(&item_id);
 5030                            this.update_window_edited(window, cx)
 5031                        })
 5032                        .ok();
 5033                }),
 5034            );
 5035            self.dirty_items.insert(item_id, s);
 5036            self.update_window_edited(window, cx);
 5037        }
 5038    }
 5039
 5040    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5041        if self.notifications.is_empty() {
 5042            None
 5043        } else {
 5044            Some(
 5045                div()
 5046                    .absolute()
 5047                    .right_3()
 5048                    .bottom_3()
 5049                    .w_112()
 5050                    .h_full()
 5051                    .flex()
 5052                    .flex_col()
 5053                    .justify_end()
 5054                    .gap_2()
 5055                    .children(
 5056                        self.notifications
 5057                            .iter()
 5058                            .map(|(_, notification)| notification.clone().into_any()),
 5059                    ),
 5060            )
 5061        }
 5062    }
 5063
 5064    // RPC handlers
 5065
 5066    fn active_view_for_follower(
 5067        &self,
 5068        follower_project_id: Option<u64>,
 5069        window: &mut Window,
 5070        cx: &mut Context<Self>,
 5071    ) -> Option<proto::View> {
 5072        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5073        let item = item?;
 5074        let leader_id = self
 5075            .pane_for(&*item)
 5076            .and_then(|pane| self.leader_for_pane(&pane));
 5077        let leader_peer_id = match leader_id {
 5078            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5079            Some(CollaboratorId::Agent) | None => None,
 5080        };
 5081
 5082        let item_handle = item.to_followable_item_handle(cx)?;
 5083        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5084        let variant = item_handle.to_state_proto(window, cx)?;
 5085
 5086        if item_handle.is_project_item(window, cx)
 5087            && (follower_project_id.is_none()
 5088                || follower_project_id != self.project.read(cx).remote_id())
 5089        {
 5090            return None;
 5091        }
 5092
 5093        Some(proto::View {
 5094            id: id.to_proto(),
 5095            leader_id: leader_peer_id,
 5096            variant: Some(variant),
 5097            panel_id: panel_id.map(|id| id as i32),
 5098        })
 5099    }
 5100
 5101    fn handle_follow(
 5102        &mut self,
 5103        follower_project_id: Option<u64>,
 5104        window: &mut Window,
 5105        cx: &mut Context<Self>,
 5106    ) -> proto::FollowResponse {
 5107        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5108
 5109        cx.notify();
 5110        proto::FollowResponse {
 5111            views: active_view.iter().cloned().collect(),
 5112            active_view,
 5113        }
 5114    }
 5115
 5116    fn handle_update_followers(
 5117        &mut self,
 5118        leader_id: PeerId,
 5119        message: proto::UpdateFollowers,
 5120        _window: &mut Window,
 5121        _cx: &mut Context<Self>,
 5122    ) {
 5123        self.leader_updates_tx
 5124            .unbounded_send((leader_id, message))
 5125            .ok();
 5126    }
 5127
 5128    async fn process_leader_update(
 5129        this: &WeakEntity<Self>,
 5130        leader_id: PeerId,
 5131        update: proto::UpdateFollowers,
 5132        cx: &mut AsyncWindowContext,
 5133    ) -> Result<()> {
 5134        match update.variant.context("invalid update")? {
 5135            proto::update_followers::Variant::CreateView(view) => {
 5136                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5137                let should_add_view = this.update(cx, |this, _| {
 5138                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5139                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5140                    } else {
 5141                        anyhow::Ok(false)
 5142                    }
 5143                })??;
 5144
 5145                if should_add_view {
 5146                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5147                }
 5148            }
 5149            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5150                let should_add_view = this.update(cx, |this, _| {
 5151                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5152                        state.active_view_id = update_active_view
 5153                            .view
 5154                            .as_ref()
 5155                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5156
 5157                        if state.active_view_id.is_some_and(|view_id| {
 5158                            !state.items_by_leader_view_id.contains_key(&view_id)
 5159                        }) {
 5160                            anyhow::Ok(true)
 5161                        } else {
 5162                            anyhow::Ok(false)
 5163                        }
 5164                    } else {
 5165                        anyhow::Ok(false)
 5166                    }
 5167                })??;
 5168
 5169                if should_add_view && let Some(view) = update_active_view.view {
 5170                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5171                }
 5172            }
 5173            proto::update_followers::Variant::UpdateView(update_view) => {
 5174                let variant = update_view.variant.context("missing update view variant")?;
 5175                let id = update_view.id.context("missing update view id")?;
 5176                let mut tasks = Vec::new();
 5177                this.update_in(cx, |this, window, cx| {
 5178                    let project = this.project.clone();
 5179                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5180                        let view_id = ViewId::from_proto(id.clone())?;
 5181                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5182                            tasks.push(item.view.apply_update_proto(
 5183                                &project,
 5184                                variant.clone(),
 5185                                window,
 5186                                cx,
 5187                            ));
 5188                        }
 5189                    }
 5190                    anyhow::Ok(())
 5191                })??;
 5192                try_join_all(tasks).await.log_err();
 5193            }
 5194        }
 5195        this.update_in(cx, |this, window, cx| {
 5196            this.leader_updated(leader_id, window, cx)
 5197        })?;
 5198        Ok(())
 5199    }
 5200
 5201    async fn add_view_from_leader(
 5202        this: WeakEntity<Self>,
 5203        leader_id: PeerId,
 5204        view: &proto::View,
 5205        cx: &mut AsyncWindowContext,
 5206    ) -> Result<()> {
 5207        let this = this.upgrade().context("workspace dropped")?;
 5208
 5209        let Some(id) = view.id.clone() else {
 5210            anyhow::bail!("no id for view");
 5211        };
 5212        let id = ViewId::from_proto(id)?;
 5213        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5214
 5215        let pane = this.update(cx, |this, _cx| {
 5216            let state = this
 5217                .follower_states
 5218                .get(&leader_id.into())
 5219                .context("stopped following")?;
 5220            anyhow::Ok(state.pane().clone())
 5221        })?;
 5222        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5223            let client = this.read(cx).client().clone();
 5224            pane.items().find_map(|item| {
 5225                let item = item.to_followable_item_handle(cx)?;
 5226                if item.remote_id(&client, window, cx) == Some(id) {
 5227                    Some(item)
 5228                } else {
 5229                    None
 5230                }
 5231            })
 5232        })?;
 5233        let item = if let Some(existing_item) = existing_item {
 5234            existing_item
 5235        } else {
 5236            let variant = view.variant.clone();
 5237            anyhow::ensure!(variant.is_some(), "missing view variant");
 5238
 5239            let task = cx.update(|window, cx| {
 5240                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5241            })?;
 5242
 5243            let Some(task) = task else {
 5244                anyhow::bail!(
 5245                    "failed to construct view from leader (maybe from a different version of zed?)"
 5246                );
 5247            };
 5248
 5249            let mut new_item = task.await?;
 5250            pane.update_in(cx, |pane, window, cx| {
 5251                let mut item_to_remove = None;
 5252                for (ix, item) in pane.items().enumerate() {
 5253                    if let Some(item) = item.to_followable_item_handle(cx) {
 5254                        match new_item.dedup(item.as_ref(), window, cx) {
 5255                            Some(item::Dedup::KeepExisting) => {
 5256                                new_item =
 5257                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5258                                break;
 5259                            }
 5260                            Some(item::Dedup::ReplaceExisting) => {
 5261                                item_to_remove = Some((ix, item.item_id()));
 5262                                break;
 5263                            }
 5264                            None => {}
 5265                        }
 5266                    }
 5267                }
 5268
 5269                if let Some((ix, id)) = item_to_remove {
 5270                    pane.remove_item(id, false, false, window, cx);
 5271                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5272                }
 5273            })?;
 5274
 5275            new_item
 5276        };
 5277
 5278        this.update_in(cx, |this, window, cx| {
 5279            let state = this.follower_states.get_mut(&leader_id.into())?;
 5280            item.set_leader_id(Some(leader_id.into()), window, cx);
 5281            state.items_by_leader_view_id.insert(
 5282                id,
 5283                FollowerView {
 5284                    view: item,
 5285                    location: panel_id,
 5286                },
 5287            );
 5288
 5289            Some(())
 5290        })
 5291        .context("no follower state")?;
 5292
 5293        Ok(())
 5294    }
 5295
 5296    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5297        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5298            return;
 5299        };
 5300
 5301        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5302            let buffer_entity_id = agent_location.buffer.entity_id();
 5303            let view_id = ViewId {
 5304                creator: CollaboratorId::Agent,
 5305                id: buffer_entity_id.as_u64(),
 5306            };
 5307            follower_state.active_view_id = Some(view_id);
 5308
 5309            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5310                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5311                hash_map::Entry::Vacant(entry) => {
 5312                    let existing_view =
 5313                        follower_state
 5314                            .center_pane
 5315                            .read(cx)
 5316                            .items()
 5317                            .find_map(|item| {
 5318                                let item = item.to_followable_item_handle(cx)?;
 5319                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5320                                    && item.project_item_model_ids(cx).as_slice()
 5321                                        == [buffer_entity_id]
 5322                                {
 5323                                    Some(item)
 5324                                } else {
 5325                                    None
 5326                                }
 5327                            });
 5328                    let view = existing_view.or_else(|| {
 5329                        agent_location.buffer.upgrade().and_then(|buffer| {
 5330                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5331                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5332                            })?
 5333                            .to_followable_item_handle(cx)
 5334                        })
 5335                    });
 5336
 5337                    view.map(|view| {
 5338                        entry.insert(FollowerView {
 5339                            view,
 5340                            location: None,
 5341                        })
 5342                    })
 5343                }
 5344            };
 5345
 5346            if let Some(item) = item {
 5347                item.view
 5348                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5349                item.view
 5350                    .update_agent_location(agent_location.position, window, cx);
 5351            }
 5352        } else {
 5353            follower_state.active_view_id = None;
 5354        }
 5355
 5356        self.leader_updated(CollaboratorId::Agent, window, cx);
 5357    }
 5358
 5359    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5360        let mut is_project_item = true;
 5361        let mut update = proto::UpdateActiveView::default();
 5362        if window.is_window_active() {
 5363            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5364
 5365            if let Some(item) = active_item
 5366                && item.item_focus_handle(cx).contains_focused(window, cx)
 5367            {
 5368                let leader_id = self
 5369                    .pane_for(&*item)
 5370                    .and_then(|pane| self.leader_for_pane(&pane));
 5371                let leader_peer_id = match leader_id {
 5372                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5373                    Some(CollaboratorId::Agent) | None => None,
 5374                };
 5375
 5376                if let Some(item) = item.to_followable_item_handle(cx) {
 5377                    let id = item
 5378                        .remote_id(&self.app_state.client, window, cx)
 5379                        .map(|id| id.to_proto());
 5380
 5381                    if let Some(id) = id
 5382                        && let Some(variant) = item.to_state_proto(window, cx)
 5383                    {
 5384                        let view = Some(proto::View {
 5385                            id,
 5386                            leader_id: leader_peer_id,
 5387                            variant: Some(variant),
 5388                            panel_id: panel_id.map(|id| id as i32),
 5389                        });
 5390
 5391                        is_project_item = item.is_project_item(window, cx);
 5392                        update = proto::UpdateActiveView { view };
 5393                    };
 5394                }
 5395            }
 5396        }
 5397
 5398        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5399        if active_view_id != self.last_active_view_id.as_ref() {
 5400            self.last_active_view_id = active_view_id.cloned();
 5401            self.update_followers(
 5402                is_project_item,
 5403                proto::update_followers::Variant::UpdateActiveView(update),
 5404                window,
 5405                cx,
 5406            );
 5407        }
 5408    }
 5409
 5410    fn active_item_for_followers(
 5411        &self,
 5412        window: &mut Window,
 5413        cx: &mut App,
 5414    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5415        let mut active_item = None;
 5416        let mut panel_id = None;
 5417        for dock in self.all_docks() {
 5418            if dock.focus_handle(cx).contains_focused(window, cx)
 5419                && let Some(panel) = dock.read(cx).active_panel()
 5420                && let Some(pane) = panel.pane(cx)
 5421                && let Some(item) = pane.read(cx).active_item()
 5422            {
 5423                active_item = Some(item);
 5424                panel_id = panel.remote_id();
 5425                break;
 5426            }
 5427        }
 5428
 5429        if active_item.is_none() {
 5430            active_item = self.active_pane().read(cx).active_item();
 5431        }
 5432        (active_item, panel_id)
 5433    }
 5434
 5435    fn update_followers(
 5436        &self,
 5437        project_only: bool,
 5438        update: proto::update_followers::Variant,
 5439        _: &mut Window,
 5440        cx: &mut App,
 5441    ) -> Option<()> {
 5442        // If this update only applies to for followers in the current project,
 5443        // then skip it unless this project is shared. If it applies to all
 5444        // followers, regardless of project, then set `project_id` to none,
 5445        // indicating that it goes to all followers.
 5446        let project_id = if project_only {
 5447            Some(self.project.read(cx).remote_id()?)
 5448        } else {
 5449            None
 5450        };
 5451        self.app_state().workspace_store.update(cx, |store, cx| {
 5452            store.update_followers(project_id, update, cx)
 5453        })
 5454    }
 5455
 5456    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5457        self.follower_states.iter().find_map(|(leader_id, state)| {
 5458            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5459                Some(*leader_id)
 5460            } else {
 5461                None
 5462            }
 5463        })
 5464    }
 5465
 5466    fn leader_updated(
 5467        &mut self,
 5468        leader_id: impl Into<CollaboratorId>,
 5469        window: &mut Window,
 5470        cx: &mut Context<Self>,
 5471    ) -> Option<Box<dyn ItemHandle>> {
 5472        cx.notify();
 5473
 5474        let leader_id = leader_id.into();
 5475        let (panel_id, item) = match leader_id {
 5476            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5477            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5478        };
 5479
 5480        let state = self.follower_states.get(&leader_id)?;
 5481        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5482        let pane;
 5483        if let Some(panel_id) = panel_id {
 5484            pane = self
 5485                .activate_panel_for_proto_id(panel_id, window, cx)?
 5486                .pane(cx)?;
 5487            let state = self.follower_states.get_mut(&leader_id)?;
 5488            state.dock_pane = Some(pane.clone());
 5489        } else {
 5490            pane = state.center_pane.clone();
 5491            let state = self.follower_states.get_mut(&leader_id)?;
 5492            if let Some(dock_pane) = state.dock_pane.take() {
 5493                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5494            }
 5495        }
 5496
 5497        pane.update(cx, |pane, cx| {
 5498            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5499            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5500                pane.activate_item(index, false, false, window, cx);
 5501            } else {
 5502                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5503            }
 5504
 5505            if focus_active_item {
 5506                pane.focus_active_item(window, cx)
 5507            }
 5508        });
 5509
 5510        Some(item)
 5511    }
 5512
 5513    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5514        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5515        let active_view_id = state.active_view_id?;
 5516        Some(
 5517            state
 5518                .items_by_leader_view_id
 5519                .get(&active_view_id)?
 5520                .view
 5521                .boxed_clone(),
 5522        )
 5523    }
 5524
 5525    fn active_item_for_peer(
 5526        &self,
 5527        peer_id: PeerId,
 5528        window: &mut Window,
 5529        cx: &mut Context<Self>,
 5530    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5531        let call = self.active_call()?;
 5532        let room = call.read(cx).room()?.read(cx);
 5533        let participant = room.remote_participant_for_peer_id(peer_id)?;
 5534        let leader_in_this_app;
 5535        let leader_in_this_project;
 5536        match participant.location {
 5537            call::ParticipantLocation::SharedProject { project_id } => {
 5538                leader_in_this_app = true;
 5539                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5540            }
 5541            call::ParticipantLocation::UnsharedProject => {
 5542                leader_in_this_app = true;
 5543                leader_in_this_project = false;
 5544            }
 5545            call::ParticipantLocation::External => {
 5546                leader_in_this_app = false;
 5547                leader_in_this_project = false;
 5548            }
 5549        };
 5550        let state = self.follower_states.get(&peer_id.into())?;
 5551        let mut item_to_activate = None;
 5552        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5553            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5554                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5555            {
 5556                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5557            }
 5558        } else if let Some(shared_screen) =
 5559            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5560        {
 5561            item_to_activate = Some((None, Box::new(shared_screen)));
 5562        }
 5563        item_to_activate
 5564    }
 5565
 5566    fn shared_screen_for_peer(
 5567        &self,
 5568        peer_id: PeerId,
 5569        pane: &Entity<Pane>,
 5570        window: &mut Window,
 5571        cx: &mut App,
 5572    ) -> Option<Entity<SharedScreen>> {
 5573        let call = self.active_call()?;
 5574        let room = call.read(cx).room()?.clone();
 5575        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 5576        let track = participant.video_tracks.values().next()?.clone();
 5577        let user = participant.user.clone();
 5578
 5579        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 5580            if item.read(cx).peer_id == peer_id {
 5581                return Some(item);
 5582            }
 5583        }
 5584
 5585        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 5586    }
 5587
 5588    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5589        if window.is_window_active() {
 5590            self.update_active_view_for_followers(window, cx);
 5591
 5592            if let Some(database_id) = self.database_id {
 5593                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5594                    .detach();
 5595            }
 5596        } else {
 5597            for pane in &self.panes {
 5598                pane.update(cx, |pane, cx| {
 5599                    if let Some(item) = pane.active_item() {
 5600                        item.workspace_deactivated(window, cx);
 5601                    }
 5602                    for item in pane.items() {
 5603                        if matches!(
 5604                            item.workspace_settings(cx).autosave,
 5605                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5606                        ) {
 5607                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5608                                .detach_and_log_err(cx);
 5609                        }
 5610                    }
 5611                });
 5612            }
 5613        }
 5614    }
 5615
 5616    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5617        self.active_call.as_ref().map(|(call, _)| call)
 5618    }
 5619
 5620    fn on_active_call_event(
 5621        &mut self,
 5622        _: &Entity<ActiveCall>,
 5623        event: &call::room::Event,
 5624        window: &mut Window,
 5625        cx: &mut Context<Self>,
 5626    ) {
 5627        match event {
 5628            call::room::Event::ParticipantLocationChanged { participant_id }
 5629            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5630                self.leader_updated(participant_id, window, cx);
 5631            }
 5632            _ => {}
 5633        }
 5634    }
 5635
 5636    pub fn database_id(&self) -> Option<WorkspaceId> {
 5637        self.database_id
 5638    }
 5639
 5640    pub fn session_id(&self) -> Option<String> {
 5641        self.session_id.clone()
 5642    }
 5643
 5644    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5645        let project = self.project().read(cx);
 5646        project
 5647            .visible_worktrees(cx)
 5648            .map(|worktree| worktree.read(cx).abs_path())
 5649            .collect::<Vec<_>>()
 5650    }
 5651
 5652    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5653        match member {
 5654            Member::Axis(PaneAxis { members, .. }) => {
 5655                for child in members.iter() {
 5656                    self.remove_panes(child.clone(), window, cx)
 5657                }
 5658            }
 5659            Member::Pane(pane) => {
 5660                self.force_remove_pane(&pane, &None, window, cx);
 5661            }
 5662        }
 5663    }
 5664
 5665    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5666        self.session_id.take();
 5667        self.serialize_workspace_internal(window, cx)
 5668    }
 5669
 5670    fn force_remove_pane(
 5671        &mut self,
 5672        pane: &Entity<Pane>,
 5673        focus_on: &Option<Entity<Pane>>,
 5674        window: &mut Window,
 5675        cx: &mut Context<Workspace>,
 5676    ) {
 5677        self.panes.retain(|p| p != pane);
 5678        if let Some(focus_on) = focus_on {
 5679            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5680        } else if self.active_pane() == pane {
 5681            self.panes
 5682                .last()
 5683                .unwrap()
 5684                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5685        }
 5686        if self.last_active_center_pane == Some(pane.downgrade()) {
 5687            self.last_active_center_pane = None;
 5688        }
 5689        cx.notify();
 5690    }
 5691
 5692    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5693        if self._schedule_serialize_workspace.is_none() {
 5694            self._schedule_serialize_workspace =
 5695                Some(cx.spawn_in(window, async move |this, cx| {
 5696                    cx.background_executor()
 5697                        .timer(SERIALIZATION_THROTTLE_TIME)
 5698                        .await;
 5699                    this.update_in(cx, |this, window, cx| {
 5700                        this.serialize_workspace_internal(window, cx).detach();
 5701                        this._schedule_serialize_workspace.take();
 5702                    })
 5703                    .log_err();
 5704                }));
 5705        }
 5706    }
 5707
 5708    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5709        let Some(database_id) = self.database_id() else {
 5710            return Task::ready(());
 5711        };
 5712
 5713        fn serialize_pane_handle(
 5714            pane_handle: &Entity<Pane>,
 5715            window: &mut Window,
 5716            cx: &mut App,
 5717        ) -> SerializedPane {
 5718            let (items, active, pinned_count) = {
 5719                let pane = pane_handle.read(cx);
 5720                let active_item_id = pane.active_item().map(|item| item.item_id());
 5721                (
 5722                    pane.items()
 5723                        .filter_map(|handle| {
 5724                            let handle = handle.to_serializable_item_handle(cx)?;
 5725
 5726                            Some(SerializedItem {
 5727                                kind: Arc::from(handle.serialized_item_kind()),
 5728                                item_id: handle.item_id().as_u64(),
 5729                                active: Some(handle.item_id()) == active_item_id,
 5730                                preview: pane.is_active_preview_item(handle.item_id()),
 5731                            })
 5732                        })
 5733                        .collect::<Vec<_>>(),
 5734                    pane.has_focus(window, cx),
 5735                    pane.pinned_count(),
 5736                )
 5737            };
 5738
 5739            SerializedPane::new(items, active, pinned_count)
 5740        }
 5741
 5742        fn build_serialized_pane_group(
 5743            pane_group: &Member,
 5744            window: &mut Window,
 5745            cx: &mut App,
 5746        ) -> SerializedPaneGroup {
 5747            match pane_group {
 5748                Member::Axis(PaneAxis {
 5749                    axis,
 5750                    members,
 5751                    flexes,
 5752                    bounding_boxes: _,
 5753                }) => SerializedPaneGroup::Group {
 5754                    axis: SerializedAxis(*axis),
 5755                    children: members
 5756                        .iter()
 5757                        .map(|member| build_serialized_pane_group(member, window, cx))
 5758                        .collect::<Vec<_>>(),
 5759                    flexes: Some(flexes.lock().clone()),
 5760                },
 5761                Member::Pane(pane_handle) => {
 5762                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5763                }
 5764            }
 5765        }
 5766
 5767        fn build_serialized_docks(
 5768            this: &Workspace,
 5769            window: &mut Window,
 5770            cx: &mut App,
 5771        ) -> DockStructure {
 5772            let left_dock = this.left_dock.read(cx);
 5773            let left_visible = left_dock.is_open();
 5774            let left_active_panel = left_dock
 5775                .active_panel()
 5776                .map(|panel| panel.persistent_name().to_string());
 5777            let left_dock_zoom = left_dock
 5778                .active_panel()
 5779                .map(|panel| panel.is_zoomed(window, cx))
 5780                .unwrap_or(false);
 5781
 5782            let right_dock = this.right_dock.read(cx);
 5783            let right_visible = right_dock.is_open();
 5784            let right_active_panel = right_dock
 5785                .active_panel()
 5786                .map(|panel| panel.persistent_name().to_string());
 5787            let right_dock_zoom = right_dock
 5788                .active_panel()
 5789                .map(|panel| panel.is_zoomed(window, cx))
 5790                .unwrap_or(false);
 5791
 5792            let bottom_dock = this.bottom_dock.read(cx);
 5793            let bottom_visible = bottom_dock.is_open();
 5794            let bottom_active_panel = bottom_dock
 5795                .active_panel()
 5796                .map(|panel| panel.persistent_name().to_string());
 5797            let bottom_dock_zoom = bottom_dock
 5798                .active_panel()
 5799                .map(|panel| panel.is_zoomed(window, cx))
 5800                .unwrap_or(false);
 5801
 5802            DockStructure {
 5803                left: DockData {
 5804                    visible: left_visible,
 5805                    active_panel: left_active_panel,
 5806                    zoom: left_dock_zoom,
 5807                },
 5808                right: DockData {
 5809                    visible: right_visible,
 5810                    active_panel: right_active_panel,
 5811                    zoom: right_dock_zoom,
 5812                },
 5813                bottom: DockData {
 5814                    visible: bottom_visible,
 5815                    active_panel: bottom_active_panel,
 5816                    zoom: bottom_dock_zoom,
 5817                },
 5818            }
 5819        }
 5820
 5821        match self.serialize_workspace_location(cx) {
 5822            WorkspaceLocation::Location(location, paths) => {
 5823                let breakpoints = self.project.update(cx, |project, cx| {
 5824                    project
 5825                        .breakpoint_store()
 5826                        .read(cx)
 5827                        .all_source_breakpoints(cx)
 5828                });
 5829                let user_toolchains = self
 5830                    .project
 5831                    .read(cx)
 5832                    .user_toolchains(cx)
 5833                    .unwrap_or_default();
 5834
 5835                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5836                let docks = build_serialized_docks(self, window, cx);
 5837                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5838
 5839                let serialized_workspace = SerializedWorkspace {
 5840                    id: database_id,
 5841                    location,
 5842                    paths,
 5843                    center_group,
 5844                    window_bounds,
 5845                    display: Default::default(),
 5846                    docks,
 5847                    centered_layout: self.centered_layout,
 5848                    session_id: self.session_id.clone(),
 5849                    breakpoints,
 5850                    window_id: Some(window.window_handle().window_id().as_u64()),
 5851                    user_toolchains,
 5852                };
 5853
 5854                window.spawn(cx, async move |_| {
 5855                    persistence::DB.save_workspace(serialized_workspace).await;
 5856                })
 5857            }
 5858            WorkspaceLocation::DetachFromSession => {
 5859                let window_bounds = SerializedWindowBounds(window.window_bounds());
 5860                let display = window.display(cx).and_then(|d| d.uuid().ok());
 5861                window.spawn(cx, async move |_| {
 5862                    persistence::DB
 5863                        .set_window_open_status(
 5864                            database_id,
 5865                            window_bounds,
 5866                            display.unwrap_or_default(),
 5867                        )
 5868                        .await
 5869                        .log_err();
 5870                    persistence::DB
 5871                        .set_session_id(database_id, None)
 5872                        .await
 5873                        .log_err();
 5874                })
 5875            }
 5876            WorkspaceLocation::None => Task::ready(()),
 5877        }
 5878    }
 5879
 5880    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5881        let paths = PathList::new(&self.root_paths(cx));
 5882        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5883            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 5884        } else if self.project.read(cx).is_local() {
 5885            if !paths.is_empty() {
 5886                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 5887            } else {
 5888                WorkspaceLocation::DetachFromSession
 5889            }
 5890        } else {
 5891            WorkspaceLocation::None
 5892        }
 5893    }
 5894
 5895    fn update_history(&self, cx: &mut App) {
 5896        let Some(id) = self.database_id() else {
 5897            return;
 5898        };
 5899        if !self.project.read(cx).is_local() {
 5900            return;
 5901        }
 5902        if let Some(manager) = HistoryManager::global(cx) {
 5903            let paths = PathList::new(&self.root_paths(cx));
 5904            manager.update(cx, |this, cx| {
 5905                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 5906            });
 5907        }
 5908    }
 5909
 5910    async fn serialize_items(
 5911        this: &WeakEntity<Self>,
 5912        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5913        cx: &mut AsyncWindowContext,
 5914    ) -> Result<()> {
 5915        const CHUNK_SIZE: usize = 200;
 5916
 5917        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5918
 5919        while let Some(items_received) = serializable_items.next().await {
 5920            let unique_items =
 5921                items_received
 5922                    .into_iter()
 5923                    .fold(HashMap::default(), |mut acc, item| {
 5924                        acc.entry(item.item_id()).or_insert(item);
 5925                        acc
 5926                    });
 5927
 5928            // We use into_iter() here so that the references to the items are moved into
 5929            // the tasks and not kept alive while we're sleeping.
 5930            for (_, item) in unique_items.into_iter() {
 5931                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5932                    item.serialize(workspace, false, window, cx)
 5933                }) {
 5934                    cx.background_spawn(async move { task.await.log_err() })
 5935                        .detach();
 5936                }
 5937            }
 5938
 5939            cx.background_executor()
 5940                .timer(SERIALIZATION_THROTTLE_TIME)
 5941                .await;
 5942        }
 5943
 5944        Ok(())
 5945    }
 5946
 5947    pub(crate) fn enqueue_item_serialization(
 5948        &mut self,
 5949        item: Box<dyn SerializableItemHandle>,
 5950    ) -> Result<()> {
 5951        self.serializable_items_tx
 5952            .unbounded_send(item)
 5953            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5954    }
 5955
 5956    pub(crate) fn load_workspace(
 5957        serialized_workspace: SerializedWorkspace,
 5958        paths_to_open: Vec<Option<ProjectPath>>,
 5959        window: &mut Window,
 5960        cx: &mut Context<Workspace>,
 5961    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5962        cx.spawn_in(window, async move |workspace, cx| {
 5963            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5964
 5965            let mut center_group = None;
 5966            let mut center_items = None;
 5967
 5968            // Traverse the splits tree and add to things
 5969            if let Some((group, active_pane, items)) = serialized_workspace
 5970                .center_group
 5971                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5972                .await
 5973            {
 5974                center_items = Some(items);
 5975                center_group = Some((group, active_pane))
 5976            }
 5977
 5978            let mut items_by_project_path = HashMap::default();
 5979            let mut item_ids_by_kind = HashMap::default();
 5980            let mut all_deserialized_items = Vec::default();
 5981            cx.update(|_, cx| {
 5982                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5983                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5984                        item_ids_by_kind
 5985                            .entry(serializable_item_handle.serialized_item_kind())
 5986                            .or_insert(Vec::new())
 5987                            .push(item.item_id().as_u64() as ItemId);
 5988                    }
 5989
 5990                    if let Some(project_path) = item.project_path(cx) {
 5991                        items_by_project_path.insert(project_path, item.clone());
 5992                    }
 5993                    all_deserialized_items.push(item);
 5994                }
 5995            })?;
 5996
 5997            let opened_items = paths_to_open
 5998                .into_iter()
 5999                .map(|path_to_open| {
 6000                    path_to_open
 6001                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6002                })
 6003                .collect::<Vec<_>>();
 6004
 6005            // Remove old panes from workspace panes list
 6006            workspace.update_in(cx, |workspace, window, cx| {
 6007                if let Some((center_group, active_pane)) = center_group {
 6008                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6009
 6010                    // Swap workspace center group
 6011                    workspace.center = PaneGroup::with_root(center_group);
 6012                    workspace.center.set_is_center(true);
 6013                    workspace.center.mark_positions(cx);
 6014
 6015                    if let Some(active_pane) = active_pane {
 6016                        workspace.set_active_pane(&active_pane, window, cx);
 6017                        cx.focus_self(window);
 6018                    } else {
 6019                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6020                    }
 6021                }
 6022
 6023                let docks = serialized_workspace.docks;
 6024
 6025                for (dock, serialized_dock) in [
 6026                    (&mut workspace.right_dock, docks.right),
 6027                    (&mut workspace.left_dock, docks.left),
 6028                    (&mut workspace.bottom_dock, docks.bottom),
 6029                ]
 6030                .iter_mut()
 6031                {
 6032                    dock.update(cx, |dock, cx| {
 6033                        dock.serialized_dock = Some(serialized_dock.clone());
 6034                        dock.restore_state(window, cx);
 6035                    });
 6036                }
 6037
 6038                cx.notify();
 6039            })?;
 6040
 6041            let _ = project
 6042                .update(cx, |project, cx| {
 6043                    project
 6044                        .breakpoint_store()
 6045                        .update(cx, |breakpoint_store, cx| {
 6046                            breakpoint_store
 6047                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6048                        })
 6049                })
 6050                .await;
 6051
 6052            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6053            // after loading the items, we might have different items and in order to avoid
 6054            // the database filling up, we delete items that haven't been loaded now.
 6055            //
 6056            // The items that have been loaded, have been saved after they've been added to the workspace.
 6057            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6058                item_ids_by_kind
 6059                    .into_iter()
 6060                    .map(|(item_kind, loaded_items)| {
 6061                        SerializableItemRegistry::cleanup(
 6062                            item_kind,
 6063                            serialized_workspace.id,
 6064                            loaded_items,
 6065                            window,
 6066                            cx,
 6067                        )
 6068                        .log_err()
 6069                    })
 6070                    .collect::<Vec<_>>()
 6071            })?;
 6072
 6073            futures::future::join_all(clean_up_tasks).await;
 6074
 6075            workspace
 6076                .update_in(cx, |workspace, window, cx| {
 6077                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6078                    workspace.serialize_workspace_internal(window, cx).detach();
 6079
 6080                    // Ensure that we mark the window as edited if we did load dirty items
 6081                    workspace.update_window_edited(window, cx);
 6082                })
 6083                .ok();
 6084
 6085            Ok(opened_items)
 6086        })
 6087    }
 6088
 6089    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6090        self.add_workspace_actions_listeners(div, window, cx)
 6091            .on_action(cx.listener(
 6092                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6093                    for action in &action_sequence.0 {
 6094                        window.dispatch_action(action.boxed_clone(), cx);
 6095                    }
 6096                },
 6097            ))
 6098            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6099            .on_action(cx.listener(Self::close_all_items_and_panes))
 6100            .on_action(cx.listener(Self::save_all))
 6101            .on_action(cx.listener(Self::send_keystrokes))
 6102            .on_action(cx.listener(Self::add_folder_to_project))
 6103            .on_action(cx.listener(Self::follow_next_collaborator))
 6104            .on_action(cx.listener(Self::close_window))
 6105            .on_action(cx.listener(Self::activate_pane_at_index))
 6106            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6107            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6108            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6109            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6110                let pane = workspace.active_pane().clone();
 6111                workspace.unfollow_in_pane(&pane, window, cx);
 6112            }))
 6113            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6114                workspace
 6115                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6116                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6117            }))
 6118            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6119                workspace
 6120                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6121                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6122            }))
 6123            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6124                workspace
 6125                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6126                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6127            }))
 6128            .on_action(
 6129                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6130                    workspace.activate_previous_pane(window, cx)
 6131                }),
 6132            )
 6133            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6134                workspace.activate_next_pane(window, cx)
 6135            }))
 6136            .on_action(
 6137                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6138                    workspace.activate_next_window(cx)
 6139                }),
 6140            )
 6141            .on_action(
 6142                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6143                    workspace.activate_previous_window(cx)
 6144                }),
 6145            )
 6146            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6147                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6148            }))
 6149            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6150                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6151            }))
 6152            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6153                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6154            }))
 6155            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6156                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6157            }))
 6158            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6159                workspace.activate_next_pane(window, cx)
 6160            }))
 6161            .on_action(cx.listener(
 6162                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6163                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6164                },
 6165            ))
 6166            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6167                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6168            }))
 6169            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6170                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6171            }))
 6172            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6173                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6174            }))
 6175            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6176                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6177            }))
 6178            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6179                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6180                    SplitDirection::Down,
 6181                    SplitDirection::Up,
 6182                    SplitDirection::Right,
 6183                    SplitDirection::Left,
 6184                ];
 6185                for dir in DIRECTION_PRIORITY {
 6186                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6187                        workspace.swap_pane_in_direction(dir, cx);
 6188                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6189                        break;
 6190                    }
 6191                }
 6192            }))
 6193            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6194                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6195            }))
 6196            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6197                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6198            }))
 6199            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6200                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6201            }))
 6202            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6203                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6204            }))
 6205            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6206                this.toggle_dock(DockPosition::Left, window, cx);
 6207            }))
 6208            .on_action(cx.listener(
 6209                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6210                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6211                },
 6212            ))
 6213            .on_action(cx.listener(
 6214                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6215                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6216                },
 6217            ))
 6218            .on_action(cx.listener(
 6219                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6220                    if !workspace.close_active_dock(window, cx) {
 6221                        cx.propagate();
 6222                    }
 6223                },
 6224            ))
 6225            .on_action(
 6226                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6227                    workspace.close_all_docks(window, cx);
 6228                }),
 6229            )
 6230            .on_action(cx.listener(Self::toggle_all_docks))
 6231            .on_action(cx.listener(
 6232                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6233                    workspace.clear_all_notifications(cx);
 6234                },
 6235            ))
 6236            .on_action(cx.listener(
 6237                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6238                    workspace.clear_navigation_history(window, cx);
 6239                },
 6240            ))
 6241            .on_action(cx.listener(
 6242                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6243                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6244                        workspace.suppress_notification(&notification_id, cx);
 6245                    }
 6246                },
 6247            ))
 6248            .on_action(cx.listener(
 6249                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6250                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6251                },
 6252            ))
 6253            .on_action(
 6254                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6255                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6256                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6257                            trusted_worktrees.clear_trusted_paths()
 6258                        });
 6259                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6260                        cx.spawn(async move |_, cx| {
 6261                            if clear_task.await.log_err().is_some() {
 6262                                cx.update(|cx| reload(cx));
 6263                            }
 6264                        })
 6265                        .detach();
 6266                    }
 6267                }),
 6268            )
 6269            .on_action(cx.listener(
 6270                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6271                    workspace.reopen_closed_item(window, cx).detach();
 6272                },
 6273            ))
 6274            .on_action(cx.listener(
 6275                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6276                    for dock in workspace.all_docks() {
 6277                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6278                            let Some(panel) = dock.read(cx).active_panel() else {
 6279                                return;
 6280                            };
 6281
 6282                            // Set to `None`, then the size will fall back to the default.
 6283                            panel.clone().set_size(None, window, cx);
 6284
 6285                            return;
 6286                        }
 6287                    }
 6288                },
 6289            ))
 6290            .on_action(cx.listener(
 6291                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6292                    for dock in workspace.all_docks() {
 6293                        if let Some(panel) = dock.read(cx).visible_panel() {
 6294                            // Set to `None`, then the size will fall back to the default.
 6295                            panel.clone().set_size(None, window, cx);
 6296                        }
 6297                    }
 6298                },
 6299            ))
 6300            .on_action(cx.listener(
 6301                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6302                    adjust_active_dock_size_by_px(
 6303                        px_with_ui_font_fallback(act.px, cx),
 6304                        workspace,
 6305                        window,
 6306                        cx,
 6307                    );
 6308                },
 6309            ))
 6310            .on_action(cx.listener(
 6311                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6312                    adjust_active_dock_size_by_px(
 6313                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6314                        workspace,
 6315                        window,
 6316                        cx,
 6317                    );
 6318                },
 6319            ))
 6320            .on_action(cx.listener(
 6321                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6322                    adjust_open_docks_size_by_px(
 6323                        px_with_ui_font_fallback(act.px, cx),
 6324                        workspace,
 6325                        window,
 6326                        cx,
 6327                    );
 6328                },
 6329            ))
 6330            .on_action(cx.listener(
 6331                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6332                    adjust_open_docks_size_by_px(
 6333                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6334                        workspace,
 6335                        window,
 6336                        cx,
 6337                    );
 6338                },
 6339            ))
 6340            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6341            .on_action(cx.listener(
 6342                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6343                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6344                        let dock = active_dock.read(cx);
 6345                        if let Some(active_panel) = dock.active_panel() {
 6346                            if active_panel.pane(cx).is_none() {
 6347                                let mut recent_pane: Option<Entity<Pane>> = None;
 6348                                let mut recent_timestamp = 0;
 6349                                for pane_handle in workspace.panes() {
 6350                                    let pane = pane_handle.read(cx);
 6351                                    for entry in pane.activation_history() {
 6352                                        if entry.timestamp > recent_timestamp {
 6353                                            recent_timestamp = entry.timestamp;
 6354                                            recent_pane = Some(pane_handle.clone());
 6355                                        }
 6356                                    }
 6357                                }
 6358
 6359                                if let Some(pane) = recent_pane {
 6360                                    pane.update(cx, |pane, cx| {
 6361                                        let current_index = pane.active_item_index();
 6362                                        let items_len = pane.items_len();
 6363                                        if items_len > 0 {
 6364                                            let next_index = if current_index + 1 < items_len {
 6365                                                current_index + 1
 6366                                            } else {
 6367                                                0
 6368                                            };
 6369                                            pane.activate_item(
 6370                                                next_index, false, false, window, cx,
 6371                                            );
 6372                                        }
 6373                                    });
 6374                                    return;
 6375                                }
 6376                            }
 6377                        }
 6378                    }
 6379                    cx.propagate();
 6380                },
 6381            ))
 6382            .on_action(cx.listener(
 6383                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6384                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6385                        let dock = active_dock.read(cx);
 6386                        if let Some(active_panel) = dock.active_panel() {
 6387                            if active_panel.pane(cx).is_none() {
 6388                                let mut recent_pane: Option<Entity<Pane>> = None;
 6389                                let mut recent_timestamp = 0;
 6390                                for pane_handle in workspace.panes() {
 6391                                    let pane = pane_handle.read(cx);
 6392                                    for entry in pane.activation_history() {
 6393                                        if entry.timestamp > recent_timestamp {
 6394                                            recent_timestamp = entry.timestamp;
 6395                                            recent_pane = Some(pane_handle.clone());
 6396                                        }
 6397                                    }
 6398                                }
 6399
 6400                                if let Some(pane) = recent_pane {
 6401                                    pane.update(cx, |pane, cx| {
 6402                                        let current_index = pane.active_item_index();
 6403                                        let items_len = pane.items_len();
 6404                                        if items_len > 0 {
 6405                                            let prev_index = if current_index > 0 {
 6406                                                current_index - 1
 6407                                            } else {
 6408                                                items_len.saturating_sub(1)
 6409                                            };
 6410                                            pane.activate_item(
 6411                                                prev_index, false, false, window, cx,
 6412                                            );
 6413                                        }
 6414                                    });
 6415                                    return;
 6416                                }
 6417                            }
 6418                        }
 6419                    }
 6420                    cx.propagate();
 6421                },
 6422            ))
 6423            .on_action(cx.listener(
 6424                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6425                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6426                        let dock = active_dock.read(cx);
 6427                        if let Some(active_panel) = dock.active_panel() {
 6428                            if active_panel.pane(cx).is_none() {
 6429                                let active_pane = workspace.active_pane().clone();
 6430                                active_pane.update(cx, |pane, cx| {
 6431                                    pane.close_active_item(action, window, cx)
 6432                                        .detach_and_log_err(cx);
 6433                                });
 6434                                return;
 6435                            }
 6436                        }
 6437                    }
 6438                    cx.propagate();
 6439                },
 6440            ))
 6441            .on_action(
 6442                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6443                    let pane = workspace.active_pane().clone();
 6444                    if let Some(item) = pane.read(cx).active_item() {
 6445                        item.toggle_read_only(window, cx);
 6446                    }
 6447                }),
 6448            )
 6449            .on_action(cx.listener(Workspace::cancel))
 6450    }
 6451
 6452    #[cfg(any(test, feature = "test-support"))]
 6453    pub fn set_random_database_id(&mut self) {
 6454        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6455    }
 6456
 6457    #[cfg(any(test, feature = "test-support"))]
 6458    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 6459        use node_runtime::NodeRuntime;
 6460        use session::Session;
 6461
 6462        let client = project.read(cx).client();
 6463        let user_store = project.read(cx).user_store();
 6464        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6465        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6466        window.activate_window();
 6467        let app_state = Arc::new(AppState {
 6468            languages: project.read(cx).languages().clone(),
 6469            workspace_store,
 6470            client,
 6471            user_store,
 6472            fs: project.read(cx).fs().clone(),
 6473            build_window_options: |_, _| Default::default(),
 6474            node_runtime: NodeRuntime::unavailable(),
 6475            session,
 6476        });
 6477        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6478        workspace
 6479            .active_pane
 6480            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6481        workspace
 6482    }
 6483
 6484    pub fn register_action<A: Action>(
 6485        &mut self,
 6486        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6487    ) -> &mut Self {
 6488        let callback = Arc::new(callback);
 6489
 6490        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6491            let callback = callback.clone();
 6492            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6493                (callback)(workspace, event, window, cx)
 6494            }))
 6495        }));
 6496        self
 6497    }
 6498    pub fn register_action_renderer(
 6499        &mut self,
 6500        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6501    ) -> &mut Self {
 6502        self.workspace_actions.push(Box::new(callback));
 6503        self
 6504    }
 6505
 6506    fn add_workspace_actions_listeners(
 6507        &self,
 6508        mut div: Div,
 6509        window: &mut Window,
 6510        cx: &mut Context<Self>,
 6511    ) -> Div {
 6512        for action in self.workspace_actions.iter() {
 6513            div = (action)(div, self, window, cx)
 6514        }
 6515        div
 6516    }
 6517
 6518    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6519        self.modal_layer.read(cx).has_active_modal()
 6520    }
 6521
 6522    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6523        self.modal_layer.read(cx).active_modal()
 6524    }
 6525
 6526    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6527    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6528    /// If no modal is active, the new modal will be shown.
 6529    ///
 6530    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6531    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6532    /// will not be shown.
 6533    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6534    where
 6535        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6536    {
 6537        self.modal_layer.update(cx, |modal_layer, cx| {
 6538            modal_layer.toggle_modal(window, cx, build)
 6539        })
 6540    }
 6541
 6542    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6543        self.modal_layer
 6544            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6545    }
 6546
 6547    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6548        self.toast_layer
 6549            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6550    }
 6551
 6552    pub fn toggle_centered_layout(
 6553        &mut self,
 6554        _: &ToggleCenteredLayout,
 6555        _: &mut Window,
 6556        cx: &mut Context<Self>,
 6557    ) {
 6558        self.centered_layout = !self.centered_layout;
 6559        if let Some(database_id) = self.database_id() {
 6560            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6561                .detach_and_log_err(cx);
 6562        }
 6563        cx.notify();
 6564    }
 6565
 6566    fn adjust_padding(padding: Option<f32>) -> f32 {
 6567        padding
 6568            .unwrap_or(CenteredPaddingSettings::default().0)
 6569            .clamp(
 6570                CenteredPaddingSettings::MIN_PADDING,
 6571                CenteredPaddingSettings::MAX_PADDING,
 6572            )
 6573    }
 6574
 6575    fn render_dock(
 6576        &self,
 6577        position: DockPosition,
 6578        dock: &Entity<Dock>,
 6579        window: &mut Window,
 6580        cx: &mut App,
 6581    ) -> Option<Div> {
 6582        if self.zoomed_position == Some(position) {
 6583            return None;
 6584        }
 6585
 6586        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6587            let pane = panel.pane(cx)?;
 6588            let follower_states = &self.follower_states;
 6589            leader_border_for_pane(follower_states, &pane, window, cx)
 6590        });
 6591
 6592        Some(
 6593            div()
 6594                .flex()
 6595                .flex_none()
 6596                .overflow_hidden()
 6597                .child(dock.clone())
 6598                .children(leader_border),
 6599        )
 6600    }
 6601
 6602    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 6603        window.root().flatten()
 6604    }
 6605
 6606    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6607        self.zoomed.as_ref()
 6608    }
 6609
 6610    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6611        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6612            return;
 6613        };
 6614        let windows = cx.windows();
 6615        let next_window =
 6616            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6617                || {
 6618                    windows
 6619                        .iter()
 6620                        .cycle()
 6621                        .skip_while(|window| window.window_id() != current_window_id)
 6622                        .nth(1)
 6623                },
 6624            );
 6625
 6626        if let Some(window) = next_window {
 6627            window
 6628                .update(cx, |_, window, _| window.activate_window())
 6629                .ok();
 6630        }
 6631    }
 6632
 6633    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6634        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6635            return;
 6636        };
 6637        let windows = cx.windows();
 6638        let prev_window =
 6639            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6640                || {
 6641                    windows
 6642                        .iter()
 6643                        .rev()
 6644                        .cycle()
 6645                        .skip_while(|window| window.window_id() != current_window_id)
 6646                        .nth(1)
 6647                },
 6648            );
 6649
 6650        if let Some(window) = prev_window {
 6651            window
 6652                .update(cx, |_, window, _| window.activate_window())
 6653                .ok();
 6654        }
 6655    }
 6656
 6657    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6658        if cx.stop_active_drag(window) {
 6659        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6660            dismiss_app_notification(&notification_id, cx);
 6661        } else {
 6662            cx.propagate();
 6663        }
 6664    }
 6665
 6666    fn adjust_dock_size_by_px(
 6667        &mut self,
 6668        panel_size: Pixels,
 6669        dock_pos: DockPosition,
 6670        px: Pixels,
 6671        window: &mut Window,
 6672        cx: &mut Context<Self>,
 6673    ) {
 6674        match dock_pos {
 6675            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6676            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6677            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6678        }
 6679    }
 6680
 6681    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6682        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6683
 6684        self.left_dock.update(cx, |left_dock, cx| {
 6685            if WorkspaceSettings::get_global(cx)
 6686                .resize_all_panels_in_dock
 6687                .contains(&DockPosition::Left)
 6688            {
 6689                left_dock.resize_all_panels(Some(size), window, cx);
 6690            } else {
 6691                left_dock.resize_active_panel(Some(size), window, cx);
 6692            }
 6693        });
 6694        self.clamp_utility_pane_widths(window, cx);
 6695    }
 6696
 6697    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6698        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6699        self.left_dock.read_with(cx, |left_dock, cx| {
 6700            let left_dock_size = left_dock
 6701                .active_panel_size(window, cx)
 6702                .unwrap_or(Pixels::ZERO);
 6703            if left_dock_size + size > self.bounds.right() {
 6704                size = self.bounds.right() - left_dock_size
 6705            }
 6706        });
 6707        self.right_dock.update(cx, |right_dock, cx| {
 6708            if WorkspaceSettings::get_global(cx)
 6709                .resize_all_panels_in_dock
 6710                .contains(&DockPosition::Right)
 6711            {
 6712                right_dock.resize_all_panels(Some(size), window, cx);
 6713            } else {
 6714                right_dock.resize_active_panel(Some(size), window, cx);
 6715            }
 6716        });
 6717        self.clamp_utility_pane_widths(window, cx);
 6718    }
 6719
 6720    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6721        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6722        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6723            if WorkspaceSettings::get_global(cx)
 6724                .resize_all_panels_in_dock
 6725                .contains(&DockPosition::Bottom)
 6726            {
 6727                bottom_dock.resize_all_panels(Some(size), window, cx);
 6728            } else {
 6729                bottom_dock.resize_active_panel(Some(size), window, cx);
 6730            }
 6731        });
 6732        self.clamp_utility_pane_widths(window, cx);
 6733    }
 6734
 6735    fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
 6736        let left_dock_width = self
 6737            .left_dock
 6738            .read(cx)
 6739            .active_panel_size(window, cx)
 6740            .unwrap_or(px(0.0));
 6741        let right_dock_width = self
 6742            .right_dock
 6743            .read(cx)
 6744            .active_panel_size(window, cx)
 6745            .unwrap_or(px(0.0));
 6746        let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
 6747        center_pane_width - px(10.0)
 6748    }
 6749
 6750    fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
 6751        let max_width = self.max_utility_pane_width(window, cx);
 6752
 6753        // Clamp left slot utility pane if it exists
 6754        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
 6755            let current_width = handle.width(cx);
 6756            if current_width > max_width {
 6757                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6758            }
 6759        }
 6760
 6761        // Clamp right slot utility pane if it exists
 6762        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
 6763            let current_width = handle.width(cx);
 6764            if current_width > max_width {
 6765                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6766            }
 6767        }
 6768    }
 6769
 6770    fn toggle_edit_predictions_all_files(
 6771        &mut self,
 6772        _: &ToggleEditPrediction,
 6773        _window: &mut Window,
 6774        cx: &mut Context<Self>,
 6775    ) {
 6776        let fs = self.project().read(cx).fs().clone();
 6777        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6778        update_settings_file(fs, cx, move |file, _| {
 6779            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6780        });
 6781    }
 6782
 6783    pub fn show_worktree_trust_security_modal(
 6784        &mut self,
 6785        toggle: bool,
 6786        window: &mut Window,
 6787        cx: &mut Context<Self>,
 6788    ) {
 6789        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 6790            if toggle {
 6791                security_modal.update(cx, |security_modal, cx| {
 6792                    security_modal.dismiss(cx);
 6793                })
 6794            } else {
 6795                security_modal.update(cx, |security_modal, cx| {
 6796                    security_modal.refresh_restricted_paths(cx);
 6797                });
 6798            }
 6799        } else {
 6800            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 6801                .map(|trusted_worktrees| {
 6802                    trusted_worktrees
 6803                        .read(cx)
 6804                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 6805                })
 6806                .unwrap_or(false);
 6807            if has_restricted_worktrees {
 6808                let project = self.project().read(cx);
 6809                let remote_host = project
 6810                    .remote_connection_options(cx)
 6811                    .map(RemoteHostLocation::from);
 6812                let worktree_store = project.worktree_store().downgrade();
 6813                self.toggle_modal(window, cx, |_, cx| {
 6814                    SecurityModal::new(worktree_store, remote_host, cx)
 6815                });
 6816            }
 6817        }
 6818    }
 6819}
 6820
 6821fn leader_border_for_pane(
 6822    follower_states: &HashMap<CollaboratorId, FollowerState>,
 6823    pane: &Entity<Pane>,
 6824    _: &Window,
 6825    cx: &App,
 6826) -> Option<Div> {
 6827    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 6828        if state.pane() == pane {
 6829            Some((*leader_id, state))
 6830        } else {
 6831            None
 6832        }
 6833    })?;
 6834
 6835    let mut leader_color = match leader_id {
 6836        CollaboratorId::PeerId(leader_peer_id) => {
 6837            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 6838            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 6839
 6840            cx.theme()
 6841                .players()
 6842                .color_for_participant(leader.participant_index.0)
 6843                .cursor
 6844        }
 6845        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 6846    };
 6847    leader_color.fade_out(0.3);
 6848    Some(
 6849        div()
 6850            .absolute()
 6851            .size_full()
 6852            .left_0()
 6853            .top_0()
 6854            .border_2()
 6855            .border_color(leader_color),
 6856    )
 6857}
 6858
 6859fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 6860    ZED_WINDOW_POSITION
 6861        .zip(*ZED_WINDOW_SIZE)
 6862        .map(|(position, size)| Bounds {
 6863            origin: position,
 6864            size,
 6865        })
 6866}
 6867
 6868fn open_items(
 6869    serialized_workspace: Option<SerializedWorkspace>,
 6870    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 6871    window: &mut Window,
 6872    cx: &mut Context<Workspace>,
 6873) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 6874    let restored_items = serialized_workspace.map(|serialized_workspace| {
 6875        Workspace::load_workspace(
 6876            serialized_workspace,
 6877            project_paths_to_open
 6878                .iter()
 6879                .map(|(_, project_path)| project_path)
 6880                .cloned()
 6881                .collect(),
 6882            window,
 6883            cx,
 6884        )
 6885    });
 6886
 6887    cx.spawn_in(window, async move |workspace, cx| {
 6888        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 6889
 6890        if let Some(restored_items) = restored_items {
 6891            let restored_items = restored_items.await?;
 6892
 6893            let restored_project_paths = restored_items
 6894                .iter()
 6895                .filter_map(|item| {
 6896                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 6897                        .ok()
 6898                        .flatten()
 6899                })
 6900                .collect::<HashSet<_>>();
 6901
 6902            for restored_item in restored_items {
 6903                opened_items.push(restored_item.map(Ok));
 6904            }
 6905
 6906            project_paths_to_open
 6907                .iter_mut()
 6908                .for_each(|(_, project_path)| {
 6909                    if let Some(project_path_to_open) = project_path
 6910                        && restored_project_paths.contains(project_path_to_open)
 6911                    {
 6912                        *project_path = None;
 6913                    }
 6914                });
 6915        } else {
 6916            for _ in 0..project_paths_to_open.len() {
 6917                opened_items.push(None);
 6918            }
 6919        }
 6920        assert!(opened_items.len() == project_paths_to_open.len());
 6921
 6922        let tasks =
 6923            project_paths_to_open
 6924                .into_iter()
 6925                .enumerate()
 6926                .map(|(ix, (abs_path, project_path))| {
 6927                    let workspace = workspace.clone();
 6928                    cx.spawn(async move |cx| {
 6929                        let file_project_path = project_path?;
 6930                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 6931                            workspace.project().update(cx, |project, cx| {
 6932                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 6933                            })
 6934                        });
 6935
 6936                        // We only want to open file paths here. If one of the items
 6937                        // here is a directory, it was already opened further above
 6938                        // with a `find_or_create_worktree`.
 6939                        if let Ok(task) = abs_path_task
 6940                            && task.await.is_none_or(|p| p.is_file())
 6941                        {
 6942                            return Some((
 6943                                ix,
 6944                                workspace
 6945                                    .update_in(cx, |workspace, window, cx| {
 6946                                        workspace.open_path(
 6947                                            file_project_path,
 6948                                            None,
 6949                                            true,
 6950                                            window,
 6951                                            cx,
 6952                                        )
 6953                                    })
 6954                                    .log_err()?
 6955                                    .await,
 6956                            ));
 6957                        }
 6958                        None
 6959                    })
 6960                });
 6961
 6962        let tasks = tasks.collect::<Vec<_>>();
 6963
 6964        let tasks = futures::future::join_all(tasks);
 6965        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6966            opened_items[ix] = Some(path_open_result);
 6967        }
 6968
 6969        Ok(opened_items)
 6970    })
 6971}
 6972
 6973enum ActivateInDirectionTarget {
 6974    Pane(Entity<Pane>),
 6975    Dock(Entity<Dock>),
 6976}
 6977
 6978fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6979    workspace
 6980        .update(cx, |workspace, _, cx| {
 6981            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6982                struct DatabaseFailedNotification;
 6983
 6984                workspace.show_notification(
 6985                    NotificationId::unique::<DatabaseFailedNotification>(),
 6986                    cx,
 6987                    |cx| {
 6988                        cx.new(|cx| {
 6989                            MessageNotification::new("Failed to load the database file.", cx)
 6990                                .primary_message("File an Issue")
 6991                                .primary_icon(IconName::Plus)
 6992                                .primary_on_click(|window, cx| {
 6993                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6994                                })
 6995                        })
 6996                    },
 6997                );
 6998            }
 6999        })
 7000        .log_err();
 7001}
 7002
 7003fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7004    if val == 0 {
 7005        ThemeSettings::get_global(cx).ui_font_size(cx)
 7006    } else {
 7007        px(val as f32)
 7008    }
 7009}
 7010
 7011fn adjust_active_dock_size_by_px(
 7012    px: Pixels,
 7013    workspace: &mut Workspace,
 7014    window: &mut Window,
 7015    cx: &mut Context<Workspace>,
 7016) {
 7017    let Some(active_dock) = workspace
 7018        .all_docks()
 7019        .into_iter()
 7020        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7021    else {
 7022        return;
 7023    };
 7024    let dock = active_dock.read(cx);
 7025    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7026        return;
 7027    };
 7028    let dock_pos = dock.position();
 7029    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7030}
 7031
 7032fn adjust_open_docks_size_by_px(
 7033    px: Pixels,
 7034    workspace: &mut Workspace,
 7035    window: &mut Window,
 7036    cx: &mut Context<Workspace>,
 7037) {
 7038    let docks = workspace
 7039        .all_docks()
 7040        .into_iter()
 7041        .filter_map(|dock| {
 7042            if dock.read(cx).is_open() {
 7043                let dock = dock.read(cx);
 7044                let panel_size = dock.active_panel_size(window, cx)?;
 7045                let dock_pos = dock.position();
 7046                Some((panel_size, dock_pos, px))
 7047            } else {
 7048                None
 7049            }
 7050        })
 7051        .collect::<Vec<_>>();
 7052
 7053    docks
 7054        .into_iter()
 7055        .for_each(|(panel_size, dock_pos, offset)| {
 7056            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7057        });
 7058}
 7059
 7060impl Focusable for Workspace {
 7061    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7062        self.active_pane.focus_handle(cx)
 7063    }
 7064}
 7065
 7066#[derive(Clone)]
 7067struct DraggedDock(DockPosition);
 7068
 7069impl Render for DraggedDock {
 7070    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7071        gpui::Empty
 7072    }
 7073}
 7074
 7075impl Render for Workspace {
 7076    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7077        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7078        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7079            log::info!("Rendered first frame");
 7080        }
 7081        let mut context = KeyContext::new_with_defaults();
 7082        context.add("Workspace");
 7083        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 7084        if let Some(status) = self
 7085            .debugger_provider
 7086            .as_ref()
 7087            .and_then(|provider| provider.active_thread_state(cx))
 7088        {
 7089            match status {
 7090                ThreadStatus::Running | ThreadStatus::Stepping => {
 7091                    context.add("debugger_running");
 7092                }
 7093                ThreadStatus::Stopped => context.add("debugger_stopped"),
 7094                ThreadStatus::Exited | ThreadStatus::Ended => {}
 7095            }
 7096        }
 7097
 7098        if self.left_dock.read(cx).is_open() {
 7099            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 7100                context.set("left_dock", active_panel.panel_key());
 7101            }
 7102        }
 7103
 7104        if self.right_dock.read(cx).is_open() {
 7105            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 7106                context.set("right_dock", active_panel.panel_key());
 7107            }
 7108        }
 7109
 7110        if self.bottom_dock.read(cx).is_open() {
 7111            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 7112                context.set("bottom_dock", active_panel.panel_key());
 7113            }
 7114        }
 7115
 7116        let centered_layout = self.centered_layout
 7117            && self.center.panes().len() == 1
 7118            && self.active_item(cx).is_some();
 7119        let render_padding = |size| {
 7120            (size > 0.0).then(|| {
 7121                div()
 7122                    .h_full()
 7123                    .w(relative(size))
 7124                    .bg(cx.theme().colors().editor_background)
 7125                    .border_color(cx.theme().colors().pane_group_border)
 7126            })
 7127        };
 7128        let paddings = if centered_layout {
 7129            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7130            (
 7131                render_padding(Self::adjust_padding(
 7132                    settings.left_padding.map(|padding| padding.0),
 7133                )),
 7134                render_padding(Self::adjust_padding(
 7135                    settings.right_padding.map(|padding| padding.0),
 7136                )),
 7137            )
 7138        } else {
 7139            (None, None)
 7140        };
 7141        let ui_font = theme::setup_ui_font(window, cx);
 7142
 7143        let theme = cx.theme().clone();
 7144        let colors = theme.colors();
 7145        let notification_entities = self
 7146            .notifications
 7147            .iter()
 7148            .map(|(_, notification)| notification.entity_id())
 7149            .collect::<Vec<_>>();
 7150        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7151
 7152        client_side_decorations(
 7153            self.actions(div(), window, cx)
 7154                .key_context(context)
 7155                .relative()
 7156                .size_full()
 7157                .flex()
 7158                .flex_col()
 7159                .font(ui_font)
 7160                .gap_0()
 7161                .justify_start()
 7162                .items_start()
 7163                .text_color(colors.text)
 7164                .overflow_hidden()
 7165                .children(self.titlebar_item.clone())
 7166                .on_modifiers_changed(move |_, _, cx| {
 7167                    for &id in &notification_entities {
 7168                        cx.notify(id);
 7169                    }
 7170                })
 7171                .child(
 7172                    div()
 7173                        .size_full()
 7174                        .relative()
 7175                        .flex_1()
 7176                        .flex()
 7177                        .flex_col()
 7178                        .child(
 7179                            div()
 7180                                .id("workspace")
 7181                                .bg(colors.background)
 7182                                .relative()
 7183                                .flex_1()
 7184                                .w_full()
 7185                                .flex()
 7186                                .flex_col()
 7187                                .overflow_hidden()
 7188                                .border_t_1()
 7189                                .border_b_1()
 7190                                .border_color(colors.border)
 7191                                .child({
 7192                                    let this = cx.entity();
 7193                                    canvas(
 7194                                        move |bounds, window, cx| {
 7195                                            this.update(cx, |this, cx| {
 7196                                                let bounds_changed = this.bounds != bounds;
 7197                                                this.bounds = bounds;
 7198
 7199                                                if bounds_changed {
 7200                                                    this.left_dock.update(cx, |dock, cx| {
 7201                                                        dock.clamp_panel_size(
 7202                                                            bounds.size.width,
 7203                                                            window,
 7204                                                            cx,
 7205                                                        )
 7206                                                    });
 7207
 7208                                                    this.right_dock.update(cx, |dock, cx| {
 7209                                                        dock.clamp_panel_size(
 7210                                                            bounds.size.width,
 7211                                                            window,
 7212                                                            cx,
 7213                                                        )
 7214                                                    });
 7215
 7216                                                    this.bottom_dock.update(cx, |dock, cx| {
 7217                                                        dock.clamp_panel_size(
 7218                                                            bounds.size.height,
 7219                                                            window,
 7220                                                            cx,
 7221                                                        )
 7222                                                    });
 7223                                                }
 7224                                            })
 7225                                        },
 7226                                        |_, _, _, _| {},
 7227                                    )
 7228                                    .absolute()
 7229                                    .size_full()
 7230                                })
 7231                                .when(self.zoomed.is_none(), |this| {
 7232                                    this.on_drag_move(cx.listener(
 7233                                        move |workspace,
 7234                                              e: &DragMoveEvent<DraggedDock>,
 7235                                              window,
 7236                                              cx| {
 7237                                            if workspace.previous_dock_drag_coordinates
 7238                                                != Some(e.event.position)
 7239                                            {
 7240                                                workspace.previous_dock_drag_coordinates =
 7241                                                    Some(e.event.position);
 7242                                                match e.drag(cx).0 {
 7243                                                    DockPosition::Left => {
 7244                                                        workspace.resize_left_dock(
 7245                                                            e.event.position.x
 7246                                                                - workspace.bounds.left(),
 7247                                                            window,
 7248                                                            cx,
 7249                                                        );
 7250                                                    }
 7251                                                    DockPosition::Right => {
 7252                                                        workspace.resize_right_dock(
 7253                                                            workspace.bounds.right()
 7254                                                                - e.event.position.x,
 7255                                                            window,
 7256                                                            cx,
 7257                                                        );
 7258                                                    }
 7259                                                    DockPosition::Bottom => {
 7260                                                        workspace.resize_bottom_dock(
 7261                                                            workspace.bounds.bottom()
 7262                                                                - e.event.position.y,
 7263                                                            window,
 7264                                                            cx,
 7265                                                        );
 7266                                                    }
 7267                                                };
 7268                                                workspace.serialize_workspace(window, cx);
 7269                                            }
 7270                                        },
 7271                                    ))
 7272                                    .on_drag_move(cx.listener(
 7273                                        move |workspace,
 7274                                              e: &DragMoveEvent<DraggedUtilityPane>,
 7275                                              window,
 7276                                              cx| {
 7277                                            let slot = e.drag(cx).0;
 7278                                            match slot {
 7279                                                UtilityPaneSlot::Left => {
 7280                                                    let left_dock_width = workspace.left_dock.read(cx)
 7281                                                        .active_panel_size(window, cx)
 7282                                                        .unwrap_or(gpui::px(0.0));
 7283                                                    let new_width = e.event.position.x
 7284                                                        - workspace.bounds.left()
 7285                                                        - left_dock_width;
 7286                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7287                                                }
 7288                                                UtilityPaneSlot::Right => {
 7289                                                    let right_dock_width = workspace.right_dock.read(cx)
 7290                                                        .active_panel_size(window, cx)
 7291                                                        .unwrap_or(gpui::px(0.0));
 7292                                                    let new_width = workspace.bounds.right()
 7293                                                        - e.event.position.x
 7294                                                        - right_dock_width;
 7295                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7296                                                }
 7297                                            }
 7298                                        },
 7299                                    ))
 7300                                })
 7301                                .child({
 7302                                    match bottom_dock_layout {
 7303                                        BottomDockLayout::Full => div()
 7304                                            .flex()
 7305                                            .flex_col()
 7306                                            .h_full()
 7307                                            .child(
 7308                                                div()
 7309                                                    .flex()
 7310                                                    .flex_row()
 7311                                                    .flex_1()
 7312                                                    .overflow_hidden()
 7313                                                    .children(self.render_dock(
 7314                                                        DockPosition::Left,
 7315                                                        &self.left_dock,
 7316                                                        window,
 7317                                                        cx,
 7318                                                    ))
 7319                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7320                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7321                                                            this.when(pane.expanded(cx), |this| {
 7322                                                                this.child(
 7323                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7324                                                                )
 7325                                                            })
 7326                                                        })
 7327                                                    })
 7328                                                    .child(
 7329                                                        div()
 7330                                                            .flex()
 7331                                                            .flex_col()
 7332                                                            .flex_1()
 7333                                                            .overflow_hidden()
 7334                                                            .child(
 7335                                                                h_flex()
 7336                                                                    .flex_1()
 7337                                                                    .when_some(
 7338                                                                        paddings.0,
 7339                                                                        |this, p| {
 7340                                                                            this.child(
 7341                                                                                p.border_r_1(),
 7342                                                                            )
 7343                                                                        },
 7344                                                                    )
 7345                                                                    .child(self.center.render(
 7346                                                                        self.zoomed.as_ref(),
 7347                                                                        &PaneRenderContext {
 7348                                                                            follower_states:
 7349                                                                                &self.follower_states,
 7350                                                                            active_call: self.active_call(),
 7351                                                                            active_pane: &self.active_pane,
 7352                                                                            app_state: &self.app_state,
 7353                                                                            project: &self.project,
 7354                                                                            workspace: &self.weak_self,
 7355                                                                        },
 7356                                                                        window,
 7357                                                                        cx,
 7358                                                                    ))
 7359                                                                    .when_some(
 7360                                                                        paddings.1,
 7361                                                                        |this, p| {
 7362                                                                            this.child(
 7363                                                                                p.border_l_1(),
 7364                                                                            )
 7365                                                                        },
 7366                                                                    ),
 7367                                                            ),
 7368                                                    )
 7369                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7370                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7371                                                            this.when(pane.expanded(cx), |this| {
 7372                                                                this.child(
 7373                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7374                                                                )
 7375                                                            })
 7376                                                        })
 7377                                                    })
 7378                                                    .children(self.render_dock(
 7379                                                        DockPosition::Right,
 7380                                                        &self.right_dock,
 7381                                                        window,
 7382                                                        cx,
 7383                                                    )),
 7384                                            )
 7385                                            .child(div().w_full().children(self.render_dock(
 7386                                                DockPosition::Bottom,
 7387                                                &self.bottom_dock,
 7388                                                window,
 7389                                                cx
 7390                                            ))),
 7391
 7392                                        BottomDockLayout::LeftAligned => div()
 7393                                            .flex()
 7394                                            .flex_row()
 7395                                            .h_full()
 7396                                            .child(
 7397                                                div()
 7398                                                    .flex()
 7399                                                    .flex_col()
 7400                                                    .flex_1()
 7401                                                    .h_full()
 7402                                                    .child(
 7403                                                        div()
 7404                                                            .flex()
 7405                                                            .flex_row()
 7406                                                            .flex_1()
 7407                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7408                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7409                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7410                                                                    this.when(pane.expanded(cx), |this| {
 7411                                                                        this.child(
 7412                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7413                                                                        )
 7414                                                                    })
 7415                                                                })
 7416                                                            })
 7417                                                            .child(
 7418                                                                div()
 7419                                                                    .flex()
 7420                                                                    .flex_col()
 7421                                                                    .flex_1()
 7422                                                                    .overflow_hidden()
 7423                                                                    .child(
 7424                                                                        h_flex()
 7425                                                                            .flex_1()
 7426                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7427                                                                            .child(self.center.render(
 7428                                                                                self.zoomed.as_ref(),
 7429                                                                                &PaneRenderContext {
 7430                                                                                    follower_states:
 7431                                                                                        &self.follower_states,
 7432                                                                                    active_call: self.active_call(),
 7433                                                                                    active_pane: &self.active_pane,
 7434                                                                                    app_state: &self.app_state,
 7435                                                                                    project: &self.project,
 7436                                                                                    workspace: &self.weak_self,
 7437                                                                                },
 7438                                                                                window,
 7439                                                                                cx,
 7440                                                                            ))
 7441                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7442                                                                    )
 7443                                                            )
 7444                                                            .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7445                                                                this.when(pane.expanded(cx), |this| {
 7446                                                                    this.child(
 7447                                                                        UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7448                                                                    )
 7449                                                                })
 7450                                                            })
 7451                                                    )
 7452                                                    .child(
 7453                                                        div()
 7454                                                            .w_full()
 7455                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7456                                                    ),
 7457                                            )
 7458                                            .children(self.render_dock(
 7459                                                DockPosition::Right,
 7460                                                &self.right_dock,
 7461                                                window,
 7462                                                cx,
 7463                                            )),
 7464
 7465                                        BottomDockLayout::RightAligned => div()
 7466                                            .flex()
 7467                                            .flex_row()
 7468                                            .h_full()
 7469                                            .children(self.render_dock(
 7470                                                DockPosition::Left,
 7471                                                &self.left_dock,
 7472                                                window,
 7473                                                cx,
 7474                                            ))
 7475                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7476                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7477                                                    this.when(pane.expanded(cx), |this| {
 7478                                                        this.child(
 7479                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7480                                                        )
 7481                                                    })
 7482                                                })
 7483                                            })
 7484                                            .child(
 7485                                                div()
 7486                                                    .flex()
 7487                                                    .flex_col()
 7488                                                    .flex_1()
 7489                                                    .h_full()
 7490                                                    .child(
 7491                                                        div()
 7492                                                            .flex()
 7493                                                            .flex_row()
 7494                                                            .flex_1()
 7495                                                            .child(
 7496                                                                div()
 7497                                                                    .flex()
 7498                                                                    .flex_col()
 7499                                                                    .flex_1()
 7500                                                                    .overflow_hidden()
 7501                                                                    .child(
 7502                                                                        h_flex()
 7503                                                                            .flex_1()
 7504                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7505                                                                            .child(self.center.render(
 7506                                                                                self.zoomed.as_ref(),
 7507                                                                                &PaneRenderContext {
 7508                                                                                    follower_states:
 7509                                                                                        &self.follower_states,
 7510                                                                                    active_call: self.active_call(),
 7511                                                                                    active_pane: &self.active_pane,
 7512                                                                                    app_state: &self.app_state,
 7513                                                                                    project: &self.project,
 7514                                                                                    workspace: &self.weak_self,
 7515                                                                                },
 7516                                                                                window,
 7517                                                                                cx,
 7518                                                                            ))
 7519                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7520                                                                    )
 7521                                                            )
 7522                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7523                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7524                                                                    this.when(pane.expanded(cx), |this| {
 7525                                                                        this.child(
 7526                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7527                                                                        )
 7528                                                                    })
 7529                                                                })
 7530                                                            })
 7531                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7532                                                    )
 7533                                                    .child(
 7534                                                        div()
 7535                                                            .w_full()
 7536                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7537                                                    ),
 7538                                            ),
 7539
 7540                                        BottomDockLayout::Contained => div()
 7541                                            .flex()
 7542                                            .flex_row()
 7543                                            .h_full()
 7544                                            .children(self.render_dock(
 7545                                                DockPosition::Left,
 7546                                                &self.left_dock,
 7547                                                window,
 7548                                                cx,
 7549                                            ))
 7550                                            .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7551                                                this.when(pane.expanded(cx), |this| {
 7552                                                    this.child(
 7553                                                        UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7554                                                    )
 7555                                                })
 7556                                            })
 7557                                            .child(
 7558                                                div()
 7559                                                    .flex()
 7560                                                    .flex_col()
 7561                                                    .flex_1()
 7562                                                    .overflow_hidden()
 7563                                                    .child(
 7564                                                        h_flex()
 7565                                                            .flex_1()
 7566                                                            .when_some(paddings.0, |this, p| {
 7567                                                                this.child(p.border_r_1())
 7568                                                            })
 7569                                                            .child(self.center.render(
 7570                                                                self.zoomed.as_ref(),
 7571                                                                &PaneRenderContext {
 7572                                                                    follower_states:
 7573                                                                        &self.follower_states,
 7574                                                                    active_call: self.active_call(),
 7575                                                                    active_pane: &self.active_pane,
 7576                                                                    app_state: &self.app_state,
 7577                                                                    project: &self.project,
 7578                                                                    workspace: &self.weak_self,
 7579                                                                },
 7580                                                                window,
 7581                                                                cx,
 7582                                                            ))
 7583                                                            .when_some(paddings.1, |this, p| {
 7584                                                                this.child(p.border_l_1())
 7585                                                            }),
 7586                                                    )
 7587                                                    .children(self.render_dock(
 7588                                                        DockPosition::Bottom,
 7589                                                        &self.bottom_dock,
 7590                                                        window,
 7591                                                        cx,
 7592                                                    )),
 7593                                            )
 7594                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7595                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7596                                                    this.when(pane.expanded(cx), |this| {
 7597                                                        this.child(
 7598                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7599                                                        )
 7600                                                    })
 7601                                                })
 7602                                            })
 7603                                            .children(self.render_dock(
 7604                                                DockPosition::Right,
 7605                                                &self.right_dock,
 7606                                                window,
 7607                                                cx,
 7608                                            )),
 7609                                    }
 7610                                })
 7611                                .children(self.zoomed.as_ref().and_then(|view| {
 7612                                    let zoomed_view = view.upgrade()?;
 7613                                    let div = div()
 7614                                        .occlude()
 7615                                        .absolute()
 7616                                        .overflow_hidden()
 7617                                        .border_color(colors.border)
 7618                                        .bg(colors.background)
 7619                                        .child(zoomed_view)
 7620                                        .inset_0()
 7621                                        .shadow_lg();
 7622
 7623                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7624                                       return Some(div);
 7625                                    }
 7626
 7627                                    Some(match self.zoomed_position {
 7628                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7629                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7630                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7631                                        None => {
 7632                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7633                                        }
 7634                                    })
 7635                                }))
 7636                                .children(self.render_notifications(window, cx)),
 7637                        )
 7638                        .when(self.status_bar_visible(cx), |parent| {
 7639                            parent.child(self.status_bar.clone())
 7640                        })
 7641                        .child(self.modal_layer.clone())
 7642                        .child(self.toast_layer.clone()),
 7643                ),
 7644            window,
 7645            cx,
 7646        )
 7647    }
 7648}
 7649
 7650impl WorkspaceStore {
 7651    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7652        Self {
 7653            workspaces: Default::default(),
 7654            _subscriptions: vec![
 7655                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7656                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7657            ],
 7658            client,
 7659        }
 7660    }
 7661
 7662    pub fn update_followers(
 7663        &self,
 7664        project_id: Option<u64>,
 7665        update: proto::update_followers::Variant,
 7666        cx: &App,
 7667    ) -> Option<()> {
 7668        let active_call = ActiveCall::try_global(cx)?;
 7669        let room_id = active_call.read(cx).room()?.read(cx).id();
 7670        self.client
 7671            .send(proto::UpdateFollowers {
 7672                room_id,
 7673                project_id,
 7674                variant: Some(update),
 7675            })
 7676            .log_err()
 7677    }
 7678
 7679    pub async fn handle_follow(
 7680        this: Entity<Self>,
 7681        envelope: TypedEnvelope<proto::Follow>,
 7682        mut cx: AsyncApp,
 7683    ) -> Result<proto::FollowResponse> {
 7684        this.update(&mut cx, |this, cx| {
 7685            let follower = Follower {
 7686                project_id: envelope.payload.project_id,
 7687                peer_id: envelope.original_sender_id()?,
 7688            };
 7689
 7690            let mut response = proto::FollowResponse::default();
 7691            this.workspaces.retain(|workspace| {
 7692                workspace
 7693                    .update(cx, |workspace, window, cx| {
 7694                        let handler_response =
 7695                            workspace.handle_follow(follower.project_id, window, cx);
 7696                        if let Some(active_view) = handler_response.active_view
 7697                            && workspace.project.read(cx).remote_id() == follower.project_id
 7698                        {
 7699                            response.active_view = Some(active_view)
 7700                        }
 7701                    })
 7702                    .is_ok()
 7703            });
 7704
 7705            Ok(response)
 7706        })
 7707    }
 7708
 7709    async fn handle_update_followers(
 7710        this: Entity<Self>,
 7711        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7712        mut cx: AsyncApp,
 7713    ) -> Result<()> {
 7714        let leader_id = envelope.original_sender_id()?;
 7715        let update = envelope.payload;
 7716
 7717        this.update(&mut cx, |this, cx| {
 7718            this.workspaces.retain(|workspace| {
 7719                workspace
 7720                    .update(cx, |workspace, window, cx| {
 7721                        let project_id = workspace.project.read(cx).remote_id();
 7722                        if update.project_id != project_id && update.project_id.is_some() {
 7723                            return;
 7724                        }
 7725                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 7726                    })
 7727                    .is_ok()
 7728            });
 7729            Ok(())
 7730        })
 7731    }
 7732
 7733    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 7734        &self.workspaces
 7735    }
 7736}
 7737
 7738impl ViewId {
 7739    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7740        Ok(Self {
 7741            creator: message
 7742                .creator
 7743                .map(CollaboratorId::PeerId)
 7744                .context("creator is missing")?,
 7745            id: message.id,
 7746        })
 7747    }
 7748
 7749    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7750        if let CollaboratorId::PeerId(peer_id) = self.creator {
 7751            Some(proto::ViewId {
 7752                creator: Some(peer_id),
 7753                id: self.id,
 7754            })
 7755        } else {
 7756            None
 7757        }
 7758    }
 7759}
 7760
 7761impl FollowerState {
 7762    fn pane(&self) -> &Entity<Pane> {
 7763        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 7764    }
 7765}
 7766
 7767pub trait WorkspaceHandle {
 7768    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 7769}
 7770
 7771impl WorkspaceHandle for Entity<Workspace> {
 7772    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 7773        self.read(cx)
 7774            .worktrees(cx)
 7775            .flat_map(|worktree| {
 7776                let worktree_id = worktree.read(cx).id();
 7777                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 7778                    worktree_id,
 7779                    path: f.path.clone(),
 7780                })
 7781            })
 7782            .collect::<Vec<_>>()
 7783    }
 7784}
 7785
 7786pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 7787    DB.last_workspace().await.log_err().flatten()
 7788}
 7789
 7790pub fn last_session_workspace_locations(
 7791    last_session_id: &str,
 7792    last_session_window_stack: Option<Vec<WindowId>>,
 7793) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 7794    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 7795        .log_err()
 7796}
 7797
 7798actions!(
 7799    collab,
 7800    [
 7801        /// Opens the channel notes for the current call.
 7802        ///
 7803        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 7804        /// channel in the collab panel.
 7805        ///
 7806        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 7807        /// can be copied via "Copy link to section" in the context menu of the channel notes
 7808        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 7809        OpenChannelNotes,
 7810        /// Mutes your microphone.
 7811        Mute,
 7812        /// Deafens yourself (mute both microphone and speakers).
 7813        Deafen,
 7814        /// Leaves the current call.
 7815        LeaveCall,
 7816        /// Shares the current project with collaborators.
 7817        ShareProject,
 7818        /// Shares your screen with collaborators.
 7819        ScreenShare,
 7820        /// Copies the current room name and session id for debugging purposes.
 7821        CopyRoomId,
 7822    ]
 7823);
 7824actions!(
 7825    zed,
 7826    [
 7827        /// Opens the Zed log file.
 7828        OpenLog,
 7829        /// Reveals the Zed log file in the system file manager.
 7830        RevealLogInFileManager
 7831    ]
 7832);
 7833
 7834async fn join_channel_internal(
 7835    channel_id: ChannelId,
 7836    app_state: &Arc<AppState>,
 7837    requesting_window: Option<WindowHandle<Workspace>>,
 7838    active_call: &Entity<ActiveCall>,
 7839    cx: &mut AsyncApp,
 7840) -> Result<bool> {
 7841    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7842        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7843            return (false, None);
 7844        };
 7845
 7846        let already_in_channel = room.channel_id() == Some(channel_id);
 7847        let should_prompt = room.is_sharing_project()
 7848            && !room.remote_participants().is_empty()
 7849            && !already_in_channel;
 7850        let open_room = if already_in_channel {
 7851            active_call.room().cloned()
 7852        } else {
 7853            None
 7854        };
 7855        (should_prompt, open_room)
 7856    });
 7857
 7858    if let Some(room) = open_room {
 7859        let task = room.update(cx, |room, cx| {
 7860            if let Some((project, host)) = room.most_active_project(cx) {
 7861                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7862            }
 7863
 7864            None
 7865        });
 7866        if let Some(task) = task {
 7867            task.await?;
 7868        }
 7869        return anyhow::Ok(true);
 7870    }
 7871
 7872    if should_prompt {
 7873        if let Some(workspace) = requesting_window {
 7874            let answer = workspace
 7875                .update(cx, |_, window, cx| {
 7876                    window.prompt(
 7877                        PromptLevel::Warning,
 7878                        "Do you want to switch channels?",
 7879                        Some("Leaving this call will unshare your current project."),
 7880                        &["Yes, Join Channel", "Cancel"],
 7881                        cx,
 7882                    )
 7883                })?
 7884                .await;
 7885
 7886            if answer == Ok(1) {
 7887                return Ok(false);
 7888            }
 7889        } else {
 7890            return Ok(false); // unreachable!() hopefully
 7891        }
 7892    }
 7893
 7894    let client = cx.update(|cx| active_call.read(cx).client());
 7895
 7896    let mut client_status = client.status();
 7897
 7898    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7899    'outer: loop {
 7900        let Some(status) = client_status.recv().await else {
 7901            anyhow::bail!("error connecting");
 7902        };
 7903
 7904        match status {
 7905            Status::Connecting
 7906            | Status::Authenticating
 7907            | Status::Authenticated
 7908            | Status::Reconnecting
 7909            | Status::Reauthenticating
 7910            | Status::Reauthenticated => continue,
 7911            Status::Connected { .. } => break 'outer,
 7912            Status::SignedOut | Status::AuthenticationError => {
 7913                return Err(ErrorCode::SignedOut.into());
 7914            }
 7915            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7916            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7917                return Err(ErrorCode::Disconnected.into());
 7918            }
 7919        }
 7920    }
 7921
 7922    let room = active_call
 7923        .update(cx, |active_call, cx| {
 7924            active_call.join_channel(channel_id, cx)
 7925        })
 7926        .await?;
 7927
 7928    let Some(room) = room else {
 7929        return anyhow::Ok(true);
 7930    };
 7931
 7932    room.update(cx, |room, _| room.room_update_completed())
 7933        .await;
 7934
 7935    let task = room.update(cx, |room, cx| {
 7936        if let Some((project, host)) = room.most_active_project(cx) {
 7937            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7938        }
 7939
 7940        // If you are the first to join a channel, see if you should share your project.
 7941        if room.remote_participants().is_empty()
 7942            && !room.local_participant_is_guest()
 7943            && let Some(workspace) = requesting_window
 7944        {
 7945            let project = workspace.update(cx, |workspace, _, cx| {
 7946                let project = workspace.project.read(cx);
 7947
 7948                if !CallSettings::get_global(cx).share_on_join {
 7949                    return None;
 7950                }
 7951
 7952                if (project.is_local() || project.is_via_remote_server())
 7953                    && project.visible_worktrees(cx).any(|tree| {
 7954                        tree.read(cx)
 7955                            .root_entry()
 7956                            .is_some_and(|entry| entry.is_dir())
 7957                    })
 7958                {
 7959                    Some(workspace.project.clone())
 7960                } else {
 7961                    None
 7962                }
 7963            });
 7964            if let Ok(Some(project)) = project {
 7965                return Some(cx.spawn(async move |room, cx| {
 7966                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7967                        .await?;
 7968                    Ok(())
 7969                }));
 7970            }
 7971        }
 7972
 7973        None
 7974    });
 7975    if let Some(task) = task {
 7976        task.await?;
 7977        return anyhow::Ok(true);
 7978    }
 7979    anyhow::Ok(false)
 7980}
 7981
 7982pub fn join_channel(
 7983    channel_id: ChannelId,
 7984    app_state: Arc<AppState>,
 7985    requesting_window: Option<WindowHandle<Workspace>>,
 7986    cx: &mut App,
 7987) -> Task<Result<()>> {
 7988    let active_call = ActiveCall::global(cx);
 7989    cx.spawn(async move |cx| {
 7990        let result =
 7991            join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
 7992                .await;
 7993
 7994        // join channel succeeded, and opened a window
 7995        if matches!(result, Ok(true)) {
 7996            return anyhow::Ok(());
 7997        }
 7998
 7999        // find an existing workspace to focus and show call controls
 8000        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8001        if active_window.is_none() {
 8002            // no open workspaces, make one to show the error in (blergh)
 8003            let (window_handle, _) = cx
 8004                .update(|cx| {
 8005                    Workspace::new_local(
 8006                        vec![],
 8007                        app_state.clone(),
 8008                        requesting_window,
 8009                        None,
 8010                        None,
 8011                        cx,
 8012                    )
 8013                })
 8014                .await?;
 8015
 8016            if result.is_ok() {
 8017                cx.update(|cx| {
 8018                    cx.dispatch_action(&OpenChannelNotes);
 8019                });
 8020            }
 8021
 8022            active_window = Some(window_handle);
 8023        }
 8024
 8025        if let Err(err) = result {
 8026            log::error!("failed to join channel: {}", err);
 8027            if let Some(active_window) = active_window {
 8028                active_window
 8029                    .update(cx, |_, window, cx| {
 8030                        let detail: SharedString = match err.error_code() {
 8031                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8032                            ErrorCode::UpgradeRequired => concat!(
 8033                                "Your are running an unsupported version of Zed. ",
 8034                                "Please update to continue."
 8035                            )
 8036                            .into(),
 8037                            ErrorCode::NoSuchChannel => concat!(
 8038                                "No matching channel was found. ",
 8039                                "Please check the link and try again."
 8040                            )
 8041                            .into(),
 8042                            ErrorCode::Forbidden => concat!(
 8043                                "This channel is private, and you do not have access. ",
 8044                                "Please ask someone to add you and try again."
 8045                            )
 8046                            .into(),
 8047                            ErrorCode::Disconnected => {
 8048                                "Please check your internet connection and try again.".into()
 8049                            }
 8050                            _ => format!("{}\n\nPlease try again.", err).into(),
 8051                        };
 8052                        window.prompt(
 8053                            PromptLevel::Critical,
 8054                            "Failed to join channel",
 8055                            Some(&detail),
 8056                            &["Ok"],
 8057                            cx,
 8058                        )
 8059                    })?
 8060                    .await
 8061                    .ok();
 8062            }
 8063        }
 8064
 8065        // return ok, we showed the error to the user.
 8066        anyhow::Ok(())
 8067    })
 8068}
 8069
 8070pub async fn get_any_active_workspace(
 8071    app_state: Arc<AppState>,
 8072    mut cx: AsyncApp,
 8073) -> anyhow::Result<WindowHandle<Workspace>> {
 8074    // find an existing workspace to focus and show call controls
 8075    let active_window = activate_any_workspace_window(&mut cx);
 8076    if active_window.is_none() {
 8077        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
 8078            .await?;
 8079    }
 8080    activate_any_workspace_window(&mut cx).context("could not open zed")
 8081}
 8082
 8083fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 8084    cx.update(|cx| {
 8085        if let Some(workspace_window) = cx
 8086            .active_window()
 8087            .and_then(|window| window.downcast::<Workspace>())
 8088        {
 8089            return Some(workspace_window);
 8090        }
 8091
 8092        for window in cx.windows() {
 8093            if let Some(workspace_window) = window.downcast::<Workspace>() {
 8094                workspace_window
 8095                    .update(cx, |_, window, _| window.activate_window())
 8096                    .ok();
 8097                return Some(workspace_window);
 8098            }
 8099        }
 8100        None
 8101    })
 8102}
 8103
 8104pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 8105    cx.windows()
 8106        .into_iter()
 8107        .filter_map(|window| window.downcast::<Workspace>())
 8108        .filter(|workspace| {
 8109            workspace
 8110                .read(cx)
 8111                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 8112        })
 8113        .collect()
 8114}
 8115
 8116#[derive(Default)]
 8117pub struct OpenOptions {
 8118    pub visible: Option<OpenVisible>,
 8119    pub focus: Option<bool>,
 8120    pub open_new_workspace: Option<bool>,
 8121    pub prefer_focused_window: bool,
 8122    pub replace_window: Option<WindowHandle<Workspace>>,
 8123    pub env: Option<HashMap<String, String>>,
 8124}
 8125
 8126#[allow(clippy::type_complexity)]
 8127pub fn open_paths(
 8128    abs_paths: &[PathBuf],
 8129    app_state: Arc<AppState>,
 8130    open_options: OpenOptions,
 8131    cx: &mut App,
 8132) -> Task<
 8133    anyhow::Result<(
 8134        WindowHandle<Workspace>,
 8135        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8136    )>,
 8137> {
 8138    let abs_paths = abs_paths.to_vec();
 8139    let mut existing = None;
 8140    let mut best_match = None;
 8141    let mut open_visible = OpenVisible::All;
 8142    #[cfg(target_os = "windows")]
 8143    let wsl_path = abs_paths
 8144        .iter()
 8145        .find_map(|p| util::paths::WslPath::from_path(p));
 8146
 8147    cx.spawn(async move |cx| {
 8148        if open_options.open_new_workspace != Some(true) {
 8149            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8150            let all_metadatas = futures::future::join_all(all_paths)
 8151                .await
 8152                .into_iter()
 8153                .filter_map(|result| result.ok().flatten())
 8154                .collect::<Vec<_>>();
 8155
 8156            cx.update(|cx| {
 8157                for window in local_workspace_windows(cx) {
 8158                    if let Ok(workspace) = window.read(cx) {
 8159                        let m = workspace.project.read(cx).visibility_for_paths(
 8160                            &abs_paths,
 8161                            &all_metadatas,
 8162                            open_options.open_new_workspace == None,
 8163                            cx,
 8164                        );
 8165                        if m > best_match {
 8166                            existing = Some(window);
 8167                            best_match = m;
 8168                        } else if best_match.is_none()
 8169                            && open_options.open_new_workspace == Some(false)
 8170                        {
 8171                            existing = Some(window)
 8172                        }
 8173                    }
 8174                }
 8175            });
 8176
 8177            if open_options.open_new_workspace.is_none()
 8178                && (existing.is_none() || open_options.prefer_focused_window)
 8179                && all_metadatas.iter().all(|file| !file.is_dir)
 8180            {
 8181                cx.update(|cx| {
 8182                    if let Some(window) = cx
 8183                        .active_window()
 8184                        .and_then(|window| window.downcast::<Workspace>())
 8185                        && let Ok(workspace) = window.read(cx)
 8186                    {
 8187                        let project = workspace.project().read(cx);
 8188                        if project.is_local() && !project.is_via_collab() {
 8189                            existing = Some(window);
 8190                            open_visible = OpenVisible::None;
 8191                            return;
 8192                        }
 8193                    }
 8194                    for window in local_workspace_windows(cx) {
 8195                        if let Ok(workspace) = window.read(cx) {
 8196                            let project = workspace.project().read(cx);
 8197                            if project.is_via_collab() {
 8198                                continue;
 8199                            }
 8200                            existing = Some(window);
 8201                            open_visible = OpenVisible::None;
 8202                            break;
 8203                        }
 8204                    }
 8205                });
 8206            }
 8207        }
 8208
 8209        let result = if let Some(existing) = existing {
 8210            let open_task = existing
 8211                .update(cx, |workspace, window, cx| {
 8212                    window.activate_window();
 8213                    workspace.open_paths(
 8214                        abs_paths,
 8215                        OpenOptions {
 8216                            visible: Some(open_visible),
 8217                            ..Default::default()
 8218                        },
 8219                        None,
 8220                        window,
 8221                        cx,
 8222                    )
 8223                })?
 8224                .await;
 8225
 8226            _ = existing.update(cx, |workspace, _, cx| {
 8227                for item in open_task.iter().flatten() {
 8228                    if let Err(e) = item {
 8229                        workspace.show_error(&e, cx);
 8230                    }
 8231                }
 8232            });
 8233
 8234            Ok((existing, open_task))
 8235        } else {
 8236            cx.update(move |cx| {
 8237                Workspace::new_local(
 8238                    abs_paths,
 8239                    app_state.clone(),
 8240                    open_options.replace_window,
 8241                    open_options.env,
 8242                    None,
 8243                    cx,
 8244                )
 8245            })
 8246            .await
 8247        };
 8248
 8249        #[cfg(target_os = "windows")]
 8250        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8251            && let Ok((workspace, _)) = &result
 8252        {
 8253            workspace
 8254                .update(cx, move |workspace, _window, cx| {
 8255                    struct OpenInWsl;
 8256                    workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8257                        let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8258                        let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8259                        cx.new(move |cx| {
 8260                            MessageNotification::new(msg, cx)
 8261                                .primary_message("Open in WSL")
 8262                                .primary_icon(IconName::FolderOpen)
 8263                                .primary_on_click(move |window, cx| {
 8264                                    window.dispatch_action(Box::new(remote::OpenWslPath {
 8265                                            distro: remote::WslConnectionOptions {
 8266                                                    distro_name: distro.clone(),
 8267                                                user: None,
 8268                                            },
 8269                                            paths: vec![path.clone().into()],
 8270                                        }), cx)
 8271                                })
 8272                        })
 8273                    });
 8274                })
 8275                .unwrap();
 8276        };
 8277        result
 8278    })
 8279}
 8280
 8281pub fn open_new(
 8282    open_options: OpenOptions,
 8283    app_state: Arc<AppState>,
 8284    cx: &mut App,
 8285    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8286) -> Task<anyhow::Result<()>> {
 8287    let task = Workspace::new_local(
 8288        Vec::new(),
 8289        app_state,
 8290        None,
 8291        open_options.env,
 8292        Some(Box::new(init)),
 8293        cx,
 8294    );
 8295    cx.spawn(async move |_cx| {
 8296        let (_workspace, _opened_paths) = task.await?;
 8297        // Init callback is called synchronously during workspace creation
 8298        Ok(())
 8299    })
 8300}
 8301
 8302pub fn create_and_open_local_file(
 8303    path: &'static Path,
 8304    window: &mut Window,
 8305    cx: &mut Context<Workspace>,
 8306    default_content: impl 'static + Send + FnOnce() -> Rope,
 8307) -> Task<Result<Box<dyn ItemHandle>>> {
 8308    cx.spawn_in(window, async move |workspace, cx| {
 8309        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8310        if !fs.is_file(path).await {
 8311            fs.create_file(path, Default::default()).await?;
 8312            fs.save(path, &default_content(), Default::default())
 8313                .await?;
 8314        }
 8315
 8316        workspace
 8317            .update_in(cx, |workspace, window, cx| {
 8318                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 8319                    let path = workspace
 8320                        .project
 8321                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 8322                    cx.spawn_in(window, async move |workspace, cx| {
 8323                        let path = path.await?;
 8324                        let mut items = workspace
 8325                            .update_in(cx, |workspace, window, cx| {
 8326                                workspace.open_paths(
 8327                                    vec![path.to_path_buf()],
 8328                                    OpenOptions {
 8329                                        visible: Some(OpenVisible::None),
 8330                                        ..Default::default()
 8331                                    },
 8332                                    None,
 8333                                    window,
 8334                                    cx,
 8335                                )
 8336                            })?
 8337                            .await;
 8338                        let item = items.pop().flatten();
 8339                        item.with_context(|| format!("path {path:?} is not a file"))?
 8340                    })
 8341                })
 8342            })?
 8343            .await?
 8344            .await
 8345    })
 8346}
 8347
 8348pub fn open_remote_project_with_new_connection(
 8349    window: WindowHandle<Workspace>,
 8350    remote_connection: Arc<dyn RemoteConnection>,
 8351    cancel_rx: oneshot::Receiver<()>,
 8352    delegate: Arc<dyn RemoteClientDelegate>,
 8353    app_state: Arc<AppState>,
 8354    paths: Vec<PathBuf>,
 8355    cx: &mut App,
 8356) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8357    cx.spawn(async move |cx| {
 8358        let (workspace_id, serialized_workspace) =
 8359            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8360                .await?;
 8361
 8362        let session = match cx
 8363            .update(|cx| {
 8364                remote::RemoteClient::new(
 8365                    ConnectionIdentifier::Workspace(workspace_id.0),
 8366                    remote_connection,
 8367                    cancel_rx,
 8368                    delegate,
 8369                    cx,
 8370                )
 8371            })
 8372            .await?
 8373        {
 8374            Some(result) => result,
 8375            None => return Ok(Vec::new()),
 8376        };
 8377
 8378        let project = cx.update(|cx| {
 8379            project::Project::remote(
 8380                session,
 8381                app_state.client.clone(),
 8382                app_state.node_runtime.clone(),
 8383                app_state.user_store.clone(),
 8384                app_state.languages.clone(),
 8385                app_state.fs.clone(),
 8386                true,
 8387                cx,
 8388            )
 8389        });
 8390
 8391        open_remote_project_inner(
 8392            project,
 8393            paths,
 8394            workspace_id,
 8395            serialized_workspace,
 8396            app_state,
 8397            window,
 8398            cx,
 8399        )
 8400        .await
 8401    })
 8402}
 8403
 8404pub fn open_remote_project_with_existing_connection(
 8405    connection_options: RemoteConnectionOptions,
 8406    project: Entity<Project>,
 8407    paths: Vec<PathBuf>,
 8408    app_state: Arc<AppState>,
 8409    window: WindowHandle<Workspace>,
 8410    cx: &mut AsyncApp,
 8411) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8412    cx.spawn(async move |cx| {
 8413        let (workspace_id, serialized_workspace) =
 8414            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 8415
 8416        open_remote_project_inner(
 8417            project,
 8418            paths,
 8419            workspace_id,
 8420            serialized_workspace,
 8421            app_state,
 8422            window,
 8423            cx,
 8424        )
 8425        .await
 8426    })
 8427}
 8428
 8429async fn open_remote_project_inner(
 8430    project: Entity<Project>,
 8431    paths: Vec<PathBuf>,
 8432    workspace_id: WorkspaceId,
 8433    serialized_workspace: Option<SerializedWorkspace>,
 8434    app_state: Arc<AppState>,
 8435    window: WindowHandle<Workspace>,
 8436    cx: &mut AsyncApp,
 8437) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 8438    let toolchains = DB.toolchains(workspace_id).await?;
 8439    for (toolchain, worktree_path, path) in toolchains {
 8440        project
 8441            .update(cx, |this, cx| {
 8442                let Some(worktree_id) =
 8443                    this.find_worktree(&worktree_path, cx)
 8444                        .and_then(|(worktree, rel_path)| {
 8445                            if rel_path.is_empty() {
 8446                                Some(worktree.read(cx).id())
 8447                            } else {
 8448                                None
 8449                            }
 8450                        })
 8451                else {
 8452                    return Task::ready(None);
 8453                };
 8454
 8455                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 8456            })
 8457            .await;
 8458    }
 8459    let mut project_paths_to_open = vec![];
 8460    let mut project_path_errors = vec![];
 8461
 8462    for path in paths {
 8463        let result = cx
 8464            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 8465            .await;
 8466        match result {
 8467            Ok((_, project_path)) => {
 8468                project_paths_to_open.push((path.clone(), Some(project_path)));
 8469            }
 8470            Err(error) => {
 8471                project_path_errors.push(error);
 8472            }
 8473        };
 8474    }
 8475
 8476    if project_paths_to_open.is_empty() {
 8477        return Err(project_path_errors.pop().context("no paths given")?);
 8478    }
 8479
 8480    if let Some(detach_session_task) = window
 8481        .update(cx, |_workspace, window, cx| {
 8482            cx.spawn_in(window, async move |this, cx| {
 8483                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 8484            })
 8485        })
 8486        .ok()
 8487    {
 8488        detach_session_task.await.ok();
 8489    }
 8490
 8491    cx.update_window(window.into(), |_, window, cx| {
 8492        window.replace_root(cx, |window, cx| {
 8493            telemetry::event!("SSH Project Opened");
 8494
 8495            let mut workspace =
 8496                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 8497            workspace.update_history(cx);
 8498
 8499            if let Some(ref serialized) = serialized_workspace {
 8500                workspace.centered_layout = serialized.centered_layout;
 8501            }
 8502
 8503            workspace
 8504        });
 8505    })?;
 8506
 8507    let items = window
 8508        .update(cx, |_, window, cx| {
 8509            window.activate_window();
 8510            open_items(serialized_workspace, project_paths_to_open, window, cx)
 8511        })?
 8512        .await?;
 8513
 8514    window.update(cx, |workspace, _, cx| {
 8515        for error in project_path_errors {
 8516            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 8517                if let Some(path) = error.error_tag("path") {
 8518                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 8519                }
 8520            } else {
 8521                workspace.show_error(&error, cx)
 8522            }
 8523        }
 8524    })?;
 8525
 8526    Ok(items.into_iter().map(|item| item?.ok()).collect())
 8527}
 8528
 8529fn deserialize_remote_project(
 8530    connection_options: RemoteConnectionOptions,
 8531    paths: Vec<PathBuf>,
 8532    cx: &AsyncApp,
 8533) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 8534    cx.background_spawn(async move {
 8535        let remote_connection_id = persistence::DB
 8536            .get_or_create_remote_connection(connection_options)
 8537            .await?;
 8538
 8539        let serialized_workspace =
 8540            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8541
 8542        let workspace_id = if let Some(workspace_id) =
 8543            serialized_workspace.as_ref().map(|workspace| workspace.id)
 8544        {
 8545            workspace_id
 8546        } else {
 8547            persistence::DB.next_id().await?
 8548        };
 8549
 8550        Ok((workspace_id, serialized_workspace))
 8551    })
 8552}
 8553
 8554pub fn join_in_room_project(
 8555    project_id: u64,
 8556    follow_user_id: u64,
 8557    app_state: Arc<AppState>,
 8558    cx: &mut App,
 8559) -> Task<Result<()>> {
 8560    let windows = cx.windows();
 8561    cx.spawn(async move |cx| {
 8562        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 8563            window_handle
 8564                .downcast::<Workspace>()
 8565                .and_then(|window_handle| {
 8566                    window_handle
 8567                        .update(cx, |workspace, _window, cx| {
 8568                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 8569                                Some(window_handle)
 8570                            } else {
 8571                                None
 8572                            }
 8573                        })
 8574                        .unwrap_or(None)
 8575                })
 8576        });
 8577
 8578        let workspace = if let Some(existing_workspace) = existing_workspace {
 8579            existing_workspace
 8580        } else {
 8581            let active_call = cx.update(|cx| ActiveCall::global(cx));
 8582            let room = active_call
 8583                .read_with(cx, |call, _| call.room().cloned())
 8584                .context("not in a call")?;
 8585            let project = room
 8586                .update(cx, |room, cx| {
 8587                    room.join_project(
 8588                        project_id,
 8589                        app_state.languages.clone(),
 8590                        app_state.fs.clone(),
 8591                        cx,
 8592                    )
 8593                })
 8594                .await?;
 8595
 8596            let window_bounds_override = window_bounds_env_override();
 8597            cx.update(|cx| {
 8598                let mut options = (app_state.build_window_options)(None, cx);
 8599                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 8600                cx.open_window(options, |window, cx| {
 8601                    cx.new(|cx| {
 8602                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 8603                    })
 8604                })
 8605            })?
 8606        };
 8607
 8608        workspace.update(cx, |workspace, window, cx| {
 8609            cx.activate(true);
 8610            window.activate_window();
 8611
 8612            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 8613                let follow_peer_id = room
 8614                    .read(cx)
 8615                    .remote_participants()
 8616                    .iter()
 8617                    .find(|(_, participant)| participant.user.id == follow_user_id)
 8618                    .map(|(_, p)| p.peer_id)
 8619                    .or_else(|| {
 8620                        // If we couldn't follow the given user, follow the host instead.
 8621                        let collaborator = workspace
 8622                            .project()
 8623                            .read(cx)
 8624                            .collaborators()
 8625                            .values()
 8626                            .find(|collaborator| collaborator.is_host)?;
 8627                        Some(collaborator.peer_id)
 8628                    });
 8629
 8630                if let Some(follow_peer_id) = follow_peer_id {
 8631                    workspace.follow(follow_peer_id, window, cx);
 8632                }
 8633            }
 8634        })?;
 8635
 8636        anyhow::Ok(())
 8637    })
 8638}
 8639
 8640pub fn reload(cx: &mut App) {
 8641    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 8642    let mut workspace_windows = cx
 8643        .windows()
 8644        .into_iter()
 8645        .filter_map(|window| window.downcast::<Workspace>())
 8646        .collect::<Vec<_>>();
 8647
 8648    // If multiple windows have unsaved changes, and need a save prompt,
 8649    // prompt in the active window before switching to a different window.
 8650    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 8651
 8652    let mut prompt = None;
 8653    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 8654        prompt = window
 8655            .update(cx, |_, window, cx| {
 8656                window.prompt(
 8657                    PromptLevel::Info,
 8658                    "Are you sure you want to restart?",
 8659                    None,
 8660                    &["Restart", "Cancel"],
 8661                    cx,
 8662                )
 8663            })
 8664            .ok();
 8665    }
 8666
 8667    cx.spawn(async move |cx| {
 8668        if let Some(prompt) = prompt {
 8669            let answer = prompt.await?;
 8670            if answer != 0 {
 8671                return anyhow::Ok(());
 8672            }
 8673        }
 8674
 8675        // If the user cancels any save prompt, then keep the app open.
 8676        for window in workspace_windows {
 8677            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 8678                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 8679            }) && !should_close.await?
 8680            {
 8681                return anyhow::Ok(());
 8682            }
 8683        }
 8684        cx.update(|cx| cx.restart());
 8685        anyhow::Ok(())
 8686    })
 8687    .detach_and_log_err(cx);
 8688}
 8689
 8690fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 8691    let mut parts = value.split(',');
 8692    let x: usize = parts.next()?.parse().ok()?;
 8693    let y: usize = parts.next()?.parse().ok()?;
 8694    Some(point(px(x as f32), px(y as f32)))
 8695}
 8696
 8697fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 8698    let mut parts = value.split(',');
 8699    let width: usize = parts.next()?.parse().ok()?;
 8700    let height: usize = parts.next()?.parse().ok()?;
 8701    Some(size(px(width as f32), px(height as f32)))
 8702}
 8703
 8704/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 8705pub fn client_side_decorations(
 8706    element: impl IntoElement,
 8707    window: &mut Window,
 8708    cx: &mut App,
 8709) -> Stateful<Div> {
 8710    const BORDER_SIZE: Pixels = px(1.0);
 8711    let decorations = window.window_decorations();
 8712
 8713    match decorations {
 8714        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 8715        Decorations::Server => window.set_client_inset(px(0.0)),
 8716    }
 8717
 8718    struct GlobalResizeEdge(ResizeEdge);
 8719    impl Global for GlobalResizeEdge {}
 8720
 8721    div()
 8722        .id("window-backdrop")
 8723        .bg(transparent_black())
 8724        .map(|div| match decorations {
 8725            Decorations::Server => div,
 8726            Decorations::Client { tiling, .. } => div
 8727                .when(!(tiling.top || tiling.right), |div| {
 8728                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8729                })
 8730                .when(!(tiling.top || tiling.left), |div| {
 8731                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8732                })
 8733                .when(!(tiling.bottom || tiling.right), |div| {
 8734                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8735                })
 8736                .when(!(tiling.bottom || tiling.left), |div| {
 8737                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8738                })
 8739                .when(!tiling.top, |div| {
 8740                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8741                })
 8742                .when(!tiling.bottom, |div| {
 8743                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8744                })
 8745                .when(!tiling.left, |div| {
 8746                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8747                })
 8748                .when(!tiling.right, |div| {
 8749                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8750                })
 8751                .on_mouse_move(move |e, window, cx| {
 8752                    let size = window.window_bounds().get_bounds().size;
 8753                    let pos = e.position;
 8754
 8755                    let new_edge =
 8756                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 8757
 8758                    let edge = cx.try_global::<GlobalResizeEdge>();
 8759                    if new_edge != edge.map(|edge| edge.0) {
 8760                        window
 8761                            .window_handle()
 8762                            .update(cx, |workspace, _, cx| {
 8763                                cx.notify(workspace.entity_id());
 8764                            })
 8765                            .ok();
 8766                    }
 8767                })
 8768                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 8769                    let size = window.window_bounds().get_bounds().size;
 8770                    let pos = e.position;
 8771
 8772                    let edge = match resize_edge(
 8773                        pos,
 8774                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 8775                        size,
 8776                        tiling,
 8777                    ) {
 8778                        Some(value) => value,
 8779                        None => return,
 8780                    };
 8781
 8782                    window.start_window_resize(edge);
 8783                }),
 8784        })
 8785        .size_full()
 8786        .child(
 8787            div()
 8788                .cursor(CursorStyle::Arrow)
 8789                .map(|div| match decorations {
 8790                    Decorations::Server => div,
 8791                    Decorations::Client { tiling } => div
 8792                        .border_color(cx.theme().colors().border)
 8793                        .when(!(tiling.top || tiling.right), |div| {
 8794                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8795                        })
 8796                        .when(!(tiling.top || tiling.left), |div| {
 8797                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8798                        })
 8799                        .when(!(tiling.bottom || tiling.right), |div| {
 8800                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8801                        })
 8802                        .when(!(tiling.bottom || tiling.left), |div| {
 8803                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8804                        })
 8805                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 8806                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 8807                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 8808                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 8809                        .when(!tiling.is_tiled(), |div| {
 8810                            div.shadow(vec![gpui::BoxShadow {
 8811                                color: Hsla {
 8812                                    h: 0.,
 8813                                    s: 0.,
 8814                                    l: 0.,
 8815                                    a: 0.4,
 8816                                },
 8817                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 8818                                spread_radius: px(0.),
 8819                                offset: point(px(0.0), px(0.0)),
 8820                            }])
 8821                        }),
 8822                })
 8823                .on_mouse_move(|_e, _, cx| {
 8824                    cx.stop_propagation();
 8825                })
 8826                .size_full()
 8827                .child(element),
 8828        )
 8829        .map(|div| match decorations {
 8830            Decorations::Server => div,
 8831            Decorations::Client { tiling, .. } => div.child(
 8832                canvas(
 8833                    |_bounds, window, _| {
 8834                        window.insert_hitbox(
 8835                            Bounds::new(
 8836                                point(px(0.0), px(0.0)),
 8837                                window.window_bounds().get_bounds().size,
 8838                            ),
 8839                            HitboxBehavior::Normal,
 8840                        )
 8841                    },
 8842                    move |_bounds, hitbox, window, cx| {
 8843                        let mouse = window.mouse_position();
 8844                        let size = window.window_bounds().get_bounds().size;
 8845                        let Some(edge) =
 8846                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 8847                        else {
 8848                            return;
 8849                        };
 8850                        cx.set_global(GlobalResizeEdge(edge));
 8851                        window.set_cursor_style(
 8852                            match edge {
 8853                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 8854                                ResizeEdge::Left | ResizeEdge::Right => {
 8855                                    CursorStyle::ResizeLeftRight
 8856                                }
 8857                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 8858                                    CursorStyle::ResizeUpLeftDownRight
 8859                                }
 8860                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 8861                                    CursorStyle::ResizeUpRightDownLeft
 8862                                }
 8863                            },
 8864                            &hitbox,
 8865                        );
 8866                    },
 8867                )
 8868                .size_full()
 8869                .absolute(),
 8870            ),
 8871        })
 8872}
 8873
 8874fn resize_edge(
 8875    pos: Point<Pixels>,
 8876    shadow_size: Pixels,
 8877    window_size: Size<Pixels>,
 8878    tiling: Tiling,
 8879) -> Option<ResizeEdge> {
 8880    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8881    if bounds.contains(&pos) {
 8882        return None;
 8883    }
 8884
 8885    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8886    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8887    if !tiling.top && top_left_bounds.contains(&pos) {
 8888        return Some(ResizeEdge::TopLeft);
 8889    }
 8890
 8891    let top_right_bounds = Bounds::new(
 8892        Point::new(window_size.width - corner_size.width, px(0.)),
 8893        corner_size,
 8894    );
 8895    if !tiling.top && top_right_bounds.contains(&pos) {
 8896        return Some(ResizeEdge::TopRight);
 8897    }
 8898
 8899    let bottom_left_bounds = Bounds::new(
 8900        Point::new(px(0.), window_size.height - corner_size.height),
 8901        corner_size,
 8902    );
 8903    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8904        return Some(ResizeEdge::BottomLeft);
 8905    }
 8906
 8907    let bottom_right_bounds = Bounds::new(
 8908        Point::new(
 8909            window_size.width - corner_size.width,
 8910            window_size.height - corner_size.height,
 8911        ),
 8912        corner_size,
 8913    );
 8914    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8915        return Some(ResizeEdge::BottomRight);
 8916    }
 8917
 8918    if !tiling.top && pos.y < shadow_size {
 8919        Some(ResizeEdge::Top)
 8920    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8921        Some(ResizeEdge::Bottom)
 8922    } else if !tiling.left && pos.x < shadow_size {
 8923        Some(ResizeEdge::Left)
 8924    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8925        Some(ResizeEdge::Right)
 8926    } else {
 8927        None
 8928    }
 8929}
 8930
 8931fn join_pane_into_active(
 8932    active_pane: &Entity<Pane>,
 8933    pane: &Entity<Pane>,
 8934    window: &mut Window,
 8935    cx: &mut App,
 8936) {
 8937    if pane == active_pane {
 8938    } else if pane.read(cx).items_len() == 0 {
 8939        pane.update(cx, |_, cx| {
 8940            cx.emit(pane::Event::Remove {
 8941                focus_on_pane: None,
 8942            });
 8943        })
 8944    } else {
 8945        move_all_items(pane, active_pane, window, cx);
 8946    }
 8947}
 8948
 8949fn move_all_items(
 8950    from_pane: &Entity<Pane>,
 8951    to_pane: &Entity<Pane>,
 8952    window: &mut Window,
 8953    cx: &mut App,
 8954) {
 8955    let destination_is_different = from_pane != to_pane;
 8956    let mut moved_items = 0;
 8957    for (item_ix, item_handle) in from_pane
 8958        .read(cx)
 8959        .items()
 8960        .enumerate()
 8961        .map(|(ix, item)| (ix, item.clone()))
 8962        .collect::<Vec<_>>()
 8963    {
 8964        let ix = item_ix - moved_items;
 8965        if destination_is_different {
 8966            // Close item from previous pane
 8967            from_pane.update(cx, |source, cx| {
 8968                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8969            });
 8970            moved_items += 1;
 8971        }
 8972
 8973        // This automatically removes duplicate items in the pane
 8974        to_pane.update(cx, |destination, cx| {
 8975            destination.add_item(item_handle, true, true, None, window, cx);
 8976            window.focus(&destination.focus_handle(cx), cx)
 8977        });
 8978    }
 8979}
 8980
 8981pub fn move_item(
 8982    source: &Entity<Pane>,
 8983    destination: &Entity<Pane>,
 8984    item_id_to_move: EntityId,
 8985    destination_index: usize,
 8986    activate: bool,
 8987    window: &mut Window,
 8988    cx: &mut App,
 8989) {
 8990    let Some((item_ix, item_handle)) = source
 8991        .read(cx)
 8992        .items()
 8993        .enumerate()
 8994        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8995        .map(|(ix, item)| (ix, item.clone()))
 8996    else {
 8997        // Tab was closed during drag
 8998        return;
 8999    };
 9000
 9001    if source != destination {
 9002        // Close item from previous pane
 9003        source.update(cx, |source, cx| {
 9004            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9005        });
 9006    }
 9007
 9008    // This automatically removes duplicate items in the pane
 9009    destination.update(cx, |destination, cx| {
 9010        destination.add_item_inner(
 9011            item_handle,
 9012            activate,
 9013            activate,
 9014            activate,
 9015            Some(destination_index),
 9016            window,
 9017            cx,
 9018        );
 9019        if activate {
 9020            window.focus(&destination.focus_handle(cx), cx)
 9021        }
 9022    });
 9023}
 9024
 9025pub fn move_active_item(
 9026    source: &Entity<Pane>,
 9027    destination: &Entity<Pane>,
 9028    focus_destination: bool,
 9029    close_if_empty: bool,
 9030    window: &mut Window,
 9031    cx: &mut App,
 9032) {
 9033    if source == destination {
 9034        return;
 9035    }
 9036    let Some(active_item) = source.read(cx).active_item() else {
 9037        return;
 9038    };
 9039    source.update(cx, |source_pane, cx| {
 9040        let item_id = active_item.item_id();
 9041        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9042        destination.update(cx, |target_pane, cx| {
 9043            target_pane.add_item(
 9044                active_item,
 9045                focus_destination,
 9046                focus_destination,
 9047                Some(target_pane.items_len()),
 9048                window,
 9049                cx,
 9050            );
 9051        });
 9052    });
 9053}
 9054
 9055pub fn clone_active_item(
 9056    workspace_id: Option<WorkspaceId>,
 9057    source: &Entity<Pane>,
 9058    destination: &Entity<Pane>,
 9059    focus_destination: bool,
 9060    window: &mut Window,
 9061    cx: &mut App,
 9062) {
 9063    if source == destination {
 9064        return;
 9065    }
 9066    let Some(active_item) = source.read(cx).active_item() else {
 9067        return;
 9068    };
 9069    if !active_item.can_split(cx) {
 9070        return;
 9071    }
 9072    let destination = destination.downgrade();
 9073    let task = active_item.clone_on_split(workspace_id, window, cx);
 9074    window
 9075        .spawn(cx, async move |cx| {
 9076            let Some(clone) = task.await else {
 9077                return;
 9078            };
 9079            destination
 9080                .update_in(cx, |target_pane, window, cx| {
 9081                    target_pane.add_item(
 9082                        clone,
 9083                        focus_destination,
 9084                        focus_destination,
 9085                        Some(target_pane.items_len()),
 9086                        window,
 9087                        cx,
 9088                    );
 9089                })
 9090                .log_err();
 9091        })
 9092        .detach();
 9093}
 9094
 9095#[derive(Debug)]
 9096pub struct WorkspacePosition {
 9097    pub window_bounds: Option<WindowBounds>,
 9098    pub display: Option<Uuid>,
 9099    pub centered_layout: bool,
 9100}
 9101
 9102pub fn remote_workspace_position_from_db(
 9103    connection_options: RemoteConnectionOptions,
 9104    paths_to_open: &[PathBuf],
 9105    cx: &App,
 9106) -> Task<Result<WorkspacePosition>> {
 9107    let paths = paths_to_open.to_vec();
 9108
 9109    cx.background_spawn(async move {
 9110        let remote_connection_id = persistence::DB
 9111            .get_or_create_remote_connection(connection_options)
 9112            .await
 9113            .context("fetching serialized ssh project")?;
 9114        let serialized_workspace =
 9115            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9116
 9117        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9118            (Some(WindowBounds::Windowed(bounds)), None)
 9119        } else {
 9120            let restorable_bounds = serialized_workspace
 9121                .as_ref()
 9122                .and_then(|workspace| {
 9123                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9124                })
 9125                .or_else(|| persistence::read_default_window_bounds());
 9126
 9127            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9128                (Some(serialized_bounds), Some(serialized_display))
 9129            } else {
 9130                (None, None)
 9131            }
 9132        };
 9133
 9134        let centered_layout = serialized_workspace
 9135            .as_ref()
 9136            .map(|w| w.centered_layout)
 9137            .unwrap_or(false);
 9138
 9139        Ok(WorkspacePosition {
 9140            window_bounds,
 9141            display,
 9142            centered_layout,
 9143        })
 9144    })
 9145}
 9146
 9147pub fn with_active_or_new_workspace(
 9148    cx: &mut App,
 9149    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9150) {
 9151    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 9152        Some(workspace) => {
 9153            cx.defer(move |cx| {
 9154                workspace
 9155                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 9156                    .log_err();
 9157            });
 9158        }
 9159        None => {
 9160            let app_state = AppState::global(cx);
 9161            if let Some(app_state) = app_state.upgrade() {
 9162                open_new(
 9163                    OpenOptions::default(),
 9164                    app_state,
 9165                    cx,
 9166                    move |workspace, window, cx| f(workspace, window, cx),
 9167                )
 9168                .detach_and_log_err(cx);
 9169            }
 9170        }
 9171    }
 9172}
 9173
 9174#[cfg(test)]
 9175mod tests {
 9176    use std::{cell::RefCell, rc::Rc};
 9177
 9178    use super::*;
 9179    use crate::{
 9180        dock::{PanelEvent, test::TestPanel},
 9181        item::{
 9182            ItemBufferKind, ItemEvent,
 9183            test::{TestItem, TestProjectItem},
 9184        },
 9185    };
 9186    use fs::FakeFs;
 9187    use gpui::{
 9188        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9189        UpdateGlobal, VisualTestContext, px,
 9190    };
 9191    use project::{Project, ProjectEntryId};
 9192    use serde_json::json;
 9193    use settings::SettingsStore;
 9194    use util::rel_path::rel_path;
 9195
 9196    #[gpui::test]
 9197    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9198        init_test(cx);
 9199
 9200        let fs = FakeFs::new(cx.executor());
 9201        let project = Project::test(fs, [], cx).await;
 9202        let (workspace, cx) =
 9203            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9204
 9205        // Adding an item with no ambiguity renders the tab without detail.
 9206        let item1 = cx.new(|cx| {
 9207            let mut item = TestItem::new(cx);
 9208            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9209            item
 9210        });
 9211        workspace.update_in(cx, |workspace, window, cx| {
 9212            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9213        });
 9214        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9215
 9216        // Adding an item that creates ambiguity increases the level of detail on
 9217        // both tabs.
 9218        let item2 = cx.new_window_entity(|_window, cx| {
 9219            let mut item = TestItem::new(cx);
 9220            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9221            item
 9222        });
 9223        workspace.update_in(cx, |workspace, window, cx| {
 9224            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9225        });
 9226        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9227        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9228
 9229        // Adding an item that creates ambiguity increases the level of detail only
 9230        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9231        // we stop at the highest detail available.
 9232        let item3 = cx.new(|cx| {
 9233            let mut item = TestItem::new(cx);
 9234            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9235            item
 9236        });
 9237        workspace.update_in(cx, |workspace, window, cx| {
 9238            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9239        });
 9240        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9241        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9242        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9243    }
 9244
 9245    #[gpui::test]
 9246    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9247        init_test(cx);
 9248
 9249        let fs = FakeFs::new(cx.executor());
 9250        fs.insert_tree(
 9251            "/root1",
 9252            json!({
 9253                "one.txt": "",
 9254                "two.txt": "",
 9255            }),
 9256        )
 9257        .await;
 9258        fs.insert_tree(
 9259            "/root2",
 9260            json!({
 9261                "three.txt": "",
 9262            }),
 9263        )
 9264        .await;
 9265
 9266        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9267        let (workspace, cx) =
 9268            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9269        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9270        let worktree_id = project.update(cx, |project, cx| {
 9271            project.worktrees(cx).next().unwrap().read(cx).id()
 9272        });
 9273
 9274        let item1 = cx.new(|cx| {
 9275            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9276        });
 9277        let item2 = cx.new(|cx| {
 9278            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9279        });
 9280
 9281        // Add an item to an empty pane
 9282        workspace.update_in(cx, |workspace, window, cx| {
 9283            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9284        });
 9285        project.update(cx, |project, cx| {
 9286            assert_eq!(
 9287                project.active_entry(),
 9288                project
 9289                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9290                    .map(|e| e.id)
 9291            );
 9292        });
 9293        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9294
 9295        // Add a second item to a non-empty pane
 9296        workspace.update_in(cx, |workspace, window, cx| {
 9297            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9298        });
 9299        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9300        project.update(cx, |project, cx| {
 9301            assert_eq!(
 9302                project.active_entry(),
 9303                project
 9304                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9305                    .map(|e| e.id)
 9306            );
 9307        });
 9308
 9309        // Close the active item
 9310        pane.update_in(cx, |pane, window, cx| {
 9311            pane.close_active_item(&Default::default(), window, cx)
 9312        })
 9313        .await
 9314        .unwrap();
 9315        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9316        project.update(cx, |project, cx| {
 9317            assert_eq!(
 9318                project.active_entry(),
 9319                project
 9320                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9321                    .map(|e| e.id)
 9322            );
 9323        });
 9324
 9325        // Add a project folder
 9326        project
 9327            .update(cx, |project, cx| {
 9328                project.find_or_create_worktree("root2", true, cx)
 9329            })
 9330            .await
 9331            .unwrap();
 9332        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 9333
 9334        // Remove a project folder
 9335        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 9336        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 9337    }
 9338
 9339    #[gpui::test]
 9340    async fn test_close_window(cx: &mut TestAppContext) {
 9341        init_test(cx);
 9342
 9343        let fs = FakeFs::new(cx.executor());
 9344        fs.insert_tree("/root", json!({ "one": "" })).await;
 9345
 9346        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9347        let (workspace, cx) =
 9348            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9349
 9350        // When there are no dirty items, there's nothing to do.
 9351        let item1 = cx.new(TestItem::new);
 9352        workspace.update_in(cx, |w, window, cx| {
 9353            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 9354        });
 9355        let task = workspace.update_in(cx, |w, window, cx| {
 9356            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9357        });
 9358        assert!(task.await.unwrap());
 9359
 9360        // When there are dirty untitled items, prompt to save each one. If the user
 9361        // cancels any prompt, then abort.
 9362        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 9363        let item3 = cx.new(|cx| {
 9364            TestItem::new(cx)
 9365                .with_dirty(true)
 9366                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9367        });
 9368        workspace.update_in(cx, |w, window, cx| {
 9369            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9370            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9371        });
 9372        let task = workspace.update_in(cx, |w, window, cx| {
 9373            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9374        });
 9375        cx.executor().run_until_parked();
 9376        cx.simulate_prompt_answer("Cancel"); // cancel save all
 9377        cx.executor().run_until_parked();
 9378        assert!(!cx.has_pending_prompt());
 9379        assert!(!task.await.unwrap());
 9380    }
 9381
 9382    #[gpui::test]
 9383    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 9384        init_test(cx);
 9385
 9386        // Register TestItem as a serializable item
 9387        cx.update(|cx| {
 9388            register_serializable_item::<TestItem>(cx);
 9389        });
 9390
 9391        let fs = FakeFs::new(cx.executor());
 9392        fs.insert_tree("/root", json!({ "one": "" })).await;
 9393
 9394        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9395        let (workspace, cx) =
 9396            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9397
 9398        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 9399        let item1 = cx.new(|cx| {
 9400            TestItem::new(cx)
 9401                .with_dirty(true)
 9402                .with_serialize(|| Some(Task::ready(Ok(()))))
 9403        });
 9404        let item2 = cx.new(|cx| {
 9405            TestItem::new(cx)
 9406                .with_dirty(true)
 9407                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9408                .with_serialize(|| Some(Task::ready(Ok(()))))
 9409        });
 9410        workspace.update_in(cx, |w, window, cx| {
 9411            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9412            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9413        });
 9414        let task = workspace.update_in(cx, |w, window, cx| {
 9415            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9416        });
 9417        assert!(task.await.unwrap());
 9418    }
 9419
 9420    #[gpui::test]
 9421    async fn test_close_pane_items(cx: &mut TestAppContext) {
 9422        init_test(cx);
 9423
 9424        let fs = FakeFs::new(cx.executor());
 9425
 9426        let project = Project::test(fs, None, cx).await;
 9427        let (workspace, cx) =
 9428            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9429
 9430        let item1 = cx.new(|cx| {
 9431            TestItem::new(cx)
 9432                .with_dirty(true)
 9433                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9434        });
 9435        let item2 = cx.new(|cx| {
 9436            TestItem::new(cx)
 9437                .with_dirty(true)
 9438                .with_conflict(true)
 9439                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9440        });
 9441        let item3 = cx.new(|cx| {
 9442            TestItem::new(cx)
 9443                .with_dirty(true)
 9444                .with_conflict(true)
 9445                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 9446        });
 9447        let item4 = cx.new(|cx| {
 9448            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 9449                let project_item = TestProjectItem::new_untitled(cx);
 9450                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9451                project_item
 9452            }])
 9453        });
 9454        let pane = workspace.update_in(cx, |workspace, window, cx| {
 9455            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9456            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9457            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9458            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 9459            workspace.active_pane().clone()
 9460        });
 9461
 9462        let close_items = pane.update_in(cx, |pane, window, cx| {
 9463            pane.activate_item(1, true, true, window, cx);
 9464            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9465            let item1_id = item1.item_id();
 9466            let item3_id = item3.item_id();
 9467            let item4_id = item4.item_id();
 9468            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 9469                [item1_id, item3_id, item4_id].contains(&id)
 9470            })
 9471        });
 9472        cx.executor().run_until_parked();
 9473
 9474        assert!(cx.has_pending_prompt());
 9475        cx.simulate_prompt_answer("Save all");
 9476
 9477        cx.executor().run_until_parked();
 9478
 9479        // Item 1 is saved. There's a prompt to save item 3.
 9480        pane.update(cx, |pane, cx| {
 9481            assert_eq!(item1.read(cx).save_count, 1);
 9482            assert_eq!(item1.read(cx).save_as_count, 0);
 9483            assert_eq!(item1.read(cx).reload_count, 0);
 9484            assert_eq!(pane.items_len(), 3);
 9485            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 9486        });
 9487        assert!(cx.has_pending_prompt());
 9488
 9489        // Cancel saving item 3.
 9490        cx.simulate_prompt_answer("Discard");
 9491        cx.executor().run_until_parked();
 9492
 9493        // Item 3 is reloaded. There's a prompt to save item 4.
 9494        pane.update(cx, |pane, cx| {
 9495            assert_eq!(item3.read(cx).save_count, 0);
 9496            assert_eq!(item3.read(cx).save_as_count, 0);
 9497            assert_eq!(item3.read(cx).reload_count, 1);
 9498            assert_eq!(pane.items_len(), 2);
 9499            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 9500        });
 9501
 9502        // There's a prompt for a path for item 4.
 9503        cx.simulate_new_path_selection(|_| Some(Default::default()));
 9504        close_items.await.unwrap();
 9505
 9506        // The requested items are closed.
 9507        pane.update(cx, |pane, cx| {
 9508            assert_eq!(item4.read(cx).save_count, 0);
 9509            assert_eq!(item4.read(cx).save_as_count, 1);
 9510            assert_eq!(item4.read(cx).reload_count, 0);
 9511            assert_eq!(pane.items_len(), 1);
 9512            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9513        });
 9514    }
 9515
 9516    #[gpui::test]
 9517    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 9518        init_test(cx);
 9519
 9520        let fs = FakeFs::new(cx.executor());
 9521        let project = Project::test(fs, [], cx).await;
 9522        let (workspace, cx) =
 9523            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9524
 9525        // Create several workspace items with single project entries, and two
 9526        // workspace items with multiple project entries.
 9527        let single_entry_items = (0..=4)
 9528            .map(|project_entry_id| {
 9529                cx.new(|cx| {
 9530                    TestItem::new(cx)
 9531                        .with_dirty(true)
 9532                        .with_project_items(&[dirty_project_item(
 9533                            project_entry_id,
 9534                            &format!("{project_entry_id}.txt"),
 9535                            cx,
 9536                        )])
 9537                })
 9538            })
 9539            .collect::<Vec<_>>();
 9540        let item_2_3 = cx.new(|cx| {
 9541            TestItem::new(cx)
 9542                .with_dirty(true)
 9543                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9544                .with_project_items(&[
 9545                    single_entry_items[2].read(cx).project_items[0].clone(),
 9546                    single_entry_items[3].read(cx).project_items[0].clone(),
 9547                ])
 9548        });
 9549        let item_3_4 = cx.new(|cx| {
 9550            TestItem::new(cx)
 9551                .with_dirty(true)
 9552                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9553                .with_project_items(&[
 9554                    single_entry_items[3].read(cx).project_items[0].clone(),
 9555                    single_entry_items[4].read(cx).project_items[0].clone(),
 9556                ])
 9557        });
 9558
 9559        // Create two panes that contain the following project entries:
 9560        //   left pane:
 9561        //     multi-entry items:   (2, 3)
 9562        //     single-entry items:  0, 2, 3, 4
 9563        //   right pane:
 9564        //     single-entry items:  4, 1
 9565        //     multi-entry items:   (3, 4)
 9566        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 9567            let left_pane = workspace.active_pane().clone();
 9568            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 9569            workspace.add_item_to_active_pane(
 9570                single_entry_items[0].boxed_clone(),
 9571                None,
 9572                true,
 9573                window,
 9574                cx,
 9575            );
 9576            workspace.add_item_to_active_pane(
 9577                single_entry_items[2].boxed_clone(),
 9578                None,
 9579                true,
 9580                window,
 9581                cx,
 9582            );
 9583            workspace.add_item_to_active_pane(
 9584                single_entry_items[3].boxed_clone(),
 9585                None,
 9586                true,
 9587                window,
 9588                cx,
 9589            );
 9590            workspace.add_item_to_active_pane(
 9591                single_entry_items[4].boxed_clone(),
 9592                None,
 9593                true,
 9594                window,
 9595                cx,
 9596            );
 9597
 9598            let right_pane =
 9599                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 9600
 9601            let boxed_clone = single_entry_items[1].boxed_clone();
 9602            let right_pane = window.spawn(cx, async move |cx| {
 9603                right_pane.await.inspect(|right_pane| {
 9604                    right_pane
 9605                        .update_in(cx, |pane, window, cx| {
 9606                            pane.add_item(boxed_clone, true, true, None, window, cx);
 9607                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 9608                        })
 9609                        .unwrap();
 9610                })
 9611            });
 9612
 9613            (left_pane, right_pane)
 9614        });
 9615        let right_pane = right_pane.await.unwrap();
 9616        cx.focus(&right_pane);
 9617
 9618        let close = right_pane.update_in(cx, |pane, window, cx| {
 9619            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9620                .unwrap()
 9621        });
 9622        cx.executor().run_until_parked();
 9623
 9624        let msg = cx.pending_prompt().unwrap().0;
 9625        assert!(msg.contains("1.txt"));
 9626        assert!(!msg.contains("2.txt"));
 9627        assert!(!msg.contains("3.txt"));
 9628        assert!(!msg.contains("4.txt"));
 9629
 9630        // With best-effort close, cancelling item 1 keeps it open but items 4
 9631        // and (3,4) still close since their entries exist in left pane.
 9632        cx.simulate_prompt_answer("Cancel");
 9633        close.await;
 9634
 9635        right_pane.read_with(cx, |pane, _| {
 9636            assert_eq!(pane.items_len(), 1);
 9637        });
 9638
 9639        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
 9640        left_pane
 9641            .update_in(cx, |left_pane, window, cx| {
 9642                left_pane.close_item_by_id(
 9643                    single_entry_items[3].entity_id(),
 9644                    SaveIntent::Skip,
 9645                    window,
 9646                    cx,
 9647                )
 9648            })
 9649            .await
 9650            .unwrap();
 9651
 9652        let close = left_pane.update_in(cx, |pane, window, cx| {
 9653            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9654                .unwrap()
 9655        });
 9656        cx.executor().run_until_parked();
 9657
 9658        let details = cx.pending_prompt().unwrap().1;
 9659        assert!(details.contains("0.txt"));
 9660        assert!(details.contains("3.txt"));
 9661        assert!(details.contains("4.txt"));
 9662        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
 9663        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
 9664        // assert!(!details.contains("2.txt"));
 9665
 9666        cx.simulate_prompt_answer("Save all");
 9667        cx.executor().run_until_parked();
 9668        close.await;
 9669
 9670        left_pane.read_with(cx, |pane, _| {
 9671            assert_eq!(pane.items_len(), 0);
 9672        });
 9673    }
 9674
 9675    #[gpui::test]
 9676    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 9677        init_test(cx);
 9678
 9679        let fs = FakeFs::new(cx.executor());
 9680        let project = Project::test(fs, [], cx).await;
 9681        let (workspace, cx) =
 9682            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9683        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9684
 9685        let item = cx.new(|cx| {
 9686            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9687        });
 9688        let item_id = item.entity_id();
 9689        workspace.update_in(cx, |workspace, window, cx| {
 9690            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9691        });
 9692
 9693        // Autosave on window change.
 9694        item.update(cx, |item, cx| {
 9695            SettingsStore::update_global(cx, |settings, cx| {
 9696                settings.update_user_settings(cx, |settings| {
 9697                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 9698                })
 9699            });
 9700            item.is_dirty = true;
 9701        });
 9702
 9703        // Deactivating the window saves the file.
 9704        cx.deactivate_window();
 9705        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9706
 9707        // Re-activating the window doesn't save the file.
 9708        cx.update(|window, _| window.activate_window());
 9709        cx.executor().run_until_parked();
 9710        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9711
 9712        // Autosave on focus change.
 9713        item.update_in(cx, |item, window, cx| {
 9714            cx.focus_self(window);
 9715            SettingsStore::update_global(cx, |settings, cx| {
 9716                settings.update_user_settings(cx, |settings| {
 9717                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9718                })
 9719            });
 9720            item.is_dirty = true;
 9721        });
 9722        // Blurring the item saves the file.
 9723        item.update_in(cx, |_, window, _| window.blur());
 9724        cx.executor().run_until_parked();
 9725        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 9726
 9727        // Deactivating the window still saves the file.
 9728        item.update_in(cx, |item, window, cx| {
 9729            cx.focus_self(window);
 9730            item.is_dirty = true;
 9731        });
 9732        cx.deactivate_window();
 9733        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 9734
 9735        // Autosave after delay.
 9736        item.update(cx, |item, cx| {
 9737            SettingsStore::update_global(cx, |settings, cx| {
 9738                settings.update_user_settings(cx, |settings| {
 9739                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 9740                        milliseconds: 500.into(),
 9741                    });
 9742                })
 9743            });
 9744            item.is_dirty = true;
 9745            cx.emit(ItemEvent::Edit);
 9746        });
 9747
 9748        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 9749        cx.executor().advance_clock(Duration::from_millis(250));
 9750        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 9751
 9752        // After delay expires, the file is saved.
 9753        cx.executor().advance_clock(Duration::from_millis(250));
 9754        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9755
 9756        // Autosave after delay, should save earlier than delay if tab is closed
 9757        item.update(cx, |item, cx| {
 9758            item.is_dirty = true;
 9759            cx.emit(ItemEvent::Edit);
 9760        });
 9761        cx.executor().advance_clock(Duration::from_millis(250));
 9762        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9763
 9764        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 9765        pane.update_in(cx, |pane, window, cx| {
 9766            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9767        })
 9768        .await
 9769        .unwrap();
 9770        assert!(!cx.has_pending_prompt());
 9771        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9772
 9773        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9774        workspace.update_in(cx, |workspace, window, cx| {
 9775            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9776        });
 9777        item.update_in(cx, |item, _window, cx| {
 9778            item.is_dirty = true;
 9779            for project_item in &mut item.project_items {
 9780                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9781            }
 9782        });
 9783        cx.run_until_parked();
 9784        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9785
 9786        // Autosave on focus change, ensuring closing the tab counts as such.
 9787        item.update(cx, |item, cx| {
 9788            SettingsStore::update_global(cx, |settings, cx| {
 9789                settings.update_user_settings(cx, |settings| {
 9790                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9791                })
 9792            });
 9793            item.is_dirty = true;
 9794            for project_item in &mut item.project_items {
 9795                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9796            }
 9797        });
 9798
 9799        pane.update_in(cx, |pane, window, cx| {
 9800            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9801        })
 9802        .await
 9803        .unwrap();
 9804        assert!(!cx.has_pending_prompt());
 9805        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9806
 9807        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9808        workspace.update_in(cx, |workspace, window, cx| {
 9809            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9810        });
 9811        item.update_in(cx, |item, window, cx| {
 9812            item.project_items[0].update(cx, |item, _| {
 9813                item.entry_id = None;
 9814            });
 9815            item.is_dirty = true;
 9816            window.blur();
 9817        });
 9818        cx.run_until_parked();
 9819        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9820
 9821        // Ensure autosave is prevented for deleted files also when closing the buffer.
 9822        let _close_items = pane.update_in(cx, |pane, window, cx| {
 9823            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9824        });
 9825        cx.run_until_parked();
 9826        assert!(cx.has_pending_prompt());
 9827        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9828    }
 9829
 9830    #[gpui::test]
 9831    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 9832        init_test(cx);
 9833
 9834        let fs = FakeFs::new(cx.executor());
 9835
 9836        let project = Project::test(fs, [], cx).await;
 9837        let (workspace, cx) =
 9838            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9839
 9840        let item = cx.new(|cx| {
 9841            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9842        });
 9843        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9844        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 9845        let toolbar_notify_count = Rc::new(RefCell::new(0));
 9846
 9847        workspace.update_in(cx, |workspace, window, cx| {
 9848            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9849            let toolbar_notification_count = toolbar_notify_count.clone();
 9850            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 9851                *toolbar_notification_count.borrow_mut() += 1
 9852            })
 9853            .detach();
 9854        });
 9855
 9856        pane.read_with(cx, |pane, _| {
 9857            assert!(!pane.can_navigate_backward());
 9858            assert!(!pane.can_navigate_forward());
 9859        });
 9860
 9861        item.update_in(cx, |item, _, cx| {
 9862            item.set_state("one".to_string(), cx);
 9863        });
 9864
 9865        // Toolbar must be notified to re-render the navigation buttons
 9866        assert_eq!(*toolbar_notify_count.borrow(), 1);
 9867
 9868        pane.read_with(cx, |pane, _| {
 9869            assert!(pane.can_navigate_backward());
 9870            assert!(!pane.can_navigate_forward());
 9871        });
 9872
 9873        workspace
 9874            .update_in(cx, |workspace, window, cx| {
 9875                workspace.go_back(pane.downgrade(), window, cx)
 9876            })
 9877            .await
 9878            .unwrap();
 9879
 9880        assert_eq!(*toolbar_notify_count.borrow(), 2);
 9881        pane.read_with(cx, |pane, _| {
 9882            assert!(!pane.can_navigate_backward());
 9883            assert!(pane.can_navigate_forward());
 9884        });
 9885    }
 9886
 9887    #[gpui::test]
 9888    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9889        init_test(cx);
 9890        let fs = FakeFs::new(cx.executor());
 9891
 9892        let project = Project::test(fs, [], cx).await;
 9893        let (workspace, cx) =
 9894            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9895
 9896        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9897            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
 9898            workspace.add_panel(panel.clone(), window, cx);
 9899
 9900            workspace
 9901                .right_dock()
 9902                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9903
 9904            panel
 9905        });
 9906
 9907        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9908        pane.update_in(cx, |pane, window, cx| {
 9909            let item = cx.new(TestItem::new);
 9910            pane.add_item(Box::new(item), true, true, None, window, cx);
 9911        });
 9912
 9913        // Transfer focus from center to panel
 9914        workspace.update_in(cx, |workspace, window, cx| {
 9915            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9916        });
 9917
 9918        workspace.update_in(cx, |workspace, window, cx| {
 9919            assert!(workspace.right_dock().read(cx).is_open());
 9920            assert!(!panel.is_zoomed(window, cx));
 9921            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9922        });
 9923
 9924        // Transfer focus from panel to center
 9925        workspace.update_in(cx, |workspace, window, cx| {
 9926            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9927        });
 9928
 9929        workspace.update_in(cx, |workspace, window, cx| {
 9930            assert!(workspace.right_dock().read(cx).is_open());
 9931            assert!(!panel.is_zoomed(window, cx));
 9932            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9933        });
 9934
 9935        // Close the dock
 9936        workspace.update_in(cx, |workspace, window, cx| {
 9937            workspace.toggle_dock(DockPosition::Right, window, cx);
 9938        });
 9939
 9940        workspace.update_in(cx, |workspace, window, cx| {
 9941            assert!(!workspace.right_dock().read(cx).is_open());
 9942            assert!(!panel.is_zoomed(window, cx));
 9943            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9944        });
 9945
 9946        // Open the dock
 9947        workspace.update_in(cx, |workspace, window, cx| {
 9948            workspace.toggle_dock(DockPosition::Right, window, cx);
 9949        });
 9950
 9951        workspace.update_in(cx, |workspace, window, cx| {
 9952            assert!(workspace.right_dock().read(cx).is_open());
 9953            assert!(!panel.is_zoomed(window, cx));
 9954            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9955        });
 9956
 9957        // Focus and zoom panel
 9958        panel.update_in(cx, |panel, window, cx| {
 9959            cx.focus_self(window);
 9960            panel.set_zoomed(true, window, cx)
 9961        });
 9962
 9963        workspace.update_in(cx, |workspace, window, cx| {
 9964            assert!(workspace.right_dock().read(cx).is_open());
 9965            assert!(panel.is_zoomed(window, cx));
 9966            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9967        });
 9968
 9969        // Transfer focus to the center closes the dock
 9970        workspace.update_in(cx, |workspace, window, cx| {
 9971            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9972        });
 9973
 9974        workspace.update_in(cx, |workspace, window, cx| {
 9975            assert!(!workspace.right_dock().read(cx).is_open());
 9976            assert!(panel.is_zoomed(window, cx));
 9977            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9978        });
 9979
 9980        // Transferring focus back to the panel keeps it zoomed
 9981        workspace.update_in(cx, |workspace, window, cx| {
 9982            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9983        });
 9984
 9985        workspace.update_in(cx, |workspace, window, cx| {
 9986            assert!(workspace.right_dock().read(cx).is_open());
 9987            assert!(panel.is_zoomed(window, cx));
 9988            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9989        });
 9990
 9991        // Close the dock while it is zoomed
 9992        workspace.update_in(cx, |workspace, window, cx| {
 9993            workspace.toggle_dock(DockPosition::Right, window, cx)
 9994        });
 9995
 9996        workspace.update_in(cx, |workspace, window, cx| {
 9997            assert!(!workspace.right_dock().read(cx).is_open());
 9998            assert!(panel.is_zoomed(window, cx));
 9999            assert!(workspace.zoomed.is_none());
10000            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10001        });
10002
10003        // Opening the dock, when it's zoomed, retains focus
10004        workspace.update_in(cx, |workspace, window, cx| {
10005            workspace.toggle_dock(DockPosition::Right, window, cx)
10006        });
10007
10008        workspace.update_in(cx, |workspace, window, cx| {
10009            assert!(workspace.right_dock().read(cx).is_open());
10010            assert!(panel.is_zoomed(window, cx));
10011            assert!(workspace.zoomed.is_some());
10012            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10013        });
10014
10015        // Unzoom and close the panel, zoom the active pane.
10016        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10017        workspace.update_in(cx, |workspace, window, cx| {
10018            workspace.toggle_dock(DockPosition::Right, window, cx)
10019        });
10020        pane.update_in(cx, |pane, window, cx| {
10021            pane.toggle_zoom(&Default::default(), window, cx)
10022        });
10023
10024        // Opening a dock unzooms the pane.
10025        workspace.update_in(cx, |workspace, window, cx| {
10026            workspace.toggle_dock(DockPosition::Right, window, cx)
10027        });
10028        workspace.update_in(cx, |workspace, window, cx| {
10029            let pane = pane.read(cx);
10030            assert!(!pane.is_zoomed());
10031            assert!(!pane.focus_handle(cx).is_focused(window));
10032            assert!(workspace.right_dock().read(cx).is_open());
10033            assert!(workspace.zoomed.is_none());
10034        });
10035    }
10036
10037    #[gpui::test]
10038    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10039        init_test(cx);
10040        let fs = FakeFs::new(cx.executor());
10041
10042        let project = Project::test(fs, [], cx).await;
10043        let (workspace, cx) =
10044            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10045
10046        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10047            workspace.active_pane().clone()
10048        });
10049
10050        // Add an item to the pane so it can be zoomed
10051        workspace.update_in(cx, |workspace, window, cx| {
10052            let item = cx.new(TestItem::new);
10053            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10054        });
10055
10056        // Initially not zoomed
10057        workspace.update_in(cx, |workspace, _window, cx| {
10058            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10059            assert!(
10060                workspace.zoomed.is_none(),
10061                "Workspace should track no zoomed pane"
10062            );
10063            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10064        });
10065
10066        // Zoom In
10067        pane.update_in(cx, |pane, window, cx| {
10068            pane.zoom_in(&crate::ZoomIn, window, cx);
10069        });
10070
10071        workspace.update_in(cx, |workspace, window, cx| {
10072            assert!(
10073                pane.read(cx).is_zoomed(),
10074                "Pane should be zoomed after ZoomIn"
10075            );
10076            assert!(
10077                workspace.zoomed.is_some(),
10078                "Workspace should track the zoomed pane"
10079            );
10080            assert!(
10081                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10082                "ZoomIn should focus the pane"
10083            );
10084        });
10085
10086        // Zoom In again is a no-op
10087        pane.update_in(cx, |pane, window, cx| {
10088            pane.zoom_in(&crate::ZoomIn, window, cx);
10089        });
10090
10091        workspace.update_in(cx, |workspace, window, cx| {
10092            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10093            assert!(
10094                workspace.zoomed.is_some(),
10095                "Workspace still tracks zoomed pane"
10096            );
10097            assert!(
10098                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10099                "Pane remains focused after repeated ZoomIn"
10100            );
10101        });
10102
10103        // Zoom Out
10104        pane.update_in(cx, |pane, window, cx| {
10105            pane.zoom_out(&crate::ZoomOut, window, cx);
10106        });
10107
10108        workspace.update_in(cx, |workspace, _window, cx| {
10109            assert!(
10110                !pane.read(cx).is_zoomed(),
10111                "Pane should unzoom after ZoomOut"
10112            );
10113            assert!(
10114                workspace.zoomed.is_none(),
10115                "Workspace clears zoom tracking after ZoomOut"
10116            );
10117        });
10118
10119        // Zoom Out again is a no-op
10120        pane.update_in(cx, |pane, window, cx| {
10121            pane.zoom_out(&crate::ZoomOut, window, cx);
10122        });
10123
10124        workspace.update_in(cx, |workspace, _window, cx| {
10125            assert!(
10126                !pane.read(cx).is_zoomed(),
10127                "Second ZoomOut keeps pane unzoomed"
10128            );
10129            assert!(
10130                workspace.zoomed.is_none(),
10131                "Workspace remains without zoomed pane"
10132            );
10133        });
10134    }
10135
10136    #[gpui::test]
10137    async fn test_zoomed_dock_persists_across_window_activation(cx: &mut gpui::TestAppContext) {
10138        init_test(cx);
10139        let fs = FakeFs::new(cx.executor());
10140
10141        let project = Project::test(fs, [], cx).await;
10142        let (workspace, cx) =
10143            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10144
10145        let panel = workspace.update_in(cx, |workspace, window, cx| {
10146            let panel = cx.new(|cx| TestPanel::new(DockPosition::Bottom, 100, cx));
10147            workspace.add_panel(panel.clone(), window, cx);
10148            workspace.toggle_dock(DockPosition::Bottom, window, cx);
10149            panel
10150        });
10151
10152        // Activate and zoom the panel
10153        panel.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10154        panel.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10155
10156        // Verify the dock is open and zoomed with focus in the panel
10157        workspace.update_in(cx, |workspace, window, cx| {
10158            assert!(
10159                workspace.bottom_dock().read(cx).is_open(),
10160                "Bottom dock should be open"
10161            );
10162            assert!(panel.is_zoomed(window, cx), "Panel should be zoomed");
10163            assert!(
10164                workspace.zoomed.is_some(),
10165                "Workspace should track the zoomed panel"
10166            );
10167            assert!(
10168                workspace.zoomed_position.is_some(),
10169                "Workspace should track the zoomed dock position"
10170            );
10171            assert!(
10172                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10173                "Panel should be focused"
10174            );
10175        });
10176
10177        // Deactivate the window (simulates cmd-tab away from Zed)
10178        cx.deactivate_window();
10179
10180        // Verify the dock is still open while window is deactivated
10181        // (the bug manifests on REactivation, not deactivation)
10182        workspace.update_in(cx, |workspace, window, cx| {
10183            assert!(
10184                workspace.bottom_dock().read(cx).is_open(),
10185                "Bottom dock should still be open while window is deactivated"
10186            );
10187            assert!(
10188                panel.is_zoomed(window, cx),
10189                "Panel should still be zoomed while window is deactivated"
10190            );
10191            assert!(
10192                workspace.zoomed_position.is_some(),
10193                "zoomed_position should still be set while window is deactivated"
10194            );
10195        });
10196
10197        // Reactivate the window (simulates cmd-tab back to Zed)
10198        // During reactivation, focus is restored to the dock panel
10199        cx.update(|window, _cx| {
10200            window.activate_window();
10201        });
10202        cx.run_until_parked();
10203
10204        // Verify zoomed dock remains open after reactivation
10205        workspace.update_in(cx, |workspace, window, cx| {
10206            assert!(
10207                workspace.bottom_dock().read(cx).is_open(),
10208                "Bottom dock should remain open after window reactivation"
10209            );
10210            assert!(
10211                panel.is_zoomed(window, cx),
10212                "Panel should remain zoomed after window reactivation"
10213            );
10214            assert!(
10215                workspace.zoomed.is_some(),
10216                "Workspace should still track the zoomed panel after window reactivation"
10217            );
10218        });
10219    }
10220
10221    #[gpui::test]
10222    async fn test_zoomed_dock_dismissed_when_focus_moves_to_center_pane(
10223        cx: &mut gpui::TestAppContext,
10224    ) {
10225        init_test(cx);
10226        let fs = FakeFs::new(cx.executor());
10227
10228        let project = Project::test(fs, [], cx).await;
10229        let (workspace, cx) =
10230            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10231
10232        let panel = workspace.update_in(cx, |workspace, window, cx| {
10233            let panel = cx.new(|cx| TestPanel::new(DockPosition::Bottom, 100, cx));
10234            workspace.add_panel(panel.clone(), window, cx);
10235            workspace.toggle_dock(DockPosition::Bottom, window, cx);
10236            panel
10237        });
10238
10239        // Activate and zoom the panel
10240        panel.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10241        panel.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10242
10243        // Verify setup
10244        workspace.update_in(cx, |workspace, window, cx| {
10245            assert!(workspace.bottom_dock().read(cx).is_open());
10246            assert!(panel.is_zoomed(window, cx));
10247            assert!(workspace.zoomed_position.is_some());
10248        });
10249
10250        // Explicitly focus the center pane (simulates user clicking in the editor)
10251        workspace.update_in(cx, |workspace, window, cx| {
10252            window.focus(&workspace.active_pane().focus_handle(cx), cx);
10253        });
10254        cx.run_until_parked();
10255
10256        // When user explicitly focuses the center pane, the zoomed dock SHOULD be dismissed
10257        workspace.update_in(cx, |workspace, _window, cx| {
10258            assert!(
10259                !workspace.bottom_dock().read(cx).is_open(),
10260                "Bottom dock should be closed when focus explicitly moves to center pane"
10261            );
10262            assert!(
10263                workspace.zoomed.is_none(),
10264                "Workspace should not track zoomed panel when focus explicitly moves to center pane"
10265            );
10266            assert!(
10267                workspace.zoomed_position.is_none(),
10268                "Workspace zoomed_position should be None when focus explicitly moves to center pane"
10269            );
10270        });
10271    }
10272
10273    #[gpui::test]
10274    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10275        init_test(cx);
10276        let fs = FakeFs::new(cx.executor());
10277
10278        let project = Project::test(fs, [], cx).await;
10279        let (workspace, cx) =
10280            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10281        workspace.update_in(cx, |workspace, window, cx| {
10282            // Open two docks
10283            let left_dock = workspace.dock_at_position(DockPosition::Left);
10284            let right_dock = workspace.dock_at_position(DockPosition::Right);
10285
10286            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10287            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10288
10289            assert!(left_dock.read(cx).is_open());
10290            assert!(right_dock.read(cx).is_open());
10291        });
10292
10293        workspace.update_in(cx, |workspace, window, cx| {
10294            // Toggle all docks - should close both
10295            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10296
10297            let left_dock = workspace.dock_at_position(DockPosition::Left);
10298            let right_dock = workspace.dock_at_position(DockPosition::Right);
10299            assert!(!left_dock.read(cx).is_open());
10300            assert!(!right_dock.read(cx).is_open());
10301        });
10302
10303        workspace.update_in(cx, |workspace, window, cx| {
10304            // Toggle again - should reopen both
10305            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10306
10307            let left_dock = workspace.dock_at_position(DockPosition::Left);
10308            let right_dock = workspace.dock_at_position(DockPosition::Right);
10309            assert!(left_dock.read(cx).is_open());
10310            assert!(right_dock.read(cx).is_open());
10311        });
10312    }
10313
10314    #[gpui::test]
10315    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10316        init_test(cx);
10317        let fs = FakeFs::new(cx.executor());
10318
10319        let project = Project::test(fs, [], cx).await;
10320        let (workspace, cx) =
10321            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10322        workspace.update_in(cx, |workspace, window, cx| {
10323            // Open two docks
10324            let left_dock = workspace.dock_at_position(DockPosition::Left);
10325            let right_dock = workspace.dock_at_position(DockPosition::Right);
10326
10327            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10328            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10329
10330            assert!(left_dock.read(cx).is_open());
10331            assert!(right_dock.read(cx).is_open());
10332        });
10333
10334        workspace.update_in(cx, |workspace, window, cx| {
10335            // Close them manually
10336            workspace.toggle_dock(DockPosition::Left, window, cx);
10337            workspace.toggle_dock(DockPosition::Right, window, cx);
10338
10339            let left_dock = workspace.dock_at_position(DockPosition::Left);
10340            let right_dock = workspace.dock_at_position(DockPosition::Right);
10341            assert!(!left_dock.read(cx).is_open());
10342            assert!(!right_dock.read(cx).is_open());
10343        });
10344
10345        workspace.update_in(cx, |workspace, window, cx| {
10346            // Toggle all docks - only last closed (right dock) should reopen
10347            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10348
10349            let left_dock = workspace.dock_at_position(DockPosition::Left);
10350            let right_dock = workspace.dock_at_position(DockPosition::Right);
10351            assert!(!left_dock.read(cx).is_open());
10352            assert!(right_dock.read(cx).is_open());
10353        });
10354    }
10355
10356    #[gpui::test]
10357    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10358        init_test(cx);
10359        let fs = FakeFs::new(cx.executor());
10360        let project = Project::test(fs, [], cx).await;
10361        let (workspace, cx) =
10362            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10363
10364        // Open two docks (left and right) with one panel each
10365        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10366            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10367            workspace.add_panel(left_panel.clone(), window, cx);
10368
10369            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10370            workspace.add_panel(right_panel.clone(), window, cx);
10371
10372            workspace.toggle_dock(DockPosition::Left, window, cx);
10373            workspace.toggle_dock(DockPosition::Right, window, cx);
10374
10375            // Verify initial state
10376            assert!(
10377                workspace.left_dock().read(cx).is_open(),
10378                "Left dock should be open"
10379            );
10380            assert_eq!(
10381                workspace
10382                    .left_dock()
10383                    .read(cx)
10384                    .visible_panel()
10385                    .unwrap()
10386                    .panel_id(),
10387                left_panel.panel_id(),
10388                "Left panel should be visible in left dock"
10389            );
10390            assert!(
10391                workspace.right_dock().read(cx).is_open(),
10392                "Right dock should be open"
10393            );
10394            assert_eq!(
10395                workspace
10396                    .right_dock()
10397                    .read(cx)
10398                    .visible_panel()
10399                    .unwrap()
10400                    .panel_id(),
10401                right_panel.panel_id(),
10402                "Right panel should be visible in right dock"
10403            );
10404            assert!(
10405                !workspace.bottom_dock().read(cx).is_open(),
10406                "Bottom dock should be closed"
10407            );
10408
10409            (left_panel, right_panel)
10410        });
10411
10412        // Focus the left panel and move it to the next position (bottom dock)
10413        workspace.update_in(cx, |workspace, window, cx| {
10414            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10415            assert!(
10416                left_panel.read(cx).focus_handle(cx).is_focused(window),
10417                "Left panel should be focused"
10418            );
10419        });
10420
10421        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10422
10423        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10424        workspace.update(cx, |workspace, cx| {
10425            assert!(
10426                !workspace.left_dock().read(cx).is_open(),
10427                "Left dock should be closed"
10428            );
10429            assert!(
10430                workspace.bottom_dock().read(cx).is_open(),
10431                "Bottom dock should now be open"
10432            );
10433            assert_eq!(
10434                left_panel.read(cx).position,
10435                DockPosition::Bottom,
10436                "Left panel should now be in the bottom dock"
10437            );
10438            assert_eq!(
10439                workspace
10440                    .bottom_dock()
10441                    .read(cx)
10442                    .visible_panel()
10443                    .unwrap()
10444                    .panel_id(),
10445                left_panel.panel_id(),
10446                "Left panel should be the visible panel in the bottom dock"
10447            );
10448        });
10449
10450        // Toggle all docks off
10451        workspace.update_in(cx, |workspace, window, cx| {
10452            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10453            assert!(
10454                !workspace.left_dock().read(cx).is_open(),
10455                "Left dock should be closed"
10456            );
10457            assert!(
10458                !workspace.right_dock().read(cx).is_open(),
10459                "Right dock should be closed"
10460            );
10461            assert!(
10462                !workspace.bottom_dock().read(cx).is_open(),
10463                "Bottom dock should be closed"
10464            );
10465        });
10466
10467        // Toggle all docks back on and verify positions are restored
10468        workspace.update_in(cx, |workspace, window, cx| {
10469            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10470            assert!(
10471                !workspace.left_dock().read(cx).is_open(),
10472                "Left dock should remain closed"
10473            );
10474            assert!(
10475                workspace.right_dock().read(cx).is_open(),
10476                "Right dock should remain open"
10477            );
10478            assert!(
10479                workspace.bottom_dock().read(cx).is_open(),
10480                "Bottom dock should remain open"
10481            );
10482            assert_eq!(
10483                left_panel.read(cx).position,
10484                DockPosition::Bottom,
10485                "Left panel should remain in the bottom dock"
10486            );
10487            assert_eq!(
10488                right_panel.read(cx).position,
10489                DockPosition::Right,
10490                "Right panel should remain in the right dock"
10491            );
10492            assert_eq!(
10493                workspace
10494                    .bottom_dock()
10495                    .read(cx)
10496                    .visible_panel()
10497                    .unwrap()
10498                    .panel_id(),
10499                left_panel.panel_id(),
10500                "Left panel should be the visible panel in the right dock"
10501            );
10502        });
10503    }
10504
10505    #[gpui::test]
10506    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10507        init_test(cx);
10508
10509        let fs = FakeFs::new(cx.executor());
10510
10511        let project = Project::test(fs, None, cx).await;
10512        let (workspace, cx) =
10513            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10514
10515        // Let's arrange the panes like this:
10516        //
10517        // +-----------------------+
10518        // |         top           |
10519        // +------+--------+-------+
10520        // | left | center | right |
10521        // +------+--------+-------+
10522        // |        bottom         |
10523        // +-----------------------+
10524
10525        let top_item = cx.new(|cx| {
10526            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10527        });
10528        let bottom_item = cx.new(|cx| {
10529            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10530        });
10531        let left_item = cx.new(|cx| {
10532            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10533        });
10534        let right_item = cx.new(|cx| {
10535            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10536        });
10537        let center_item = cx.new(|cx| {
10538            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10539        });
10540
10541        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10542            let top_pane_id = workspace.active_pane().entity_id();
10543            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10544            workspace.split_pane(
10545                workspace.active_pane().clone(),
10546                SplitDirection::Down,
10547                window,
10548                cx,
10549            );
10550            top_pane_id
10551        });
10552        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10553            let bottom_pane_id = workspace.active_pane().entity_id();
10554            workspace.add_item_to_active_pane(
10555                Box::new(bottom_item.clone()),
10556                None,
10557                false,
10558                window,
10559                cx,
10560            );
10561            workspace.split_pane(
10562                workspace.active_pane().clone(),
10563                SplitDirection::Up,
10564                window,
10565                cx,
10566            );
10567            bottom_pane_id
10568        });
10569        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10570            let left_pane_id = workspace.active_pane().entity_id();
10571            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10572            workspace.split_pane(
10573                workspace.active_pane().clone(),
10574                SplitDirection::Right,
10575                window,
10576                cx,
10577            );
10578            left_pane_id
10579        });
10580        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10581            let right_pane_id = workspace.active_pane().entity_id();
10582            workspace.add_item_to_active_pane(
10583                Box::new(right_item.clone()),
10584                None,
10585                false,
10586                window,
10587                cx,
10588            );
10589            workspace.split_pane(
10590                workspace.active_pane().clone(),
10591                SplitDirection::Left,
10592                window,
10593                cx,
10594            );
10595            right_pane_id
10596        });
10597        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10598            let center_pane_id = workspace.active_pane().entity_id();
10599            workspace.add_item_to_active_pane(
10600                Box::new(center_item.clone()),
10601                None,
10602                false,
10603                window,
10604                cx,
10605            );
10606            center_pane_id
10607        });
10608        cx.executor().run_until_parked();
10609
10610        workspace.update_in(cx, |workspace, window, cx| {
10611            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10612
10613            // Join into next from center pane into right
10614            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10615        });
10616
10617        workspace.update_in(cx, |workspace, window, cx| {
10618            let active_pane = workspace.active_pane();
10619            assert_eq!(right_pane_id, active_pane.entity_id());
10620            assert_eq!(2, active_pane.read(cx).items_len());
10621            let item_ids_in_pane =
10622                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10623            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10624            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10625
10626            // Join into next from right pane into bottom
10627            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10628        });
10629
10630        workspace.update_in(cx, |workspace, window, cx| {
10631            let active_pane = workspace.active_pane();
10632            assert_eq!(bottom_pane_id, active_pane.entity_id());
10633            assert_eq!(3, active_pane.read(cx).items_len());
10634            let item_ids_in_pane =
10635                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10636            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10637            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10638            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10639
10640            // Join into next from bottom pane into left
10641            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10642        });
10643
10644        workspace.update_in(cx, |workspace, window, cx| {
10645            let active_pane = workspace.active_pane();
10646            assert_eq!(left_pane_id, active_pane.entity_id());
10647            assert_eq!(4, active_pane.read(cx).items_len());
10648            let item_ids_in_pane =
10649                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10650            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10651            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10652            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10653            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10654
10655            // Join into next from left pane into top
10656            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10657        });
10658
10659        workspace.update_in(cx, |workspace, window, cx| {
10660            let active_pane = workspace.active_pane();
10661            assert_eq!(top_pane_id, active_pane.entity_id());
10662            assert_eq!(5, active_pane.read(cx).items_len());
10663            let item_ids_in_pane =
10664                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10665            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10666            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10667            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10668            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10669            assert!(item_ids_in_pane.contains(&top_item.item_id()));
10670
10671            // Single pane left: no-op
10672            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10673        });
10674
10675        workspace.update(cx, |workspace, _cx| {
10676            let active_pane = workspace.active_pane();
10677            assert_eq!(top_pane_id, active_pane.entity_id());
10678        });
10679    }
10680
10681    fn add_an_item_to_active_pane(
10682        cx: &mut VisualTestContext,
10683        workspace: &Entity<Workspace>,
10684        item_id: u64,
10685    ) -> Entity<TestItem> {
10686        let item = cx.new(|cx| {
10687            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10688                item_id,
10689                "item{item_id}.txt",
10690                cx,
10691            )])
10692        });
10693        workspace.update_in(cx, |workspace, window, cx| {
10694            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10695        });
10696        item
10697    }
10698
10699    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10700        workspace.update_in(cx, |workspace, window, cx| {
10701            workspace.split_pane(
10702                workspace.active_pane().clone(),
10703                SplitDirection::Right,
10704                window,
10705                cx,
10706            )
10707        })
10708    }
10709
10710    #[gpui::test]
10711    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10712        init_test(cx);
10713        let fs = FakeFs::new(cx.executor());
10714        let project = Project::test(fs, None, cx).await;
10715        let (workspace, cx) =
10716            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10717
10718        add_an_item_to_active_pane(cx, &workspace, 1);
10719        split_pane(cx, &workspace);
10720        add_an_item_to_active_pane(cx, &workspace, 2);
10721        split_pane(cx, &workspace); // empty pane
10722        split_pane(cx, &workspace);
10723        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
10724
10725        cx.executor().run_until_parked();
10726
10727        workspace.update(cx, |workspace, cx| {
10728            let num_panes = workspace.panes().len();
10729            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10730            let active_item = workspace
10731                .active_pane()
10732                .read(cx)
10733                .active_item()
10734                .expect("item is in focus");
10735
10736            assert_eq!(num_panes, 4);
10737            assert_eq!(num_items_in_current_pane, 1);
10738            assert_eq!(active_item.item_id(), last_item.item_id());
10739        });
10740
10741        workspace.update_in(cx, |workspace, window, cx| {
10742            workspace.join_all_panes(window, cx);
10743        });
10744
10745        workspace.update(cx, |workspace, cx| {
10746            let num_panes = workspace.panes().len();
10747            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10748            let active_item = workspace
10749                .active_pane()
10750                .read(cx)
10751                .active_item()
10752                .expect("item is in focus");
10753
10754            assert_eq!(num_panes, 1);
10755            assert_eq!(num_items_in_current_pane, 3);
10756            assert_eq!(active_item.item_id(), last_item.item_id());
10757        });
10758    }
10759    struct TestModal(FocusHandle);
10760
10761    impl TestModal {
10762        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
10763            Self(cx.focus_handle())
10764        }
10765    }
10766
10767    impl EventEmitter<DismissEvent> for TestModal {}
10768
10769    impl Focusable for TestModal {
10770        fn focus_handle(&self, _cx: &App) -> FocusHandle {
10771            self.0.clone()
10772        }
10773    }
10774
10775    impl ModalView for TestModal {}
10776
10777    impl Render for TestModal {
10778        fn render(
10779            &mut self,
10780            _window: &mut Window,
10781            _cx: &mut Context<TestModal>,
10782        ) -> impl IntoElement {
10783            div().track_focus(&self.0)
10784        }
10785    }
10786
10787    #[gpui::test]
10788    async fn test_panels(cx: &mut gpui::TestAppContext) {
10789        init_test(cx);
10790        let fs = FakeFs::new(cx.executor());
10791
10792        let project = Project::test(fs, [], cx).await;
10793        let (workspace, cx) =
10794            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10795
10796        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
10797            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10798            workspace.add_panel(panel_1.clone(), window, cx);
10799            workspace.toggle_dock(DockPosition::Left, window, cx);
10800            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10801            workspace.add_panel(panel_2.clone(), window, cx);
10802            workspace.toggle_dock(DockPosition::Right, window, cx);
10803
10804            let left_dock = workspace.left_dock();
10805            assert_eq!(
10806                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10807                panel_1.panel_id()
10808            );
10809            assert_eq!(
10810                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10811                panel_1.size(window, cx)
10812            );
10813
10814            left_dock.update(cx, |left_dock, cx| {
10815                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
10816            });
10817            assert_eq!(
10818                workspace
10819                    .right_dock()
10820                    .read(cx)
10821                    .visible_panel()
10822                    .unwrap()
10823                    .panel_id(),
10824                panel_2.panel_id(),
10825            );
10826
10827            (panel_1, panel_2)
10828        });
10829
10830        // Move panel_1 to the right
10831        panel_1.update_in(cx, |panel_1, window, cx| {
10832            panel_1.set_position(DockPosition::Right, window, cx)
10833        });
10834
10835        workspace.update_in(cx, |workspace, window, cx| {
10836            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
10837            // Since it was the only panel on the left, the left dock should now be closed.
10838            assert!(!workspace.left_dock().read(cx).is_open());
10839            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
10840            let right_dock = workspace.right_dock();
10841            assert_eq!(
10842                right_dock.read(cx).visible_panel().unwrap().panel_id(),
10843                panel_1.panel_id()
10844            );
10845            assert_eq!(
10846                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
10847                px(1337.)
10848            );
10849
10850            // Now we move panel_2 to the left
10851            panel_2.set_position(DockPosition::Left, window, cx);
10852        });
10853
10854        workspace.update(cx, |workspace, cx| {
10855            // Since panel_2 was not visible on the right, we don't open the left dock.
10856            assert!(!workspace.left_dock().read(cx).is_open());
10857            // And the right dock is unaffected in its displaying of panel_1
10858            assert!(workspace.right_dock().read(cx).is_open());
10859            assert_eq!(
10860                workspace
10861                    .right_dock()
10862                    .read(cx)
10863                    .visible_panel()
10864                    .unwrap()
10865                    .panel_id(),
10866                panel_1.panel_id(),
10867            );
10868        });
10869
10870        // Move panel_1 back to the left
10871        panel_1.update_in(cx, |panel_1, window, cx| {
10872            panel_1.set_position(DockPosition::Left, window, cx)
10873        });
10874
10875        workspace.update_in(cx, |workspace, window, cx| {
10876            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10877            let left_dock = workspace.left_dock();
10878            assert!(left_dock.read(cx).is_open());
10879            assert_eq!(
10880                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10881                panel_1.panel_id()
10882            );
10883            assert_eq!(
10884                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10885                px(1337.)
10886            );
10887            // And the right dock should be closed as it no longer has any panels.
10888            assert!(!workspace.right_dock().read(cx).is_open());
10889
10890            // Now we move panel_1 to the bottom
10891            panel_1.set_position(DockPosition::Bottom, window, cx);
10892        });
10893
10894        workspace.update_in(cx, |workspace, window, cx| {
10895            // Since panel_1 was visible on the left, we close the left dock.
10896            assert!(!workspace.left_dock().read(cx).is_open());
10897            // The bottom dock is sized based on the panel's default size,
10898            // since the panel orientation changed from vertical to horizontal.
10899            let bottom_dock = workspace.bottom_dock();
10900            assert_eq!(
10901                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10902                panel_1.size(window, cx),
10903            );
10904            // Close bottom dock and move panel_1 back to the left.
10905            bottom_dock.update(cx, |bottom_dock, cx| {
10906                bottom_dock.set_open(false, window, cx)
10907            });
10908            panel_1.set_position(DockPosition::Left, window, cx);
10909        });
10910
10911        // Emit activated event on panel 1
10912        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10913
10914        // Now the left dock is open and panel_1 is active and focused.
10915        workspace.update_in(cx, |workspace, window, cx| {
10916            let left_dock = workspace.left_dock();
10917            assert!(left_dock.read(cx).is_open());
10918            assert_eq!(
10919                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10920                panel_1.panel_id(),
10921            );
10922            assert!(panel_1.focus_handle(cx).is_focused(window));
10923        });
10924
10925        // Emit closed event on panel 2, which is not active
10926        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10927
10928        // Wo don't close the left dock, because panel_2 wasn't the active panel
10929        workspace.update(cx, |workspace, cx| {
10930            let left_dock = workspace.left_dock();
10931            assert!(left_dock.read(cx).is_open());
10932            assert_eq!(
10933                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10934                panel_1.panel_id(),
10935            );
10936        });
10937
10938        // Emitting a ZoomIn event shows the panel as zoomed.
10939        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10940        workspace.read_with(cx, |workspace, _| {
10941            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10942            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10943        });
10944
10945        // Move panel to another dock while it is zoomed
10946        panel_1.update_in(cx, |panel, window, cx| {
10947            panel.set_position(DockPosition::Right, window, cx)
10948        });
10949        workspace.read_with(cx, |workspace, _| {
10950            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10951
10952            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10953        });
10954
10955        // This is a helper for getting a:
10956        // - valid focus on an element,
10957        // - that isn't a part of the panes and panels system of the Workspace,
10958        // - and doesn't trigger the 'on_focus_lost' API.
10959        let focus_other_view = {
10960            let workspace = workspace.clone();
10961            move |cx: &mut VisualTestContext| {
10962                workspace.update_in(cx, |workspace, window, cx| {
10963                    if workspace.active_modal::<TestModal>(cx).is_some() {
10964                        workspace.toggle_modal(window, cx, TestModal::new);
10965                        workspace.toggle_modal(window, cx, TestModal::new);
10966                    } else {
10967                        workspace.toggle_modal(window, cx, TestModal::new);
10968                    }
10969                })
10970            }
10971        };
10972
10973        // If focus is transferred to another view that's not a panel or another pane, we still show
10974        // the panel as zoomed.
10975        focus_other_view(cx);
10976        workspace.read_with(cx, |workspace, _| {
10977            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10978            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10979        });
10980
10981        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10982        workspace.update_in(cx, |_workspace, window, cx| {
10983            cx.focus_self(window);
10984        });
10985        workspace.read_with(cx, |workspace, _| {
10986            assert_eq!(workspace.zoomed, None);
10987            assert_eq!(workspace.zoomed_position, None);
10988        });
10989
10990        // If focus is transferred again to another view that's not a panel or a pane, we won't
10991        // show the panel as zoomed because it wasn't zoomed before.
10992        focus_other_view(cx);
10993        workspace.read_with(cx, |workspace, _| {
10994            assert_eq!(workspace.zoomed, None);
10995            assert_eq!(workspace.zoomed_position, None);
10996        });
10997
10998        // When the panel is activated, it is zoomed again.
10999        cx.dispatch_action(ToggleRightDock);
11000        workspace.read_with(cx, |workspace, _| {
11001            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11002            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11003        });
11004
11005        // Emitting a ZoomOut event unzooms the panel.
11006        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11007        workspace.read_with(cx, |workspace, _| {
11008            assert_eq!(workspace.zoomed, None);
11009            assert_eq!(workspace.zoomed_position, None);
11010        });
11011
11012        // Emit closed event on panel 1, which is active
11013        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11014
11015        // Now the left dock is closed, because panel_1 was the active panel
11016        workspace.update(cx, |workspace, cx| {
11017            let right_dock = workspace.right_dock();
11018            assert!(!right_dock.read(cx).is_open());
11019        });
11020    }
11021
11022    #[gpui::test]
11023    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11024        init_test(cx);
11025
11026        let fs = FakeFs::new(cx.background_executor.clone());
11027        let project = Project::test(fs, [], cx).await;
11028        let (workspace, cx) =
11029            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11030        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11031
11032        let dirty_regular_buffer = cx.new(|cx| {
11033            TestItem::new(cx)
11034                .with_dirty(true)
11035                .with_label("1.txt")
11036                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11037        });
11038        let dirty_regular_buffer_2 = cx.new(|cx| {
11039            TestItem::new(cx)
11040                .with_dirty(true)
11041                .with_label("2.txt")
11042                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11043        });
11044        let dirty_multi_buffer_with_both = cx.new(|cx| {
11045            TestItem::new(cx)
11046                .with_dirty(true)
11047                .with_buffer_kind(ItemBufferKind::Multibuffer)
11048                .with_label("Fake Project Search")
11049                .with_project_items(&[
11050                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11051                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11052                ])
11053        });
11054        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11055        workspace.update_in(cx, |workspace, window, cx| {
11056            workspace.add_item(
11057                pane.clone(),
11058                Box::new(dirty_regular_buffer.clone()),
11059                None,
11060                false,
11061                false,
11062                window,
11063                cx,
11064            );
11065            workspace.add_item(
11066                pane.clone(),
11067                Box::new(dirty_regular_buffer_2.clone()),
11068                None,
11069                false,
11070                false,
11071                window,
11072                cx,
11073            );
11074            workspace.add_item(
11075                pane.clone(),
11076                Box::new(dirty_multi_buffer_with_both.clone()),
11077                None,
11078                false,
11079                false,
11080                window,
11081                cx,
11082            );
11083        });
11084
11085        pane.update_in(cx, |pane, window, cx| {
11086            pane.activate_item(2, true, true, window, cx);
11087            assert_eq!(
11088                pane.active_item().unwrap().item_id(),
11089                multi_buffer_with_both_files_id,
11090                "Should select the multi buffer in the pane"
11091            );
11092        });
11093        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11094            pane.close_other_items(
11095                &CloseOtherItems {
11096                    save_intent: Some(SaveIntent::Save),
11097                    close_pinned: true,
11098                },
11099                None,
11100                window,
11101                cx,
11102            )
11103        });
11104        cx.background_executor.run_until_parked();
11105        assert!(!cx.has_pending_prompt());
11106        close_all_but_multi_buffer_task
11107            .await
11108            .expect("Closing all buffers but the multi buffer failed");
11109        pane.update(cx, |pane, cx| {
11110            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11111            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11112            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11113            assert_eq!(pane.items_len(), 1);
11114            assert_eq!(
11115                pane.active_item().unwrap().item_id(),
11116                multi_buffer_with_both_files_id,
11117                "Should have only the multi buffer left in the pane"
11118            );
11119            assert!(
11120                dirty_multi_buffer_with_both.read(cx).is_dirty,
11121                "The multi buffer containing the unsaved buffer should still be dirty"
11122            );
11123        });
11124
11125        dirty_regular_buffer.update(cx, |buffer, cx| {
11126            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11127        });
11128
11129        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11130            pane.close_active_item(
11131                &CloseActiveItem {
11132                    save_intent: Some(SaveIntent::Close),
11133                    close_pinned: false,
11134                },
11135                window,
11136                cx,
11137            )
11138        });
11139        cx.background_executor.run_until_parked();
11140        assert!(
11141            cx.has_pending_prompt(),
11142            "Dirty multi buffer should prompt a save dialog"
11143        );
11144        cx.simulate_prompt_answer("Save");
11145        cx.background_executor.run_until_parked();
11146        close_multi_buffer_task
11147            .await
11148            .expect("Closing the multi buffer failed");
11149        pane.update(cx, |pane, cx| {
11150            assert_eq!(
11151                dirty_multi_buffer_with_both.read(cx).save_count,
11152                1,
11153                "Multi buffer item should get be saved"
11154            );
11155            // Test impl does not save inner items, so we do not assert them
11156            assert_eq!(
11157                pane.items_len(),
11158                0,
11159                "No more items should be left in the pane"
11160            );
11161            assert!(pane.active_item().is_none());
11162        });
11163    }
11164
11165    #[gpui::test]
11166    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11167        cx: &mut TestAppContext,
11168    ) {
11169        init_test(cx);
11170
11171        let fs = FakeFs::new(cx.background_executor.clone());
11172        let project = Project::test(fs, [], cx).await;
11173        let (workspace, cx) =
11174            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11175        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11176
11177        let dirty_regular_buffer = cx.new(|cx| {
11178            TestItem::new(cx)
11179                .with_dirty(true)
11180                .with_label("1.txt")
11181                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11182        });
11183        let dirty_regular_buffer_2 = cx.new(|cx| {
11184            TestItem::new(cx)
11185                .with_dirty(true)
11186                .with_label("2.txt")
11187                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11188        });
11189        let clear_regular_buffer = cx.new(|cx| {
11190            TestItem::new(cx)
11191                .with_label("3.txt")
11192                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11193        });
11194
11195        let dirty_multi_buffer_with_both = cx.new(|cx| {
11196            TestItem::new(cx)
11197                .with_dirty(true)
11198                .with_buffer_kind(ItemBufferKind::Multibuffer)
11199                .with_label("Fake Project Search")
11200                .with_project_items(&[
11201                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11202                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11203                    clear_regular_buffer.read(cx).project_items[0].clone(),
11204                ])
11205        });
11206        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11207        workspace.update_in(cx, |workspace, window, cx| {
11208            workspace.add_item(
11209                pane.clone(),
11210                Box::new(dirty_regular_buffer.clone()),
11211                None,
11212                false,
11213                false,
11214                window,
11215                cx,
11216            );
11217            workspace.add_item(
11218                pane.clone(),
11219                Box::new(dirty_multi_buffer_with_both.clone()),
11220                None,
11221                false,
11222                false,
11223                window,
11224                cx,
11225            );
11226        });
11227
11228        pane.update_in(cx, |pane, window, cx| {
11229            pane.activate_item(1, true, true, window, cx);
11230            assert_eq!(
11231                pane.active_item().unwrap().item_id(),
11232                multi_buffer_with_both_files_id,
11233                "Should select the multi buffer in the pane"
11234            );
11235        });
11236        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11237            pane.close_active_item(
11238                &CloseActiveItem {
11239                    save_intent: None,
11240                    close_pinned: false,
11241                },
11242                window,
11243                cx,
11244            )
11245        });
11246        cx.background_executor.run_until_parked();
11247        assert!(
11248            cx.has_pending_prompt(),
11249            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11250        );
11251    }
11252
11253    /// Tests that when `close_on_file_delete` is enabled, files are automatically
11254    /// closed when they are deleted from disk.
11255    #[gpui::test]
11256    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11257        init_test(cx);
11258
11259        // Enable the close_on_disk_deletion setting
11260        cx.update_global(|store: &mut SettingsStore, cx| {
11261            store.update_user_settings(cx, |settings| {
11262                settings.workspace.close_on_file_delete = Some(true);
11263            });
11264        });
11265
11266        let fs = FakeFs::new(cx.background_executor.clone());
11267        let project = Project::test(fs, [], cx).await;
11268        let (workspace, cx) =
11269            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11270        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11271
11272        // Create a test item that simulates a file
11273        let item = cx.new(|cx| {
11274            TestItem::new(cx)
11275                .with_label("test.txt")
11276                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11277        });
11278
11279        // Add item to workspace
11280        workspace.update_in(cx, |workspace, window, cx| {
11281            workspace.add_item(
11282                pane.clone(),
11283                Box::new(item.clone()),
11284                None,
11285                false,
11286                false,
11287                window,
11288                cx,
11289            );
11290        });
11291
11292        // Verify the item is in the pane
11293        pane.read_with(cx, |pane, _| {
11294            assert_eq!(pane.items().count(), 1);
11295        });
11296
11297        // Simulate file deletion by setting the item's deleted state
11298        item.update(cx, |item, _| {
11299            item.set_has_deleted_file(true);
11300        });
11301
11302        // Emit UpdateTab event to trigger the close behavior
11303        cx.run_until_parked();
11304        item.update(cx, |_, cx| {
11305            cx.emit(ItemEvent::UpdateTab);
11306        });
11307
11308        // Allow the close operation to complete
11309        cx.run_until_parked();
11310
11311        // Verify the item was automatically closed
11312        pane.read_with(cx, |pane, _| {
11313            assert_eq!(
11314                pane.items().count(),
11315                0,
11316                "Item should be automatically closed when file is deleted"
11317            );
11318        });
11319    }
11320
11321    /// Tests that when `close_on_file_delete` is disabled (default), files remain
11322    /// open with a strikethrough when they are deleted from disk.
11323    #[gpui::test]
11324    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11325        init_test(cx);
11326
11327        // Ensure close_on_disk_deletion is disabled (default)
11328        cx.update_global(|store: &mut SettingsStore, cx| {
11329            store.update_user_settings(cx, |settings| {
11330                settings.workspace.close_on_file_delete = Some(false);
11331            });
11332        });
11333
11334        let fs = FakeFs::new(cx.background_executor.clone());
11335        let project = Project::test(fs, [], cx).await;
11336        let (workspace, cx) =
11337            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11338        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11339
11340        // Create a test item that simulates a file
11341        let item = cx.new(|cx| {
11342            TestItem::new(cx)
11343                .with_label("test.txt")
11344                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11345        });
11346
11347        // Add item to workspace
11348        workspace.update_in(cx, |workspace, window, cx| {
11349            workspace.add_item(
11350                pane.clone(),
11351                Box::new(item.clone()),
11352                None,
11353                false,
11354                false,
11355                window,
11356                cx,
11357            );
11358        });
11359
11360        // Verify the item is in the pane
11361        pane.read_with(cx, |pane, _| {
11362            assert_eq!(pane.items().count(), 1);
11363        });
11364
11365        // Simulate file deletion
11366        item.update(cx, |item, _| {
11367            item.set_has_deleted_file(true);
11368        });
11369
11370        // Emit UpdateTab event
11371        cx.run_until_parked();
11372        item.update(cx, |_, cx| {
11373            cx.emit(ItemEvent::UpdateTab);
11374        });
11375
11376        // Allow any potential close operation to complete
11377        cx.run_until_parked();
11378
11379        // Verify the item remains open (with strikethrough)
11380        pane.read_with(cx, |pane, _| {
11381            assert_eq!(
11382                pane.items().count(),
11383                1,
11384                "Item should remain open when close_on_disk_deletion is disabled"
11385            );
11386        });
11387
11388        // Verify the item shows as deleted
11389        item.read_with(cx, |item, _| {
11390            assert!(
11391                item.has_deleted_file,
11392                "Item should be marked as having deleted file"
11393            );
11394        });
11395    }
11396
11397    /// Tests that dirty files are not automatically closed when deleted from disk,
11398    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11399    /// unsaved changes without being prompted.
11400    #[gpui::test]
11401    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11402        init_test(cx);
11403
11404        // Enable the close_on_file_delete setting
11405        cx.update_global(|store: &mut SettingsStore, cx| {
11406            store.update_user_settings(cx, |settings| {
11407                settings.workspace.close_on_file_delete = Some(true);
11408            });
11409        });
11410
11411        let fs = FakeFs::new(cx.background_executor.clone());
11412        let project = Project::test(fs, [], cx).await;
11413        let (workspace, cx) =
11414            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11415        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11416
11417        // Create a dirty test item
11418        let item = cx.new(|cx| {
11419            TestItem::new(cx)
11420                .with_dirty(true)
11421                .with_label("test.txt")
11422                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11423        });
11424
11425        // Add item to workspace
11426        workspace.update_in(cx, |workspace, window, cx| {
11427            workspace.add_item(
11428                pane.clone(),
11429                Box::new(item.clone()),
11430                None,
11431                false,
11432                false,
11433                window,
11434                cx,
11435            );
11436        });
11437
11438        // Simulate file deletion
11439        item.update(cx, |item, _| {
11440            item.set_has_deleted_file(true);
11441        });
11442
11443        // Emit UpdateTab event to trigger the close behavior
11444        cx.run_until_parked();
11445        item.update(cx, |_, cx| {
11446            cx.emit(ItemEvent::UpdateTab);
11447        });
11448
11449        // Allow any potential close operation to complete
11450        cx.run_until_parked();
11451
11452        // Verify the item remains open (dirty files are not auto-closed)
11453        pane.read_with(cx, |pane, _| {
11454            assert_eq!(
11455                pane.items().count(),
11456                1,
11457                "Dirty items should not be automatically closed even when file is deleted"
11458            );
11459        });
11460
11461        // Verify the item is marked as deleted and still dirty
11462        item.read_with(cx, |item, _| {
11463            assert!(
11464                item.has_deleted_file,
11465                "Item should be marked as having deleted file"
11466            );
11467            assert!(item.is_dirty, "Item should still be dirty");
11468        });
11469    }
11470
11471    /// Tests that navigation history is cleaned up when files are auto-closed
11472    /// due to deletion from disk.
11473    #[gpui::test]
11474    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11475        init_test(cx);
11476
11477        // Enable the close_on_file_delete setting
11478        cx.update_global(|store: &mut SettingsStore, cx| {
11479            store.update_user_settings(cx, |settings| {
11480                settings.workspace.close_on_file_delete = Some(true);
11481            });
11482        });
11483
11484        let fs = FakeFs::new(cx.background_executor.clone());
11485        let project = Project::test(fs, [], cx).await;
11486        let (workspace, cx) =
11487            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11488        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11489
11490        // Create test items
11491        let item1 = cx.new(|cx| {
11492            TestItem::new(cx)
11493                .with_label("test1.txt")
11494                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11495        });
11496        let item1_id = item1.item_id();
11497
11498        let item2 = cx.new(|cx| {
11499            TestItem::new(cx)
11500                .with_label("test2.txt")
11501                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11502        });
11503
11504        // Add items to workspace
11505        workspace.update_in(cx, |workspace, window, cx| {
11506            workspace.add_item(
11507                pane.clone(),
11508                Box::new(item1.clone()),
11509                None,
11510                false,
11511                false,
11512                window,
11513                cx,
11514            );
11515            workspace.add_item(
11516                pane.clone(),
11517                Box::new(item2.clone()),
11518                None,
11519                false,
11520                false,
11521                window,
11522                cx,
11523            );
11524        });
11525
11526        // Activate item1 to ensure it gets navigation entries
11527        pane.update_in(cx, |pane, window, cx| {
11528            pane.activate_item(0, true, true, window, cx);
11529        });
11530
11531        // Switch to item2 and back to create navigation history
11532        pane.update_in(cx, |pane, window, cx| {
11533            pane.activate_item(1, true, true, window, cx);
11534        });
11535        cx.run_until_parked();
11536
11537        pane.update_in(cx, |pane, window, cx| {
11538            pane.activate_item(0, true, true, window, cx);
11539        });
11540        cx.run_until_parked();
11541
11542        // Simulate file deletion for item1
11543        item1.update(cx, |item, _| {
11544            item.set_has_deleted_file(true);
11545        });
11546
11547        // Emit UpdateTab event to trigger the close behavior
11548        item1.update(cx, |_, cx| {
11549            cx.emit(ItemEvent::UpdateTab);
11550        });
11551        cx.run_until_parked();
11552
11553        // Verify item1 was closed
11554        pane.read_with(cx, |pane, _| {
11555            assert_eq!(
11556                pane.items().count(),
11557                1,
11558                "Should have 1 item remaining after auto-close"
11559            );
11560        });
11561
11562        // Check navigation history after close
11563        let has_item = pane.read_with(cx, |pane, cx| {
11564            let mut has_item = false;
11565            pane.nav_history().for_each_entry(cx, |entry, _| {
11566                if entry.item.id() == item1_id {
11567                    has_item = true;
11568                }
11569            });
11570            has_item
11571        });
11572
11573        assert!(
11574            !has_item,
11575            "Navigation history should not contain closed item entries"
11576        );
11577    }
11578
11579    #[gpui::test]
11580    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11581        cx: &mut TestAppContext,
11582    ) {
11583        init_test(cx);
11584
11585        let fs = FakeFs::new(cx.background_executor.clone());
11586        let project = Project::test(fs, [], cx).await;
11587        let (workspace, cx) =
11588            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11589        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11590
11591        let dirty_regular_buffer = cx.new(|cx| {
11592            TestItem::new(cx)
11593                .with_dirty(true)
11594                .with_label("1.txt")
11595                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11596        });
11597        let dirty_regular_buffer_2 = cx.new(|cx| {
11598            TestItem::new(cx)
11599                .with_dirty(true)
11600                .with_label("2.txt")
11601                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11602        });
11603        let clear_regular_buffer = cx.new(|cx| {
11604            TestItem::new(cx)
11605                .with_label("3.txt")
11606                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11607        });
11608
11609        let dirty_multi_buffer = cx.new(|cx| {
11610            TestItem::new(cx)
11611                .with_dirty(true)
11612                .with_buffer_kind(ItemBufferKind::Multibuffer)
11613                .with_label("Fake Project Search")
11614                .with_project_items(&[
11615                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11616                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11617                    clear_regular_buffer.read(cx).project_items[0].clone(),
11618                ])
11619        });
11620        workspace.update_in(cx, |workspace, window, cx| {
11621            workspace.add_item(
11622                pane.clone(),
11623                Box::new(dirty_regular_buffer.clone()),
11624                None,
11625                false,
11626                false,
11627                window,
11628                cx,
11629            );
11630            workspace.add_item(
11631                pane.clone(),
11632                Box::new(dirty_regular_buffer_2.clone()),
11633                None,
11634                false,
11635                false,
11636                window,
11637                cx,
11638            );
11639            workspace.add_item(
11640                pane.clone(),
11641                Box::new(dirty_multi_buffer.clone()),
11642                None,
11643                false,
11644                false,
11645                window,
11646                cx,
11647            );
11648        });
11649
11650        pane.update_in(cx, |pane, window, cx| {
11651            pane.activate_item(2, true, true, window, cx);
11652            assert_eq!(
11653                pane.active_item().unwrap().item_id(),
11654                dirty_multi_buffer.item_id(),
11655                "Should select the multi buffer in the pane"
11656            );
11657        });
11658        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11659            pane.close_active_item(
11660                &CloseActiveItem {
11661                    save_intent: None,
11662                    close_pinned: false,
11663                },
11664                window,
11665                cx,
11666            )
11667        });
11668        cx.background_executor.run_until_parked();
11669        assert!(
11670            !cx.has_pending_prompt(),
11671            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11672        );
11673        close_multi_buffer_task
11674            .await
11675            .expect("Closing multi buffer failed");
11676        pane.update(cx, |pane, cx| {
11677            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11678            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11679            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11680            assert_eq!(
11681                pane.items()
11682                    .map(|item| item.item_id())
11683                    .sorted()
11684                    .collect::<Vec<_>>(),
11685                vec![
11686                    dirty_regular_buffer.item_id(),
11687                    dirty_regular_buffer_2.item_id(),
11688                ],
11689                "Should have no multi buffer left in the pane"
11690            );
11691            assert!(dirty_regular_buffer.read(cx).is_dirty);
11692            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11693        });
11694    }
11695
11696    #[gpui::test]
11697    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11698        init_test(cx);
11699        let fs = FakeFs::new(cx.executor());
11700        let project = Project::test(fs, [], cx).await;
11701        let (workspace, cx) =
11702            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11703
11704        // Add a new panel to the right dock, opening the dock and setting the
11705        // focus to the new panel.
11706        let panel = workspace.update_in(cx, |workspace, window, cx| {
11707            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11708            workspace.add_panel(panel.clone(), window, cx);
11709
11710            workspace
11711                .right_dock()
11712                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11713
11714            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11715
11716            panel
11717        });
11718
11719        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11720        // panel to the next valid position which, in this case, is the left
11721        // dock.
11722        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11723        workspace.update(cx, |workspace, cx| {
11724            assert!(workspace.left_dock().read(cx).is_open());
11725            assert_eq!(panel.read(cx).position, DockPosition::Left);
11726        });
11727
11728        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11729        // panel to the next valid position which, in this case, is the bottom
11730        // dock.
11731        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11732        workspace.update(cx, |workspace, cx| {
11733            assert!(workspace.bottom_dock().read(cx).is_open());
11734            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
11735        });
11736
11737        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
11738        // around moving the panel to its initial position, the right dock.
11739        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11740        workspace.update(cx, |workspace, cx| {
11741            assert!(workspace.right_dock().read(cx).is_open());
11742            assert_eq!(panel.read(cx).position, DockPosition::Right);
11743        });
11744
11745        // Remove focus from the panel, ensuring that, if the panel is not
11746        // focused, the `MoveFocusedPanelToNextPosition` action does not update
11747        // the panel's position, so the panel is still in the right dock.
11748        workspace.update_in(cx, |workspace, window, cx| {
11749            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11750        });
11751
11752        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11753        workspace.update(cx, |workspace, cx| {
11754            assert!(workspace.right_dock().read(cx).is_open());
11755            assert_eq!(panel.read(cx).position, DockPosition::Right);
11756        });
11757    }
11758
11759    #[gpui::test]
11760    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
11761        init_test(cx);
11762
11763        let fs = FakeFs::new(cx.executor());
11764        let project = Project::test(fs, [], cx).await;
11765        let (workspace, cx) =
11766            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11767
11768        let item_1 = cx.new(|cx| {
11769            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11770        });
11771        workspace.update_in(cx, |workspace, window, cx| {
11772            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11773            workspace.move_item_to_pane_in_direction(
11774                &MoveItemToPaneInDirection {
11775                    direction: SplitDirection::Right,
11776                    focus: true,
11777                    clone: false,
11778                },
11779                window,
11780                cx,
11781            );
11782            workspace.move_item_to_pane_at_index(
11783                &MoveItemToPane {
11784                    destination: 3,
11785                    focus: true,
11786                    clone: false,
11787                },
11788                window,
11789                cx,
11790            );
11791
11792            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
11793            assert_eq!(
11794                pane_items_paths(&workspace.active_pane, cx),
11795                vec!["first.txt".to_string()],
11796                "Single item was not moved anywhere"
11797            );
11798        });
11799
11800        let item_2 = cx.new(|cx| {
11801            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
11802        });
11803        workspace.update_in(cx, |workspace, window, cx| {
11804            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
11805            assert_eq!(
11806                pane_items_paths(&workspace.panes[0], cx),
11807                vec!["first.txt".to_string(), "second.txt".to_string()],
11808            );
11809            workspace.move_item_to_pane_in_direction(
11810                &MoveItemToPaneInDirection {
11811                    direction: SplitDirection::Right,
11812                    focus: true,
11813                    clone: false,
11814                },
11815                window,
11816                cx,
11817            );
11818
11819            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
11820            assert_eq!(
11821                pane_items_paths(&workspace.panes[0], cx),
11822                vec!["first.txt".to_string()],
11823                "After moving, one item should be left in the original pane"
11824            );
11825            assert_eq!(
11826                pane_items_paths(&workspace.panes[1], cx),
11827                vec!["second.txt".to_string()],
11828                "New item should have been moved to the new pane"
11829            );
11830        });
11831
11832        let item_3 = cx.new(|cx| {
11833            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
11834        });
11835        workspace.update_in(cx, |workspace, window, cx| {
11836            let original_pane = workspace.panes[0].clone();
11837            workspace.set_active_pane(&original_pane, window, cx);
11838            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
11839            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
11840            assert_eq!(
11841                pane_items_paths(&workspace.active_pane, cx),
11842                vec!["first.txt".to_string(), "third.txt".to_string()],
11843                "New pane should be ready to move one item out"
11844            );
11845
11846            workspace.move_item_to_pane_at_index(
11847                &MoveItemToPane {
11848                    destination: 3,
11849                    focus: true,
11850                    clone: false,
11851                },
11852                window,
11853                cx,
11854            );
11855            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11856            assert_eq!(
11857                pane_items_paths(&workspace.active_pane, cx),
11858                vec!["first.txt".to_string()],
11859                "After moving, one item should be left in the original pane"
11860            );
11861            assert_eq!(
11862                pane_items_paths(&workspace.panes[1], cx),
11863                vec!["second.txt".to_string()],
11864                "Previously created pane should be unchanged"
11865            );
11866            assert_eq!(
11867                pane_items_paths(&workspace.panes[2], cx),
11868                vec!["third.txt".to_string()],
11869                "New item should have been moved to the new pane"
11870            );
11871        });
11872    }
11873
11874    #[gpui::test]
11875    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11876        init_test(cx);
11877
11878        let fs = FakeFs::new(cx.executor());
11879        let project = Project::test(fs, [], cx).await;
11880        let (workspace, cx) =
11881            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11882
11883        let item_1 = cx.new(|cx| {
11884            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11885        });
11886        workspace.update_in(cx, |workspace, window, cx| {
11887            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11888            workspace.move_item_to_pane_in_direction(
11889                &MoveItemToPaneInDirection {
11890                    direction: SplitDirection::Right,
11891                    focus: true,
11892                    clone: true,
11893                },
11894                window,
11895                cx,
11896            );
11897        });
11898        cx.run_until_parked();
11899        workspace.update_in(cx, |workspace, window, cx| {
11900            workspace.move_item_to_pane_at_index(
11901                &MoveItemToPane {
11902                    destination: 3,
11903                    focus: true,
11904                    clone: true,
11905                },
11906                window,
11907                cx,
11908            );
11909        });
11910        cx.run_until_parked();
11911
11912        workspace.update(cx, |workspace, cx| {
11913            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11914            for pane in workspace.panes() {
11915                assert_eq!(
11916                    pane_items_paths(pane, cx),
11917                    vec!["first.txt".to_string()],
11918                    "Single item exists in all panes"
11919                );
11920            }
11921        });
11922
11923        // verify that the active pane has been updated after waiting for the
11924        // pane focus event to fire and resolve
11925        workspace.read_with(cx, |workspace, _app| {
11926            assert_eq!(
11927                workspace.active_pane(),
11928                &workspace.panes[2],
11929                "The third pane should be the active one: {:?}",
11930                workspace.panes
11931            );
11932        })
11933    }
11934
11935    mod register_project_item_tests {
11936
11937        use super::*;
11938
11939        // View
11940        struct TestPngItemView {
11941            focus_handle: FocusHandle,
11942        }
11943        // Model
11944        struct TestPngItem {}
11945
11946        impl project::ProjectItem for TestPngItem {
11947            fn try_open(
11948                _project: &Entity<Project>,
11949                path: &ProjectPath,
11950                cx: &mut App,
11951            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11952                if path.path.extension().unwrap() == "png" {
11953                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
11954                } else {
11955                    None
11956                }
11957            }
11958
11959            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11960                None
11961            }
11962
11963            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11964                None
11965            }
11966
11967            fn is_dirty(&self) -> bool {
11968                false
11969            }
11970        }
11971
11972        impl Item for TestPngItemView {
11973            type Event = ();
11974            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11975                "".into()
11976            }
11977        }
11978        impl EventEmitter<()> for TestPngItemView {}
11979        impl Focusable for TestPngItemView {
11980            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11981                self.focus_handle.clone()
11982            }
11983        }
11984
11985        impl Render for TestPngItemView {
11986            fn render(
11987                &mut self,
11988                _window: &mut Window,
11989                _cx: &mut Context<Self>,
11990            ) -> impl IntoElement {
11991                Empty
11992            }
11993        }
11994
11995        impl ProjectItem for TestPngItemView {
11996            type Item = TestPngItem;
11997
11998            fn for_project_item(
11999                _project: Entity<Project>,
12000                _pane: Option<&Pane>,
12001                _item: Entity<Self::Item>,
12002                _: &mut Window,
12003                cx: &mut Context<Self>,
12004            ) -> Self
12005            where
12006                Self: Sized,
12007            {
12008                Self {
12009                    focus_handle: cx.focus_handle(),
12010                }
12011            }
12012        }
12013
12014        // View
12015        struct TestIpynbItemView {
12016            focus_handle: FocusHandle,
12017        }
12018        // Model
12019        struct TestIpynbItem {}
12020
12021        impl project::ProjectItem for TestIpynbItem {
12022            fn try_open(
12023                _project: &Entity<Project>,
12024                path: &ProjectPath,
12025                cx: &mut App,
12026            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12027                if path.path.extension().unwrap() == "ipynb" {
12028                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12029                } else {
12030                    None
12031                }
12032            }
12033
12034            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12035                None
12036            }
12037
12038            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12039                None
12040            }
12041
12042            fn is_dirty(&self) -> bool {
12043                false
12044            }
12045        }
12046
12047        impl Item for TestIpynbItemView {
12048            type Event = ();
12049            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12050                "".into()
12051            }
12052        }
12053        impl EventEmitter<()> for TestIpynbItemView {}
12054        impl Focusable for TestIpynbItemView {
12055            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12056                self.focus_handle.clone()
12057            }
12058        }
12059
12060        impl Render for TestIpynbItemView {
12061            fn render(
12062                &mut self,
12063                _window: &mut Window,
12064                _cx: &mut Context<Self>,
12065            ) -> impl IntoElement {
12066                Empty
12067            }
12068        }
12069
12070        impl ProjectItem for TestIpynbItemView {
12071            type Item = TestIpynbItem;
12072
12073            fn for_project_item(
12074                _project: Entity<Project>,
12075                _pane: Option<&Pane>,
12076                _item: Entity<Self::Item>,
12077                _: &mut Window,
12078                cx: &mut Context<Self>,
12079            ) -> Self
12080            where
12081                Self: Sized,
12082            {
12083                Self {
12084                    focus_handle: cx.focus_handle(),
12085                }
12086            }
12087        }
12088
12089        struct TestAlternatePngItemView {
12090            focus_handle: FocusHandle,
12091        }
12092
12093        impl Item for TestAlternatePngItemView {
12094            type Event = ();
12095            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12096                "".into()
12097            }
12098        }
12099
12100        impl EventEmitter<()> for TestAlternatePngItemView {}
12101        impl Focusable for TestAlternatePngItemView {
12102            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12103                self.focus_handle.clone()
12104            }
12105        }
12106
12107        impl Render for TestAlternatePngItemView {
12108            fn render(
12109                &mut self,
12110                _window: &mut Window,
12111                _cx: &mut Context<Self>,
12112            ) -> impl IntoElement {
12113                Empty
12114            }
12115        }
12116
12117        impl ProjectItem for TestAlternatePngItemView {
12118            type Item = TestPngItem;
12119
12120            fn for_project_item(
12121                _project: Entity<Project>,
12122                _pane: Option<&Pane>,
12123                _item: Entity<Self::Item>,
12124                _: &mut Window,
12125                cx: &mut Context<Self>,
12126            ) -> Self
12127            where
12128                Self: Sized,
12129            {
12130                Self {
12131                    focus_handle: cx.focus_handle(),
12132                }
12133            }
12134        }
12135
12136        #[gpui::test]
12137        async fn test_register_project_item(cx: &mut TestAppContext) {
12138            init_test(cx);
12139
12140            cx.update(|cx| {
12141                register_project_item::<TestPngItemView>(cx);
12142                register_project_item::<TestIpynbItemView>(cx);
12143            });
12144
12145            let fs = FakeFs::new(cx.executor());
12146            fs.insert_tree(
12147                "/root1",
12148                json!({
12149                    "one.png": "BINARYDATAHERE",
12150                    "two.ipynb": "{ totally a notebook }",
12151                    "three.txt": "editing text, sure why not?"
12152                }),
12153            )
12154            .await;
12155
12156            let project = Project::test(fs, ["root1".as_ref()], cx).await;
12157            let (workspace, cx) =
12158                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12159
12160            let worktree_id = project.update(cx, |project, cx| {
12161                project.worktrees(cx).next().unwrap().read(cx).id()
12162            });
12163
12164            let handle = workspace
12165                .update_in(cx, |workspace, window, cx| {
12166                    let project_path = (worktree_id, rel_path("one.png"));
12167                    workspace.open_path(project_path, None, true, window, cx)
12168                })
12169                .await
12170                .unwrap();
12171
12172            // Now we can check if the handle we got back errored or not
12173            assert_eq!(
12174                handle.to_any_view().entity_type(),
12175                TypeId::of::<TestPngItemView>()
12176            );
12177
12178            let handle = workspace
12179                .update_in(cx, |workspace, window, cx| {
12180                    let project_path = (worktree_id, rel_path("two.ipynb"));
12181                    workspace.open_path(project_path, None, true, window, cx)
12182                })
12183                .await
12184                .unwrap();
12185
12186            assert_eq!(
12187                handle.to_any_view().entity_type(),
12188                TypeId::of::<TestIpynbItemView>()
12189            );
12190
12191            let handle = workspace
12192                .update_in(cx, |workspace, window, cx| {
12193                    let project_path = (worktree_id, rel_path("three.txt"));
12194                    workspace.open_path(project_path, None, true, window, cx)
12195                })
12196                .await;
12197            assert!(handle.is_err());
12198        }
12199
12200        #[gpui::test]
12201        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12202            init_test(cx);
12203
12204            cx.update(|cx| {
12205                register_project_item::<TestPngItemView>(cx);
12206                register_project_item::<TestAlternatePngItemView>(cx);
12207            });
12208
12209            let fs = FakeFs::new(cx.executor());
12210            fs.insert_tree(
12211                "/root1",
12212                json!({
12213                    "one.png": "BINARYDATAHERE",
12214                    "two.ipynb": "{ totally a notebook }",
12215                    "three.txt": "editing text, sure why not?"
12216                }),
12217            )
12218            .await;
12219            let project = Project::test(fs, ["root1".as_ref()], cx).await;
12220            let (workspace, cx) =
12221                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12222            let worktree_id = project.update(cx, |project, cx| {
12223                project.worktrees(cx).next().unwrap().read(cx).id()
12224            });
12225
12226            let handle = workspace
12227                .update_in(cx, |workspace, window, cx| {
12228                    let project_path = (worktree_id, rel_path("one.png"));
12229                    workspace.open_path(project_path, None, true, window, cx)
12230                })
12231                .await
12232                .unwrap();
12233
12234            // This _must_ be the second item registered
12235            assert_eq!(
12236                handle.to_any_view().entity_type(),
12237                TypeId::of::<TestAlternatePngItemView>()
12238            );
12239
12240            let handle = workspace
12241                .update_in(cx, |workspace, window, cx| {
12242                    let project_path = (worktree_id, rel_path("three.txt"));
12243                    workspace.open_path(project_path, None, true, window, cx)
12244                })
12245                .await;
12246            assert!(handle.is_err());
12247        }
12248    }
12249
12250    #[gpui::test]
12251    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12252        init_test(cx);
12253
12254        let fs = FakeFs::new(cx.executor());
12255        let project = Project::test(fs, [], cx).await;
12256        let (workspace, _cx) =
12257            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12258
12259        // Test with status bar shown (default)
12260        workspace.read_with(cx, |workspace, cx| {
12261            let visible = workspace.status_bar_visible(cx);
12262            assert!(visible, "Status bar should be visible by default");
12263        });
12264
12265        // Test with status bar hidden
12266        cx.update_global(|store: &mut SettingsStore, cx| {
12267            store.update_user_settings(cx, |settings| {
12268                settings.status_bar.get_or_insert_default().show = Some(false);
12269            });
12270        });
12271
12272        workspace.read_with(cx, |workspace, cx| {
12273            let visible = workspace.status_bar_visible(cx);
12274            assert!(!visible, "Status bar should be hidden when show is false");
12275        });
12276
12277        // Test with status bar shown explicitly
12278        cx.update_global(|store: &mut SettingsStore, cx| {
12279            store.update_user_settings(cx, |settings| {
12280                settings.status_bar.get_or_insert_default().show = Some(true);
12281            });
12282        });
12283
12284        workspace.read_with(cx, |workspace, cx| {
12285            let visible = workspace.status_bar_visible(cx);
12286            assert!(visible, "Status bar should be visible when show is true");
12287        });
12288    }
12289
12290    #[gpui::test]
12291    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12292        init_test(cx);
12293
12294        let fs = FakeFs::new(cx.executor());
12295        let project = Project::test(fs, [], cx).await;
12296        let (workspace, cx) =
12297            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12298        let panel = workspace.update_in(cx, |workspace, window, cx| {
12299            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12300            workspace.add_panel(panel.clone(), window, cx);
12301
12302            workspace
12303                .right_dock()
12304                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12305
12306            panel
12307        });
12308
12309        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12310        let item_a = cx.new(TestItem::new);
12311        let item_b = cx.new(TestItem::new);
12312        let item_a_id = item_a.entity_id();
12313        let item_b_id = item_b.entity_id();
12314
12315        pane.update_in(cx, |pane, window, cx| {
12316            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12317            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12318        });
12319
12320        pane.read_with(cx, |pane, _| {
12321            assert_eq!(pane.items_len(), 2);
12322            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12323        });
12324
12325        workspace.update_in(cx, |workspace, window, cx| {
12326            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12327        });
12328
12329        workspace.update_in(cx, |_, window, cx| {
12330            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12331        });
12332
12333        // Assert that the `pane::CloseActiveItem` action is handled at the
12334        // workspace level when one of the dock panels is focused and, in that
12335        // case, the center pane's active item is closed but the focus is not
12336        // moved.
12337        cx.dispatch_action(pane::CloseActiveItem::default());
12338        cx.run_until_parked();
12339
12340        pane.read_with(cx, |pane, _| {
12341            assert_eq!(pane.items_len(), 1);
12342            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12343        });
12344
12345        workspace.update_in(cx, |workspace, window, cx| {
12346            assert!(workspace.right_dock().read(cx).is_open());
12347            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12348        });
12349    }
12350
12351    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
12352        pane.read(cx)
12353            .items()
12354            .flat_map(|item| {
12355                item.project_paths(cx)
12356                    .into_iter()
12357                    .map(|path| path.path.display(PathStyle::local()).into_owned())
12358            })
12359            .collect()
12360    }
12361
12362    pub fn init_test(cx: &mut TestAppContext) {
12363        cx.update(|cx| {
12364            let settings_store = SettingsStore::test(cx);
12365            cx.set_global(settings_store);
12366            theme::init(theme::LoadThemes::JustBase, cx);
12367        });
12368    }
12369
12370    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
12371        let item = TestProjectItem::new(id, path, cx);
12372        item.update(cx, |item, _| {
12373            item.is_dirty = true;
12374        });
12375        item
12376    }
12377}