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