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