workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6mod multi_workspace;
    7pub mod notifications;
    8pub mod pane;
    9pub mod pane_group;
   10mod path_list;
   11mod persistence;
   12pub mod searchable;
   13mod security_modal;
   14pub mod shared_screen;
   15mod status_bar;
   16pub mod tasks;
   17mod theme_preview;
   18mod toast_layer;
   19mod toolbar;
   20pub mod utility_pane;
   21pub mod welcome;
   22mod workspace_settings;
   23
   24pub use crate::notifications::NotificationFrame;
   25pub use dock::Panel;
   26pub use multi_workspace::{
   27    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
   28    NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
   29    ToggleWorkspaceSidebar,
   30};
   31pub use path_list::PathList;
   32pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   33
   34use anyhow::{Context as _, Result, anyhow};
   35use call::{ActiveCall, call_settings::CallSettings};
   36use client::{
   37    ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
   38    proto::{self, ErrorCode, PanelId, PeerId},
   39};
   40use collections::{HashMap, HashSet, hash_map};
   41use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   42use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   43use futures::{
   44    Future, FutureExt, StreamExt,
   45    channel::{
   46        mpsc::{self, UnboundedReceiver, UnboundedSender},
   47        oneshot,
   48    },
   49    future::{Shared, try_join_all},
   50};
   51use gpui::{
   52    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   53    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   54    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   55    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   56    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   57    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   58};
   59pub use history_manager::*;
   60pub use item::{
   61    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   62    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   63};
   64use itertools::Itertools;
   65use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   66pub use modal_layer::*;
   67use node_runtime::NodeRuntime;
   68use notifications::{
   69    DetachAndPromptErr, Notifications, dismiss_app_notification,
   70    simple_message_notification::MessageNotification,
   71};
   72pub use pane::*;
   73pub use pane_group::{
   74    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   75    SplitDirection,
   76};
   77use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   78pub use persistence::{
   79    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   80    model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
   81    read_serialized_multi_workspaces,
   82};
   83use postage::stream::Stream;
   84use project::{
   85    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   86    WorktreeSettings,
   87    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   88    project_settings::ProjectSettings,
   89    toolchain_store::ToolchainStoreEvent,
   90    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   91};
   92use remote::{
   93    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   94    remote_client::ConnectionIdentifier,
   95};
   96use schemars::JsonSchema;
   97use serde::Deserialize;
   98use session::AppSession;
   99use settings::{
  100    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  101};
  102use shared_screen::SharedScreen;
  103use sqlez::{
  104    bindable::{Bind, Column, StaticColumnCount},
  105    statement::Statement,
  106};
  107use status_bar::StatusBar;
  108pub use status_bar::StatusItemView;
  109use std::{
  110    any::TypeId,
  111    borrow::Cow,
  112    cell::RefCell,
  113    cmp,
  114    collections::VecDeque,
  115    env,
  116    hash::Hash,
  117    path::{Path, PathBuf},
  118    process::ExitStatus,
  119    rc::Rc,
  120    sync::{
  121        Arc, LazyLock, Weak,
  122        atomic::{AtomicBool, AtomicUsize},
  123    },
  124    time::Duration,
  125};
  126use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  127use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  128pub use toolbar::{
  129    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  130};
  131pub use ui;
  132use ui::{Window, prelude::*};
  133use util::{
  134    ResultExt, TryFutureExt,
  135    paths::{PathStyle, SanitizedPath},
  136    rel_path::RelPath,
  137    serde::default_true,
  138};
  139use uuid::Uuid;
  140pub use workspace_settings::{
  141    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  142    WorkspaceSettings,
  143};
  144use zed_actions::{Spawn, feedback::FileBugReport};
  145
  146use crate::{
  147    item::ItemBufferKind,
  148    notifications::NotificationId,
  149    utility_pane::{UTILITY_PANE_MIN_WIDTH, utility_slot_for_dock_position},
  150};
  151use crate::{
  152    persistence::{
  153        SerializedAxis,
  154        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  155    },
  156    security_modal::SecurityModal,
  157    utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
  158};
  159
  160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  161
  162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  163    env::var("ZED_WINDOW_SIZE")
  164        .ok()
  165        .as_deref()
  166        .and_then(parse_pixel_size_env_var)
  167});
  168
  169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  170    env::var("ZED_WINDOW_POSITION")
  171        .ok()
  172        .as_deref()
  173        .and_then(parse_pixel_position_env_var)
  174});
  175
  176pub trait TerminalProvider {
  177    fn spawn(
  178        &self,
  179        task: SpawnInTerminal,
  180        window: &mut Window,
  181        cx: &mut App,
  182    ) -> Task<Option<Result<ExitStatus>>>;
  183}
  184
  185pub trait DebuggerProvider {
  186    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  187    fn start_session(
  188        &self,
  189        definition: DebugScenario,
  190        task_context: SharedTaskContext,
  191        active_buffer: Option<Entity<Buffer>>,
  192        worktree_id: Option<WorktreeId>,
  193        window: &mut Window,
  194        cx: &mut App,
  195    );
  196
  197    fn spawn_task_or_modal(
  198        &self,
  199        workspace: &mut Workspace,
  200        action: &Spawn,
  201        window: &mut Window,
  202        cx: &mut Context<Workspace>,
  203    );
  204
  205    fn task_scheduled(&self, cx: &mut App);
  206    fn debug_scenario_scheduled(&self, cx: &mut App);
  207    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  208
  209    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  210}
  211
  212actions!(
  213    workspace,
  214    [
  215        /// Activates the next pane in the workspace.
  216        ActivateNextPane,
  217        /// Activates the previous pane in the workspace.
  218        ActivatePreviousPane,
  219        /// Switches to the next window.
  220        ActivateNextWindow,
  221        /// Switches to the previous window.
  222        ActivatePreviousWindow,
  223        /// Adds a folder to the current project.
  224        AddFolderToProject,
  225        /// Opens the project switcher dropdown (only visible when multiple folders are open).
  226        SwitchProject,
  227        /// Clears all notifications.
  228        ClearAllNotifications,
  229        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  230        ClearNavigationHistory,
  231        /// Closes the active dock.
  232        CloseActiveDock,
  233        /// Closes all docks.
  234        CloseAllDocks,
  235        /// Toggles all docks.
  236        ToggleAllDocks,
  237        /// Closes the current window.
  238        CloseWindow,
  239        /// Closes the current project.
  240        CloseProject,
  241        /// Opens the feedback dialog.
  242        Feedback,
  243        /// Follows the next collaborator in the session.
  244        FollowNextCollaborator,
  245        /// Moves the focused panel to the next position.
  246        MoveFocusedPanelToNextPosition,
  247        /// Creates a new file.
  248        NewFile,
  249        /// Creates a new file in a vertical split.
  250        NewFileSplitVertical,
  251        /// Creates a new file in a horizontal split.
  252        NewFileSplitHorizontal,
  253        /// Opens a new search.
  254        NewSearch,
  255        /// Opens a new window.
  256        NewWindow,
  257        /// Opens a file or directory.
  258        Open,
  259        /// Opens multiple files.
  260        OpenFiles,
  261        /// Opens the current location in terminal.
  262        OpenInTerminal,
  263        /// Opens the component preview.
  264        OpenComponentPreview,
  265        /// Reloads the active item.
  266        ReloadActiveItem,
  267        /// Resets the active dock to its default size.
  268        ResetActiveDockSize,
  269        /// Resets all open docks to their default sizes.
  270        ResetOpenDocksSize,
  271        /// Reloads the application
  272        Reload,
  273        /// Saves the current file with a new name.
  274        SaveAs,
  275        /// Saves without formatting.
  276        SaveWithoutFormat,
  277        /// Shuts down all debug adapters.
  278        ShutdownDebugAdapters,
  279        /// Suppresses the current notification.
  280        SuppressNotification,
  281        /// Toggles the bottom dock.
  282        ToggleBottomDock,
  283        /// Toggles centered layout mode.
  284        ToggleCenteredLayout,
  285        /// Toggles edit prediction feature globally for all files.
  286        ToggleEditPrediction,
  287        /// Toggles the left dock.
  288        ToggleLeftDock,
  289        /// Toggles the right dock.
  290        ToggleRightDock,
  291        /// Toggles zoom on the active pane.
  292        ToggleZoom,
  293        /// Toggles read-only mode for the active item (if supported by that item).
  294        ToggleReadOnlyFile,
  295        /// Zooms in on the active pane.
  296        ZoomIn,
  297        /// Zooms out of the active pane.
  298        ZoomOut,
  299        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  300        /// If the modal is shown already, closes it without trusting any worktree.
  301        ToggleWorktreeSecurity,
  302        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  303        /// Requires restart to take effect on already opened projects.
  304        ClearTrustedWorktrees,
  305        /// Stops following a collaborator.
  306        Unfollow,
  307        /// Restores the banner.
  308        RestoreBanner,
  309        /// Toggles expansion of the selected item.
  310        ToggleExpandItem,
  311    ]
  312);
  313
  314/// Activates a specific pane by its index.
  315#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  316#[action(namespace = workspace)]
  317pub struct ActivatePane(pub usize);
  318
  319/// Moves an item to a specific pane by index.
  320#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  321#[action(namespace = workspace)]
  322#[serde(deny_unknown_fields)]
  323pub struct MoveItemToPane {
  324    #[serde(default = "default_1")]
  325    pub destination: usize,
  326    #[serde(default = "default_true")]
  327    pub focus: bool,
  328    #[serde(default)]
  329    pub clone: bool,
  330}
  331
  332fn default_1() -> usize {
  333    1
  334}
  335
  336/// Moves an item to a pane in the specified direction.
  337#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  338#[action(namespace = workspace)]
  339#[serde(deny_unknown_fields)]
  340pub struct MoveItemToPaneInDirection {
  341    #[serde(default = "default_right")]
  342    pub direction: SplitDirection,
  343    #[serde(default = "default_true")]
  344    pub focus: bool,
  345    #[serde(default)]
  346    pub clone: bool,
  347}
  348
  349/// Creates a new file in a split of the desired direction.
  350#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  351#[action(namespace = workspace)]
  352#[serde(deny_unknown_fields)]
  353pub struct NewFileSplit(pub SplitDirection);
  354
  355fn default_right() -> SplitDirection {
  356    SplitDirection::Right
  357}
  358
  359/// Saves all open files in the workspace.
  360#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  361#[action(namespace = workspace)]
  362#[serde(deny_unknown_fields)]
  363pub struct SaveAll {
  364    #[serde(default)]
  365    pub save_intent: Option<SaveIntent>,
  366}
  367
  368/// Saves the current file with the specified options.
  369#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  370#[action(namespace = workspace)]
  371#[serde(deny_unknown_fields)]
  372pub struct Save {
  373    #[serde(default)]
  374    pub save_intent: Option<SaveIntent>,
  375}
  376
  377/// Closes all items and panes in the workspace.
  378#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  379#[action(namespace = workspace)]
  380#[serde(deny_unknown_fields)]
  381pub struct CloseAllItemsAndPanes {
  382    #[serde(default)]
  383    pub save_intent: Option<SaveIntent>,
  384}
  385
  386/// Closes all inactive tabs and panes in the workspace.
  387#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  388#[action(namespace = workspace)]
  389#[serde(deny_unknown_fields)]
  390pub struct CloseInactiveTabsAndPanes {
  391    #[serde(default)]
  392    pub save_intent: Option<SaveIntent>,
  393}
  394
  395/// Sends a sequence of keystrokes to the active element.
  396#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  397#[action(namespace = workspace)]
  398pub struct SendKeystrokes(pub String);
  399
  400actions!(
  401    project_symbols,
  402    [
  403        /// Toggles the project symbols search.
  404        #[action(name = "Toggle")]
  405        ToggleProjectSymbols
  406    ]
  407);
  408
  409/// Toggles the file finder interface.
  410#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  411#[action(namespace = file_finder, name = "Toggle")]
  412#[serde(deny_unknown_fields)]
  413pub struct ToggleFileFinder {
  414    #[serde(default)]
  415    pub separate_history: bool,
  416}
  417
  418/// Opens a new terminal in the center.
  419#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  420#[action(namespace = workspace)]
  421#[serde(deny_unknown_fields)]
  422pub struct NewCenterTerminal {
  423    /// If true, creates a local terminal even in remote projects.
  424    #[serde(default)]
  425    pub local: bool,
  426}
  427
  428/// Opens a new terminal.
  429#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  430#[action(namespace = workspace)]
  431#[serde(deny_unknown_fields)]
  432pub struct NewTerminal {
  433    /// If true, creates a local terminal even in remote projects.
  434    #[serde(default)]
  435    pub local: bool,
  436}
  437
  438/// Increases size of a currently focused dock by a given amount of pixels.
  439#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  440#[action(namespace = workspace)]
  441#[serde(deny_unknown_fields)]
  442pub struct IncreaseActiveDockSize {
  443    /// For 0px parameter, uses UI font size value.
  444    #[serde(default)]
  445    pub px: u32,
  446}
  447
  448/// Decreases size of a currently focused dock by a given amount of pixels.
  449#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  450#[action(namespace = workspace)]
  451#[serde(deny_unknown_fields)]
  452pub struct DecreaseActiveDockSize {
  453    /// For 0px parameter, uses UI font size value.
  454    #[serde(default)]
  455    pub px: u32,
  456}
  457
  458/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  459#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  460#[action(namespace = workspace)]
  461#[serde(deny_unknown_fields)]
  462pub struct IncreaseOpenDocksSize {
  463    /// For 0px parameter, uses UI font size value.
  464    #[serde(default)]
  465    pub px: u32,
  466}
  467
  468/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  469#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  470#[action(namespace = workspace)]
  471#[serde(deny_unknown_fields)]
  472pub struct DecreaseOpenDocksSize {
  473    /// For 0px parameter, uses UI font size value.
  474    #[serde(default)]
  475    pub px: u32,
  476}
  477
  478actions!(
  479    workspace,
  480    [
  481        /// Activates the pane to the left.
  482        ActivatePaneLeft,
  483        /// Activates the pane to the right.
  484        ActivatePaneRight,
  485        /// Activates the pane above.
  486        ActivatePaneUp,
  487        /// Activates the pane below.
  488        ActivatePaneDown,
  489        /// Swaps the current pane with the one to the left.
  490        SwapPaneLeft,
  491        /// Swaps the current pane with the one to the right.
  492        SwapPaneRight,
  493        /// Swaps the current pane with the one above.
  494        SwapPaneUp,
  495        /// Swaps the current pane with the one below.
  496        SwapPaneDown,
  497        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  498        SwapPaneAdjacent,
  499        /// Move the current pane to be at the far left.
  500        MovePaneLeft,
  501        /// Move the current pane to be at the far right.
  502        MovePaneRight,
  503        /// Move the current pane to be at the very top.
  504        MovePaneUp,
  505        /// Move the current pane to be at the very bottom.
  506        MovePaneDown,
  507    ]
  508);
  509
  510#[derive(PartialEq, Eq, Debug)]
  511pub enum CloseIntent {
  512    /// Quit the program entirely.
  513    Quit,
  514    /// Close a window.
  515    CloseWindow,
  516    /// Replace the workspace in an existing window.
  517    ReplaceWindow,
  518}
  519
  520#[derive(Clone)]
  521pub struct Toast {
  522    id: NotificationId,
  523    msg: Cow<'static, str>,
  524    autohide: bool,
  525    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  526}
  527
  528impl Toast {
  529    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  530        Toast {
  531            id,
  532            msg: msg.into(),
  533            on_click: None,
  534            autohide: false,
  535        }
  536    }
  537
  538    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  539    where
  540        M: Into<Cow<'static, str>>,
  541        F: Fn(&mut Window, &mut App) + 'static,
  542    {
  543        self.on_click = Some((message.into(), Arc::new(on_click)));
  544        self
  545    }
  546
  547    pub fn autohide(mut self) -> Self {
  548        self.autohide = true;
  549        self
  550    }
  551}
  552
  553impl PartialEq for Toast {
  554    fn eq(&self, other: &Self) -> bool {
  555        self.id == other.id
  556            && self.msg == other.msg
  557            && self.on_click.is_some() == other.on_click.is_some()
  558    }
  559}
  560
  561/// Opens a new terminal with the specified working directory.
  562#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  563#[action(namespace = workspace)]
  564#[serde(deny_unknown_fields)]
  565pub struct OpenTerminal {
  566    pub working_directory: PathBuf,
  567    /// If true, creates a local terminal even in remote projects.
  568    #[serde(default)]
  569    pub local: bool,
  570}
  571
  572#[derive(
  573    Clone,
  574    Copy,
  575    Debug,
  576    Default,
  577    Hash,
  578    PartialEq,
  579    Eq,
  580    PartialOrd,
  581    Ord,
  582    serde::Serialize,
  583    serde::Deserialize,
  584)]
  585pub struct WorkspaceId(i64);
  586
  587impl WorkspaceId {
  588    pub fn from_i64(value: i64) -> Self {
  589        Self(value)
  590    }
  591}
  592
  593impl StaticColumnCount for WorkspaceId {}
  594impl Bind for WorkspaceId {
  595    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  596        self.0.bind(statement, start_index)
  597    }
  598}
  599impl Column for WorkspaceId {
  600    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  601        i64::column(statement, start_index)
  602            .map(|(i, next_index)| (Self(i), next_index))
  603            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  604    }
  605}
  606impl From<WorkspaceId> for i64 {
  607    fn from(val: WorkspaceId) -> Self {
  608        val.0
  609    }
  610}
  611
  612fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  613    let paths = cx.prompt_for_paths(options);
  614    cx.spawn(
  615        async move |cx| match paths.await.anyhow().and_then(|res| res) {
  616            Ok(Some(paths)) => {
  617                cx.update(|cx| {
  618                    open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
  619                });
  620            }
  621            Ok(None) => {}
  622            Err(err) => {
  623                util::log_err(&err);
  624                cx.update(|cx| {
  625                    if let Some(workspace_window) = cx
  626                        .active_window()
  627                        .and_then(|window| window.downcast::<MultiWorkspace>())
  628                    {
  629                        workspace_window
  630                            .update(cx, |multi_workspace, _, cx| {
  631                                let workspace = multi_workspace.workspace().clone();
  632                                workspace.update(cx, |workspace, cx| {
  633                                    workspace.show_portal_error(err.to_string(), cx);
  634                                });
  635                            })
  636                            .ok();
  637                    }
  638                });
  639            }
  640        },
  641    )
  642    .detach();
  643}
  644
  645pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  646    component::init();
  647    theme_preview::init(cx);
  648    toast_layer::init(cx);
  649    history_manager::init(app_state.fs.clone(), cx);
  650
  651    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  652        .on_action(|_: &Reload, cx| reload(cx))
  653        .on_action({
  654            let app_state = Arc::downgrade(&app_state);
  655            move |_: &Open, cx: &mut App| {
  656                if let Some(app_state) = app_state.upgrade() {
  657                    prompt_and_open_paths(
  658                        app_state,
  659                        PathPromptOptions {
  660                            files: true,
  661                            directories: true,
  662                            multiple: true,
  663                            prompt: None,
  664                        },
  665                        cx,
  666                    );
  667                }
  668            }
  669        })
  670        .on_action({
  671            let app_state = Arc::downgrade(&app_state);
  672            move |_: &OpenFiles, cx: &mut App| {
  673                let directories = cx.can_select_mixed_files_and_dirs();
  674                if let Some(app_state) = app_state.upgrade() {
  675                    prompt_and_open_paths(
  676                        app_state,
  677                        PathPromptOptions {
  678                            files: true,
  679                            directories,
  680                            multiple: true,
  681                            prompt: None,
  682                        },
  683                        cx,
  684                    );
  685                }
  686            }
  687        });
  688}
  689
  690type BuildProjectItemFn =
  691    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  692
  693type BuildProjectItemForPathFn =
  694    fn(
  695        &Entity<Project>,
  696        &ProjectPath,
  697        &mut Window,
  698        &mut App,
  699    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  700
  701#[derive(Clone, Default)]
  702struct ProjectItemRegistry {
  703    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  704    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  705}
  706
  707impl ProjectItemRegistry {
  708    fn register<T: ProjectItem>(&mut self) {
  709        self.build_project_item_fns_by_type.insert(
  710            TypeId::of::<T::Item>(),
  711            |item, project, pane, window, cx| {
  712                let item = item.downcast().unwrap();
  713                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  714                    as Box<dyn ItemHandle>
  715            },
  716        );
  717        self.build_project_item_for_path_fns
  718            .push(|project, project_path, window, cx| {
  719                let project_path = project_path.clone();
  720                let is_file = project
  721                    .read(cx)
  722                    .entry_for_path(&project_path, cx)
  723                    .is_some_and(|entry| entry.is_file());
  724                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  725                let is_local = project.read(cx).is_local();
  726                let project_item =
  727                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  728                let project = project.clone();
  729                Some(window.spawn(cx, async move |cx| {
  730                    match project_item.await.with_context(|| {
  731                        format!(
  732                            "opening project path {:?}",
  733                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  734                        )
  735                    }) {
  736                        Ok(project_item) => {
  737                            let project_item = project_item;
  738                            let project_entry_id: Option<ProjectEntryId> =
  739                                project_item.read_with(cx, project::ProjectItem::entry_id);
  740                            let build_workspace_item = Box::new(
  741                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  742                                    Box::new(cx.new(|cx| {
  743                                        T::for_project_item(
  744                                            project,
  745                                            Some(pane),
  746                                            project_item,
  747                                            window,
  748                                            cx,
  749                                        )
  750                                    })) as Box<dyn ItemHandle>
  751                                },
  752                            ) as Box<_>;
  753                            Ok((project_entry_id, build_workspace_item))
  754                        }
  755                        Err(e) => {
  756                            log::warn!("Failed to open a project item: {e:#}");
  757                            if e.error_code() == ErrorCode::Internal {
  758                                if let Some(abs_path) =
  759                                    entry_abs_path.as_deref().filter(|_| is_file)
  760                                {
  761                                    if let Some(broken_project_item_view) =
  762                                        cx.update(|window, cx| {
  763                                            T::for_broken_project_item(
  764                                                abs_path, is_local, &e, window, cx,
  765                                            )
  766                                        })?
  767                                    {
  768                                        let build_workspace_item = Box::new(
  769                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  770                                                cx.new(|_| broken_project_item_view).boxed_clone()
  771                                            },
  772                                        )
  773                                        as Box<_>;
  774                                        return Ok((None, build_workspace_item));
  775                                    }
  776                                }
  777                            }
  778                            Err(e)
  779                        }
  780                    }
  781                }))
  782            });
  783    }
  784
  785    fn open_path(
  786        &self,
  787        project: &Entity<Project>,
  788        path: &ProjectPath,
  789        window: &mut Window,
  790        cx: &mut App,
  791    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  792        let Some(open_project_item) = self
  793            .build_project_item_for_path_fns
  794            .iter()
  795            .rev()
  796            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  797        else {
  798            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  799        };
  800        open_project_item
  801    }
  802
  803    fn build_item<T: project::ProjectItem>(
  804        &self,
  805        item: Entity<T>,
  806        project: Entity<Project>,
  807        pane: Option<&Pane>,
  808        window: &mut Window,
  809        cx: &mut App,
  810    ) -> Option<Box<dyn ItemHandle>> {
  811        let build = self
  812            .build_project_item_fns_by_type
  813            .get(&TypeId::of::<T>())?;
  814        Some(build(item.into_any(), project, pane, window, cx))
  815    }
  816}
  817
  818type WorkspaceItemBuilder =
  819    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  820
  821impl Global for ProjectItemRegistry {}
  822
  823/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  824/// items will get a chance to open the file, starting from the project item that
  825/// was added last.
  826pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  827    cx.default_global::<ProjectItemRegistry>().register::<I>();
  828}
  829
  830#[derive(Default)]
  831pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  832
  833struct FollowableViewDescriptor {
  834    from_state_proto: fn(
  835        Entity<Workspace>,
  836        ViewId,
  837        &mut Option<proto::view::Variant>,
  838        &mut Window,
  839        &mut App,
  840    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  841    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  842}
  843
  844impl Global for FollowableViewRegistry {}
  845
  846impl FollowableViewRegistry {
  847    pub fn register<I: FollowableItem>(cx: &mut App) {
  848        cx.default_global::<Self>().0.insert(
  849            TypeId::of::<I>(),
  850            FollowableViewDescriptor {
  851                from_state_proto: |workspace, id, state, window, cx| {
  852                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  853                        cx.foreground_executor()
  854                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  855                    })
  856                },
  857                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  858            },
  859        );
  860    }
  861
  862    pub fn from_state_proto(
  863        workspace: Entity<Workspace>,
  864        view_id: ViewId,
  865        mut state: Option<proto::view::Variant>,
  866        window: &mut Window,
  867        cx: &mut App,
  868    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  869        cx.update_default_global(|this: &mut Self, cx| {
  870            this.0.values().find_map(|descriptor| {
  871                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  872            })
  873        })
  874    }
  875
  876    pub fn to_followable_view(
  877        view: impl Into<AnyView>,
  878        cx: &App,
  879    ) -> Option<Box<dyn FollowableItemHandle>> {
  880        let this = cx.try_global::<Self>()?;
  881        let view = view.into();
  882        let descriptor = this.0.get(&view.entity_type())?;
  883        Some((descriptor.to_followable_view)(&view))
  884    }
  885}
  886
  887#[derive(Copy, Clone)]
  888struct SerializableItemDescriptor {
  889    deserialize: fn(
  890        Entity<Project>,
  891        WeakEntity<Workspace>,
  892        WorkspaceId,
  893        ItemId,
  894        &mut Window,
  895        &mut Context<Pane>,
  896    ) -> Task<Result<Box<dyn ItemHandle>>>,
  897    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  898    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  899}
  900
  901#[derive(Default)]
  902struct SerializableItemRegistry {
  903    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  904    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  905}
  906
  907impl Global for SerializableItemRegistry {}
  908
  909impl SerializableItemRegistry {
  910    fn deserialize(
  911        item_kind: &str,
  912        project: Entity<Project>,
  913        workspace: WeakEntity<Workspace>,
  914        workspace_id: WorkspaceId,
  915        item_item: ItemId,
  916        window: &mut Window,
  917        cx: &mut Context<Pane>,
  918    ) -> Task<Result<Box<dyn ItemHandle>>> {
  919        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  920            return Task::ready(Err(anyhow!(
  921                "cannot deserialize {}, descriptor not found",
  922                item_kind
  923            )));
  924        };
  925
  926        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  927    }
  928
  929    fn cleanup(
  930        item_kind: &str,
  931        workspace_id: WorkspaceId,
  932        loaded_items: Vec<ItemId>,
  933        window: &mut Window,
  934        cx: &mut App,
  935    ) -> Task<Result<()>> {
  936        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  937            return Task::ready(Err(anyhow!(
  938                "cannot cleanup {}, descriptor not found",
  939                item_kind
  940            )));
  941        };
  942
  943        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  944    }
  945
  946    fn view_to_serializable_item_handle(
  947        view: AnyView,
  948        cx: &App,
  949    ) -> Option<Box<dyn SerializableItemHandle>> {
  950        let this = cx.try_global::<Self>()?;
  951        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  952        Some((descriptor.view_to_serializable_item)(view))
  953    }
  954
  955    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  956        let this = cx.try_global::<Self>()?;
  957        this.descriptors_by_kind.get(item_kind).copied()
  958    }
  959}
  960
  961pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  962    let serialized_item_kind = I::serialized_item_kind();
  963
  964    let registry = cx.default_global::<SerializableItemRegistry>();
  965    let descriptor = SerializableItemDescriptor {
  966        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  967            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  968            cx.foreground_executor()
  969                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
  970        },
  971        cleanup: |workspace_id, loaded_items, window, cx| {
  972            I::cleanup(workspace_id, loaded_items, window, cx)
  973        },
  974        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
  975    };
  976    registry
  977        .descriptors_by_kind
  978        .insert(Arc::from(serialized_item_kind), descriptor);
  979    registry
  980        .descriptors_by_type
  981        .insert(TypeId::of::<I>(), descriptor);
  982}
  983
  984pub struct AppState {
  985    pub languages: Arc<LanguageRegistry>,
  986    pub client: Arc<Client>,
  987    pub user_store: Entity<UserStore>,
  988    pub workspace_store: Entity<WorkspaceStore>,
  989    pub fs: Arc<dyn fs::Fs>,
  990    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
  991    pub node_runtime: NodeRuntime,
  992    pub session: Entity<AppSession>,
  993}
  994
  995struct GlobalAppState(Weak<AppState>);
  996
  997impl Global for GlobalAppState {}
  998
  999pub struct WorkspaceStore {
 1000    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1001    client: Arc<Client>,
 1002    _subscriptions: Vec<client::Subscription>,
 1003}
 1004
 1005#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1006pub enum CollaboratorId {
 1007    PeerId(PeerId),
 1008    Agent,
 1009}
 1010
 1011impl From<PeerId> for CollaboratorId {
 1012    fn from(peer_id: PeerId) -> Self {
 1013        CollaboratorId::PeerId(peer_id)
 1014    }
 1015}
 1016
 1017impl From<&PeerId> for CollaboratorId {
 1018    fn from(peer_id: &PeerId) -> Self {
 1019        CollaboratorId::PeerId(*peer_id)
 1020    }
 1021}
 1022
 1023#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1024struct Follower {
 1025    project_id: Option<u64>,
 1026    peer_id: PeerId,
 1027}
 1028
 1029impl AppState {
 1030    #[track_caller]
 1031    pub fn global(cx: &App) -> Weak<Self> {
 1032        cx.global::<GlobalAppState>().0.clone()
 1033    }
 1034    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1035        cx.try_global::<GlobalAppState>()
 1036            .map(|state| state.0.clone())
 1037    }
 1038    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1039        cx.set_global(GlobalAppState(state));
 1040    }
 1041
 1042    #[cfg(any(test, feature = "test-support"))]
 1043    pub fn test(cx: &mut App) -> Arc<Self> {
 1044        use fs::Fs;
 1045        use node_runtime::NodeRuntime;
 1046        use session::Session;
 1047        use settings::SettingsStore;
 1048
 1049        if !cx.has_global::<SettingsStore>() {
 1050            let settings_store = SettingsStore::test(cx);
 1051            cx.set_global(settings_store);
 1052        }
 1053
 1054        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1055        <dyn Fs>::set_global(fs.clone(), cx);
 1056        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1057        let clock = Arc::new(clock::FakeSystemClock::new());
 1058        let http_client = http_client::FakeHttpClient::with_404_response();
 1059        let client = Client::new(clock, http_client, cx);
 1060        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1061        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1062        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1063
 1064        theme::init(theme::LoadThemes::JustBase, cx);
 1065        client::init(&client, cx);
 1066
 1067        Arc::new(Self {
 1068            client,
 1069            fs,
 1070            languages,
 1071            user_store,
 1072            workspace_store,
 1073            node_runtime: NodeRuntime::unavailable(),
 1074            build_window_options: |_, _| Default::default(),
 1075            session,
 1076        })
 1077    }
 1078}
 1079
 1080struct DelayedDebouncedEditAction {
 1081    task: Option<Task<()>>,
 1082    cancel_channel: Option<oneshot::Sender<()>>,
 1083}
 1084
 1085impl DelayedDebouncedEditAction {
 1086    fn new() -> DelayedDebouncedEditAction {
 1087        DelayedDebouncedEditAction {
 1088            task: None,
 1089            cancel_channel: None,
 1090        }
 1091    }
 1092
 1093    fn fire_new<F>(
 1094        &mut self,
 1095        delay: Duration,
 1096        window: &mut Window,
 1097        cx: &mut Context<Workspace>,
 1098        func: F,
 1099    ) where
 1100        F: 'static
 1101            + Send
 1102            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1103    {
 1104        if let Some(channel) = self.cancel_channel.take() {
 1105            _ = channel.send(());
 1106        }
 1107
 1108        let (sender, mut receiver) = oneshot::channel::<()>();
 1109        self.cancel_channel = Some(sender);
 1110
 1111        let previous_task = self.task.take();
 1112        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1113            let mut timer = cx.background_executor().timer(delay).fuse();
 1114            if let Some(previous_task) = previous_task {
 1115                previous_task.await;
 1116            }
 1117
 1118            futures::select_biased! {
 1119                _ = receiver => return,
 1120                    _ = timer => {}
 1121            }
 1122
 1123            if let Some(result) = workspace
 1124                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1125                .log_err()
 1126            {
 1127                result.await.log_err();
 1128            }
 1129        }));
 1130    }
 1131}
 1132
 1133pub enum Event {
 1134    PaneAdded(Entity<Pane>),
 1135    PaneRemoved,
 1136    ItemAdded {
 1137        item: Box<dyn ItemHandle>,
 1138    },
 1139    ActiveItemChanged,
 1140    ItemRemoved {
 1141        item_id: EntityId,
 1142    },
 1143    UserSavedItem {
 1144        pane: WeakEntity<Pane>,
 1145        item: Box<dyn WeakItemHandle>,
 1146        save_intent: SaveIntent,
 1147    },
 1148    ContactRequestedJoin(u64),
 1149    WorkspaceCreated(WeakEntity<Workspace>),
 1150    OpenBundledFile {
 1151        text: Cow<'static, str>,
 1152        title: &'static str,
 1153        language: &'static str,
 1154    },
 1155    ZoomChanged,
 1156    ModalOpened,
 1157}
 1158
 1159#[derive(Debug)]
 1160pub enum OpenVisible {
 1161    All,
 1162    None,
 1163    OnlyFiles,
 1164    OnlyDirectories,
 1165}
 1166
 1167enum WorkspaceLocation {
 1168    // Valid local paths or SSH project to serialize
 1169    Location(SerializedWorkspaceLocation, PathList),
 1170    // No valid location found hence clear session id
 1171    DetachFromSession,
 1172    // No valid location found to serialize
 1173    None,
 1174}
 1175
 1176type PromptForNewPath = Box<
 1177    dyn Fn(
 1178        &mut Workspace,
 1179        DirectoryLister,
 1180        Option<String>,
 1181        &mut Window,
 1182        &mut Context<Workspace>,
 1183    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1184>;
 1185
 1186type PromptForOpenPath = Box<
 1187    dyn Fn(
 1188        &mut Workspace,
 1189        DirectoryLister,
 1190        &mut Window,
 1191        &mut Context<Workspace>,
 1192    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1193>;
 1194
 1195#[derive(Default)]
 1196struct DispatchingKeystrokes {
 1197    dispatched: HashSet<Vec<Keystroke>>,
 1198    queue: VecDeque<Keystroke>,
 1199    task: Option<Shared<Task<()>>>,
 1200}
 1201
 1202/// Collects everything project-related for a certain window opened.
 1203/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1204///
 1205/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1206/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1207/// that can be used to register a global action to be triggered from any place in the window.
 1208pub struct Workspace {
 1209    weak_self: WeakEntity<Self>,
 1210    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1211    zoomed: Option<AnyWeakView>,
 1212    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1213    zoomed_position: Option<DockPosition>,
 1214    center: PaneGroup,
 1215    left_dock: Entity<Dock>,
 1216    bottom_dock: Entity<Dock>,
 1217    right_dock: Entity<Dock>,
 1218    panes: Vec<Entity<Pane>>,
 1219    active_worktree_override: Option<WorktreeId>,
 1220    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1221    active_pane: Entity<Pane>,
 1222    last_active_center_pane: Option<WeakEntity<Pane>>,
 1223    last_active_view_id: Option<proto::ViewId>,
 1224    status_bar: Entity<StatusBar>,
 1225    modal_layer: Entity<ModalLayer>,
 1226    toast_layer: Entity<ToastLayer>,
 1227    titlebar_item: Option<AnyView>,
 1228    notifications: Notifications,
 1229    suppressed_notifications: HashSet<NotificationId>,
 1230    project: Entity<Project>,
 1231    follower_states: HashMap<CollaboratorId, FollowerState>,
 1232    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1233    window_edited: bool,
 1234    last_window_title: Option<String>,
 1235    dirty_items: HashMap<EntityId, Subscription>,
 1236    active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
 1237    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1238    database_id: Option<WorkspaceId>,
 1239    app_state: Arc<AppState>,
 1240    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1241    _subscriptions: Vec<Subscription>,
 1242    _apply_leader_updates: Task<Result<()>>,
 1243    _observe_current_user: Task<Result<()>>,
 1244    _schedule_serialize_workspace: Option<Task<()>>,
 1245    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1246    pane_history_timestamp: Arc<AtomicUsize>,
 1247    bounds: Bounds<Pixels>,
 1248    pub centered_layout: bool,
 1249    bounds_save_task_queued: Option<Task<()>>,
 1250    on_prompt_for_new_path: Option<PromptForNewPath>,
 1251    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1252    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1253    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1254    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1255    _items_serializer: Task<Result<()>>,
 1256    session_id: Option<String>,
 1257    scheduled_tasks: Vec<Task<()>>,
 1258    last_open_dock_positions: Vec<DockPosition>,
 1259    removing: bool,
 1260    utility_panes: UtilityPaneState,
 1261}
 1262
 1263impl EventEmitter<Event> for Workspace {}
 1264
 1265#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1266pub struct ViewId {
 1267    pub creator: CollaboratorId,
 1268    pub id: u64,
 1269}
 1270
 1271pub struct FollowerState {
 1272    center_pane: Entity<Pane>,
 1273    dock_pane: Option<Entity<Pane>>,
 1274    active_view_id: Option<ViewId>,
 1275    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1276}
 1277
 1278struct FollowerView {
 1279    view: Box<dyn FollowableItemHandle>,
 1280    location: Option<proto::PanelId>,
 1281}
 1282
 1283impl Workspace {
 1284    pub fn new(
 1285        workspace_id: Option<WorkspaceId>,
 1286        project: Entity<Project>,
 1287        app_state: Arc<AppState>,
 1288        window: &mut Window,
 1289        cx: &mut Context<Self>,
 1290    ) -> Self {
 1291        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1292            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1293                if let TrustedWorktreesEvent::Trusted(..) = e {
 1294                    // Do not persist auto trusted worktrees
 1295                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1296                        worktrees_store.update(cx, |worktrees_store, cx| {
 1297                            worktrees_store.schedule_serialization(
 1298                                cx,
 1299                                |new_trusted_worktrees, cx| {
 1300                                    let timeout =
 1301                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1302                                    cx.background_spawn(async move {
 1303                                        timeout.await;
 1304                                        persistence::DB
 1305                                            .save_trusted_worktrees(new_trusted_worktrees)
 1306                                            .await
 1307                                            .log_err();
 1308                                    })
 1309                                },
 1310                            )
 1311                        });
 1312                    }
 1313                }
 1314            })
 1315            .detach();
 1316
 1317            cx.observe_global::<SettingsStore>(|_, cx| {
 1318                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1319                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1320                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1321                            trusted_worktrees.auto_trust_all(cx);
 1322                        })
 1323                    }
 1324                }
 1325            })
 1326            .detach();
 1327        }
 1328
 1329        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1330            match event {
 1331                project::Event::RemoteIdChanged(_) => {
 1332                    this.update_window_title(window, cx);
 1333                }
 1334
 1335                project::Event::CollaboratorLeft(peer_id) => {
 1336                    this.collaborator_left(*peer_id, window, cx);
 1337                }
 1338
 1339                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1340                    this.update_window_title(window, cx);
 1341                    if this
 1342                        .project()
 1343                        .read(cx)
 1344                        .worktree_for_id(id, cx)
 1345                        .is_some_and(|wt| wt.read(cx).is_visible())
 1346                    {
 1347                        this.serialize_workspace(window, cx);
 1348                        this.update_history(cx);
 1349                    }
 1350                }
 1351                project::Event::WorktreeUpdatedEntries(..) => {
 1352                    this.update_window_title(window, cx);
 1353                    this.serialize_workspace(window, cx);
 1354                }
 1355
 1356                project::Event::DisconnectedFromHost => {
 1357                    this.update_window_edited(window, cx);
 1358                    let leaders_to_unfollow =
 1359                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1360                    for leader_id in leaders_to_unfollow {
 1361                        this.unfollow(leader_id, window, cx);
 1362                    }
 1363                }
 1364
 1365                project::Event::DisconnectedFromRemote {
 1366                    server_not_running: _,
 1367                } => {
 1368                    this.update_window_edited(window, cx);
 1369                }
 1370
 1371                project::Event::Closed => {
 1372                    window.remove_window();
 1373                }
 1374
 1375                project::Event::DeletedEntry(_, entry_id) => {
 1376                    for pane in this.panes.iter() {
 1377                        pane.update(cx, |pane, cx| {
 1378                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1379                        });
 1380                    }
 1381                }
 1382
 1383                project::Event::Toast {
 1384                    notification_id,
 1385                    message,
 1386                    link,
 1387                } => this.show_notification(
 1388                    NotificationId::named(notification_id.clone()),
 1389                    cx,
 1390                    |cx| {
 1391                        let mut notification = MessageNotification::new(message.clone(), cx);
 1392                        if let Some(link) = link {
 1393                            notification = notification
 1394                                .more_info_message(link.label)
 1395                                .more_info_url(link.url);
 1396                        }
 1397
 1398                        cx.new(|_| notification)
 1399                    },
 1400                ),
 1401
 1402                project::Event::HideToast { notification_id } => {
 1403                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1404                }
 1405
 1406                project::Event::LanguageServerPrompt(request) => {
 1407                    struct LanguageServerPrompt;
 1408
 1409                    this.show_notification(
 1410                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1411                        cx,
 1412                        |cx| {
 1413                            cx.new(|cx| {
 1414                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1415                            })
 1416                        },
 1417                    );
 1418                }
 1419
 1420                project::Event::AgentLocationChanged => {
 1421                    this.handle_agent_location_changed(window, cx)
 1422                }
 1423
 1424                _ => {}
 1425            }
 1426            cx.notify()
 1427        })
 1428        .detach();
 1429
 1430        cx.subscribe_in(
 1431            &project.read(cx).breakpoint_store(),
 1432            window,
 1433            |workspace, _, event, window, cx| match event {
 1434                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1435                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1436                    workspace.serialize_workspace(window, cx);
 1437                }
 1438                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1439            },
 1440        )
 1441        .detach();
 1442        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1443            cx.subscribe_in(
 1444                &toolchain_store,
 1445                window,
 1446                |workspace, _, event, window, cx| match event {
 1447                    ToolchainStoreEvent::CustomToolchainsModified => {
 1448                        workspace.serialize_workspace(window, cx);
 1449                    }
 1450                    _ => {}
 1451                },
 1452            )
 1453            .detach();
 1454        }
 1455
 1456        cx.on_focus_lost(window, |this, window, cx| {
 1457            let focus_handle = this.focus_handle(cx);
 1458            window.focus(&focus_handle, cx);
 1459        })
 1460        .detach();
 1461
 1462        let weak_handle = cx.entity().downgrade();
 1463        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1464
 1465        let center_pane = cx.new(|cx| {
 1466            let mut center_pane = Pane::new(
 1467                weak_handle.clone(),
 1468                project.clone(),
 1469                pane_history_timestamp.clone(),
 1470                None,
 1471                NewFile.boxed_clone(),
 1472                true,
 1473                window,
 1474                cx,
 1475            );
 1476            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1477            center_pane.set_should_display_welcome_page(true);
 1478            center_pane
 1479        });
 1480        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1481            .detach();
 1482
 1483        window.focus(&center_pane.focus_handle(cx), cx);
 1484
 1485        cx.emit(Event::PaneAdded(center_pane.clone()));
 1486
 1487        let any_window_handle = window.window_handle();
 1488        app_state.workspace_store.update(cx, |store, _| {
 1489            store
 1490                .workspaces
 1491                .insert((any_window_handle, weak_handle.clone()));
 1492        });
 1493
 1494        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1495        let mut connection_status = app_state.client.status();
 1496        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1497            current_user.next().await;
 1498            connection_status.next().await;
 1499            let mut stream =
 1500                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1501
 1502            while stream.recv().await.is_some() {
 1503                this.update(cx, |_, cx| cx.notify())?;
 1504            }
 1505            anyhow::Ok(())
 1506        });
 1507
 1508        // All leader updates are enqueued and then processed in a single task, so
 1509        // that each asynchronous operation can be run in order.
 1510        let (leader_updates_tx, mut leader_updates_rx) =
 1511            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1512        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1513            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1514                Self::process_leader_update(&this, leader_id, update, cx)
 1515                    .await
 1516                    .log_err();
 1517            }
 1518
 1519            Ok(())
 1520        });
 1521
 1522        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1523        let modal_layer = cx.new(|_| ModalLayer::new());
 1524        let toast_layer = cx.new(|_| ToastLayer::new());
 1525        cx.subscribe(
 1526            &modal_layer,
 1527            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1528                cx.emit(Event::ModalOpened);
 1529            },
 1530        )
 1531        .detach();
 1532
 1533        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1534        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1535        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1536        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1537        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1538        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1539        let status_bar = cx.new(|cx| {
 1540            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1541            status_bar.add_left_item(left_dock_buttons, window, cx);
 1542            status_bar.add_right_item(right_dock_buttons, window, cx);
 1543            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1544            status_bar
 1545        });
 1546
 1547        let session_id = app_state.session.read(cx).id().to_owned();
 1548
 1549        let mut active_call = None;
 1550        if let Some(call) = ActiveCall::try_global(cx) {
 1551            let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
 1552            active_call = Some((call, subscriptions));
 1553        }
 1554
 1555        let (serializable_items_tx, serializable_items_rx) =
 1556            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1557        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1558            Self::serialize_items(&this, serializable_items_rx, cx).await
 1559        });
 1560
 1561        let subscriptions = vec![
 1562            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1563            cx.observe_window_bounds(window, move |this, window, cx| {
 1564                if this.bounds_save_task_queued.is_some() {
 1565                    return;
 1566                }
 1567                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1568                    cx.background_executor()
 1569                        .timer(Duration::from_millis(100))
 1570                        .await;
 1571                    this.update_in(cx, |this, window, cx| {
 1572                        if let Some(display) = window.display(cx)
 1573                            && let Ok(display_uuid) = display.uuid()
 1574                        {
 1575                            let window_bounds = window.inner_window_bounds();
 1576                            let has_paths = !this.root_paths(cx).is_empty();
 1577                            if !has_paths {
 1578                                cx.background_executor()
 1579                                    .spawn(persistence::write_default_window_bounds(
 1580                                        window_bounds,
 1581                                        display_uuid,
 1582                                    ))
 1583                                    .detach_and_log_err(cx);
 1584                            }
 1585                            if let Some(database_id) = workspace_id {
 1586                                cx.background_executor()
 1587                                    .spawn(DB.set_window_open_status(
 1588                                        database_id,
 1589                                        SerializedWindowBounds(window_bounds),
 1590                                        display_uuid,
 1591                                    ))
 1592                                    .detach_and_log_err(cx);
 1593                            } else {
 1594                                cx.background_executor()
 1595                                    .spawn(persistence::write_default_window_bounds(
 1596                                        window_bounds,
 1597                                        display_uuid,
 1598                                    ))
 1599                                    .detach_and_log_err(cx);
 1600                            }
 1601                        }
 1602                        this.bounds_save_task_queued.take();
 1603                    })
 1604                    .ok();
 1605                }));
 1606                cx.notify();
 1607            }),
 1608            cx.observe_window_appearance(window, |_, window, cx| {
 1609                let window_appearance = window.appearance();
 1610
 1611                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1612
 1613                GlobalTheme::reload_theme(cx);
 1614                GlobalTheme::reload_icon_theme(cx);
 1615            }),
 1616            cx.on_release({
 1617                let weak_handle = weak_handle.clone();
 1618                move |this, cx| {
 1619                    this.app_state.workspace_store.update(cx, move |store, _| {
 1620                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1621                    })
 1622                }
 1623            }),
 1624        ];
 1625
 1626        cx.defer_in(window, move |this, window, cx| {
 1627            this.update_window_title(window, cx);
 1628            this.show_initial_notifications(cx);
 1629        });
 1630
 1631        let mut center = PaneGroup::new(center_pane.clone());
 1632        center.set_is_center(true);
 1633        center.mark_positions(cx);
 1634
 1635        Workspace {
 1636            weak_self: weak_handle.clone(),
 1637            zoomed: None,
 1638            zoomed_position: None,
 1639            previous_dock_drag_coordinates: None,
 1640            center,
 1641            panes: vec![center_pane.clone()],
 1642            panes_by_item: Default::default(),
 1643            active_pane: center_pane.clone(),
 1644            last_active_center_pane: Some(center_pane.downgrade()),
 1645            last_active_view_id: None,
 1646            status_bar,
 1647            modal_layer,
 1648            toast_layer,
 1649            titlebar_item: None,
 1650            active_worktree_override: None,
 1651            notifications: Notifications::default(),
 1652            suppressed_notifications: HashSet::default(),
 1653            left_dock,
 1654            bottom_dock,
 1655            right_dock,
 1656            project: project.clone(),
 1657            follower_states: Default::default(),
 1658            last_leaders_by_pane: Default::default(),
 1659            dispatching_keystrokes: Default::default(),
 1660            window_edited: false,
 1661            last_window_title: None,
 1662            dirty_items: Default::default(),
 1663            active_call,
 1664            database_id: workspace_id,
 1665            app_state,
 1666            _observe_current_user,
 1667            _apply_leader_updates,
 1668            _schedule_serialize_workspace: None,
 1669            _schedule_serialize_ssh_paths: None,
 1670            leader_updates_tx,
 1671            _subscriptions: subscriptions,
 1672            pane_history_timestamp,
 1673            workspace_actions: Default::default(),
 1674            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1675            bounds: Default::default(),
 1676            centered_layout: false,
 1677            bounds_save_task_queued: None,
 1678            on_prompt_for_new_path: None,
 1679            on_prompt_for_open_path: None,
 1680            terminal_provider: None,
 1681            debugger_provider: None,
 1682            serializable_items_tx,
 1683            _items_serializer,
 1684            session_id: Some(session_id),
 1685
 1686            scheduled_tasks: Vec::new(),
 1687            last_open_dock_positions: Vec::new(),
 1688            removing: false,
 1689            utility_panes: UtilityPaneState::default(),
 1690        }
 1691    }
 1692
 1693    pub fn new_local(
 1694        abs_paths: Vec<PathBuf>,
 1695        app_state: Arc<AppState>,
 1696        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1697        env: Option<HashMap<String, String>>,
 1698        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1699        cx: &mut App,
 1700    ) -> Task<
 1701        anyhow::Result<(
 1702            WindowHandle<MultiWorkspace>,
 1703            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1704        )>,
 1705    > {
 1706        let project_handle = Project::local(
 1707            app_state.client.clone(),
 1708            app_state.node_runtime.clone(),
 1709            app_state.user_store.clone(),
 1710            app_state.languages.clone(),
 1711            app_state.fs.clone(),
 1712            env,
 1713            Default::default(),
 1714            cx,
 1715        );
 1716
 1717        cx.spawn(async move |cx| {
 1718            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1719            for path in abs_paths.into_iter() {
 1720                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1721                    paths_to_open.push(canonical)
 1722                } else {
 1723                    paths_to_open.push(path)
 1724                }
 1725            }
 1726
 1727            let serialized_workspace =
 1728                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1729
 1730            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1731                paths_to_open = paths.ordered_paths().cloned().collect();
 1732                if !paths.is_lexicographically_ordered() {
 1733                    project_handle.update(cx, |project, cx| {
 1734                        project.set_worktrees_reordered(true, cx);
 1735                    });
 1736                }
 1737            }
 1738
 1739            // Get project paths for all of the abs_paths
 1740            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1741                Vec::with_capacity(paths_to_open.len());
 1742
 1743            for path in paths_to_open.into_iter() {
 1744                if let Some((_, project_entry)) = cx
 1745                    .update(|cx| {
 1746                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1747                    })
 1748                    .await
 1749                    .log_err()
 1750                {
 1751                    project_paths.push((path, Some(project_entry)));
 1752                } else {
 1753                    project_paths.push((path, None));
 1754                }
 1755            }
 1756
 1757            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1758                serialized_workspace.id
 1759            } else {
 1760                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1761            };
 1762
 1763            let toolchains = DB.toolchains(workspace_id).await?;
 1764
 1765            for (toolchain, worktree_path, path) in toolchains {
 1766                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1767                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1768                    this.find_worktree(&worktree_path, cx)
 1769                        .and_then(|(worktree, rel_path)| {
 1770                            if rel_path.is_empty() {
 1771                                Some(worktree.read(cx).id())
 1772                            } else {
 1773                                None
 1774                            }
 1775                        })
 1776                }) else {
 1777                    // We did not find a worktree with a given path, but that's whatever.
 1778                    continue;
 1779                };
 1780                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1781                    continue;
 1782                }
 1783
 1784                project_handle
 1785                    .update(cx, |this, cx| {
 1786                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1787                    })
 1788                    .await;
 1789            }
 1790            if let Some(workspace) = serialized_workspace.as_ref() {
 1791                project_handle.update(cx, |this, cx| {
 1792                    for (scope, toolchains) in &workspace.user_toolchains {
 1793                        for toolchain in toolchains {
 1794                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1795                        }
 1796                    }
 1797                });
 1798            }
 1799
 1800            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1801                if let Some(window) = requesting_window {
 1802                    let centered_layout = serialized_workspace
 1803                        .as_ref()
 1804                        .map(|w| w.centered_layout)
 1805                        .unwrap_or(false);
 1806
 1807                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1808                        let workspace = cx.new(|cx| {
 1809                            let mut workspace = Workspace::new(
 1810                                Some(workspace_id),
 1811                                project_handle.clone(),
 1812                                app_state.clone(),
 1813                                window,
 1814                                cx,
 1815                            );
 1816
 1817                            workspace.centered_layout = centered_layout;
 1818
 1819                            // Call init callback to add items before window renders
 1820                            if let Some(init) = init {
 1821                                init(&mut workspace, window, cx);
 1822                            }
 1823
 1824                            workspace
 1825                        });
 1826                        multi_workspace.activate(workspace.clone(), cx);
 1827                        workspace
 1828                    })?;
 1829                    (window, workspace)
 1830                } else {
 1831                    let window_bounds_override = window_bounds_env_override();
 1832
 1833                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1834                        (Some(WindowBounds::Windowed(bounds)), None)
 1835                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1836                        && let Some(display) = workspace.display
 1837                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1838                    {
 1839                        // Reopening an existing workspace - restore its saved bounds
 1840                        (Some(bounds.0), Some(display))
 1841                    } else if let Some((display, bounds)) =
 1842                        persistence::read_default_window_bounds()
 1843                    {
 1844                        // New or empty workspace - use the last known window bounds
 1845                        (Some(bounds), Some(display))
 1846                    } else {
 1847                        // New window - let GPUI's default_bounds() handle cascading
 1848                        (None, None)
 1849                    };
 1850
 1851                    // Use the serialized workspace to construct the new window
 1852                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1853                    options.window_bounds = window_bounds;
 1854                    let centered_layout = serialized_workspace
 1855                        .as_ref()
 1856                        .map(|w| w.centered_layout)
 1857                        .unwrap_or(false);
 1858                    let window = cx.open_window(options, {
 1859                        let app_state = app_state.clone();
 1860                        let project_handle = project_handle.clone();
 1861                        move |window, cx| {
 1862                            let workspace = cx.new(|cx| {
 1863                                let mut workspace = Workspace::new(
 1864                                    Some(workspace_id),
 1865                                    project_handle,
 1866                                    app_state,
 1867                                    window,
 1868                                    cx,
 1869                                );
 1870                                workspace.centered_layout = centered_layout;
 1871
 1872                                // Call init callback to add items before window renders
 1873                                if let Some(init) = init {
 1874                                    init(&mut workspace, window, cx);
 1875                                }
 1876
 1877                                workspace
 1878                            });
 1879                            cx.new(|cx| MultiWorkspace::new(workspace, cx))
 1880                        }
 1881                    })?;
 1882                    let workspace =
 1883                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1884                            multi_workspace.workspace().clone()
 1885                        })?;
 1886                    (window, workspace)
 1887                };
 1888
 1889            notify_if_database_failed(window, cx);
 1890            // Check if this is an empty workspace (no paths to open)
 1891            // An empty workspace is one where project_paths is empty
 1892            let is_empty_workspace = project_paths.is_empty();
 1893            // Check if serialized workspace has paths before it's moved
 1894            let serialized_workspace_has_paths = serialized_workspace
 1895                .as_ref()
 1896                .map(|ws| !ws.paths.is_empty())
 1897                .unwrap_or(false);
 1898
 1899            let opened_items = window
 1900                .update(cx, |_, window, cx| {
 1901                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1902                        open_items(serialized_workspace, project_paths, window, cx)
 1903                    })
 1904                })?
 1905                .await
 1906                .unwrap_or_default();
 1907
 1908            // Restore default dock state for empty workspaces
 1909            // Only restore if:
 1910            // 1. This is an empty workspace (no paths), AND
 1911            // 2. The serialized workspace either doesn't exist or has no paths
 1912            if is_empty_workspace && !serialized_workspace_has_paths {
 1913                if let Some(default_docks) = persistence::read_default_dock_state() {
 1914                    window
 1915                        .update(cx, |_, window, cx| {
 1916                            workspace.update(cx, |workspace, cx| {
 1917                                for (dock, serialized_dock) in [
 1918                                    (&workspace.right_dock, &default_docks.right),
 1919                                    (&workspace.left_dock, &default_docks.left),
 1920                                    (&workspace.bottom_dock, &default_docks.bottom),
 1921                                ] {
 1922                                    dock.update(cx, |dock, cx| {
 1923                                        dock.serialized_dock = Some(serialized_dock.clone());
 1924                                        dock.restore_state(window, cx);
 1925                                    });
 1926                                }
 1927                                cx.notify();
 1928                            });
 1929                        })
 1930                        .log_err();
 1931                }
 1932            }
 1933
 1934            window
 1935                .update(cx, |_, _window, cx| {
 1936                    workspace.update(cx, |this: &mut Workspace, cx| {
 1937                        this.update_history(cx);
 1938                    });
 1939                })
 1940                .log_err();
 1941            Ok((window, opened_items))
 1942        })
 1943    }
 1944
 1945    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1946        self.weak_self.clone()
 1947    }
 1948
 1949    pub fn left_dock(&self) -> &Entity<Dock> {
 1950        &self.left_dock
 1951    }
 1952
 1953    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1954        &self.bottom_dock
 1955    }
 1956
 1957    pub fn set_bottom_dock_layout(
 1958        &mut self,
 1959        layout: BottomDockLayout,
 1960        window: &mut Window,
 1961        cx: &mut Context<Self>,
 1962    ) {
 1963        let fs = self.project().read(cx).fs();
 1964        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1965            content.workspace.bottom_dock_layout = Some(layout);
 1966        });
 1967
 1968        cx.notify();
 1969        self.serialize_workspace(window, cx);
 1970    }
 1971
 1972    pub fn right_dock(&self) -> &Entity<Dock> {
 1973        &self.right_dock
 1974    }
 1975
 1976    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1977        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1978    }
 1979
 1980    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1981        match position {
 1982            DockPosition::Left => &self.left_dock,
 1983            DockPosition::Bottom => &self.bottom_dock,
 1984            DockPosition::Right => &self.right_dock,
 1985        }
 1986    }
 1987
 1988    pub fn is_edited(&self) -> bool {
 1989        self.window_edited
 1990    }
 1991
 1992    pub fn add_panel<T: Panel>(
 1993        &mut self,
 1994        panel: Entity<T>,
 1995        window: &mut Window,
 1996        cx: &mut Context<Self>,
 1997    ) {
 1998        let focus_handle = panel.panel_focus_handle(cx);
 1999        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2000            .detach();
 2001
 2002        let dock_position = panel.position(window, cx);
 2003        let dock = self.dock_at_position(dock_position);
 2004
 2005        dock.update(cx, |dock, cx| {
 2006            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2007        });
 2008    }
 2009
 2010    pub fn remove_panel<T: Panel>(
 2011        &mut self,
 2012        panel: &Entity<T>,
 2013        window: &mut Window,
 2014        cx: &mut Context<Self>,
 2015    ) {
 2016        let mut found_in_dock = None;
 2017        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2018            let found = dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2019
 2020            if found {
 2021                found_in_dock = Some(dock.clone());
 2022            }
 2023        }
 2024        if let Some(found_in_dock) = found_in_dock {
 2025            let position = found_in_dock.read(cx).position();
 2026            let slot = utility_slot_for_dock_position(position);
 2027            self.clear_utility_pane_if_provider(slot, Entity::entity_id(panel), cx);
 2028        }
 2029    }
 2030
 2031    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2032        &self.status_bar
 2033    }
 2034
 2035    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2036        self.status_bar.update(cx, |status_bar, cx| {
 2037            status_bar.set_workspace_sidebar_open(open, cx);
 2038        });
 2039    }
 2040
 2041    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2042        StatusBarSettings::get_global(cx).show
 2043    }
 2044
 2045    pub fn app_state(&self) -> &Arc<AppState> {
 2046        &self.app_state
 2047    }
 2048
 2049    pub fn user_store(&self) -> &Entity<UserStore> {
 2050        &self.app_state.user_store
 2051    }
 2052
 2053    pub fn project(&self) -> &Entity<Project> {
 2054        &self.project
 2055    }
 2056
 2057    pub fn path_style(&self, cx: &App) -> PathStyle {
 2058        self.project.read(cx).path_style(cx)
 2059    }
 2060
 2061    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2062        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2063
 2064        for pane_handle in &self.panes {
 2065            let pane = pane_handle.read(cx);
 2066
 2067            for entry in pane.activation_history() {
 2068                history.insert(
 2069                    entry.entity_id,
 2070                    history
 2071                        .get(&entry.entity_id)
 2072                        .cloned()
 2073                        .unwrap_or(0)
 2074                        .max(entry.timestamp),
 2075                );
 2076            }
 2077        }
 2078
 2079        history
 2080    }
 2081
 2082    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2083        let mut recent_item: Option<Entity<T>> = None;
 2084        let mut recent_timestamp = 0;
 2085        for pane_handle in &self.panes {
 2086            let pane = pane_handle.read(cx);
 2087            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2088                pane.items().map(|item| (item.item_id(), item)).collect();
 2089            for entry in pane.activation_history() {
 2090                if entry.timestamp > recent_timestamp
 2091                    && let Some(&item) = item_map.get(&entry.entity_id)
 2092                    && let Some(typed_item) = item.act_as::<T>(cx)
 2093                {
 2094                    recent_timestamp = entry.timestamp;
 2095                    recent_item = Some(typed_item);
 2096                }
 2097            }
 2098        }
 2099        recent_item
 2100    }
 2101
 2102    pub fn recent_navigation_history_iter(
 2103        &self,
 2104        cx: &App,
 2105    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2106        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2107        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2108
 2109        for pane in &self.panes {
 2110            let pane = pane.read(cx);
 2111
 2112            pane.nav_history()
 2113                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 2114                    if let Some(fs_path) = &fs_path {
 2115                        abs_paths_opened
 2116                            .entry(fs_path.clone())
 2117                            .or_default()
 2118                            .insert(project_path.clone());
 2119                    }
 2120                    let timestamp = entry.timestamp;
 2121                    match history.entry(project_path) {
 2122                        hash_map::Entry::Occupied(mut entry) => {
 2123                            let (_, old_timestamp) = entry.get();
 2124                            if &timestamp > old_timestamp {
 2125                                entry.insert((fs_path, timestamp));
 2126                            }
 2127                        }
 2128                        hash_map::Entry::Vacant(entry) => {
 2129                            entry.insert((fs_path, timestamp));
 2130                        }
 2131                    }
 2132                });
 2133
 2134            if let Some(item) = pane.active_item()
 2135                && let Some(project_path) = item.project_path(cx)
 2136            {
 2137                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2138
 2139                if let Some(fs_path) = &fs_path {
 2140                    abs_paths_opened
 2141                        .entry(fs_path.clone())
 2142                        .or_default()
 2143                        .insert(project_path.clone());
 2144                }
 2145
 2146                history.insert(project_path, (fs_path, std::usize::MAX));
 2147            }
 2148        }
 2149
 2150        history
 2151            .into_iter()
 2152            .sorted_by_key(|(_, (_, order))| *order)
 2153            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2154            .rev()
 2155            .filter(move |(history_path, abs_path)| {
 2156                let latest_project_path_opened = abs_path
 2157                    .as_ref()
 2158                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2159                    .and_then(|project_paths| {
 2160                        project_paths
 2161                            .iter()
 2162                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2163                    });
 2164
 2165                latest_project_path_opened.is_none_or(|path| path == history_path)
 2166            })
 2167    }
 2168
 2169    pub fn recent_navigation_history(
 2170        &self,
 2171        limit: Option<usize>,
 2172        cx: &App,
 2173    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2174        self.recent_navigation_history_iter(cx)
 2175            .take(limit.unwrap_or(usize::MAX))
 2176            .collect()
 2177    }
 2178
 2179    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2180        for pane in &self.panes {
 2181            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2182        }
 2183    }
 2184
 2185    fn navigate_history(
 2186        &mut self,
 2187        pane: WeakEntity<Pane>,
 2188        mode: NavigationMode,
 2189        window: &mut Window,
 2190        cx: &mut Context<Workspace>,
 2191    ) -> Task<Result<()>> {
 2192        self.navigate_history_impl(pane, mode, window, |history, cx| history.pop(mode, cx), cx)
 2193    }
 2194
 2195    fn navigate_tag_history(
 2196        &mut self,
 2197        pane: WeakEntity<Pane>,
 2198        mode: TagNavigationMode,
 2199        window: &mut Window,
 2200        cx: &mut Context<Workspace>,
 2201    ) -> Task<Result<()>> {
 2202        self.navigate_history_impl(
 2203            pane,
 2204            NavigationMode::Normal,
 2205            window,
 2206            |history, _cx| history.pop_tag(mode),
 2207            cx,
 2208        )
 2209    }
 2210
 2211    fn navigate_history_impl(
 2212        &mut self,
 2213        pane: WeakEntity<Pane>,
 2214        mode: NavigationMode,
 2215        window: &mut Window,
 2216        mut cb: impl FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2217        cx: &mut Context<Workspace>,
 2218    ) -> Task<Result<()>> {
 2219        let to_load = if let Some(pane) = pane.upgrade() {
 2220            pane.update(cx, |pane, cx| {
 2221                window.focus(&pane.focus_handle(cx), cx);
 2222                loop {
 2223                    // Retrieve the weak item handle from the history.
 2224                    let entry = cb(pane.nav_history_mut(), cx)?;
 2225
 2226                    // If the item is still present in this pane, then activate it.
 2227                    if let Some(index) = entry
 2228                        .item
 2229                        .upgrade()
 2230                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2231                    {
 2232                        let prev_active_item_index = pane.active_item_index();
 2233                        pane.nav_history_mut().set_mode(mode);
 2234                        pane.activate_item(index, true, true, window, cx);
 2235                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2236
 2237                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2238                        if let Some(data) = entry.data {
 2239                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2240                        }
 2241
 2242                        if navigated {
 2243                            break None;
 2244                        }
 2245                    } else {
 2246                        // If the item is no longer present in this pane, then retrieve its
 2247                        // path info in order to reopen it.
 2248                        break pane
 2249                            .nav_history()
 2250                            .path_for_item(entry.item.id())
 2251                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2252                    }
 2253                }
 2254            })
 2255        } else {
 2256            None
 2257        };
 2258
 2259        if let Some((project_path, abs_path, entry)) = to_load {
 2260            // If the item was no longer present, then load it again from its previous path, first try the local path
 2261            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2262
 2263            cx.spawn_in(window, async move  |workspace, cx| {
 2264                let open_by_project_path = open_by_project_path.await;
 2265                let mut navigated = false;
 2266                match open_by_project_path
 2267                    .with_context(|| format!("Navigating to {project_path:?}"))
 2268                {
 2269                    Ok((project_entry_id, build_item)) => {
 2270                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2271                            pane.nav_history_mut().set_mode(mode);
 2272                            pane.active_item().map(|p| p.item_id())
 2273                        })?;
 2274
 2275                        pane.update_in(cx, |pane, window, cx| {
 2276                            let item = pane.open_item(
 2277                                project_entry_id,
 2278                                project_path,
 2279                                true,
 2280                                entry.is_preview,
 2281                                true,
 2282                                None,
 2283                                window, cx,
 2284                                build_item,
 2285                            );
 2286                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2287                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2288                            if let Some(data) = entry.data {
 2289                                navigated |= item.navigate(data, window, cx);
 2290                            }
 2291                        })?;
 2292                    }
 2293                    Err(open_by_project_path_e) => {
 2294                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2295                        // and its worktree is now dropped
 2296                        if let Some(abs_path) = abs_path {
 2297                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2298                                pane.nav_history_mut().set_mode(mode);
 2299                                pane.active_item().map(|p| p.item_id())
 2300                            })?;
 2301                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2302                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2303                            })?;
 2304                            match open_by_abs_path
 2305                                .await
 2306                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2307                            {
 2308                                Ok(item) => {
 2309                                    pane.update_in(cx, |pane, window, cx| {
 2310                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2311                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2312                                        if let Some(data) = entry.data {
 2313                                            navigated |= item.navigate(data, window, cx);
 2314                                        }
 2315                                    })?;
 2316                                }
 2317                                Err(open_by_abs_path_e) => {
 2318                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2319                                }
 2320                            }
 2321                        }
 2322                    }
 2323                }
 2324
 2325                if !navigated {
 2326                    workspace
 2327                        .update_in(cx, |workspace, window, cx| {
 2328                            Self::navigate_history(workspace, pane, mode, window, cx)
 2329                        })?
 2330                        .await?;
 2331                }
 2332
 2333                Ok(())
 2334            })
 2335        } else {
 2336            Task::ready(Ok(()))
 2337        }
 2338    }
 2339
 2340    pub fn go_back(
 2341        &mut self,
 2342        pane: WeakEntity<Pane>,
 2343        window: &mut Window,
 2344        cx: &mut Context<Workspace>,
 2345    ) -> Task<Result<()>> {
 2346        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2347    }
 2348
 2349    pub fn go_forward(
 2350        &mut self,
 2351        pane: WeakEntity<Pane>,
 2352        window: &mut Window,
 2353        cx: &mut Context<Workspace>,
 2354    ) -> Task<Result<()>> {
 2355        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2356    }
 2357
 2358    pub fn reopen_closed_item(
 2359        &mut self,
 2360        window: &mut Window,
 2361        cx: &mut Context<Workspace>,
 2362    ) -> Task<Result<()>> {
 2363        self.navigate_history(
 2364            self.active_pane().downgrade(),
 2365            NavigationMode::ReopeningClosedItem,
 2366            window,
 2367            cx,
 2368        )
 2369    }
 2370
 2371    pub fn client(&self) -> &Arc<Client> {
 2372        &self.app_state.client
 2373    }
 2374
 2375    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2376        self.titlebar_item = Some(item);
 2377        cx.notify();
 2378    }
 2379
 2380    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2381        self.on_prompt_for_new_path = Some(prompt)
 2382    }
 2383
 2384    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2385        self.on_prompt_for_open_path = Some(prompt)
 2386    }
 2387
 2388    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2389        self.terminal_provider = Some(Box::new(provider));
 2390    }
 2391
 2392    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2393        self.debugger_provider = Some(Arc::new(provider));
 2394    }
 2395
 2396    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2397        self.debugger_provider.clone()
 2398    }
 2399
 2400    pub fn prompt_for_open_path(
 2401        &mut self,
 2402        path_prompt_options: PathPromptOptions,
 2403        lister: DirectoryLister,
 2404        window: &mut Window,
 2405        cx: &mut Context<Self>,
 2406    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2407        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2408            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2409            let rx = prompt(self, lister, window, cx);
 2410            self.on_prompt_for_open_path = Some(prompt);
 2411            rx
 2412        } else {
 2413            let (tx, rx) = oneshot::channel();
 2414            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2415
 2416            cx.spawn_in(window, async move |workspace, cx| {
 2417                let Ok(result) = abs_path.await else {
 2418                    return Ok(());
 2419                };
 2420
 2421                match result {
 2422                    Ok(result) => {
 2423                        tx.send(result).ok();
 2424                    }
 2425                    Err(err) => {
 2426                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2427                            workspace.show_portal_error(err.to_string(), cx);
 2428                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2429                            let rx = prompt(workspace, lister, window, cx);
 2430                            workspace.on_prompt_for_open_path = Some(prompt);
 2431                            rx
 2432                        })?;
 2433                        if let Ok(path) = rx.await {
 2434                            tx.send(path).ok();
 2435                        }
 2436                    }
 2437                };
 2438                anyhow::Ok(())
 2439            })
 2440            .detach();
 2441
 2442            rx
 2443        }
 2444    }
 2445
 2446    pub fn prompt_for_new_path(
 2447        &mut self,
 2448        lister: DirectoryLister,
 2449        suggested_name: Option<String>,
 2450        window: &mut Window,
 2451        cx: &mut Context<Self>,
 2452    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2453        if self.project.read(cx).is_via_collab()
 2454            || self.project.read(cx).is_via_remote_server()
 2455            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2456        {
 2457            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2458            let rx = prompt(self, lister, suggested_name, window, cx);
 2459            self.on_prompt_for_new_path = Some(prompt);
 2460            return rx;
 2461        }
 2462
 2463        let (tx, rx) = oneshot::channel();
 2464        cx.spawn_in(window, async move |workspace, cx| {
 2465            let abs_path = workspace.update(cx, |workspace, cx| {
 2466                let relative_to = workspace
 2467                    .most_recent_active_path(cx)
 2468                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2469                    .or_else(|| {
 2470                        let project = workspace.project.read(cx);
 2471                        project.visible_worktrees(cx).find_map(|worktree| {
 2472                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2473                        })
 2474                    })
 2475                    .or_else(std::env::home_dir)
 2476                    .unwrap_or_else(|| PathBuf::from(""));
 2477                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2478            })?;
 2479            let abs_path = match abs_path.await? {
 2480                Ok(path) => path,
 2481                Err(err) => {
 2482                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2483                        workspace.show_portal_error(err.to_string(), cx);
 2484
 2485                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2486                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2487                        workspace.on_prompt_for_new_path = Some(prompt);
 2488                        rx
 2489                    })?;
 2490                    if let Ok(path) = rx.await {
 2491                        tx.send(path).ok();
 2492                    }
 2493                    return anyhow::Ok(());
 2494                }
 2495            };
 2496
 2497            tx.send(abs_path.map(|path| vec![path])).ok();
 2498            anyhow::Ok(())
 2499        })
 2500        .detach();
 2501
 2502        rx
 2503    }
 2504
 2505    pub fn titlebar_item(&self) -> Option<AnyView> {
 2506        self.titlebar_item.clone()
 2507    }
 2508
 2509    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2510    /// When set, git-related operations should use this worktree instead of deriving
 2511    /// the active worktree from the focused file.
 2512    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2513        self.active_worktree_override
 2514    }
 2515
 2516    pub fn set_active_worktree_override(
 2517        &mut self,
 2518        worktree_id: Option<WorktreeId>,
 2519        cx: &mut Context<Self>,
 2520    ) {
 2521        self.active_worktree_override = worktree_id;
 2522        cx.notify();
 2523    }
 2524
 2525    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2526        self.active_worktree_override = None;
 2527        cx.notify();
 2528    }
 2529
 2530    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2531    ///
 2532    /// If the given workspace has a local project, then it will be passed
 2533    /// to the callback. Otherwise, a new empty window will be created.
 2534    pub fn with_local_workspace<T, F>(
 2535        &mut self,
 2536        window: &mut Window,
 2537        cx: &mut Context<Self>,
 2538        callback: F,
 2539    ) -> Task<Result<T>>
 2540    where
 2541        T: 'static,
 2542        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2543    {
 2544        if self.project.read(cx).is_local() {
 2545            Task::ready(Ok(callback(self, window, cx)))
 2546        } else {
 2547            let env = self.project.read(cx).cli_environment(cx);
 2548            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2549            cx.spawn_in(window, async move |_vh, cx| {
 2550                let (multi_workspace_window, _) = task.await?;
 2551                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2552                    let workspace = multi_workspace.workspace().clone();
 2553                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2554                })
 2555            })
 2556        }
 2557    }
 2558
 2559    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2560    ///
 2561    /// If the given workspace has a local project, then it will be passed
 2562    /// to the callback. Otherwise, a new empty window will be created.
 2563    pub fn with_local_or_wsl_workspace<T, F>(
 2564        &mut self,
 2565        window: &mut Window,
 2566        cx: &mut Context<Self>,
 2567        callback: F,
 2568    ) -> Task<Result<T>>
 2569    where
 2570        T: 'static,
 2571        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2572    {
 2573        let project = self.project.read(cx);
 2574        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2575            Task::ready(Ok(callback(self, window, cx)))
 2576        } else {
 2577            let env = self.project.read(cx).cli_environment(cx);
 2578            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2579            cx.spawn_in(window, async move |_vh, cx| {
 2580                let (multi_workspace_window, _) = task.await?;
 2581                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2582                    let workspace = multi_workspace.workspace().clone();
 2583                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2584                })
 2585            })
 2586        }
 2587    }
 2588
 2589    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2590        self.project.read(cx).worktrees(cx)
 2591    }
 2592
 2593    pub fn visible_worktrees<'a>(
 2594        &self,
 2595        cx: &'a App,
 2596    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2597        self.project.read(cx).visible_worktrees(cx)
 2598    }
 2599
 2600    #[cfg(any(test, feature = "test-support"))]
 2601    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2602        let futures = self
 2603            .worktrees(cx)
 2604            .filter_map(|worktree| worktree.read(cx).as_local())
 2605            .map(|worktree| worktree.scan_complete())
 2606            .collect::<Vec<_>>();
 2607        async move {
 2608            for future in futures {
 2609                future.await;
 2610            }
 2611        }
 2612    }
 2613
 2614    pub fn close_global(cx: &mut App) {
 2615        cx.defer(|cx| {
 2616            cx.windows().iter().find(|window| {
 2617                window
 2618                    .update(cx, |_, window, _| {
 2619                        if window.is_window_active() {
 2620                            //This can only get called when the window's project connection has been lost
 2621                            //so we don't need to prompt the user for anything and instead just close the window
 2622                            window.remove_window();
 2623                            true
 2624                        } else {
 2625                            false
 2626                        }
 2627                    })
 2628                    .unwrap_or(false)
 2629            });
 2630        });
 2631    }
 2632
 2633    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2634        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2635        cx.spawn_in(window, async move |_, cx| {
 2636            if prepare.await? {
 2637                cx.update(|window, _cx| window.remove_window())?;
 2638            }
 2639            anyhow::Ok(())
 2640        })
 2641        .detach_and_log_err(cx)
 2642    }
 2643
 2644    pub fn move_focused_panel_to_next_position(
 2645        &mut self,
 2646        _: &MoveFocusedPanelToNextPosition,
 2647        window: &mut Window,
 2648        cx: &mut Context<Self>,
 2649    ) {
 2650        let docks = self.all_docks();
 2651        let active_dock = docks
 2652            .into_iter()
 2653            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2654
 2655        if let Some(dock) = active_dock {
 2656            dock.update(cx, |dock, cx| {
 2657                let active_panel = dock
 2658                    .active_panel()
 2659                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2660
 2661                if let Some(panel) = active_panel {
 2662                    panel.move_to_next_position(window, cx);
 2663                }
 2664            })
 2665        }
 2666    }
 2667
 2668    pub fn prepare_to_close(
 2669        &mut self,
 2670        close_intent: CloseIntent,
 2671        window: &mut Window,
 2672        cx: &mut Context<Self>,
 2673    ) -> Task<Result<bool>> {
 2674        let active_call = self.active_call().cloned();
 2675
 2676        cx.spawn_in(window, async move |this, cx| {
 2677            this.update(cx, |this, _| {
 2678                if close_intent == CloseIntent::CloseWindow {
 2679                    this.removing = true;
 2680                }
 2681            })?;
 2682
 2683            let workspace_count = cx.update(|_window, cx| {
 2684                cx.windows()
 2685                    .iter()
 2686                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2687                    .count()
 2688            })?;
 2689
 2690            #[cfg(target_os = "macos")]
 2691            let save_last_workspace = false;
 2692
 2693            // On Linux and Windows, closing the last window should restore the last workspace.
 2694            #[cfg(not(target_os = "macos"))]
 2695            let save_last_workspace = {
 2696                let remaining_workspaces = cx.update(|_window, cx| {
 2697                    cx.windows()
 2698                        .iter()
 2699                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2700                        .filter_map(|multi_workspace| {
 2701                            multi_workspace
 2702                                .update(cx, |multi_workspace, _, cx| {
 2703                                    multi_workspace.workspace().read(cx).removing
 2704                                })
 2705                                .ok()
 2706                        })
 2707                        .filter(|removing| !removing)
 2708                        .count()
 2709                })?;
 2710
 2711                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2712            };
 2713
 2714            if let Some(active_call) = active_call
 2715                && workspace_count == 1
 2716                && active_call.read_with(cx, |call, _| call.room().is_some())
 2717            {
 2718                if close_intent == CloseIntent::CloseWindow {
 2719                    let answer = cx.update(|window, cx| {
 2720                        window.prompt(
 2721                            PromptLevel::Warning,
 2722                            "Do you want to leave the current call?",
 2723                            None,
 2724                            &["Close window and hang up", "Cancel"],
 2725                            cx,
 2726                        )
 2727                    })?;
 2728
 2729                    if answer.await.log_err() == Some(1) {
 2730                        return anyhow::Ok(false);
 2731                    } else {
 2732                        active_call
 2733                            .update(cx, |call, cx| call.hang_up(cx))
 2734                            .await
 2735                            .log_err();
 2736                    }
 2737                }
 2738                if close_intent == CloseIntent::ReplaceWindow {
 2739                    _ = active_call.update(cx, |this, cx| {
 2740                        let multi_workspace = cx
 2741                            .windows()
 2742                            .iter()
 2743                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2744                            .next()
 2745                            .unwrap();
 2746                        let project = multi_workspace
 2747                            .read(cx)?
 2748                            .workspace()
 2749                            .read(cx)
 2750                            .project
 2751                            .clone();
 2752                        if project.read(cx).is_shared() {
 2753                            this.unshare_project(project, cx)?;
 2754                        }
 2755                        Ok::<_, anyhow::Error>(())
 2756                    })?;
 2757                }
 2758            }
 2759
 2760            let save_result = this
 2761                .update_in(cx, |this, window, cx| {
 2762                    this.save_all_internal(SaveIntent::Close, window, cx)
 2763                })?
 2764                .await;
 2765
 2766            // If we're not quitting, but closing, we remove the workspace from
 2767            // the current session.
 2768            if close_intent != CloseIntent::Quit
 2769                && !save_last_workspace
 2770                && save_result.as_ref().is_ok_and(|&res| res)
 2771            {
 2772                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2773                    .await;
 2774            }
 2775
 2776            save_result
 2777        })
 2778    }
 2779
 2780    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2781        self.save_all_internal(
 2782            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2783            window,
 2784            cx,
 2785        )
 2786        .detach_and_log_err(cx);
 2787    }
 2788
 2789    fn send_keystrokes(
 2790        &mut self,
 2791        action: &SendKeystrokes,
 2792        window: &mut Window,
 2793        cx: &mut Context<Self>,
 2794    ) {
 2795        let keystrokes: Vec<Keystroke> = action
 2796            .0
 2797            .split(' ')
 2798            .flat_map(|k| Keystroke::parse(k).log_err())
 2799            .map(|k| {
 2800                cx.keyboard_mapper()
 2801                    .map_key_equivalent(k, false)
 2802                    .inner()
 2803                    .clone()
 2804            })
 2805            .collect();
 2806        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2807    }
 2808
 2809    pub fn send_keystrokes_impl(
 2810        &mut self,
 2811        keystrokes: Vec<Keystroke>,
 2812        window: &mut Window,
 2813        cx: &mut Context<Self>,
 2814    ) -> Shared<Task<()>> {
 2815        let mut state = self.dispatching_keystrokes.borrow_mut();
 2816        if !state.dispatched.insert(keystrokes.clone()) {
 2817            cx.propagate();
 2818            return state.task.clone().unwrap();
 2819        }
 2820
 2821        state.queue.extend(keystrokes);
 2822
 2823        let keystrokes = self.dispatching_keystrokes.clone();
 2824        if state.task.is_none() {
 2825            state.task = Some(
 2826                window
 2827                    .spawn(cx, async move |cx| {
 2828                        // limit to 100 keystrokes to avoid infinite recursion.
 2829                        for _ in 0..100 {
 2830                            let mut state = keystrokes.borrow_mut();
 2831                            let Some(keystroke) = state.queue.pop_front() else {
 2832                                state.dispatched.clear();
 2833                                state.task.take();
 2834                                return;
 2835                            };
 2836                            drop(state);
 2837                            cx.update(|window, cx| {
 2838                                let focused = window.focused(cx);
 2839                                window.dispatch_keystroke(keystroke.clone(), cx);
 2840                                if window.focused(cx) != focused {
 2841                                    // dispatch_keystroke may cause the focus to change.
 2842                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2843                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2844                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2845                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2846                                    // )
 2847                                    window.draw(cx).clear();
 2848                                }
 2849                            })
 2850                            .ok();
 2851                        }
 2852
 2853                        *keystrokes.borrow_mut() = Default::default();
 2854                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2855                    })
 2856                    .shared(),
 2857            );
 2858        }
 2859        state.task.clone().unwrap()
 2860    }
 2861
 2862    fn save_all_internal(
 2863        &mut self,
 2864        mut save_intent: SaveIntent,
 2865        window: &mut Window,
 2866        cx: &mut Context<Self>,
 2867    ) -> Task<Result<bool>> {
 2868        if self.project.read(cx).is_disconnected(cx) {
 2869            return Task::ready(Ok(true));
 2870        }
 2871        let dirty_items = self
 2872            .panes
 2873            .iter()
 2874            .flat_map(|pane| {
 2875                pane.read(cx).items().filter_map(|item| {
 2876                    if item.is_dirty(cx) {
 2877                        item.tab_content_text(0, cx);
 2878                        Some((pane.downgrade(), item.boxed_clone()))
 2879                    } else {
 2880                        None
 2881                    }
 2882                })
 2883            })
 2884            .collect::<Vec<_>>();
 2885
 2886        let project = self.project.clone();
 2887        cx.spawn_in(window, async move |workspace, cx| {
 2888            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2889                let (serialize_tasks, remaining_dirty_items) =
 2890                    workspace.update_in(cx, |workspace, window, cx| {
 2891                        let mut remaining_dirty_items = Vec::new();
 2892                        let mut serialize_tasks = Vec::new();
 2893                        for (pane, item) in dirty_items {
 2894                            if let Some(task) = item
 2895                                .to_serializable_item_handle(cx)
 2896                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2897                            {
 2898                                serialize_tasks.push(task);
 2899                            } else {
 2900                                remaining_dirty_items.push((pane, item));
 2901                            }
 2902                        }
 2903                        (serialize_tasks, remaining_dirty_items)
 2904                    })?;
 2905
 2906                futures::future::try_join_all(serialize_tasks).await?;
 2907
 2908                if remaining_dirty_items.len() > 1 {
 2909                    let answer = workspace.update_in(cx, |_, window, cx| {
 2910                        let detail = Pane::file_names_for_prompt(
 2911                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2912                            cx,
 2913                        );
 2914                        window.prompt(
 2915                            PromptLevel::Warning,
 2916                            "Do you want to save all changes in the following files?",
 2917                            Some(&detail),
 2918                            &["Save all", "Discard all", "Cancel"],
 2919                            cx,
 2920                        )
 2921                    })?;
 2922                    match answer.await.log_err() {
 2923                        Some(0) => save_intent = SaveIntent::SaveAll,
 2924                        Some(1) => save_intent = SaveIntent::Skip,
 2925                        Some(2) => return Ok(false),
 2926                        _ => {}
 2927                    }
 2928                }
 2929
 2930                remaining_dirty_items
 2931            } else {
 2932                dirty_items
 2933            };
 2934
 2935            for (pane, item) in dirty_items {
 2936                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2937                    (
 2938                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2939                        item.project_entry_ids(cx),
 2940                    )
 2941                })?;
 2942                if (singleton || !project_entry_ids.is_empty())
 2943                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2944                {
 2945                    return Ok(false);
 2946                }
 2947            }
 2948            Ok(true)
 2949        })
 2950    }
 2951
 2952    pub fn open_workspace_for_paths(
 2953        &mut self,
 2954        replace_current_window: bool,
 2955        paths: Vec<PathBuf>,
 2956        window: &mut Window,
 2957        cx: &mut Context<Self>,
 2958    ) -> Task<Result<()>> {
 2959        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 2960        let is_remote = self.project.read(cx).is_via_collab();
 2961        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2962        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2963
 2964        let window_to_replace = if replace_current_window {
 2965            window_handle
 2966        } else if is_remote || has_worktree || has_dirty_items {
 2967            None
 2968        } else {
 2969            window_handle
 2970        };
 2971        let app_state = self.app_state.clone();
 2972
 2973        cx.spawn(async move |_, cx| {
 2974            cx.update(|cx| {
 2975                open_paths(
 2976                    &paths,
 2977                    app_state,
 2978                    OpenOptions {
 2979                        replace_window: window_to_replace,
 2980                        ..Default::default()
 2981                    },
 2982                    cx,
 2983                )
 2984            })
 2985            .await?;
 2986            Ok(())
 2987        })
 2988    }
 2989
 2990    #[allow(clippy::type_complexity)]
 2991    pub fn open_paths(
 2992        &mut self,
 2993        mut abs_paths: Vec<PathBuf>,
 2994        options: OpenOptions,
 2995        pane: Option<WeakEntity<Pane>>,
 2996        window: &mut Window,
 2997        cx: &mut Context<Self>,
 2998    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2999        let fs = self.app_state.fs.clone();
 3000
 3001        let caller_ordered_abs_paths = abs_paths.clone();
 3002
 3003        // Sort the paths to ensure we add worktrees for parents before their children.
 3004        abs_paths.sort_unstable();
 3005        cx.spawn_in(window, async move |this, cx| {
 3006            let mut tasks = Vec::with_capacity(abs_paths.len());
 3007
 3008            for abs_path in &abs_paths {
 3009                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3010                    OpenVisible::All => Some(true),
 3011                    OpenVisible::None => Some(false),
 3012                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3013                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3014                        Some(None) => Some(true),
 3015                        None => None,
 3016                    },
 3017                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3018                        Some(Some(metadata)) => Some(metadata.is_dir),
 3019                        Some(None) => Some(false),
 3020                        None => None,
 3021                    },
 3022                };
 3023                let project_path = match visible {
 3024                    Some(visible) => match this
 3025                        .update(cx, |this, cx| {
 3026                            Workspace::project_path_for_path(
 3027                                this.project.clone(),
 3028                                abs_path,
 3029                                visible,
 3030                                cx,
 3031                            )
 3032                        })
 3033                        .log_err()
 3034                    {
 3035                        Some(project_path) => project_path.await.log_err(),
 3036                        None => None,
 3037                    },
 3038                    None => None,
 3039                };
 3040
 3041                let this = this.clone();
 3042                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3043                let fs = fs.clone();
 3044                let pane = pane.clone();
 3045                let task = cx.spawn(async move |cx| {
 3046                    let (_worktree, project_path) = project_path?;
 3047                    if fs.is_dir(&abs_path).await {
 3048                        // Opening a directory should not race to update the active entry.
 3049                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3050                        None
 3051                    } else {
 3052                        Some(
 3053                            this.update_in(cx, |this, window, cx| {
 3054                                this.open_path(
 3055                                    project_path,
 3056                                    pane,
 3057                                    options.focus.unwrap_or(true),
 3058                                    window,
 3059                                    cx,
 3060                                )
 3061                            })
 3062                            .ok()?
 3063                            .await,
 3064                        )
 3065                    }
 3066                });
 3067                tasks.push(task);
 3068            }
 3069
 3070            let results = futures::future::join_all(tasks).await;
 3071
 3072            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3073            let mut winner: Option<(PathBuf, bool)> = None;
 3074            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3075                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3076                    if !metadata.is_dir {
 3077                        winner = Some((abs_path, false));
 3078                        break;
 3079                    }
 3080                    if winner.is_none() {
 3081                        winner = Some((abs_path, true));
 3082                    }
 3083                } else if winner.is_none() {
 3084                    winner = Some((abs_path, false));
 3085                }
 3086            }
 3087
 3088            // Compute the winner entry id on the foreground thread and emit once, after all
 3089            // paths finish opening. This avoids races between concurrently-opening paths
 3090            // (directories in particular) and makes the resulting project panel selection
 3091            // deterministic.
 3092            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3093                'emit_winner: {
 3094                    let winner_abs_path: Arc<Path> =
 3095                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3096
 3097                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3098                        OpenVisible::All => true,
 3099                        OpenVisible::None => false,
 3100                        OpenVisible::OnlyFiles => !winner_is_dir,
 3101                        OpenVisible::OnlyDirectories => winner_is_dir,
 3102                    };
 3103
 3104                    let Some(worktree_task) = this
 3105                        .update(cx, |workspace, cx| {
 3106                            workspace.project.update(cx, |project, cx| {
 3107                                project.find_or_create_worktree(
 3108                                    winner_abs_path.as_ref(),
 3109                                    visible,
 3110                                    cx,
 3111                                )
 3112                            })
 3113                        })
 3114                        .ok()
 3115                    else {
 3116                        break 'emit_winner;
 3117                    };
 3118
 3119                    let Ok((worktree, _)) = worktree_task.await else {
 3120                        break 'emit_winner;
 3121                    };
 3122
 3123                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3124                        let worktree = worktree.read(cx);
 3125                        let worktree_abs_path = worktree.abs_path();
 3126                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3127                            worktree.root_entry()
 3128                        } else {
 3129                            winner_abs_path
 3130                                .strip_prefix(worktree_abs_path.as_ref())
 3131                                .ok()
 3132                                .and_then(|relative_path| {
 3133                                    let relative_path =
 3134                                        RelPath::new(relative_path, PathStyle::local())
 3135                                            .log_err()?;
 3136                                    worktree.entry_for_path(&relative_path)
 3137                                })
 3138                        }?;
 3139                        Some(entry.id)
 3140                    }) else {
 3141                        break 'emit_winner;
 3142                    };
 3143
 3144                    this.update(cx, |workspace, cx| {
 3145                        workspace.project.update(cx, |_, cx| {
 3146                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3147                        });
 3148                    })
 3149                    .ok();
 3150                }
 3151            }
 3152
 3153            results
 3154        })
 3155    }
 3156
 3157    pub fn open_resolved_path(
 3158        &mut self,
 3159        path: ResolvedPath,
 3160        window: &mut Window,
 3161        cx: &mut Context<Self>,
 3162    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3163        match path {
 3164            ResolvedPath::ProjectPath { project_path, .. } => {
 3165                self.open_path(project_path, None, true, window, cx)
 3166            }
 3167            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3168                PathBuf::from(path),
 3169                OpenOptions {
 3170                    visible: Some(OpenVisible::None),
 3171                    ..Default::default()
 3172                },
 3173                window,
 3174                cx,
 3175            ),
 3176        }
 3177    }
 3178
 3179    pub fn absolute_path_of_worktree(
 3180        &self,
 3181        worktree_id: WorktreeId,
 3182        cx: &mut Context<Self>,
 3183    ) -> Option<PathBuf> {
 3184        self.project
 3185            .read(cx)
 3186            .worktree_for_id(worktree_id, cx)
 3187            // TODO: use `abs_path` or `root_dir`
 3188            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3189    }
 3190
 3191    fn add_folder_to_project(
 3192        &mut self,
 3193        _: &AddFolderToProject,
 3194        window: &mut Window,
 3195        cx: &mut Context<Self>,
 3196    ) {
 3197        let project = self.project.read(cx);
 3198        if project.is_via_collab() {
 3199            self.show_error(
 3200                &anyhow!("You cannot add folders to someone else's project"),
 3201                cx,
 3202            );
 3203            return;
 3204        }
 3205        let paths = self.prompt_for_open_path(
 3206            PathPromptOptions {
 3207                files: false,
 3208                directories: true,
 3209                multiple: true,
 3210                prompt: None,
 3211            },
 3212            DirectoryLister::Project(self.project.clone()),
 3213            window,
 3214            cx,
 3215        );
 3216        cx.spawn_in(window, async move |this, cx| {
 3217            if let Some(paths) = paths.await.log_err().flatten() {
 3218                let results = this
 3219                    .update_in(cx, |this, window, cx| {
 3220                        this.open_paths(
 3221                            paths,
 3222                            OpenOptions {
 3223                                visible: Some(OpenVisible::All),
 3224                                ..Default::default()
 3225                            },
 3226                            None,
 3227                            window,
 3228                            cx,
 3229                        )
 3230                    })?
 3231                    .await;
 3232                for result in results.into_iter().flatten() {
 3233                    result.log_err();
 3234                }
 3235            }
 3236            anyhow::Ok(())
 3237        })
 3238        .detach_and_log_err(cx);
 3239    }
 3240
 3241    pub fn project_path_for_path(
 3242        project: Entity<Project>,
 3243        abs_path: &Path,
 3244        visible: bool,
 3245        cx: &mut App,
 3246    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3247        let entry = project.update(cx, |project, cx| {
 3248            project.find_or_create_worktree(abs_path, visible, cx)
 3249        });
 3250        cx.spawn(async move |cx| {
 3251            let (worktree, path) = entry.await?;
 3252            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3253            Ok((worktree, ProjectPath { worktree_id, path }))
 3254        })
 3255    }
 3256
 3257    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3258        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3259    }
 3260
 3261    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3262        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3263    }
 3264
 3265    pub fn items_of_type<'a, T: Item>(
 3266        &'a self,
 3267        cx: &'a App,
 3268    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3269        self.panes
 3270            .iter()
 3271            .flat_map(|pane| pane.read(cx).items_of_type())
 3272    }
 3273
 3274    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3275        self.active_pane().read(cx).active_item()
 3276    }
 3277
 3278    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3279        let item = self.active_item(cx)?;
 3280        item.to_any_view().downcast::<I>().ok()
 3281    }
 3282
 3283    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3284        self.active_item(cx).and_then(|item| item.project_path(cx))
 3285    }
 3286
 3287    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3288        self.recent_navigation_history_iter(cx)
 3289            .filter_map(|(path, abs_path)| {
 3290                let worktree = self
 3291                    .project
 3292                    .read(cx)
 3293                    .worktree_for_id(path.worktree_id, cx)?;
 3294                if worktree.read(cx).is_visible() {
 3295                    abs_path
 3296                } else {
 3297                    None
 3298                }
 3299            })
 3300            .next()
 3301    }
 3302
 3303    pub fn save_active_item(
 3304        &mut self,
 3305        save_intent: SaveIntent,
 3306        window: &mut Window,
 3307        cx: &mut App,
 3308    ) -> Task<Result<()>> {
 3309        let project = self.project.clone();
 3310        let pane = self.active_pane();
 3311        let item = pane.read(cx).active_item();
 3312        let pane = pane.downgrade();
 3313
 3314        window.spawn(cx, async move |cx| {
 3315            if let Some(item) = item {
 3316                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3317                    .await
 3318                    .map(|_| ())
 3319            } else {
 3320                Ok(())
 3321            }
 3322        })
 3323    }
 3324
 3325    pub fn close_inactive_items_and_panes(
 3326        &mut self,
 3327        action: &CloseInactiveTabsAndPanes,
 3328        window: &mut Window,
 3329        cx: &mut Context<Self>,
 3330    ) {
 3331        if let Some(task) = self.close_all_internal(
 3332            true,
 3333            action.save_intent.unwrap_or(SaveIntent::Close),
 3334            window,
 3335            cx,
 3336        ) {
 3337            task.detach_and_log_err(cx)
 3338        }
 3339    }
 3340
 3341    pub fn close_all_items_and_panes(
 3342        &mut self,
 3343        action: &CloseAllItemsAndPanes,
 3344        window: &mut Window,
 3345        cx: &mut Context<Self>,
 3346    ) {
 3347        if let Some(task) = self.close_all_internal(
 3348            false,
 3349            action.save_intent.unwrap_or(SaveIntent::Close),
 3350            window,
 3351            cx,
 3352        ) {
 3353            task.detach_and_log_err(cx)
 3354        }
 3355    }
 3356
 3357    fn close_all_internal(
 3358        &mut self,
 3359        retain_active_pane: bool,
 3360        save_intent: SaveIntent,
 3361        window: &mut Window,
 3362        cx: &mut Context<Self>,
 3363    ) -> Option<Task<Result<()>>> {
 3364        let current_pane = self.active_pane();
 3365
 3366        let mut tasks = Vec::new();
 3367
 3368        if retain_active_pane {
 3369            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3370                pane.close_other_items(
 3371                    &CloseOtherItems {
 3372                        save_intent: None,
 3373                        close_pinned: false,
 3374                    },
 3375                    None,
 3376                    window,
 3377                    cx,
 3378                )
 3379            });
 3380
 3381            tasks.push(current_pane_close);
 3382        }
 3383
 3384        for pane in self.panes() {
 3385            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3386                continue;
 3387            }
 3388
 3389            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3390                pane.close_all_items(
 3391                    &CloseAllItems {
 3392                        save_intent: Some(save_intent),
 3393                        close_pinned: false,
 3394                    },
 3395                    window,
 3396                    cx,
 3397                )
 3398            });
 3399
 3400            tasks.push(close_pane_items)
 3401        }
 3402
 3403        if tasks.is_empty() {
 3404            None
 3405        } else {
 3406            Some(cx.spawn_in(window, async move |_, _| {
 3407                for task in tasks {
 3408                    task.await?
 3409                }
 3410                Ok(())
 3411            }))
 3412        }
 3413    }
 3414
 3415    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3416        self.dock_at_position(position).read(cx).is_open()
 3417    }
 3418
 3419    pub fn toggle_dock(
 3420        &mut self,
 3421        dock_side: DockPosition,
 3422        window: &mut Window,
 3423        cx: &mut Context<Self>,
 3424    ) {
 3425        let mut focus_center = false;
 3426        let mut reveal_dock = false;
 3427
 3428        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3429        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3430
 3431        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3432            telemetry::event!(
 3433                "Panel Button Clicked",
 3434                name = panel.persistent_name(),
 3435                toggle_state = !was_visible
 3436            );
 3437        }
 3438        if was_visible {
 3439            self.save_open_dock_positions(cx);
 3440        }
 3441
 3442        let dock = self.dock_at_position(dock_side);
 3443        dock.update(cx, |dock, cx| {
 3444            dock.set_open(!was_visible, window, cx);
 3445
 3446            if dock.active_panel().is_none() {
 3447                let Some(panel_ix) = dock
 3448                    .first_enabled_panel_idx(cx)
 3449                    .log_with_level(log::Level::Info)
 3450                else {
 3451                    return;
 3452                };
 3453                dock.activate_panel(panel_ix, window, cx);
 3454            }
 3455
 3456            if let Some(active_panel) = dock.active_panel() {
 3457                if was_visible {
 3458                    if active_panel
 3459                        .panel_focus_handle(cx)
 3460                        .contains_focused(window, cx)
 3461                    {
 3462                        focus_center = true;
 3463                    }
 3464                } else {
 3465                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3466                    window.focus(focus_handle, cx);
 3467                    reveal_dock = true;
 3468                }
 3469            }
 3470        });
 3471
 3472        if reveal_dock {
 3473            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3474        }
 3475
 3476        if focus_center {
 3477            self.active_pane
 3478                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3479        }
 3480
 3481        cx.notify();
 3482        self.serialize_workspace(window, cx);
 3483    }
 3484
 3485    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3486        self.all_docks().into_iter().find(|&dock| {
 3487            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3488        })
 3489    }
 3490
 3491    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3492        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3493            self.save_open_dock_positions(cx);
 3494            dock.update(cx, |dock, cx| {
 3495                dock.set_open(false, window, cx);
 3496            });
 3497            return true;
 3498        }
 3499        false
 3500    }
 3501
 3502    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3503        self.save_open_dock_positions(cx);
 3504        for dock in self.all_docks() {
 3505            dock.update(cx, |dock, cx| {
 3506                dock.set_open(false, window, cx);
 3507            });
 3508        }
 3509
 3510        cx.focus_self(window);
 3511        cx.notify();
 3512        self.serialize_workspace(window, cx);
 3513    }
 3514
 3515    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3516        self.all_docks()
 3517            .into_iter()
 3518            .filter_map(|dock| {
 3519                let dock_ref = dock.read(cx);
 3520                if dock_ref.is_open() {
 3521                    Some(dock_ref.position())
 3522                } else {
 3523                    None
 3524                }
 3525            })
 3526            .collect()
 3527    }
 3528
 3529    /// Saves the positions of currently open docks.
 3530    ///
 3531    /// Updates `last_open_dock_positions` with positions of all currently open
 3532    /// docks, to later be restored by the 'Toggle All Docks' action.
 3533    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3534        let open_dock_positions = self.get_open_dock_positions(cx);
 3535        if !open_dock_positions.is_empty() {
 3536            self.last_open_dock_positions = open_dock_positions;
 3537        }
 3538    }
 3539
 3540    /// Toggles all docks between open and closed states.
 3541    ///
 3542    /// If any docks are open, closes all and remembers their positions. If all
 3543    /// docks are closed, restores the last remembered dock configuration.
 3544    fn toggle_all_docks(
 3545        &mut self,
 3546        _: &ToggleAllDocks,
 3547        window: &mut Window,
 3548        cx: &mut Context<Self>,
 3549    ) {
 3550        let open_dock_positions = self.get_open_dock_positions(cx);
 3551
 3552        if !open_dock_positions.is_empty() {
 3553            self.close_all_docks(window, cx);
 3554        } else if !self.last_open_dock_positions.is_empty() {
 3555            self.restore_last_open_docks(window, cx);
 3556        }
 3557    }
 3558
 3559    /// Reopens docks from the most recently remembered configuration.
 3560    ///
 3561    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3562    /// and clears the stored positions.
 3563    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3564        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3565
 3566        for position in positions_to_open {
 3567            let dock = self.dock_at_position(position);
 3568            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3569        }
 3570
 3571        cx.focus_self(window);
 3572        cx.notify();
 3573        self.serialize_workspace(window, cx);
 3574    }
 3575
 3576    /// Transfer focus to the panel of the given type.
 3577    pub fn focus_panel<T: Panel>(
 3578        &mut self,
 3579        window: &mut Window,
 3580        cx: &mut Context<Self>,
 3581    ) -> Option<Entity<T>> {
 3582        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 3583        panel.to_any().downcast().ok()
 3584    }
 3585
 3586    /// Focus the panel of the given type if it isn't already focused. If it is
 3587    /// already focused, then transfer focus back to the workspace center.
 3588    pub fn toggle_panel_focus<T: Panel>(
 3589        &mut self,
 3590        window: &mut Window,
 3591        cx: &mut Context<Self>,
 3592    ) -> bool {
 3593        let mut did_focus_panel = false;
 3594        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 3595            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3596            did_focus_panel
 3597        });
 3598
 3599        telemetry::event!(
 3600            "Panel Button Clicked",
 3601            name = T::persistent_name(),
 3602            toggle_state = did_focus_panel
 3603        );
 3604
 3605        did_focus_panel
 3606    }
 3607
 3608    pub fn activate_panel_for_proto_id(
 3609        &mut self,
 3610        panel_id: PanelId,
 3611        window: &mut Window,
 3612        cx: &mut Context<Self>,
 3613    ) -> Option<Arc<dyn PanelHandle>> {
 3614        let mut panel = None;
 3615        for dock in self.all_docks() {
 3616            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3617                panel = dock.update(cx, |dock, cx| {
 3618                    dock.activate_panel(panel_index, window, cx);
 3619                    dock.set_open(true, window, cx);
 3620                    dock.active_panel().cloned()
 3621                });
 3622                break;
 3623            }
 3624        }
 3625
 3626        if panel.is_some() {
 3627            cx.notify();
 3628            self.serialize_workspace(window, cx);
 3629        }
 3630
 3631        panel
 3632    }
 3633
 3634    /// Focus or unfocus the given panel type, depending on the given callback.
 3635    fn focus_or_unfocus_panel<T: Panel>(
 3636        &mut self,
 3637        window: &mut Window,
 3638        cx: &mut Context<Self>,
 3639        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3640    ) -> Option<Arc<dyn PanelHandle>> {
 3641        let mut result_panel = None;
 3642        let mut serialize = false;
 3643        for dock in self.all_docks() {
 3644            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3645                let mut focus_center = false;
 3646                let panel = dock.update(cx, |dock, cx| {
 3647                    dock.activate_panel(panel_index, window, cx);
 3648
 3649                    let panel = dock.active_panel().cloned();
 3650                    if let Some(panel) = panel.as_ref() {
 3651                        if should_focus(&**panel, window, cx) {
 3652                            dock.set_open(true, window, cx);
 3653                            panel.panel_focus_handle(cx).focus(window, cx);
 3654                        } else {
 3655                            focus_center = true;
 3656                        }
 3657                    }
 3658                    panel
 3659                });
 3660
 3661                if focus_center {
 3662                    self.active_pane
 3663                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3664                }
 3665
 3666                result_panel = panel;
 3667                serialize = true;
 3668                break;
 3669            }
 3670        }
 3671
 3672        if serialize {
 3673            self.serialize_workspace(window, cx);
 3674        }
 3675
 3676        cx.notify();
 3677        result_panel
 3678    }
 3679
 3680    /// Open the panel of the given type
 3681    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3682        for dock in self.all_docks() {
 3683            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3684                dock.update(cx, |dock, cx| {
 3685                    dock.activate_panel(panel_index, window, cx);
 3686                    dock.set_open(true, window, cx);
 3687                });
 3688            }
 3689        }
 3690    }
 3691
 3692    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3693        for dock in self.all_docks().iter() {
 3694            dock.update(cx, |dock, cx| {
 3695                if dock.panel::<T>().is_some() {
 3696                    dock.set_open(false, window, cx)
 3697                }
 3698            })
 3699        }
 3700    }
 3701
 3702    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3703        self.all_docks()
 3704            .iter()
 3705            .find_map(|dock| dock.read(cx).panel::<T>())
 3706    }
 3707
 3708    fn dismiss_zoomed_items_to_reveal(
 3709        &mut self,
 3710        dock_to_reveal: Option<DockPosition>,
 3711        window: &mut Window,
 3712        cx: &mut Context<Self>,
 3713    ) {
 3714        // If a center pane is zoomed, unzoom it.
 3715        for pane in &self.panes {
 3716            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3717                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3718            }
 3719        }
 3720
 3721        // If another dock is zoomed, hide it.
 3722        let mut focus_center = false;
 3723        for dock in self.all_docks() {
 3724            dock.update(cx, |dock, cx| {
 3725                if Some(dock.position()) != dock_to_reveal
 3726                    && let Some(panel) = dock.active_panel()
 3727                    && panel.is_zoomed(window, cx)
 3728                {
 3729                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3730                    dock.set_open(false, window, cx);
 3731                }
 3732            });
 3733        }
 3734
 3735        if focus_center {
 3736            self.active_pane
 3737                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3738        }
 3739
 3740        if self.zoomed_position != dock_to_reveal {
 3741            self.zoomed = None;
 3742            self.zoomed_position = None;
 3743            cx.emit(Event::ZoomChanged);
 3744        }
 3745
 3746        cx.notify();
 3747    }
 3748
 3749    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3750        let pane = cx.new(|cx| {
 3751            let mut pane = Pane::new(
 3752                self.weak_handle(),
 3753                self.project.clone(),
 3754                self.pane_history_timestamp.clone(),
 3755                None,
 3756                NewFile.boxed_clone(),
 3757                true,
 3758                window,
 3759                cx,
 3760            );
 3761            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3762            pane
 3763        });
 3764        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3765            .detach();
 3766        self.panes.push(pane.clone());
 3767
 3768        window.focus(&pane.focus_handle(cx), cx);
 3769
 3770        cx.emit(Event::PaneAdded(pane.clone()));
 3771        pane
 3772    }
 3773
 3774    pub fn add_item_to_center(
 3775        &mut self,
 3776        item: Box<dyn ItemHandle>,
 3777        window: &mut Window,
 3778        cx: &mut Context<Self>,
 3779    ) -> bool {
 3780        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3781            if let Some(center_pane) = center_pane.upgrade() {
 3782                center_pane.update(cx, |pane, cx| {
 3783                    pane.add_item(item, true, true, None, window, cx)
 3784                });
 3785                true
 3786            } else {
 3787                false
 3788            }
 3789        } else {
 3790            false
 3791        }
 3792    }
 3793
 3794    pub fn add_item_to_active_pane(
 3795        &mut self,
 3796        item: Box<dyn ItemHandle>,
 3797        destination_index: Option<usize>,
 3798        focus_item: bool,
 3799        window: &mut Window,
 3800        cx: &mut App,
 3801    ) {
 3802        self.add_item(
 3803            self.active_pane.clone(),
 3804            item,
 3805            destination_index,
 3806            false,
 3807            focus_item,
 3808            window,
 3809            cx,
 3810        )
 3811    }
 3812
 3813    pub fn add_item(
 3814        &mut self,
 3815        pane: Entity<Pane>,
 3816        item: Box<dyn ItemHandle>,
 3817        destination_index: Option<usize>,
 3818        activate_pane: bool,
 3819        focus_item: bool,
 3820        window: &mut Window,
 3821        cx: &mut App,
 3822    ) {
 3823        pane.update(cx, |pane, cx| {
 3824            pane.add_item(
 3825                item,
 3826                activate_pane,
 3827                focus_item,
 3828                destination_index,
 3829                window,
 3830                cx,
 3831            )
 3832        });
 3833    }
 3834
 3835    pub fn split_item(
 3836        &mut self,
 3837        split_direction: SplitDirection,
 3838        item: Box<dyn ItemHandle>,
 3839        window: &mut Window,
 3840        cx: &mut Context<Self>,
 3841    ) {
 3842        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3843        self.add_item(new_pane, item, None, true, true, window, cx);
 3844    }
 3845
 3846    pub fn open_abs_path(
 3847        &mut self,
 3848        abs_path: PathBuf,
 3849        options: OpenOptions,
 3850        window: &mut Window,
 3851        cx: &mut Context<Self>,
 3852    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3853        cx.spawn_in(window, async move |workspace, cx| {
 3854            let open_paths_task_result = workspace
 3855                .update_in(cx, |workspace, window, cx| {
 3856                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3857                })
 3858                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3859                .await;
 3860            anyhow::ensure!(
 3861                open_paths_task_result.len() == 1,
 3862                "open abs path {abs_path:?} task returned incorrect number of results"
 3863            );
 3864            match open_paths_task_result
 3865                .into_iter()
 3866                .next()
 3867                .expect("ensured single task result")
 3868            {
 3869                Some(open_result) => {
 3870                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3871                }
 3872                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3873            }
 3874        })
 3875    }
 3876
 3877    pub fn split_abs_path(
 3878        &mut self,
 3879        abs_path: PathBuf,
 3880        visible: bool,
 3881        window: &mut Window,
 3882        cx: &mut Context<Self>,
 3883    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3884        let project_path_task =
 3885            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3886        cx.spawn_in(window, async move |this, cx| {
 3887            let (_, path) = project_path_task.await?;
 3888            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3889                .await
 3890        })
 3891    }
 3892
 3893    pub fn open_path(
 3894        &mut self,
 3895        path: impl Into<ProjectPath>,
 3896        pane: Option<WeakEntity<Pane>>,
 3897        focus_item: bool,
 3898        window: &mut Window,
 3899        cx: &mut App,
 3900    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3901        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3902    }
 3903
 3904    pub fn open_path_preview(
 3905        &mut self,
 3906        path: impl Into<ProjectPath>,
 3907        pane: Option<WeakEntity<Pane>>,
 3908        focus_item: bool,
 3909        allow_preview: bool,
 3910        activate: bool,
 3911        window: &mut Window,
 3912        cx: &mut App,
 3913    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3914        let pane = pane.unwrap_or_else(|| {
 3915            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3916                self.panes
 3917                    .first()
 3918                    .expect("There must be an active pane")
 3919                    .downgrade()
 3920            })
 3921        });
 3922
 3923        let project_path = path.into();
 3924        let task = self.load_path(project_path.clone(), window, cx);
 3925        window.spawn(cx, async move |cx| {
 3926            let (project_entry_id, build_item) = task.await?;
 3927
 3928            pane.update_in(cx, |pane, window, cx| {
 3929                pane.open_item(
 3930                    project_entry_id,
 3931                    project_path,
 3932                    focus_item,
 3933                    allow_preview,
 3934                    activate,
 3935                    None,
 3936                    window,
 3937                    cx,
 3938                    build_item,
 3939                )
 3940            })
 3941        })
 3942    }
 3943
 3944    pub fn split_path(
 3945        &mut self,
 3946        path: impl Into<ProjectPath>,
 3947        window: &mut Window,
 3948        cx: &mut Context<Self>,
 3949    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3950        self.split_path_preview(path, false, None, window, cx)
 3951    }
 3952
 3953    pub fn split_path_preview(
 3954        &mut self,
 3955        path: impl Into<ProjectPath>,
 3956        allow_preview: bool,
 3957        split_direction: Option<SplitDirection>,
 3958        window: &mut Window,
 3959        cx: &mut Context<Self>,
 3960    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3961        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3962            self.panes
 3963                .first()
 3964                .expect("There must be an active pane")
 3965                .downgrade()
 3966        });
 3967
 3968        if let Member::Pane(center_pane) = &self.center.root
 3969            && center_pane.read(cx).items_len() == 0
 3970        {
 3971            return self.open_path(path, Some(pane), true, window, cx);
 3972        }
 3973
 3974        let project_path = path.into();
 3975        let task = self.load_path(project_path.clone(), window, cx);
 3976        cx.spawn_in(window, async move |this, cx| {
 3977            let (project_entry_id, build_item) = task.await?;
 3978            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3979                let pane = pane.upgrade()?;
 3980                let new_pane = this.split_pane(
 3981                    pane,
 3982                    split_direction.unwrap_or(SplitDirection::Right),
 3983                    window,
 3984                    cx,
 3985                );
 3986                new_pane.update(cx, |new_pane, cx| {
 3987                    Some(new_pane.open_item(
 3988                        project_entry_id,
 3989                        project_path,
 3990                        true,
 3991                        allow_preview,
 3992                        true,
 3993                        None,
 3994                        window,
 3995                        cx,
 3996                        build_item,
 3997                    ))
 3998                })
 3999            })
 4000            .map(|option| option.context("pane was dropped"))?
 4001        })
 4002    }
 4003
 4004    fn load_path(
 4005        &mut self,
 4006        path: ProjectPath,
 4007        window: &mut Window,
 4008        cx: &mut App,
 4009    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4010        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4011        registry.open_path(self.project(), &path, window, cx)
 4012    }
 4013
 4014    pub fn find_project_item<T>(
 4015        &self,
 4016        pane: &Entity<Pane>,
 4017        project_item: &Entity<T::Item>,
 4018        cx: &App,
 4019    ) -> Option<Entity<T>>
 4020    where
 4021        T: ProjectItem,
 4022    {
 4023        use project::ProjectItem as _;
 4024        let project_item = project_item.read(cx);
 4025        let entry_id = project_item.entry_id(cx);
 4026        let project_path = project_item.project_path(cx);
 4027
 4028        let mut item = None;
 4029        if let Some(entry_id) = entry_id {
 4030            item = pane.read(cx).item_for_entry(entry_id, cx);
 4031        }
 4032        if item.is_none()
 4033            && let Some(project_path) = project_path
 4034        {
 4035            item = pane.read(cx).item_for_path(project_path, cx);
 4036        }
 4037
 4038        item.and_then(|item| item.downcast::<T>())
 4039    }
 4040
 4041    pub fn is_project_item_open<T>(
 4042        &self,
 4043        pane: &Entity<Pane>,
 4044        project_item: &Entity<T::Item>,
 4045        cx: &App,
 4046    ) -> bool
 4047    where
 4048        T: ProjectItem,
 4049    {
 4050        self.find_project_item::<T>(pane, project_item, cx)
 4051            .is_some()
 4052    }
 4053
 4054    pub fn open_project_item<T>(
 4055        &mut self,
 4056        pane: Entity<Pane>,
 4057        project_item: Entity<T::Item>,
 4058        activate_pane: bool,
 4059        focus_item: bool,
 4060        keep_old_preview: bool,
 4061        allow_new_preview: bool,
 4062        window: &mut Window,
 4063        cx: &mut Context<Self>,
 4064    ) -> Entity<T>
 4065    where
 4066        T: ProjectItem,
 4067    {
 4068        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4069
 4070        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4071            if !keep_old_preview
 4072                && let Some(old_id) = old_item_id
 4073                && old_id != item.item_id()
 4074            {
 4075                // switching to a different item, so unpreview old active item
 4076                pane.update(cx, |pane, _| {
 4077                    pane.unpreview_item_if_preview(old_id);
 4078                });
 4079            }
 4080
 4081            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4082            if !allow_new_preview {
 4083                pane.update(cx, |pane, _| {
 4084                    pane.unpreview_item_if_preview(item.item_id());
 4085                });
 4086            }
 4087            return item;
 4088        }
 4089
 4090        let item = pane.update(cx, |pane, cx| {
 4091            cx.new(|cx| {
 4092                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4093            })
 4094        });
 4095        let mut destination_index = None;
 4096        pane.update(cx, |pane, cx| {
 4097            if !keep_old_preview && let Some(old_id) = old_item_id {
 4098                pane.unpreview_item_if_preview(old_id);
 4099            }
 4100            if allow_new_preview {
 4101                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4102            }
 4103        });
 4104
 4105        self.add_item(
 4106            pane,
 4107            Box::new(item.clone()),
 4108            destination_index,
 4109            activate_pane,
 4110            focus_item,
 4111            window,
 4112            cx,
 4113        );
 4114        item
 4115    }
 4116
 4117    pub fn open_shared_screen(
 4118        &mut self,
 4119        peer_id: PeerId,
 4120        window: &mut Window,
 4121        cx: &mut Context<Self>,
 4122    ) {
 4123        if let Some(shared_screen) =
 4124            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4125        {
 4126            self.active_pane.update(cx, |pane, cx| {
 4127                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4128            });
 4129        }
 4130    }
 4131
 4132    pub fn activate_item(
 4133        &mut self,
 4134        item: &dyn ItemHandle,
 4135        activate_pane: bool,
 4136        focus_item: bool,
 4137        window: &mut Window,
 4138        cx: &mut App,
 4139    ) -> bool {
 4140        let result = self.panes.iter().find_map(|pane| {
 4141            pane.read(cx)
 4142                .index_for_item(item)
 4143                .map(|ix| (pane.clone(), ix))
 4144        });
 4145        if let Some((pane, ix)) = result {
 4146            pane.update(cx, |pane, cx| {
 4147                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4148            });
 4149            true
 4150        } else {
 4151            false
 4152        }
 4153    }
 4154
 4155    fn activate_pane_at_index(
 4156        &mut self,
 4157        action: &ActivatePane,
 4158        window: &mut Window,
 4159        cx: &mut Context<Self>,
 4160    ) {
 4161        let panes = self.center.panes();
 4162        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4163            window.focus(&pane.focus_handle(cx), cx);
 4164        } else {
 4165            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4166                .detach();
 4167        }
 4168    }
 4169
 4170    fn move_item_to_pane_at_index(
 4171        &mut self,
 4172        action: &MoveItemToPane,
 4173        window: &mut Window,
 4174        cx: &mut Context<Self>,
 4175    ) {
 4176        let panes = self.center.panes();
 4177        let destination = match panes.get(action.destination) {
 4178            Some(&destination) => destination.clone(),
 4179            None => {
 4180                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4181                    return;
 4182                }
 4183                let direction = SplitDirection::Right;
 4184                let split_off_pane = self
 4185                    .find_pane_in_direction(direction, cx)
 4186                    .unwrap_or_else(|| self.active_pane.clone());
 4187                let new_pane = self.add_pane(window, cx);
 4188                if self
 4189                    .center
 4190                    .split(&split_off_pane, &new_pane, direction, cx)
 4191                    .log_err()
 4192                    .is_none()
 4193                {
 4194                    return;
 4195                };
 4196                new_pane
 4197            }
 4198        };
 4199
 4200        if action.clone {
 4201            if self
 4202                .active_pane
 4203                .read(cx)
 4204                .active_item()
 4205                .is_some_and(|item| item.can_split(cx))
 4206            {
 4207                clone_active_item(
 4208                    self.database_id(),
 4209                    &self.active_pane,
 4210                    &destination,
 4211                    action.focus,
 4212                    window,
 4213                    cx,
 4214                );
 4215                return;
 4216            }
 4217        }
 4218        move_active_item(
 4219            &self.active_pane,
 4220            &destination,
 4221            action.focus,
 4222            true,
 4223            window,
 4224            cx,
 4225        )
 4226    }
 4227
 4228    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4229        let panes = self.center.panes();
 4230        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4231            let next_ix = (ix + 1) % panes.len();
 4232            let next_pane = panes[next_ix].clone();
 4233            window.focus(&next_pane.focus_handle(cx), cx);
 4234        }
 4235    }
 4236
 4237    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4238        let panes = self.center.panes();
 4239        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4240            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4241            let prev_pane = panes[prev_ix].clone();
 4242            window.focus(&prev_pane.focus_handle(cx), cx);
 4243        }
 4244    }
 4245
 4246    pub fn activate_pane_in_direction(
 4247        &mut self,
 4248        direction: SplitDirection,
 4249        window: &mut Window,
 4250        cx: &mut App,
 4251    ) {
 4252        use ActivateInDirectionTarget as Target;
 4253        enum Origin {
 4254            LeftDock,
 4255            RightDock,
 4256            BottomDock,
 4257            Center,
 4258        }
 4259
 4260        let origin: Origin = [
 4261            (&self.left_dock, Origin::LeftDock),
 4262            (&self.right_dock, Origin::RightDock),
 4263            (&self.bottom_dock, Origin::BottomDock),
 4264        ]
 4265        .into_iter()
 4266        .find_map(|(dock, origin)| {
 4267            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4268                Some(origin)
 4269            } else {
 4270                None
 4271            }
 4272        })
 4273        .unwrap_or(Origin::Center);
 4274
 4275        let get_last_active_pane = || {
 4276            let pane = self
 4277                .last_active_center_pane
 4278                .clone()
 4279                .unwrap_or_else(|| {
 4280                    self.panes
 4281                        .first()
 4282                        .expect("There must be an active pane")
 4283                        .downgrade()
 4284                })
 4285                .upgrade()?;
 4286            (pane.read(cx).items_len() != 0).then_some(pane)
 4287        };
 4288
 4289        let try_dock =
 4290            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4291
 4292        let target = match (origin, direction) {
 4293            // We're in the center, so we first try to go to a different pane,
 4294            // otherwise try to go to a dock.
 4295            (Origin::Center, direction) => {
 4296                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4297                    Some(Target::Pane(pane))
 4298                } else {
 4299                    match direction {
 4300                        SplitDirection::Up => None,
 4301                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4302                        SplitDirection::Left => try_dock(&self.left_dock),
 4303                        SplitDirection::Right => try_dock(&self.right_dock),
 4304                    }
 4305                }
 4306            }
 4307
 4308            (Origin::LeftDock, SplitDirection::Right) => {
 4309                if let Some(last_active_pane) = get_last_active_pane() {
 4310                    Some(Target::Pane(last_active_pane))
 4311                } else {
 4312                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4313                }
 4314            }
 4315
 4316            (Origin::LeftDock, SplitDirection::Down)
 4317            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4318
 4319            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4320            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4321            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4322
 4323            (Origin::RightDock, SplitDirection::Left) => {
 4324                if let Some(last_active_pane) = get_last_active_pane() {
 4325                    Some(Target::Pane(last_active_pane))
 4326                } else {
 4327                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4328                }
 4329            }
 4330
 4331            _ => None,
 4332        };
 4333
 4334        match target {
 4335            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4336                let pane = pane.read(cx);
 4337                if let Some(item) = pane.active_item() {
 4338                    item.item_focus_handle(cx).focus(window, cx);
 4339                } else {
 4340                    log::error!(
 4341                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4342                    );
 4343                }
 4344            }
 4345            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4346                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4347                window.defer(cx, move |window, cx| {
 4348                    let dock = dock.read(cx);
 4349                    if let Some(panel) = dock.active_panel() {
 4350                        panel.panel_focus_handle(cx).focus(window, cx);
 4351                    } else {
 4352                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4353                    }
 4354                })
 4355            }
 4356            None => {}
 4357        }
 4358    }
 4359
 4360    pub fn move_item_to_pane_in_direction(
 4361        &mut self,
 4362        action: &MoveItemToPaneInDirection,
 4363        window: &mut Window,
 4364        cx: &mut Context<Self>,
 4365    ) {
 4366        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4367            Some(destination) => destination,
 4368            None => {
 4369                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4370                    return;
 4371                }
 4372                let new_pane = self.add_pane(window, cx);
 4373                if self
 4374                    .center
 4375                    .split(&self.active_pane, &new_pane, action.direction, cx)
 4376                    .log_err()
 4377                    .is_none()
 4378                {
 4379                    return;
 4380                };
 4381                new_pane
 4382            }
 4383        };
 4384
 4385        if action.clone {
 4386            if self
 4387                .active_pane
 4388                .read(cx)
 4389                .active_item()
 4390                .is_some_and(|item| item.can_split(cx))
 4391            {
 4392                clone_active_item(
 4393                    self.database_id(),
 4394                    &self.active_pane,
 4395                    &destination,
 4396                    action.focus,
 4397                    window,
 4398                    cx,
 4399                );
 4400                return;
 4401            }
 4402        }
 4403        move_active_item(
 4404            &self.active_pane,
 4405            &destination,
 4406            action.focus,
 4407            true,
 4408            window,
 4409            cx,
 4410        );
 4411    }
 4412
 4413    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4414        self.center.bounding_box_for_pane(pane)
 4415    }
 4416
 4417    pub fn find_pane_in_direction(
 4418        &mut self,
 4419        direction: SplitDirection,
 4420        cx: &App,
 4421    ) -> Option<Entity<Pane>> {
 4422        self.center
 4423            .find_pane_in_direction(&self.active_pane, direction, cx)
 4424            .cloned()
 4425    }
 4426
 4427    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4428        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4429            self.center.swap(&self.active_pane, &to, cx);
 4430            cx.notify();
 4431        }
 4432    }
 4433
 4434    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4435        if self
 4436            .center
 4437            .move_to_border(&self.active_pane, direction, cx)
 4438            .unwrap()
 4439        {
 4440            cx.notify();
 4441        }
 4442    }
 4443
 4444    pub fn resize_pane(
 4445        &mut self,
 4446        axis: gpui::Axis,
 4447        amount: Pixels,
 4448        window: &mut Window,
 4449        cx: &mut Context<Self>,
 4450    ) {
 4451        let docks = self.all_docks();
 4452        let active_dock = docks
 4453            .into_iter()
 4454            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4455
 4456        if let Some(dock) = active_dock {
 4457            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4458                return;
 4459            };
 4460            match dock.read(cx).position() {
 4461                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4462                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4463                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4464            }
 4465        } else {
 4466            self.center
 4467                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4468        }
 4469        cx.notify();
 4470    }
 4471
 4472    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4473        self.center.reset_pane_sizes(cx);
 4474        cx.notify();
 4475    }
 4476
 4477    fn handle_pane_focused(
 4478        &mut self,
 4479        pane: Entity<Pane>,
 4480        window: &mut Window,
 4481        cx: &mut Context<Self>,
 4482    ) {
 4483        // This is explicitly hoisted out of the following check for pane identity as
 4484        // terminal panel panes are not registered as a center panes.
 4485        self.status_bar.update(cx, |status_bar, cx| {
 4486            status_bar.set_active_pane(&pane, window, cx);
 4487        });
 4488        if self.active_pane != pane {
 4489            self.set_active_pane(&pane, window, cx);
 4490        }
 4491
 4492        if self.last_active_center_pane.is_none() {
 4493            self.last_active_center_pane = Some(pane.downgrade());
 4494        }
 4495
 4496        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4497        // This prevents the dock from closing when focus events fire during window activation.
 4498        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4499            let dock_read = dock.read(cx);
 4500            if let Some(panel) = dock_read.active_panel()
 4501                && let Some(dock_pane) = panel.pane(cx)
 4502                && dock_pane == pane
 4503            {
 4504                Some(dock_read.position())
 4505            } else {
 4506                None
 4507            }
 4508        });
 4509
 4510        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4511        if pane.read(cx).is_zoomed() {
 4512            self.zoomed = Some(pane.downgrade().into());
 4513        } else {
 4514            self.zoomed = None;
 4515        }
 4516        self.zoomed_position = None;
 4517        cx.emit(Event::ZoomChanged);
 4518        self.update_active_view_for_followers(window, cx);
 4519        pane.update(cx, |pane, _| {
 4520            pane.track_alternate_file_items();
 4521        });
 4522
 4523        cx.notify();
 4524    }
 4525
 4526    fn set_active_pane(
 4527        &mut self,
 4528        pane: &Entity<Pane>,
 4529        window: &mut Window,
 4530        cx: &mut Context<Self>,
 4531    ) {
 4532        self.active_pane = pane.clone();
 4533        self.active_item_path_changed(true, window, cx);
 4534        self.last_active_center_pane = Some(pane.downgrade());
 4535    }
 4536
 4537    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4538        self.update_active_view_for_followers(window, cx);
 4539    }
 4540
 4541    fn handle_pane_event(
 4542        &mut self,
 4543        pane: &Entity<Pane>,
 4544        event: &pane::Event,
 4545        window: &mut Window,
 4546        cx: &mut Context<Self>,
 4547    ) {
 4548        let mut serialize_workspace = true;
 4549        match event {
 4550            pane::Event::AddItem { item } => {
 4551                item.added_to_pane(self, pane.clone(), window, cx);
 4552                cx.emit(Event::ItemAdded {
 4553                    item: item.boxed_clone(),
 4554                });
 4555            }
 4556            pane::Event::Split { direction, mode } => {
 4557                match mode {
 4558                    SplitMode::ClonePane => {
 4559                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4560                            .detach();
 4561                    }
 4562                    SplitMode::EmptyPane => {
 4563                        self.split_pane(pane.clone(), *direction, window, cx);
 4564                    }
 4565                    SplitMode::MovePane => {
 4566                        self.split_and_move(pane.clone(), *direction, window, cx);
 4567                    }
 4568                };
 4569            }
 4570            pane::Event::JoinIntoNext => {
 4571                self.join_pane_into_next(pane.clone(), window, cx);
 4572            }
 4573            pane::Event::JoinAll => {
 4574                self.join_all_panes(window, cx);
 4575            }
 4576            pane::Event::Remove { focus_on_pane } => {
 4577                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4578            }
 4579            pane::Event::ActivateItem {
 4580                local,
 4581                focus_changed,
 4582            } => {
 4583                window.invalidate_character_coordinates();
 4584
 4585                pane.update(cx, |pane, _| {
 4586                    pane.track_alternate_file_items();
 4587                });
 4588                if *local {
 4589                    self.unfollow_in_pane(pane, window, cx);
 4590                }
 4591                serialize_workspace = *focus_changed || pane != self.active_pane();
 4592                if pane == self.active_pane() {
 4593                    self.active_item_path_changed(*focus_changed, window, cx);
 4594                    self.update_active_view_for_followers(window, cx);
 4595                } else if *local {
 4596                    self.set_active_pane(pane, window, cx);
 4597                }
 4598            }
 4599            pane::Event::UserSavedItem { item, save_intent } => {
 4600                cx.emit(Event::UserSavedItem {
 4601                    pane: pane.downgrade(),
 4602                    item: item.boxed_clone(),
 4603                    save_intent: *save_intent,
 4604                });
 4605                serialize_workspace = false;
 4606            }
 4607            pane::Event::ChangeItemTitle => {
 4608                if *pane == self.active_pane {
 4609                    self.active_item_path_changed(false, window, cx);
 4610                }
 4611                serialize_workspace = false;
 4612            }
 4613            pane::Event::RemovedItem { item } => {
 4614                cx.emit(Event::ActiveItemChanged);
 4615                self.update_window_edited(window, cx);
 4616                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4617                    && entry.get().entity_id() == pane.entity_id()
 4618                {
 4619                    entry.remove();
 4620                }
 4621                cx.emit(Event::ItemRemoved {
 4622                    item_id: item.item_id(),
 4623                });
 4624            }
 4625            pane::Event::Focus => {
 4626                window.invalidate_character_coordinates();
 4627                self.handle_pane_focused(pane.clone(), window, cx);
 4628            }
 4629            pane::Event::ZoomIn => {
 4630                if *pane == self.active_pane {
 4631                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4632                    if pane.read(cx).has_focus(window, cx) {
 4633                        self.zoomed = Some(pane.downgrade().into());
 4634                        self.zoomed_position = None;
 4635                        cx.emit(Event::ZoomChanged);
 4636                    }
 4637                    cx.notify();
 4638                }
 4639            }
 4640            pane::Event::ZoomOut => {
 4641                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4642                if self.zoomed_position.is_none() {
 4643                    self.zoomed = None;
 4644                    cx.emit(Event::ZoomChanged);
 4645                }
 4646                cx.notify();
 4647            }
 4648            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4649        }
 4650
 4651        if serialize_workspace {
 4652            self.serialize_workspace(window, cx);
 4653        }
 4654    }
 4655
 4656    pub fn unfollow_in_pane(
 4657        &mut self,
 4658        pane: &Entity<Pane>,
 4659        window: &mut Window,
 4660        cx: &mut Context<Workspace>,
 4661    ) -> Option<CollaboratorId> {
 4662        let leader_id = self.leader_for_pane(pane)?;
 4663        self.unfollow(leader_id, window, cx);
 4664        Some(leader_id)
 4665    }
 4666
 4667    pub fn split_pane(
 4668        &mut self,
 4669        pane_to_split: Entity<Pane>,
 4670        split_direction: SplitDirection,
 4671        window: &mut Window,
 4672        cx: &mut Context<Self>,
 4673    ) -> Entity<Pane> {
 4674        let new_pane = self.add_pane(window, cx);
 4675        self.center
 4676            .split(&pane_to_split, &new_pane, split_direction, cx)
 4677            .unwrap();
 4678        cx.notify();
 4679        new_pane
 4680    }
 4681
 4682    pub fn split_and_move(
 4683        &mut self,
 4684        pane: Entity<Pane>,
 4685        direction: SplitDirection,
 4686        window: &mut Window,
 4687        cx: &mut Context<Self>,
 4688    ) {
 4689        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4690            return;
 4691        };
 4692        let new_pane = self.add_pane(window, cx);
 4693        new_pane.update(cx, |pane, cx| {
 4694            pane.add_item(item, true, true, None, window, cx)
 4695        });
 4696        self.center.split(&pane, &new_pane, direction, cx).unwrap();
 4697        cx.notify();
 4698    }
 4699
 4700    pub fn split_and_clone(
 4701        &mut self,
 4702        pane: Entity<Pane>,
 4703        direction: SplitDirection,
 4704        window: &mut Window,
 4705        cx: &mut Context<Self>,
 4706    ) -> Task<Option<Entity<Pane>>> {
 4707        let Some(item) = pane.read(cx).active_item() else {
 4708            return Task::ready(None);
 4709        };
 4710        if !item.can_split(cx) {
 4711            return Task::ready(None);
 4712        }
 4713        let task = item.clone_on_split(self.database_id(), window, cx);
 4714        cx.spawn_in(window, async move |this, cx| {
 4715            if let Some(clone) = task.await {
 4716                this.update_in(cx, |this, window, cx| {
 4717                    let new_pane = this.add_pane(window, cx);
 4718                    let nav_history = pane.read(cx).fork_nav_history();
 4719                    new_pane.update(cx, |pane, cx| {
 4720                        pane.set_nav_history(nav_history, cx);
 4721                        pane.add_item(clone, true, true, None, window, cx)
 4722                    });
 4723                    this.center.split(&pane, &new_pane, direction, cx).unwrap();
 4724                    cx.notify();
 4725                    new_pane
 4726                })
 4727                .ok()
 4728            } else {
 4729                None
 4730            }
 4731        })
 4732    }
 4733
 4734    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4735        let active_item = self.active_pane.read(cx).active_item();
 4736        for pane in &self.panes {
 4737            join_pane_into_active(&self.active_pane, pane, window, cx);
 4738        }
 4739        if let Some(active_item) = active_item {
 4740            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4741        }
 4742        cx.notify();
 4743    }
 4744
 4745    pub fn join_pane_into_next(
 4746        &mut self,
 4747        pane: Entity<Pane>,
 4748        window: &mut Window,
 4749        cx: &mut Context<Self>,
 4750    ) {
 4751        let next_pane = self
 4752            .find_pane_in_direction(SplitDirection::Right, cx)
 4753            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4754            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4755            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4756        let Some(next_pane) = next_pane else {
 4757            return;
 4758        };
 4759        move_all_items(&pane, &next_pane, window, cx);
 4760        cx.notify();
 4761    }
 4762
 4763    fn remove_pane(
 4764        &mut self,
 4765        pane: Entity<Pane>,
 4766        focus_on: Option<Entity<Pane>>,
 4767        window: &mut Window,
 4768        cx: &mut Context<Self>,
 4769    ) {
 4770        if self.center.remove(&pane, cx).unwrap() {
 4771            self.force_remove_pane(&pane, &focus_on, window, cx);
 4772            self.unfollow_in_pane(&pane, window, cx);
 4773            self.last_leaders_by_pane.remove(&pane.downgrade());
 4774            for removed_item in pane.read(cx).items() {
 4775                self.panes_by_item.remove(&removed_item.item_id());
 4776            }
 4777
 4778            cx.notify();
 4779        } else {
 4780            self.active_item_path_changed(true, window, cx);
 4781        }
 4782        cx.emit(Event::PaneRemoved);
 4783    }
 4784
 4785    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4786        &mut self.panes
 4787    }
 4788
 4789    pub fn panes(&self) -> &[Entity<Pane>] {
 4790        &self.panes
 4791    }
 4792
 4793    pub fn active_pane(&self) -> &Entity<Pane> {
 4794        &self.active_pane
 4795    }
 4796
 4797    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4798        for dock in self.all_docks() {
 4799            if dock.focus_handle(cx).contains_focused(window, cx)
 4800                && let Some(pane) = dock
 4801                    .read(cx)
 4802                    .active_panel()
 4803                    .and_then(|panel| panel.pane(cx))
 4804            {
 4805                return pane;
 4806            }
 4807        }
 4808        self.active_pane().clone()
 4809    }
 4810
 4811    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4812        self.find_pane_in_direction(SplitDirection::Right, cx)
 4813            .unwrap_or_else(|| {
 4814                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4815            })
 4816    }
 4817
 4818    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4819        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4820        weak_pane.upgrade()
 4821    }
 4822
 4823    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4824        self.follower_states.retain(|leader_id, state| {
 4825            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4826                for item in state.items_by_leader_view_id.values() {
 4827                    item.view.set_leader_id(None, window, cx);
 4828                }
 4829                false
 4830            } else {
 4831                true
 4832            }
 4833        });
 4834        cx.notify();
 4835    }
 4836
 4837    pub fn start_following(
 4838        &mut self,
 4839        leader_id: impl Into<CollaboratorId>,
 4840        window: &mut Window,
 4841        cx: &mut Context<Self>,
 4842    ) -> Option<Task<Result<()>>> {
 4843        let leader_id = leader_id.into();
 4844        let pane = self.active_pane().clone();
 4845
 4846        self.last_leaders_by_pane
 4847            .insert(pane.downgrade(), leader_id);
 4848        self.unfollow(leader_id, window, cx);
 4849        self.unfollow_in_pane(&pane, window, cx);
 4850        self.follower_states.insert(
 4851            leader_id,
 4852            FollowerState {
 4853                center_pane: pane.clone(),
 4854                dock_pane: None,
 4855                active_view_id: None,
 4856                items_by_leader_view_id: Default::default(),
 4857            },
 4858        );
 4859        cx.notify();
 4860
 4861        match leader_id {
 4862            CollaboratorId::PeerId(leader_peer_id) => {
 4863                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4864                let project_id = self.project.read(cx).remote_id();
 4865                let request = self.app_state.client.request(proto::Follow {
 4866                    room_id,
 4867                    project_id,
 4868                    leader_id: Some(leader_peer_id),
 4869                });
 4870
 4871                Some(cx.spawn_in(window, async move |this, cx| {
 4872                    let response = request.await?;
 4873                    this.update(cx, |this, _| {
 4874                        let state = this
 4875                            .follower_states
 4876                            .get_mut(&leader_id)
 4877                            .context("following interrupted")?;
 4878                        state.active_view_id = response
 4879                            .active_view
 4880                            .as_ref()
 4881                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4882                        anyhow::Ok(())
 4883                    })??;
 4884                    if let Some(view) = response.active_view {
 4885                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4886                    }
 4887                    this.update_in(cx, |this, window, cx| {
 4888                        this.leader_updated(leader_id, window, cx)
 4889                    })?;
 4890                    Ok(())
 4891                }))
 4892            }
 4893            CollaboratorId::Agent => {
 4894                self.leader_updated(leader_id, window, cx)?;
 4895                Some(Task::ready(Ok(())))
 4896            }
 4897        }
 4898    }
 4899
 4900    pub fn follow_next_collaborator(
 4901        &mut self,
 4902        _: &FollowNextCollaborator,
 4903        window: &mut Window,
 4904        cx: &mut Context<Self>,
 4905    ) {
 4906        let collaborators = self.project.read(cx).collaborators();
 4907        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4908            let mut collaborators = collaborators.keys().copied();
 4909            for peer_id in collaborators.by_ref() {
 4910                if CollaboratorId::PeerId(peer_id) == leader_id {
 4911                    break;
 4912                }
 4913            }
 4914            collaborators.next().map(CollaboratorId::PeerId)
 4915        } else if let Some(last_leader_id) =
 4916            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4917        {
 4918            match last_leader_id {
 4919                CollaboratorId::PeerId(peer_id) => {
 4920                    if collaborators.contains_key(peer_id) {
 4921                        Some(*last_leader_id)
 4922                    } else {
 4923                        None
 4924                    }
 4925                }
 4926                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4927            }
 4928        } else {
 4929            None
 4930        };
 4931
 4932        let pane = self.active_pane.clone();
 4933        let Some(leader_id) = next_leader_id.or_else(|| {
 4934            Some(CollaboratorId::PeerId(
 4935                collaborators.keys().copied().next()?,
 4936            ))
 4937        }) else {
 4938            return;
 4939        };
 4940        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4941            return;
 4942        }
 4943        if let Some(task) = self.start_following(leader_id, window, cx) {
 4944            task.detach_and_log_err(cx)
 4945        }
 4946    }
 4947
 4948    pub fn follow(
 4949        &mut self,
 4950        leader_id: impl Into<CollaboratorId>,
 4951        window: &mut Window,
 4952        cx: &mut Context<Self>,
 4953    ) {
 4954        let leader_id = leader_id.into();
 4955
 4956        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4957            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4958                return;
 4959            };
 4960            let room = room.read(cx);
 4961            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4962                return;
 4963            };
 4964
 4965            let project = self.project.read(cx);
 4966
 4967            let other_project_id = match remote_participant.location {
 4968                call::ParticipantLocation::External => None,
 4969                call::ParticipantLocation::UnsharedProject => None,
 4970                call::ParticipantLocation::SharedProject { project_id } => {
 4971                    if Some(project_id) == project.remote_id() {
 4972                        None
 4973                    } else {
 4974                        Some(project_id)
 4975                    }
 4976                }
 4977            };
 4978
 4979            // if they are active in another project, follow there.
 4980            if let Some(project_id) = other_project_id {
 4981                let app_state = self.app_state.clone();
 4982                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4983                    .detach_and_log_err(cx);
 4984            }
 4985        }
 4986
 4987        // if you're already following, find the right pane and focus it.
 4988        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4989            window.focus(&follower_state.pane().focus_handle(cx), cx);
 4990
 4991            return;
 4992        }
 4993
 4994        // Otherwise, follow.
 4995        if let Some(task) = self.start_following(leader_id, window, cx) {
 4996            task.detach_and_log_err(cx)
 4997        }
 4998    }
 4999
 5000    pub fn unfollow(
 5001        &mut self,
 5002        leader_id: impl Into<CollaboratorId>,
 5003        window: &mut Window,
 5004        cx: &mut Context<Self>,
 5005    ) -> Option<()> {
 5006        cx.notify();
 5007
 5008        let leader_id = leader_id.into();
 5009        let state = self.follower_states.remove(&leader_id)?;
 5010        for (_, item) in state.items_by_leader_view_id {
 5011            item.view.set_leader_id(None, window, cx);
 5012        }
 5013
 5014        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5015            let project_id = self.project.read(cx).remote_id();
 5016            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 5017            self.app_state
 5018                .client
 5019                .send(proto::Unfollow {
 5020                    room_id,
 5021                    project_id,
 5022                    leader_id: Some(leader_peer_id),
 5023                })
 5024                .log_err();
 5025        }
 5026
 5027        Some(())
 5028    }
 5029
 5030    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5031        self.follower_states.contains_key(&id.into())
 5032    }
 5033
 5034    fn active_item_path_changed(
 5035        &mut self,
 5036        focus_changed: bool,
 5037        window: &mut Window,
 5038        cx: &mut Context<Self>,
 5039    ) {
 5040        cx.emit(Event::ActiveItemChanged);
 5041        let active_entry = self.active_project_path(cx);
 5042        self.project.update(cx, |project, cx| {
 5043            project.set_active_path(active_entry.clone(), cx)
 5044        });
 5045
 5046        if focus_changed && let Some(project_path) = &active_entry {
 5047            let git_store_entity = self.project.read(cx).git_store().clone();
 5048            git_store_entity.update(cx, |git_store, cx| {
 5049                git_store.set_active_repo_for_path(project_path, cx);
 5050            });
 5051        }
 5052
 5053        self.update_window_title(window, cx);
 5054    }
 5055
 5056    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5057        let project = self.project().read(cx);
 5058        let mut title = String::new();
 5059
 5060        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5061            let name = {
 5062                let settings_location = SettingsLocation {
 5063                    worktree_id: worktree.read(cx).id(),
 5064                    path: RelPath::empty(),
 5065                };
 5066
 5067                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5068                match &settings.project_name {
 5069                    Some(name) => name.as_str(),
 5070                    None => worktree.read(cx).root_name_str(),
 5071                }
 5072            };
 5073            if i > 0 {
 5074                title.push_str(", ");
 5075            }
 5076            title.push_str(name);
 5077        }
 5078
 5079        if title.is_empty() {
 5080            title = "empty project".to_string();
 5081        }
 5082
 5083        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5084            let filename = path.path.file_name().or_else(|| {
 5085                Some(
 5086                    project
 5087                        .worktree_for_id(path.worktree_id, cx)?
 5088                        .read(cx)
 5089                        .root_name_str(),
 5090                )
 5091            });
 5092
 5093            if let Some(filename) = filename {
 5094                title.push_str("");
 5095                title.push_str(filename.as_ref());
 5096            }
 5097        }
 5098
 5099        if project.is_via_collab() {
 5100            title.push_str("");
 5101        } else if project.is_shared() {
 5102            title.push_str("");
 5103        }
 5104
 5105        if let Some(last_title) = self.last_window_title.as_ref()
 5106            && &title == last_title
 5107        {
 5108            return;
 5109        }
 5110        window.set_window_title(&title);
 5111        SystemWindowTabController::update_tab_title(
 5112            cx,
 5113            window.window_handle().window_id(),
 5114            SharedString::from(&title),
 5115        );
 5116        self.last_window_title = Some(title);
 5117    }
 5118
 5119    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5120        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5121        if is_edited != self.window_edited {
 5122            self.window_edited = is_edited;
 5123            window.set_window_edited(self.window_edited)
 5124        }
 5125    }
 5126
 5127    fn update_item_dirty_state(
 5128        &mut self,
 5129        item: &dyn ItemHandle,
 5130        window: &mut Window,
 5131        cx: &mut App,
 5132    ) {
 5133        let is_dirty = item.is_dirty(cx);
 5134        let item_id = item.item_id();
 5135        let was_dirty = self.dirty_items.contains_key(&item_id);
 5136        if is_dirty == was_dirty {
 5137            return;
 5138        }
 5139        if was_dirty {
 5140            self.dirty_items.remove(&item_id);
 5141            self.update_window_edited(window, cx);
 5142            return;
 5143        }
 5144
 5145        let workspace = self.weak_handle();
 5146        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5147            return;
 5148        };
 5149        let on_release_callback = Box::new(move |cx: &mut App| {
 5150            window_handle
 5151                .update(cx, |_, window, cx| {
 5152                    workspace
 5153                        .update(cx, |workspace, cx| {
 5154                            workspace.dirty_items.remove(&item_id);
 5155                            workspace.update_window_edited(window, cx)
 5156                        })
 5157                        .ok();
 5158                })
 5159                .ok();
 5160        });
 5161
 5162        let s = item.on_release(cx, on_release_callback);
 5163        self.dirty_items.insert(item_id, s);
 5164        self.update_window_edited(window, cx);
 5165    }
 5166
 5167    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5168        if self.notifications.is_empty() {
 5169            None
 5170        } else {
 5171            Some(
 5172                div()
 5173                    .absolute()
 5174                    .right_3()
 5175                    .bottom_3()
 5176                    .w_112()
 5177                    .h_full()
 5178                    .flex()
 5179                    .flex_col()
 5180                    .justify_end()
 5181                    .gap_2()
 5182                    .children(
 5183                        self.notifications
 5184                            .iter()
 5185                            .map(|(_, notification)| notification.clone().into_any()),
 5186                    ),
 5187            )
 5188        }
 5189    }
 5190
 5191    // RPC handlers
 5192
 5193    fn active_view_for_follower(
 5194        &self,
 5195        follower_project_id: Option<u64>,
 5196        window: &mut Window,
 5197        cx: &mut Context<Self>,
 5198    ) -> Option<proto::View> {
 5199        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5200        let item = item?;
 5201        let leader_id = self
 5202            .pane_for(&*item)
 5203            .and_then(|pane| self.leader_for_pane(&pane));
 5204        let leader_peer_id = match leader_id {
 5205            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5206            Some(CollaboratorId::Agent) | None => None,
 5207        };
 5208
 5209        let item_handle = item.to_followable_item_handle(cx)?;
 5210        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5211        let variant = item_handle.to_state_proto(window, cx)?;
 5212
 5213        if item_handle.is_project_item(window, cx)
 5214            && (follower_project_id.is_none()
 5215                || follower_project_id != self.project.read(cx).remote_id())
 5216        {
 5217            return None;
 5218        }
 5219
 5220        Some(proto::View {
 5221            id: id.to_proto(),
 5222            leader_id: leader_peer_id,
 5223            variant: Some(variant),
 5224            panel_id: panel_id.map(|id| id as i32),
 5225        })
 5226    }
 5227
 5228    fn handle_follow(
 5229        &mut self,
 5230        follower_project_id: Option<u64>,
 5231        window: &mut Window,
 5232        cx: &mut Context<Self>,
 5233    ) -> proto::FollowResponse {
 5234        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5235
 5236        cx.notify();
 5237        proto::FollowResponse {
 5238            views: active_view.iter().cloned().collect(),
 5239            active_view,
 5240        }
 5241    }
 5242
 5243    fn handle_update_followers(
 5244        &mut self,
 5245        leader_id: PeerId,
 5246        message: proto::UpdateFollowers,
 5247        _window: &mut Window,
 5248        _cx: &mut Context<Self>,
 5249    ) {
 5250        self.leader_updates_tx
 5251            .unbounded_send((leader_id, message))
 5252            .ok();
 5253    }
 5254
 5255    async fn process_leader_update(
 5256        this: &WeakEntity<Self>,
 5257        leader_id: PeerId,
 5258        update: proto::UpdateFollowers,
 5259        cx: &mut AsyncWindowContext,
 5260    ) -> Result<()> {
 5261        match update.variant.context("invalid update")? {
 5262            proto::update_followers::Variant::CreateView(view) => {
 5263                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5264                let should_add_view = this.update(cx, |this, _| {
 5265                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5266                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5267                    } else {
 5268                        anyhow::Ok(false)
 5269                    }
 5270                })??;
 5271
 5272                if should_add_view {
 5273                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5274                }
 5275            }
 5276            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5277                let should_add_view = this.update(cx, |this, _| {
 5278                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5279                        state.active_view_id = update_active_view
 5280                            .view
 5281                            .as_ref()
 5282                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5283
 5284                        if state.active_view_id.is_some_and(|view_id| {
 5285                            !state.items_by_leader_view_id.contains_key(&view_id)
 5286                        }) {
 5287                            anyhow::Ok(true)
 5288                        } else {
 5289                            anyhow::Ok(false)
 5290                        }
 5291                    } else {
 5292                        anyhow::Ok(false)
 5293                    }
 5294                })??;
 5295
 5296                if should_add_view && let Some(view) = update_active_view.view {
 5297                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5298                }
 5299            }
 5300            proto::update_followers::Variant::UpdateView(update_view) => {
 5301                let variant = update_view.variant.context("missing update view variant")?;
 5302                let id = update_view.id.context("missing update view id")?;
 5303                let mut tasks = Vec::new();
 5304                this.update_in(cx, |this, window, cx| {
 5305                    let project = this.project.clone();
 5306                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5307                        let view_id = ViewId::from_proto(id.clone())?;
 5308                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5309                            tasks.push(item.view.apply_update_proto(
 5310                                &project,
 5311                                variant.clone(),
 5312                                window,
 5313                                cx,
 5314                            ));
 5315                        }
 5316                    }
 5317                    anyhow::Ok(())
 5318                })??;
 5319                try_join_all(tasks).await.log_err();
 5320            }
 5321        }
 5322        this.update_in(cx, |this, window, cx| {
 5323            this.leader_updated(leader_id, window, cx)
 5324        })?;
 5325        Ok(())
 5326    }
 5327
 5328    async fn add_view_from_leader(
 5329        this: WeakEntity<Self>,
 5330        leader_id: PeerId,
 5331        view: &proto::View,
 5332        cx: &mut AsyncWindowContext,
 5333    ) -> Result<()> {
 5334        let this = this.upgrade().context("workspace dropped")?;
 5335
 5336        let Some(id) = view.id.clone() else {
 5337            anyhow::bail!("no id for view");
 5338        };
 5339        let id = ViewId::from_proto(id)?;
 5340        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5341
 5342        let pane = this.update(cx, |this, _cx| {
 5343            let state = this
 5344                .follower_states
 5345                .get(&leader_id.into())
 5346                .context("stopped following")?;
 5347            anyhow::Ok(state.pane().clone())
 5348        })?;
 5349        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5350            let client = this.read(cx).client().clone();
 5351            pane.items().find_map(|item| {
 5352                let item = item.to_followable_item_handle(cx)?;
 5353                if item.remote_id(&client, window, cx) == Some(id) {
 5354                    Some(item)
 5355                } else {
 5356                    None
 5357                }
 5358            })
 5359        })?;
 5360        let item = if let Some(existing_item) = existing_item {
 5361            existing_item
 5362        } else {
 5363            let variant = view.variant.clone();
 5364            anyhow::ensure!(variant.is_some(), "missing view variant");
 5365
 5366            let task = cx.update(|window, cx| {
 5367                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5368            })?;
 5369
 5370            let Some(task) = task else {
 5371                anyhow::bail!(
 5372                    "failed to construct view from leader (maybe from a different version of zed?)"
 5373                );
 5374            };
 5375
 5376            let mut new_item = task.await?;
 5377            pane.update_in(cx, |pane, window, cx| {
 5378                let mut item_to_remove = None;
 5379                for (ix, item) in pane.items().enumerate() {
 5380                    if let Some(item) = item.to_followable_item_handle(cx) {
 5381                        match new_item.dedup(item.as_ref(), window, cx) {
 5382                            Some(item::Dedup::KeepExisting) => {
 5383                                new_item =
 5384                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5385                                break;
 5386                            }
 5387                            Some(item::Dedup::ReplaceExisting) => {
 5388                                item_to_remove = Some((ix, item.item_id()));
 5389                                break;
 5390                            }
 5391                            None => {}
 5392                        }
 5393                    }
 5394                }
 5395
 5396                if let Some((ix, id)) = item_to_remove {
 5397                    pane.remove_item(id, false, false, window, cx);
 5398                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5399                }
 5400            })?;
 5401
 5402            new_item
 5403        };
 5404
 5405        this.update_in(cx, |this, window, cx| {
 5406            let state = this.follower_states.get_mut(&leader_id.into())?;
 5407            item.set_leader_id(Some(leader_id.into()), window, cx);
 5408            state.items_by_leader_view_id.insert(
 5409                id,
 5410                FollowerView {
 5411                    view: item,
 5412                    location: panel_id,
 5413                },
 5414            );
 5415
 5416            Some(())
 5417        })
 5418        .context("no follower state")?;
 5419
 5420        Ok(())
 5421    }
 5422
 5423    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5424        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5425            return;
 5426        };
 5427
 5428        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5429            let buffer_entity_id = agent_location.buffer.entity_id();
 5430            let view_id = ViewId {
 5431                creator: CollaboratorId::Agent,
 5432                id: buffer_entity_id.as_u64(),
 5433            };
 5434            follower_state.active_view_id = Some(view_id);
 5435
 5436            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5437                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5438                hash_map::Entry::Vacant(entry) => {
 5439                    let existing_view =
 5440                        follower_state
 5441                            .center_pane
 5442                            .read(cx)
 5443                            .items()
 5444                            .find_map(|item| {
 5445                                let item = item.to_followable_item_handle(cx)?;
 5446                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5447                                    && item.project_item_model_ids(cx).as_slice()
 5448                                        == [buffer_entity_id]
 5449                                {
 5450                                    Some(item)
 5451                                } else {
 5452                                    None
 5453                                }
 5454                            });
 5455                    let view = existing_view.or_else(|| {
 5456                        agent_location.buffer.upgrade().and_then(|buffer| {
 5457                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5458                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5459                            })?
 5460                            .to_followable_item_handle(cx)
 5461                        })
 5462                    });
 5463
 5464                    view.map(|view| {
 5465                        entry.insert(FollowerView {
 5466                            view,
 5467                            location: None,
 5468                        })
 5469                    })
 5470                }
 5471            };
 5472
 5473            if let Some(item) = item {
 5474                item.view
 5475                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5476                item.view
 5477                    .update_agent_location(agent_location.position, window, cx);
 5478            }
 5479        } else {
 5480            follower_state.active_view_id = None;
 5481        }
 5482
 5483        self.leader_updated(CollaboratorId::Agent, window, cx);
 5484    }
 5485
 5486    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5487        let mut is_project_item = true;
 5488        let mut update = proto::UpdateActiveView::default();
 5489        if window.is_window_active() {
 5490            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5491
 5492            if let Some(item) = active_item
 5493                && item.item_focus_handle(cx).contains_focused(window, cx)
 5494            {
 5495                let leader_id = self
 5496                    .pane_for(&*item)
 5497                    .and_then(|pane| self.leader_for_pane(&pane));
 5498                let leader_peer_id = match leader_id {
 5499                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5500                    Some(CollaboratorId::Agent) | None => None,
 5501                };
 5502
 5503                if let Some(item) = item.to_followable_item_handle(cx) {
 5504                    let id = item
 5505                        .remote_id(&self.app_state.client, window, cx)
 5506                        .map(|id| id.to_proto());
 5507
 5508                    if let Some(id) = id
 5509                        && let Some(variant) = item.to_state_proto(window, cx)
 5510                    {
 5511                        let view = Some(proto::View {
 5512                            id,
 5513                            leader_id: leader_peer_id,
 5514                            variant: Some(variant),
 5515                            panel_id: panel_id.map(|id| id as i32),
 5516                        });
 5517
 5518                        is_project_item = item.is_project_item(window, cx);
 5519                        update = proto::UpdateActiveView { view };
 5520                    };
 5521                }
 5522            }
 5523        }
 5524
 5525        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5526        if active_view_id != self.last_active_view_id.as_ref() {
 5527            self.last_active_view_id = active_view_id.cloned();
 5528            self.update_followers(
 5529                is_project_item,
 5530                proto::update_followers::Variant::UpdateActiveView(update),
 5531                window,
 5532                cx,
 5533            );
 5534        }
 5535    }
 5536
 5537    fn active_item_for_followers(
 5538        &self,
 5539        window: &mut Window,
 5540        cx: &mut App,
 5541    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5542        let mut active_item = None;
 5543        let mut panel_id = None;
 5544        for dock in self.all_docks() {
 5545            if dock.focus_handle(cx).contains_focused(window, cx)
 5546                && let Some(panel) = dock.read(cx).active_panel()
 5547                && let Some(pane) = panel.pane(cx)
 5548                && let Some(item) = pane.read(cx).active_item()
 5549            {
 5550                active_item = Some(item);
 5551                panel_id = panel.remote_id();
 5552                break;
 5553            }
 5554        }
 5555
 5556        if active_item.is_none() {
 5557            active_item = self.active_pane().read(cx).active_item();
 5558        }
 5559        (active_item, panel_id)
 5560    }
 5561
 5562    fn update_followers(
 5563        &self,
 5564        project_only: bool,
 5565        update: proto::update_followers::Variant,
 5566        _: &mut Window,
 5567        cx: &mut App,
 5568    ) -> Option<()> {
 5569        // If this update only applies to for followers in the current project,
 5570        // then skip it unless this project is shared. If it applies to all
 5571        // followers, regardless of project, then set `project_id` to none,
 5572        // indicating that it goes to all followers.
 5573        let project_id = if project_only {
 5574            Some(self.project.read(cx).remote_id()?)
 5575        } else {
 5576            None
 5577        };
 5578        self.app_state().workspace_store.update(cx, |store, cx| {
 5579            store.update_followers(project_id, update, cx)
 5580        })
 5581    }
 5582
 5583    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5584        self.follower_states.iter().find_map(|(leader_id, state)| {
 5585            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5586                Some(*leader_id)
 5587            } else {
 5588                None
 5589            }
 5590        })
 5591    }
 5592
 5593    fn leader_updated(
 5594        &mut self,
 5595        leader_id: impl Into<CollaboratorId>,
 5596        window: &mut Window,
 5597        cx: &mut Context<Self>,
 5598    ) -> Option<Box<dyn ItemHandle>> {
 5599        cx.notify();
 5600
 5601        let leader_id = leader_id.into();
 5602        let (panel_id, item) = match leader_id {
 5603            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5604            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5605        };
 5606
 5607        let state = self.follower_states.get(&leader_id)?;
 5608        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5609        let pane;
 5610        if let Some(panel_id) = panel_id {
 5611            pane = self
 5612                .activate_panel_for_proto_id(panel_id, window, cx)?
 5613                .pane(cx)?;
 5614            let state = self.follower_states.get_mut(&leader_id)?;
 5615            state.dock_pane = Some(pane.clone());
 5616        } else {
 5617            pane = state.center_pane.clone();
 5618            let state = self.follower_states.get_mut(&leader_id)?;
 5619            if let Some(dock_pane) = state.dock_pane.take() {
 5620                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5621            }
 5622        }
 5623
 5624        pane.update(cx, |pane, cx| {
 5625            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5626            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5627                pane.activate_item(index, false, false, window, cx);
 5628            } else {
 5629                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5630            }
 5631
 5632            if focus_active_item {
 5633                pane.focus_active_item(window, cx)
 5634            }
 5635        });
 5636
 5637        Some(item)
 5638    }
 5639
 5640    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5641        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5642        let active_view_id = state.active_view_id?;
 5643        Some(
 5644            state
 5645                .items_by_leader_view_id
 5646                .get(&active_view_id)?
 5647                .view
 5648                .boxed_clone(),
 5649        )
 5650    }
 5651
 5652    fn active_item_for_peer(
 5653        &self,
 5654        peer_id: PeerId,
 5655        window: &mut Window,
 5656        cx: &mut Context<Self>,
 5657    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5658        let call = self.active_call()?;
 5659        let room = call.read(cx).room()?.read(cx);
 5660        let participant = room.remote_participant_for_peer_id(peer_id)?;
 5661        let leader_in_this_app;
 5662        let leader_in_this_project;
 5663        match participant.location {
 5664            call::ParticipantLocation::SharedProject { project_id } => {
 5665                leader_in_this_app = true;
 5666                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5667            }
 5668            call::ParticipantLocation::UnsharedProject => {
 5669                leader_in_this_app = true;
 5670                leader_in_this_project = false;
 5671            }
 5672            call::ParticipantLocation::External => {
 5673                leader_in_this_app = false;
 5674                leader_in_this_project = false;
 5675            }
 5676        };
 5677        let state = self.follower_states.get(&peer_id.into())?;
 5678        let mut item_to_activate = None;
 5679        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5680            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5681                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5682            {
 5683                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5684            }
 5685        } else if let Some(shared_screen) =
 5686            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5687        {
 5688            item_to_activate = Some((None, Box::new(shared_screen)));
 5689        }
 5690        item_to_activate
 5691    }
 5692
 5693    fn shared_screen_for_peer(
 5694        &self,
 5695        peer_id: PeerId,
 5696        pane: &Entity<Pane>,
 5697        window: &mut Window,
 5698        cx: &mut App,
 5699    ) -> Option<Entity<SharedScreen>> {
 5700        let call = self.active_call()?;
 5701        let room = call.read(cx).room()?.clone();
 5702        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 5703        let track = participant.video_tracks.values().next()?.clone();
 5704        let user = participant.user.clone();
 5705
 5706        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 5707            if item.read(cx).peer_id == peer_id {
 5708                return Some(item);
 5709            }
 5710        }
 5711
 5712        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 5713    }
 5714
 5715    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5716        if window.is_window_active() {
 5717            self.update_active_view_for_followers(window, cx);
 5718
 5719            if let Some(database_id) = self.database_id {
 5720                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5721                    .detach();
 5722            }
 5723        } else {
 5724            for pane in &self.panes {
 5725                pane.update(cx, |pane, cx| {
 5726                    if let Some(item) = pane.active_item() {
 5727                        item.workspace_deactivated(window, cx);
 5728                    }
 5729                    for item in pane.items() {
 5730                        if matches!(
 5731                            item.workspace_settings(cx).autosave,
 5732                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5733                        ) {
 5734                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5735                                .detach_and_log_err(cx);
 5736                        }
 5737                    }
 5738                });
 5739            }
 5740        }
 5741    }
 5742
 5743    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5744        self.active_call.as_ref().map(|(call, _)| call)
 5745    }
 5746
 5747    fn on_active_call_event(
 5748        &mut self,
 5749        _: &Entity<ActiveCall>,
 5750        event: &call::room::Event,
 5751        window: &mut Window,
 5752        cx: &mut Context<Self>,
 5753    ) {
 5754        match event {
 5755            call::room::Event::ParticipantLocationChanged { participant_id }
 5756            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5757                self.leader_updated(participant_id, window, cx);
 5758            }
 5759            _ => {}
 5760        }
 5761    }
 5762
 5763    pub fn database_id(&self) -> Option<WorkspaceId> {
 5764        self.database_id
 5765    }
 5766
 5767    pub fn session_id(&self) -> Option<String> {
 5768        self.session_id.clone()
 5769    }
 5770
 5771    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5772        let project = self.project().read(cx);
 5773        project
 5774            .visible_worktrees(cx)
 5775            .map(|worktree| worktree.read(cx).abs_path())
 5776            .collect::<Vec<_>>()
 5777    }
 5778
 5779    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5780        match member {
 5781            Member::Axis(PaneAxis { members, .. }) => {
 5782                for child in members.iter() {
 5783                    self.remove_panes(child.clone(), window, cx)
 5784                }
 5785            }
 5786            Member::Pane(pane) => {
 5787                self.force_remove_pane(&pane, &None, window, cx);
 5788            }
 5789        }
 5790    }
 5791
 5792    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5793        self.session_id.take();
 5794        self.serialize_workspace_internal(window, cx)
 5795    }
 5796
 5797    fn force_remove_pane(
 5798        &mut self,
 5799        pane: &Entity<Pane>,
 5800        focus_on: &Option<Entity<Pane>>,
 5801        window: &mut Window,
 5802        cx: &mut Context<Workspace>,
 5803    ) {
 5804        self.panes.retain(|p| p != pane);
 5805        if let Some(focus_on) = focus_on {
 5806            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5807        } else if self.active_pane() == pane {
 5808            self.panes
 5809                .last()
 5810                .unwrap()
 5811                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5812        }
 5813        if self.last_active_center_pane == Some(pane.downgrade()) {
 5814            self.last_active_center_pane = None;
 5815        }
 5816        cx.notify();
 5817    }
 5818
 5819    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5820        if self._schedule_serialize_workspace.is_none() {
 5821            self._schedule_serialize_workspace =
 5822                Some(cx.spawn_in(window, async move |this, cx| {
 5823                    cx.background_executor()
 5824                        .timer(SERIALIZATION_THROTTLE_TIME)
 5825                        .await;
 5826                    this.update_in(cx, |this, window, cx| {
 5827                        this.serialize_workspace_internal(window, cx).detach();
 5828                        this._schedule_serialize_workspace.take();
 5829                    })
 5830                    .log_err();
 5831                }));
 5832        }
 5833    }
 5834
 5835    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5836        let Some(database_id) = self.database_id() else {
 5837            return Task::ready(());
 5838        };
 5839
 5840        fn serialize_pane_handle(
 5841            pane_handle: &Entity<Pane>,
 5842            window: &mut Window,
 5843            cx: &mut App,
 5844        ) -> SerializedPane {
 5845            let (items, active, pinned_count) = {
 5846                let pane = pane_handle.read(cx);
 5847                let active_item_id = pane.active_item().map(|item| item.item_id());
 5848                (
 5849                    pane.items()
 5850                        .filter_map(|handle| {
 5851                            let handle = handle.to_serializable_item_handle(cx)?;
 5852
 5853                            Some(SerializedItem {
 5854                                kind: Arc::from(handle.serialized_item_kind()),
 5855                                item_id: handle.item_id().as_u64(),
 5856                                active: Some(handle.item_id()) == active_item_id,
 5857                                preview: pane.is_active_preview_item(handle.item_id()),
 5858                            })
 5859                        })
 5860                        .collect::<Vec<_>>(),
 5861                    pane.has_focus(window, cx),
 5862                    pane.pinned_count(),
 5863                )
 5864            };
 5865
 5866            SerializedPane::new(items, active, pinned_count)
 5867        }
 5868
 5869        fn build_serialized_pane_group(
 5870            pane_group: &Member,
 5871            window: &mut Window,
 5872            cx: &mut App,
 5873        ) -> SerializedPaneGroup {
 5874            match pane_group {
 5875                Member::Axis(PaneAxis {
 5876                    axis,
 5877                    members,
 5878                    flexes,
 5879                    bounding_boxes: _,
 5880                }) => SerializedPaneGroup::Group {
 5881                    axis: SerializedAxis(*axis),
 5882                    children: members
 5883                        .iter()
 5884                        .map(|member| build_serialized_pane_group(member, window, cx))
 5885                        .collect::<Vec<_>>(),
 5886                    flexes: Some(flexes.lock().clone()),
 5887                },
 5888                Member::Pane(pane_handle) => {
 5889                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5890                }
 5891            }
 5892        }
 5893
 5894        fn build_serialized_docks(
 5895            this: &Workspace,
 5896            window: &mut Window,
 5897            cx: &mut App,
 5898        ) -> DockStructure {
 5899            let left_dock = this.left_dock.read(cx);
 5900            let left_visible = left_dock.is_open();
 5901            let left_active_panel = left_dock
 5902                .active_panel()
 5903                .map(|panel| panel.persistent_name().to_string());
 5904            let left_dock_zoom = left_dock
 5905                .active_panel()
 5906                .map(|panel| panel.is_zoomed(window, cx))
 5907                .unwrap_or(false);
 5908
 5909            let right_dock = this.right_dock.read(cx);
 5910            let right_visible = right_dock.is_open();
 5911            let right_active_panel = right_dock
 5912                .active_panel()
 5913                .map(|panel| panel.persistent_name().to_string());
 5914            let right_dock_zoom = right_dock
 5915                .active_panel()
 5916                .map(|panel| panel.is_zoomed(window, cx))
 5917                .unwrap_or(false);
 5918
 5919            let bottom_dock = this.bottom_dock.read(cx);
 5920            let bottom_visible = bottom_dock.is_open();
 5921            let bottom_active_panel = bottom_dock
 5922                .active_panel()
 5923                .map(|panel| panel.persistent_name().to_string());
 5924            let bottom_dock_zoom = bottom_dock
 5925                .active_panel()
 5926                .map(|panel| panel.is_zoomed(window, cx))
 5927                .unwrap_or(false);
 5928
 5929            DockStructure {
 5930                left: DockData {
 5931                    visible: left_visible,
 5932                    active_panel: left_active_panel,
 5933                    zoom: left_dock_zoom,
 5934                },
 5935                right: DockData {
 5936                    visible: right_visible,
 5937                    active_panel: right_active_panel,
 5938                    zoom: right_dock_zoom,
 5939                },
 5940                bottom: DockData {
 5941                    visible: bottom_visible,
 5942                    active_panel: bottom_active_panel,
 5943                    zoom: bottom_dock_zoom,
 5944                },
 5945            }
 5946        }
 5947
 5948        match self.serialize_workspace_location(cx) {
 5949            WorkspaceLocation::Location(location, paths) => {
 5950                let breakpoints = self.project.update(cx, |project, cx| {
 5951                    project
 5952                        .breakpoint_store()
 5953                        .read(cx)
 5954                        .all_source_breakpoints(cx)
 5955                });
 5956                let user_toolchains = self
 5957                    .project
 5958                    .read(cx)
 5959                    .user_toolchains(cx)
 5960                    .unwrap_or_default();
 5961
 5962                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5963                let docks = build_serialized_docks(self, window, cx);
 5964                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5965
 5966                let serialized_workspace = SerializedWorkspace {
 5967                    id: database_id,
 5968                    location,
 5969                    paths,
 5970                    center_group,
 5971                    window_bounds,
 5972                    display: Default::default(),
 5973                    docks,
 5974                    centered_layout: self.centered_layout,
 5975                    session_id: self.session_id.clone(),
 5976                    breakpoints,
 5977                    window_id: Some(window.window_handle().window_id().as_u64()),
 5978                    user_toolchains,
 5979                };
 5980
 5981                window.spawn(cx, async move |_| {
 5982                    persistence::DB.save_workspace(serialized_workspace).await;
 5983                })
 5984            }
 5985            WorkspaceLocation::DetachFromSession => {
 5986                let window_bounds = SerializedWindowBounds(window.window_bounds());
 5987                let display = window.display(cx).and_then(|d| d.uuid().ok());
 5988                // Save dock state for empty local workspaces
 5989                let docks = build_serialized_docks(self, window, cx);
 5990                window.spawn(cx, async move |_| {
 5991                    persistence::DB
 5992                        .set_window_open_status(
 5993                            database_id,
 5994                            window_bounds,
 5995                            display.unwrap_or_default(),
 5996                        )
 5997                        .await
 5998                        .log_err();
 5999                    persistence::DB
 6000                        .set_session_id(database_id, None)
 6001                        .await
 6002                        .log_err();
 6003                    persistence::write_default_dock_state(docks).await.log_err();
 6004                })
 6005            }
 6006            WorkspaceLocation::None => {
 6007                // Save dock state for empty non-local workspaces
 6008                let docks = build_serialized_docks(self, window, cx);
 6009                window.spawn(cx, async move |_| {
 6010                    persistence::write_default_dock_state(docks).await.log_err();
 6011                })
 6012            }
 6013        }
 6014    }
 6015
 6016    fn has_any_items_open(&self, cx: &App) -> bool {
 6017        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6018    }
 6019
 6020    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6021        let paths = PathList::new(&self.root_paths(cx));
 6022        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6023            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6024        } else if self.project.read(cx).is_local() {
 6025            if !paths.is_empty() || self.has_any_items_open(cx) {
 6026                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6027            } else {
 6028                WorkspaceLocation::DetachFromSession
 6029            }
 6030        } else {
 6031            WorkspaceLocation::None
 6032        }
 6033    }
 6034
 6035    fn update_history(&self, cx: &mut App) {
 6036        let Some(id) = self.database_id() else {
 6037            return;
 6038        };
 6039        if !self.project.read(cx).is_local() {
 6040            return;
 6041        }
 6042        if let Some(manager) = HistoryManager::global(cx) {
 6043            let paths = PathList::new(&self.root_paths(cx));
 6044            manager.update(cx, |this, cx| {
 6045                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6046            });
 6047        }
 6048    }
 6049
 6050    async fn serialize_items(
 6051        this: &WeakEntity<Self>,
 6052        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6053        cx: &mut AsyncWindowContext,
 6054    ) -> Result<()> {
 6055        const CHUNK_SIZE: usize = 200;
 6056
 6057        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6058
 6059        while let Some(items_received) = serializable_items.next().await {
 6060            let unique_items =
 6061                items_received
 6062                    .into_iter()
 6063                    .fold(HashMap::default(), |mut acc, item| {
 6064                        acc.entry(item.item_id()).or_insert(item);
 6065                        acc
 6066                    });
 6067
 6068            // We use into_iter() here so that the references to the items are moved into
 6069            // the tasks and not kept alive while we're sleeping.
 6070            for (_, item) in unique_items.into_iter() {
 6071                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6072                    item.serialize(workspace, false, window, cx)
 6073                }) {
 6074                    cx.background_spawn(async move { task.await.log_err() })
 6075                        .detach();
 6076                }
 6077            }
 6078
 6079            cx.background_executor()
 6080                .timer(SERIALIZATION_THROTTLE_TIME)
 6081                .await;
 6082        }
 6083
 6084        Ok(())
 6085    }
 6086
 6087    pub(crate) fn enqueue_item_serialization(
 6088        &mut self,
 6089        item: Box<dyn SerializableItemHandle>,
 6090    ) -> Result<()> {
 6091        self.serializable_items_tx
 6092            .unbounded_send(item)
 6093            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6094    }
 6095
 6096    pub(crate) fn load_workspace(
 6097        serialized_workspace: SerializedWorkspace,
 6098        paths_to_open: Vec<Option<ProjectPath>>,
 6099        window: &mut Window,
 6100        cx: &mut Context<Workspace>,
 6101    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6102        cx.spawn_in(window, async move |workspace, cx| {
 6103            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6104
 6105            let mut center_group = None;
 6106            let mut center_items = None;
 6107
 6108            // Traverse the splits tree and add to things
 6109            if let Some((group, active_pane, items)) = serialized_workspace
 6110                .center_group
 6111                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6112                .await
 6113            {
 6114                center_items = Some(items);
 6115                center_group = Some((group, active_pane))
 6116            }
 6117
 6118            let mut items_by_project_path = HashMap::default();
 6119            let mut item_ids_by_kind = HashMap::default();
 6120            let mut all_deserialized_items = Vec::default();
 6121            cx.update(|_, cx| {
 6122                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6123                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6124                        item_ids_by_kind
 6125                            .entry(serializable_item_handle.serialized_item_kind())
 6126                            .or_insert(Vec::new())
 6127                            .push(item.item_id().as_u64() as ItemId);
 6128                    }
 6129
 6130                    if let Some(project_path) = item.project_path(cx) {
 6131                        items_by_project_path.insert(project_path, item.clone());
 6132                    }
 6133                    all_deserialized_items.push(item);
 6134                }
 6135            })?;
 6136
 6137            let opened_items = paths_to_open
 6138                .into_iter()
 6139                .map(|path_to_open| {
 6140                    path_to_open
 6141                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6142                })
 6143                .collect::<Vec<_>>();
 6144
 6145            // Remove old panes from workspace panes list
 6146            workspace.update_in(cx, |workspace, window, cx| {
 6147                if let Some((center_group, active_pane)) = center_group {
 6148                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6149
 6150                    // Swap workspace center group
 6151                    workspace.center = PaneGroup::with_root(center_group);
 6152                    workspace.center.set_is_center(true);
 6153                    workspace.center.mark_positions(cx);
 6154
 6155                    if let Some(active_pane) = active_pane {
 6156                        workspace.set_active_pane(&active_pane, window, cx);
 6157                        cx.focus_self(window);
 6158                    } else {
 6159                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6160                    }
 6161                }
 6162
 6163                let docks = serialized_workspace.docks;
 6164
 6165                for (dock, serialized_dock) in [
 6166                    (&mut workspace.right_dock, docks.right),
 6167                    (&mut workspace.left_dock, docks.left),
 6168                    (&mut workspace.bottom_dock, docks.bottom),
 6169                ]
 6170                .iter_mut()
 6171                {
 6172                    dock.update(cx, |dock, cx| {
 6173                        dock.serialized_dock = Some(serialized_dock.clone());
 6174                        dock.restore_state(window, cx);
 6175                    });
 6176                }
 6177
 6178                cx.notify();
 6179            })?;
 6180
 6181            let _ = project
 6182                .update(cx, |project, cx| {
 6183                    project
 6184                        .breakpoint_store()
 6185                        .update(cx, |breakpoint_store, cx| {
 6186                            breakpoint_store
 6187                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6188                        })
 6189                })
 6190                .await;
 6191
 6192            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6193            // after loading the items, we might have different items and in order to avoid
 6194            // the database filling up, we delete items that haven't been loaded now.
 6195            //
 6196            // The items that have been loaded, have been saved after they've been added to the workspace.
 6197            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6198                item_ids_by_kind
 6199                    .into_iter()
 6200                    .map(|(item_kind, loaded_items)| {
 6201                        SerializableItemRegistry::cleanup(
 6202                            item_kind,
 6203                            serialized_workspace.id,
 6204                            loaded_items,
 6205                            window,
 6206                            cx,
 6207                        )
 6208                        .log_err()
 6209                    })
 6210                    .collect::<Vec<_>>()
 6211            })?;
 6212
 6213            futures::future::join_all(clean_up_tasks).await;
 6214
 6215            workspace
 6216                .update_in(cx, |workspace, window, cx| {
 6217                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6218                    workspace.serialize_workspace_internal(window, cx).detach();
 6219
 6220                    // Ensure that we mark the window as edited if we did load dirty items
 6221                    workspace.update_window_edited(window, cx);
 6222                })
 6223                .ok();
 6224
 6225            Ok(opened_items)
 6226        })
 6227    }
 6228
 6229    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6230        self.add_workspace_actions_listeners(div, window, cx)
 6231            .on_action(cx.listener(
 6232                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6233                    for action in &action_sequence.0 {
 6234                        window.dispatch_action(action.boxed_clone(), cx);
 6235                    }
 6236                },
 6237            ))
 6238            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6239            .on_action(cx.listener(Self::close_all_items_and_panes))
 6240            .on_action(cx.listener(Self::save_all))
 6241            .on_action(cx.listener(Self::send_keystrokes))
 6242            .on_action(cx.listener(Self::add_folder_to_project))
 6243            .on_action(cx.listener(Self::follow_next_collaborator))
 6244            .on_action(cx.listener(Self::close_window))
 6245            .on_action(cx.listener(Self::activate_pane_at_index))
 6246            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6247            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6248            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6249            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6250                let pane = workspace.active_pane().clone();
 6251                workspace.unfollow_in_pane(&pane, window, cx);
 6252            }))
 6253            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6254                workspace
 6255                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6256                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6257            }))
 6258            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6259                workspace
 6260                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6261                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6262            }))
 6263            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6264                workspace
 6265                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6266                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6267            }))
 6268            .on_action(
 6269                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6270                    workspace.activate_previous_pane(window, cx)
 6271                }),
 6272            )
 6273            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6274                workspace.activate_next_pane(window, cx)
 6275            }))
 6276            .on_action(
 6277                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6278                    workspace.activate_next_window(cx)
 6279                }),
 6280            )
 6281            .on_action(
 6282                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6283                    workspace.activate_previous_window(cx)
 6284                }),
 6285            )
 6286            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6287                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6288            }))
 6289            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6290                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6291            }))
 6292            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6293                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6294            }))
 6295            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6296                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6297            }))
 6298            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6299                workspace.activate_next_pane(window, cx)
 6300            }))
 6301            .on_action(cx.listener(
 6302                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6303                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6304                },
 6305            ))
 6306            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6307                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6308            }))
 6309            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6310                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6311            }))
 6312            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6313                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6314            }))
 6315            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6316                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6317            }))
 6318            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6319                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6320                    SplitDirection::Down,
 6321                    SplitDirection::Up,
 6322                    SplitDirection::Right,
 6323                    SplitDirection::Left,
 6324                ];
 6325                for dir in DIRECTION_PRIORITY {
 6326                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6327                        workspace.swap_pane_in_direction(dir, cx);
 6328                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6329                        break;
 6330                    }
 6331                }
 6332            }))
 6333            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6334                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6335            }))
 6336            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6337                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6338            }))
 6339            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6340                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6341            }))
 6342            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6343                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6344            }))
 6345            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6346                this.toggle_dock(DockPosition::Left, window, cx);
 6347            }))
 6348            .on_action(cx.listener(
 6349                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6350                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6351                },
 6352            ))
 6353            .on_action(cx.listener(
 6354                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6355                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6356                },
 6357            ))
 6358            .on_action(cx.listener(
 6359                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6360                    if !workspace.close_active_dock(window, cx) {
 6361                        cx.propagate();
 6362                    }
 6363                },
 6364            ))
 6365            .on_action(
 6366                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6367                    workspace.close_all_docks(window, cx);
 6368                }),
 6369            )
 6370            .on_action(cx.listener(Self::toggle_all_docks))
 6371            .on_action(cx.listener(
 6372                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6373                    workspace.clear_all_notifications(cx);
 6374                },
 6375            ))
 6376            .on_action(cx.listener(
 6377                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6378                    workspace.clear_navigation_history(window, cx);
 6379                },
 6380            ))
 6381            .on_action(cx.listener(
 6382                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6383                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6384                        workspace.suppress_notification(&notification_id, cx);
 6385                    }
 6386                },
 6387            ))
 6388            .on_action(cx.listener(
 6389                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6390                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6391                },
 6392            ))
 6393            .on_action(
 6394                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6395                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6396                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6397                            trusted_worktrees.clear_trusted_paths()
 6398                        });
 6399                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6400                        cx.spawn(async move |_, cx| {
 6401                            if clear_task.await.log_err().is_some() {
 6402                                cx.update(|cx| reload(cx));
 6403                            }
 6404                        })
 6405                        .detach();
 6406                    }
 6407                }),
 6408            )
 6409            .on_action(cx.listener(
 6410                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6411                    workspace.reopen_closed_item(window, cx).detach();
 6412                },
 6413            ))
 6414            .on_action(cx.listener(
 6415                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6416                    for dock in workspace.all_docks() {
 6417                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6418                            let Some(panel) = dock.read(cx).active_panel() else {
 6419                                return;
 6420                            };
 6421
 6422                            // Set to `None`, then the size will fall back to the default.
 6423                            panel.clone().set_size(None, window, cx);
 6424
 6425                            return;
 6426                        }
 6427                    }
 6428                },
 6429            ))
 6430            .on_action(cx.listener(
 6431                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6432                    for dock in workspace.all_docks() {
 6433                        if let Some(panel) = dock.read(cx).visible_panel() {
 6434                            // Set to `None`, then the size will fall back to the default.
 6435                            panel.clone().set_size(None, window, cx);
 6436                        }
 6437                    }
 6438                },
 6439            ))
 6440            .on_action(cx.listener(
 6441                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6442                    adjust_active_dock_size_by_px(
 6443                        px_with_ui_font_fallback(act.px, cx),
 6444                        workspace,
 6445                        window,
 6446                        cx,
 6447                    );
 6448                },
 6449            ))
 6450            .on_action(cx.listener(
 6451                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6452                    adjust_active_dock_size_by_px(
 6453                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6454                        workspace,
 6455                        window,
 6456                        cx,
 6457                    );
 6458                },
 6459            ))
 6460            .on_action(cx.listener(
 6461                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6462                    adjust_open_docks_size_by_px(
 6463                        px_with_ui_font_fallback(act.px, cx),
 6464                        workspace,
 6465                        window,
 6466                        cx,
 6467                    );
 6468                },
 6469            ))
 6470            .on_action(cx.listener(
 6471                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6472                    adjust_open_docks_size_by_px(
 6473                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6474                        workspace,
 6475                        window,
 6476                        cx,
 6477                    );
 6478                },
 6479            ))
 6480            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6481            .on_action(cx.listener(
 6482                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6483                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6484                        let dock = active_dock.read(cx);
 6485                        if let Some(active_panel) = dock.active_panel() {
 6486                            if active_panel.pane(cx).is_none() {
 6487                                let mut recent_pane: Option<Entity<Pane>> = None;
 6488                                let mut recent_timestamp = 0;
 6489                                for pane_handle in workspace.panes() {
 6490                                    let pane = pane_handle.read(cx);
 6491                                    for entry in pane.activation_history() {
 6492                                        if entry.timestamp > recent_timestamp {
 6493                                            recent_timestamp = entry.timestamp;
 6494                                            recent_pane = Some(pane_handle.clone());
 6495                                        }
 6496                                    }
 6497                                }
 6498
 6499                                if let Some(pane) = recent_pane {
 6500                                    pane.update(cx, |pane, cx| {
 6501                                        let current_index = pane.active_item_index();
 6502                                        let items_len = pane.items_len();
 6503                                        if items_len > 0 {
 6504                                            let next_index = if current_index + 1 < items_len {
 6505                                                current_index + 1
 6506                                            } else {
 6507                                                0
 6508                                            };
 6509                                            pane.activate_item(
 6510                                                next_index, false, false, window, cx,
 6511                                            );
 6512                                        }
 6513                                    });
 6514                                    return;
 6515                                }
 6516                            }
 6517                        }
 6518                    }
 6519                    cx.propagate();
 6520                },
 6521            ))
 6522            .on_action(cx.listener(
 6523                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6524                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6525                        let dock = active_dock.read(cx);
 6526                        if let Some(active_panel) = dock.active_panel() {
 6527                            if active_panel.pane(cx).is_none() {
 6528                                let mut recent_pane: Option<Entity<Pane>> = None;
 6529                                let mut recent_timestamp = 0;
 6530                                for pane_handle in workspace.panes() {
 6531                                    let pane = pane_handle.read(cx);
 6532                                    for entry in pane.activation_history() {
 6533                                        if entry.timestamp > recent_timestamp {
 6534                                            recent_timestamp = entry.timestamp;
 6535                                            recent_pane = Some(pane_handle.clone());
 6536                                        }
 6537                                    }
 6538                                }
 6539
 6540                                if let Some(pane) = recent_pane {
 6541                                    pane.update(cx, |pane, cx| {
 6542                                        let current_index = pane.active_item_index();
 6543                                        let items_len = pane.items_len();
 6544                                        if items_len > 0 {
 6545                                            let prev_index = if current_index > 0 {
 6546                                                current_index - 1
 6547                                            } else {
 6548                                                items_len.saturating_sub(1)
 6549                                            };
 6550                                            pane.activate_item(
 6551                                                prev_index, false, false, window, cx,
 6552                                            );
 6553                                        }
 6554                                    });
 6555                                    return;
 6556                                }
 6557                            }
 6558                        }
 6559                    }
 6560                    cx.propagate();
 6561                },
 6562            ))
 6563            .on_action(cx.listener(
 6564                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6565                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6566                        let dock = active_dock.read(cx);
 6567                        if let Some(active_panel) = dock.active_panel() {
 6568                            if active_panel.pane(cx).is_none() {
 6569                                let active_pane = workspace.active_pane().clone();
 6570                                active_pane.update(cx, |pane, cx| {
 6571                                    pane.close_active_item(action, window, cx)
 6572                                        .detach_and_log_err(cx);
 6573                                });
 6574                                return;
 6575                            }
 6576                        }
 6577                    }
 6578                    cx.propagate();
 6579                },
 6580            ))
 6581            .on_action(
 6582                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6583                    let pane = workspace.active_pane().clone();
 6584                    if let Some(item) = pane.read(cx).active_item() {
 6585                        item.toggle_read_only(window, cx);
 6586                    }
 6587                }),
 6588            )
 6589            .on_action(cx.listener(Workspace::cancel))
 6590    }
 6591
 6592    #[cfg(any(test, feature = "test-support"))]
 6593    pub fn set_random_database_id(&mut self) {
 6594        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6595    }
 6596
 6597    #[cfg(any(test, feature = "test-support"))]
 6598    pub(crate) fn test_new(
 6599        project: Entity<Project>,
 6600        window: &mut Window,
 6601        cx: &mut Context<Self>,
 6602    ) -> Self {
 6603        use node_runtime::NodeRuntime;
 6604        use session::Session;
 6605
 6606        let client = project.read(cx).client();
 6607        let user_store = project.read(cx).user_store();
 6608        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6609        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6610        window.activate_window();
 6611        let app_state = Arc::new(AppState {
 6612            languages: project.read(cx).languages().clone(),
 6613            workspace_store,
 6614            client,
 6615            user_store,
 6616            fs: project.read(cx).fs().clone(),
 6617            build_window_options: |_, _| Default::default(),
 6618            node_runtime: NodeRuntime::unavailable(),
 6619            session,
 6620        });
 6621        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6622        workspace
 6623            .active_pane
 6624            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6625        workspace
 6626    }
 6627
 6628    pub fn register_action<A: Action>(
 6629        &mut self,
 6630        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6631    ) -> &mut Self {
 6632        let callback = Arc::new(callback);
 6633
 6634        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6635            let callback = callback.clone();
 6636            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6637                (callback)(workspace, event, window, cx)
 6638            }))
 6639        }));
 6640        self
 6641    }
 6642    pub fn register_action_renderer(
 6643        &mut self,
 6644        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6645    ) -> &mut Self {
 6646        self.workspace_actions.push(Box::new(callback));
 6647        self
 6648    }
 6649
 6650    fn add_workspace_actions_listeners(
 6651        &self,
 6652        mut div: Div,
 6653        window: &mut Window,
 6654        cx: &mut Context<Self>,
 6655    ) -> Div {
 6656        for action in self.workspace_actions.iter() {
 6657            div = (action)(div, self, window, cx)
 6658        }
 6659        div
 6660    }
 6661
 6662    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6663        self.modal_layer.read(cx).has_active_modal()
 6664    }
 6665
 6666    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6667        self.modal_layer.read(cx).active_modal()
 6668    }
 6669
 6670    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6671    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6672    /// If no modal is active, the new modal will be shown.
 6673    ///
 6674    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6675    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6676    /// will not be shown.
 6677    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6678    where
 6679        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6680    {
 6681        self.modal_layer.update(cx, |modal_layer, cx| {
 6682            modal_layer.toggle_modal(window, cx, build)
 6683        })
 6684    }
 6685
 6686    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6687        self.modal_layer
 6688            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6689    }
 6690
 6691    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6692        self.toast_layer
 6693            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6694    }
 6695
 6696    pub fn toggle_centered_layout(
 6697        &mut self,
 6698        _: &ToggleCenteredLayout,
 6699        _: &mut Window,
 6700        cx: &mut Context<Self>,
 6701    ) {
 6702        self.centered_layout = !self.centered_layout;
 6703        if let Some(database_id) = self.database_id() {
 6704            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6705                .detach_and_log_err(cx);
 6706        }
 6707        cx.notify();
 6708    }
 6709
 6710    fn adjust_padding(padding: Option<f32>) -> f32 {
 6711        padding
 6712            .unwrap_or(CenteredPaddingSettings::default().0)
 6713            .clamp(
 6714                CenteredPaddingSettings::MIN_PADDING,
 6715                CenteredPaddingSettings::MAX_PADDING,
 6716            )
 6717    }
 6718
 6719    fn render_dock(
 6720        &self,
 6721        position: DockPosition,
 6722        dock: &Entity<Dock>,
 6723        window: &mut Window,
 6724        cx: &mut App,
 6725    ) -> Option<Div> {
 6726        if self.zoomed_position == Some(position) {
 6727            return None;
 6728        }
 6729
 6730        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6731            let pane = panel.pane(cx)?;
 6732            let follower_states = &self.follower_states;
 6733            leader_border_for_pane(follower_states, &pane, window, cx)
 6734        });
 6735
 6736        Some(
 6737            div()
 6738                .flex()
 6739                .flex_none()
 6740                .overflow_hidden()
 6741                .child(dock.clone())
 6742                .children(leader_border),
 6743        )
 6744    }
 6745
 6746    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 6747        window
 6748            .root::<MultiWorkspace>()
 6749            .flatten()
 6750            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 6751    }
 6752
 6753    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6754        self.zoomed.as_ref()
 6755    }
 6756
 6757    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6758        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6759            return;
 6760        };
 6761        let windows = cx.windows();
 6762        let next_window =
 6763            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6764                || {
 6765                    windows
 6766                        .iter()
 6767                        .cycle()
 6768                        .skip_while(|window| window.window_id() != current_window_id)
 6769                        .nth(1)
 6770                },
 6771            );
 6772
 6773        if let Some(window) = next_window {
 6774            window
 6775                .update(cx, |_, window, _| window.activate_window())
 6776                .ok();
 6777        }
 6778    }
 6779
 6780    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6781        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6782            return;
 6783        };
 6784        let windows = cx.windows();
 6785        let prev_window =
 6786            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6787                || {
 6788                    windows
 6789                        .iter()
 6790                        .rev()
 6791                        .cycle()
 6792                        .skip_while(|window| window.window_id() != current_window_id)
 6793                        .nth(1)
 6794                },
 6795            );
 6796
 6797        if let Some(window) = prev_window {
 6798            window
 6799                .update(cx, |_, window, _| window.activate_window())
 6800                .ok();
 6801        }
 6802    }
 6803
 6804    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6805        if cx.stop_active_drag(window) {
 6806        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6807            dismiss_app_notification(&notification_id, cx);
 6808        } else {
 6809            cx.propagate();
 6810        }
 6811    }
 6812
 6813    fn adjust_dock_size_by_px(
 6814        &mut self,
 6815        panel_size: Pixels,
 6816        dock_pos: DockPosition,
 6817        px: Pixels,
 6818        window: &mut Window,
 6819        cx: &mut Context<Self>,
 6820    ) {
 6821        match dock_pos {
 6822            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6823            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6824            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6825        }
 6826    }
 6827
 6828    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6829        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6830
 6831        self.left_dock.update(cx, |left_dock, cx| {
 6832            if WorkspaceSettings::get_global(cx)
 6833                .resize_all_panels_in_dock
 6834                .contains(&DockPosition::Left)
 6835            {
 6836                left_dock.resize_all_panels(Some(size), window, cx);
 6837            } else {
 6838                left_dock.resize_active_panel(Some(size), window, cx);
 6839            }
 6840        });
 6841        self.clamp_utility_pane_widths(window, cx);
 6842    }
 6843
 6844    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6845        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6846        self.left_dock.read_with(cx, |left_dock, cx| {
 6847            let left_dock_size = left_dock
 6848                .active_panel_size(window, cx)
 6849                .unwrap_or(Pixels::ZERO);
 6850            if left_dock_size + size > self.bounds.right() {
 6851                size = self.bounds.right() - left_dock_size
 6852            }
 6853        });
 6854        self.right_dock.update(cx, |right_dock, cx| {
 6855            if WorkspaceSettings::get_global(cx)
 6856                .resize_all_panels_in_dock
 6857                .contains(&DockPosition::Right)
 6858            {
 6859                right_dock.resize_all_panels(Some(size), window, cx);
 6860            } else {
 6861                right_dock.resize_active_panel(Some(size), window, cx);
 6862            }
 6863        });
 6864        self.clamp_utility_pane_widths(window, cx);
 6865    }
 6866
 6867    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6868        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6869        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6870            if WorkspaceSettings::get_global(cx)
 6871                .resize_all_panels_in_dock
 6872                .contains(&DockPosition::Bottom)
 6873            {
 6874                bottom_dock.resize_all_panels(Some(size), window, cx);
 6875            } else {
 6876                bottom_dock.resize_active_panel(Some(size), window, cx);
 6877            }
 6878        });
 6879        self.clamp_utility_pane_widths(window, cx);
 6880    }
 6881
 6882    fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
 6883        let left_dock_width = self
 6884            .left_dock
 6885            .read(cx)
 6886            .active_panel_size(window, cx)
 6887            .unwrap_or(px(0.0));
 6888        let right_dock_width = self
 6889            .right_dock
 6890            .read(cx)
 6891            .active_panel_size(window, cx)
 6892            .unwrap_or(px(0.0));
 6893        let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
 6894        center_pane_width - px(10.0)
 6895    }
 6896
 6897    fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
 6898        let max_width = self.max_utility_pane_width(window, cx);
 6899
 6900        // Clamp left slot utility pane if it exists
 6901        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
 6902            let current_width = handle.width(cx);
 6903            if current_width > max_width {
 6904                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6905            }
 6906        }
 6907
 6908        // Clamp right slot utility pane if it exists
 6909        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
 6910            let current_width = handle.width(cx);
 6911            if current_width > max_width {
 6912                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6913            }
 6914        }
 6915    }
 6916
 6917    fn toggle_edit_predictions_all_files(
 6918        &mut self,
 6919        _: &ToggleEditPrediction,
 6920        _window: &mut Window,
 6921        cx: &mut Context<Self>,
 6922    ) {
 6923        let fs = self.project().read(cx).fs().clone();
 6924        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6925        update_settings_file(fs, cx, move |file, _| {
 6926            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6927        });
 6928    }
 6929
 6930    pub fn show_worktree_trust_security_modal(
 6931        &mut self,
 6932        toggle: bool,
 6933        window: &mut Window,
 6934        cx: &mut Context<Self>,
 6935    ) {
 6936        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 6937            if toggle {
 6938                security_modal.update(cx, |security_modal, cx| {
 6939                    security_modal.dismiss(cx);
 6940                })
 6941            } else {
 6942                security_modal.update(cx, |security_modal, cx| {
 6943                    security_modal.refresh_restricted_paths(cx);
 6944                });
 6945            }
 6946        } else {
 6947            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 6948                .map(|trusted_worktrees| {
 6949                    trusted_worktrees
 6950                        .read(cx)
 6951                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 6952                })
 6953                .unwrap_or(false);
 6954            if has_restricted_worktrees {
 6955                let project = self.project().read(cx);
 6956                let remote_host = project
 6957                    .remote_connection_options(cx)
 6958                    .map(RemoteHostLocation::from);
 6959                let worktree_store = project.worktree_store().downgrade();
 6960                self.toggle_modal(window, cx, |_, cx| {
 6961                    SecurityModal::new(worktree_store, remote_host, cx)
 6962                });
 6963            }
 6964        }
 6965    }
 6966}
 6967
 6968fn leader_border_for_pane(
 6969    follower_states: &HashMap<CollaboratorId, FollowerState>,
 6970    pane: &Entity<Pane>,
 6971    _: &Window,
 6972    cx: &App,
 6973) -> Option<Div> {
 6974    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 6975        if state.pane() == pane {
 6976            Some((*leader_id, state))
 6977        } else {
 6978            None
 6979        }
 6980    })?;
 6981
 6982    let mut leader_color = match leader_id {
 6983        CollaboratorId::PeerId(leader_peer_id) => {
 6984            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 6985            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 6986
 6987            cx.theme()
 6988                .players()
 6989                .color_for_participant(leader.participant_index.0)
 6990                .cursor
 6991        }
 6992        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 6993    };
 6994    leader_color.fade_out(0.3);
 6995    Some(
 6996        div()
 6997            .absolute()
 6998            .size_full()
 6999            .left_0()
 7000            .top_0()
 7001            .border_2()
 7002            .border_color(leader_color),
 7003    )
 7004}
 7005
 7006fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7007    ZED_WINDOW_POSITION
 7008        .zip(*ZED_WINDOW_SIZE)
 7009        .map(|(position, size)| Bounds {
 7010            origin: position,
 7011            size,
 7012        })
 7013}
 7014
 7015fn open_items(
 7016    serialized_workspace: Option<SerializedWorkspace>,
 7017    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7018    window: &mut Window,
 7019    cx: &mut Context<Workspace>,
 7020) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7021    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7022        Workspace::load_workspace(
 7023            serialized_workspace,
 7024            project_paths_to_open
 7025                .iter()
 7026                .map(|(_, project_path)| project_path)
 7027                .cloned()
 7028                .collect(),
 7029            window,
 7030            cx,
 7031        )
 7032    });
 7033
 7034    cx.spawn_in(window, async move |workspace, cx| {
 7035        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7036
 7037        if let Some(restored_items) = restored_items {
 7038            let restored_items = restored_items.await?;
 7039
 7040            let restored_project_paths = restored_items
 7041                .iter()
 7042                .filter_map(|item| {
 7043                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7044                        .ok()
 7045                        .flatten()
 7046                })
 7047                .collect::<HashSet<_>>();
 7048
 7049            for restored_item in restored_items {
 7050                opened_items.push(restored_item.map(Ok));
 7051            }
 7052
 7053            project_paths_to_open
 7054                .iter_mut()
 7055                .for_each(|(_, project_path)| {
 7056                    if let Some(project_path_to_open) = project_path
 7057                        && restored_project_paths.contains(project_path_to_open)
 7058                    {
 7059                        *project_path = None;
 7060                    }
 7061                });
 7062        } else {
 7063            for _ in 0..project_paths_to_open.len() {
 7064                opened_items.push(None);
 7065            }
 7066        }
 7067        assert!(opened_items.len() == project_paths_to_open.len());
 7068
 7069        let tasks =
 7070            project_paths_to_open
 7071                .into_iter()
 7072                .enumerate()
 7073                .map(|(ix, (abs_path, project_path))| {
 7074                    let workspace = workspace.clone();
 7075                    cx.spawn(async move |cx| {
 7076                        let file_project_path = project_path?;
 7077                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7078                            workspace.project().update(cx, |project, cx| {
 7079                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7080                            })
 7081                        });
 7082
 7083                        // We only want to open file paths here. If one of the items
 7084                        // here is a directory, it was already opened further above
 7085                        // with a `find_or_create_worktree`.
 7086                        if let Ok(task) = abs_path_task
 7087                            && task.await.is_none_or(|p| p.is_file())
 7088                        {
 7089                            return Some((
 7090                                ix,
 7091                                workspace
 7092                                    .update_in(cx, |workspace, window, cx| {
 7093                                        workspace.open_path(
 7094                                            file_project_path,
 7095                                            None,
 7096                                            true,
 7097                                            window,
 7098                                            cx,
 7099                                        )
 7100                                    })
 7101                                    .log_err()?
 7102                                    .await,
 7103                            ));
 7104                        }
 7105                        None
 7106                    })
 7107                });
 7108
 7109        let tasks = tasks.collect::<Vec<_>>();
 7110
 7111        let tasks = futures::future::join_all(tasks);
 7112        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7113            opened_items[ix] = Some(path_open_result);
 7114        }
 7115
 7116        Ok(opened_items)
 7117    })
 7118}
 7119
 7120enum ActivateInDirectionTarget {
 7121    Pane(Entity<Pane>),
 7122    Dock(Entity<Dock>),
 7123}
 7124
 7125fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7126    window
 7127        .update(cx, |multi_workspace, _, cx| {
 7128            let workspace = multi_workspace.workspace().clone();
 7129            workspace.update(cx, |workspace, cx| {
 7130                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7131                    struct DatabaseFailedNotification;
 7132
 7133                    workspace.show_notification(
 7134                        NotificationId::unique::<DatabaseFailedNotification>(),
 7135                        cx,
 7136                        |cx| {
 7137                            cx.new(|cx| {
 7138                                MessageNotification::new("Failed to load the database file.", cx)
 7139                                    .primary_message("File an Issue")
 7140                                    .primary_icon(IconName::Plus)
 7141                                    .primary_on_click(|window, cx| {
 7142                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7143                                    })
 7144                            })
 7145                        },
 7146                    );
 7147                }
 7148            });
 7149        })
 7150        .log_err();
 7151}
 7152
 7153fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7154    if val == 0 {
 7155        ThemeSettings::get_global(cx).ui_font_size(cx)
 7156    } else {
 7157        px(val as f32)
 7158    }
 7159}
 7160
 7161fn adjust_active_dock_size_by_px(
 7162    px: Pixels,
 7163    workspace: &mut Workspace,
 7164    window: &mut Window,
 7165    cx: &mut Context<Workspace>,
 7166) {
 7167    let Some(active_dock) = workspace
 7168        .all_docks()
 7169        .into_iter()
 7170        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7171    else {
 7172        return;
 7173    };
 7174    let dock = active_dock.read(cx);
 7175    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7176        return;
 7177    };
 7178    let dock_pos = dock.position();
 7179    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7180}
 7181
 7182fn adjust_open_docks_size_by_px(
 7183    px: Pixels,
 7184    workspace: &mut Workspace,
 7185    window: &mut Window,
 7186    cx: &mut Context<Workspace>,
 7187) {
 7188    let docks = workspace
 7189        .all_docks()
 7190        .into_iter()
 7191        .filter_map(|dock| {
 7192            if dock.read(cx).is_open() {
 7193                let dock = dock.read(cx);
 7194                let panel_size = dock.active_panel_size(window, cx)?;
 7195                let dock_pos = dock.position();
 7196                Some((panel_size, dock_pos, px))
 7197            } else {
 7198                None
 7199            }
 7200        })
 7201        .collect::<Vec<_>>();
 7202
 7203    docks
 7204        .into_iter()
 7205        .for_each(|(panel_size, dock_pos, offset)| {
 7206            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7207        });
 7208}
 7209
 7210impl Focusable for Workspace {
 7211    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7212        self.active_pane.focus_handle(cx)
 7213    }
 7214}
 7215
 7216#[derive(Clone)]
 7217struct DraggedDock(DockPosition);
 7218
 7219impl Render for DraggedDock {
 7220    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7221        gpui::Empty
 7222    }
 7223}
 7224
 7225impl Render for Workspace {
 7226    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7227        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7228        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7229            log::info!("Rendered first frame");
 7230        }
 7231        let mut context = KeyContext::new_with_defaults();
 7232        context.add("Workspace");
 7233        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 7234        if let Some(status) = self
 7235            .debugger_provider
 7236            .as_ref()
 7237            .and_then(|provider| provider.active_thread_state(cx))
 7238        {
 7239            match status {
 7240                ThreadStatus::Running | ThreadStatus::Stepping => {
 7241                    context.add("debugger_running");
 7242                }
 7243                ThreadStatus::Stopped => context.add("debugger_stopped"),
 7244                ThreadStatus::Exited | ThreadStatus::Ended => {}
 7245            }
 7246        }
 7247
 7248        if self.left_dock.read(cx).is_open() {
 7249            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 7250                context.set("left_dock", active_panel.panel_key());
 7251            }
 7252        }
 7253
 7254        if self.right_dock.read(cx).is_open() {
 7255            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 7256                context.set("right_dock", active_panel.panel_key());
 7257            }
 7258        }
 7259
 7260        if self.bottom_dock.read(cx).is_open() {
 7261            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 7262                context.set("bottom_dock", active_panel.panel_key());
 7263            }
 7264        }
 7265
 7266        let centered_layout = self.centered_layout
 7267            && self.center.panes().len() == 1
 7268            && self.active_item(cx).is_some();
 7269        let render_padding = |size| {
 7270            (size > 0.0).then(|| {
 7271                div()
 7272                    .h_full()
 7273                    .w(relative(size))
 7274                    .bg(cx.theme().colors().editor_background)
 7275                    .border_color(cx.theme().colors().pane_group_border)
 7276            })
 7277        };
 7278        let paddings = if centered_layout {
 7279            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7280            (
 7281                render_padding(Self::adjust_padding(
 7282                    settings.left_padding.map(|padding| padding.0),
 7283                )),
 7284                render_padding(Self::adjust_padding(
 7285                    settings.right_padding.map(|padding| padding.0),
 7286                )),
 7287            )
 7288        } else {
 7289            (None, None)
 7290        };
 7291        let ui_font = theme::setup_ui_font(window, cx);
 7292
 7293        let theme = cx.theme().clone();
 7294        let colors = theme.colors();
 7295        let notification_entities = self
 7296            .notifications
 7297            .iter()
 7298            .map(|(_, notification)| notification.entity_id())
 7299            .collect::<Vec<_>>();
 7300        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7301
 7302        self.actions(div(), window, cx)
 7303            .key_context(context)
 7304            .relative()
 7305            .size_full()
 7306            .flex()
 7307            .flex_col()
 7308            .font(ui_font)
 7309            .gap_0()
 7310                .justify_start()
 7311                .items_start()
 7312                .text_color(colors.text)
 7313                .overflow_hidden()
 7314                .children(self.titlebar_item.clone())
 7315                .on_modifiers_changed(move |_, _, cx| {
 7316                    for &id in &notification_entities {
 7317                        cx.notify(id);
 7318                    }
 7319                })
 7320                .child(
 7321                    div()
 7322                        .size_full()
 7323                        .relative()
 7324                        .flex_1()
 7325                        .flex()
 7326                        .flex_col()
 7327                        .child(
 7328                            div()
 7329                                .id("workspace")
 7330                                .bg(colors.background)
 7331                                .relative()
 7332                                .flex_1()
 7333                                .w_full()
 7334                                .flex()
 7335                                .flex_col()
 7336                                .overflow_hidden()
 7337                                .border_t_1()
 7338                                .border_b_1()
 7339                                .border_color(colors.border)
 7340                                .child({
 7341                                    let this = cx.entity();
 7342                                    canvas(
 7343                                        move |bounds, window, cx| {
 7344                                            this.update(cx, |this, cx| {
 7345                                                let bounds_changed = this.bounds != bounds;
 7346                                                this.bounds = bounds;
 7347
 7348                                                if bounds_changed {
 7349                                                    this.left_dock.update(cx, |dock, cx| {
 7350                                                        dock.clamp_panel_size(
 7351                                                            bounds.size.width,
 7352                                                            window,
 7353                                                            cx,
 7354                                                        )
 7355                                                    });
 7356
 7357                                                    this.right_dock.update(cx, |dock, cx| {
 7358                                                        dock.clamp_panel_size(
 7359                                                            bounds.size.width,
 7360                                                            window,
 7361                                                            cx,
 7362                                                        )
 7363                                                    });
 7364
 7365                                                    this.bottom_dock.update(cx, |dock, cx| {
 7366                                                        dock.clamp_panel_size(
 7367                                                            bounds.size.height,
 7368                                                            window,
 7369                                                            cx,
 7370                                                        )
 7371                                                    });
 7372                                                }
 7373                                            })
 7374                                        },
 7375                                        |_, _, _, _| {},
 7376                                    )
 7377                                    .absolute()
 7378                                    .size_full()
 7379                                })
 7380                                .when(self.zoomed.is_none(), |this| {
 7381                                    this.on_drag_move(cx.listener(
 7382                                        move |workspace,
 7383                                              e: &DragMoveEvent<DraggedDock>,
 7384                                              window,
 7385                                              cx| {
 7386                                            if workspace.previous_dock_drag_coordinates
 7387                                                != Some(e.event.position)
 7388                                            {
 7389                                                workspace.previous_dock_drag_coordinates =
 7390                                                    Some(e.event.position);
 7391                                                match e.drag(cx).0 {
 7392                                                    DockPosition::Left => {
 7393                                                        workspace.resize_left_dock(
 7394                                                            e.event.position.x
 7395                                                                - workspace.bounds.left(),
 7396                                                            window,
 7397                                                            cx,
 7398                                                        );
 7399                                                    }
 7400                                                    DockPosition::Right => {
 7401                                                        workspace.resize_right_dock(
 7402                                                            workspace.bounds.right()
 7403                                                                - e.event.position.x,
 7404                                                            window,
 7405                                                            cx,
 7406                                                        );
 7407                                                    }
 7408                                                    DockPosition::Bottom => {
 7409                                                        workspace.resize_bottom_dock(
 7410                                                            workspace.bounds.bottom()
 7411                                                                - e.event.position.y,
 7412                                                            window,
 7413                                                            cx,
 7414                                                        );
 7415                                                    }
 7416                                                };
 7417                                                workspace.serialize_workspace(window, cx);
 7418                                            }
 7419                                        },
 7420                                    ))
 7421                                    .on_drag_move(cx.listener(
 7422                                        move |workspace,
 7423                                              e: &DragMoveEvent<DraggedUtilityPane>,
 7424                                              window,
 7425                                              cx| {
 7426                                            let slot = e.drag(cx).0;
 7427                                            match slot {
 7428                                                UtilityPaneSlot::Left => {
 7429                                                    let left_dock_width = workspace.left_dock.read(cx)
 7430                                                        .active_panel_size(window, cx)
 7431                                                        .unwrap_or(gpui::px(0.0));
 7432                                                    let new_width = e.event.position.x
 7433                                                        - workspace.bounds.left()
 7434                                                        - left_dock_width;
 7435                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7436                                                }
 7437                                                UtilityPaneSlot::Right => {
 7438                                                    let right_dock_width = workspace.right_dock.read(cx)
 7439                                                        .active_panel_size(window, cx)
 7440                                                        .unwrap_or(gpui::px(0.0));
 7441                                                    let new_width = workspace.bounds.right()
 7442                                                        - e.event.position.x
 7443                                                        - right_dock_width;
 7444                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 7445                                                }
 7446                                            }
 7447                                        },
 7448                                    ))
 7449                                })
 7450                                .child({
 7451                                    match bottom_dock_layout {
 7452                                        BottomDockLayout::Full => div()
 7453                                            .flex()
 7454                                            .flex_col()
 7455                                            .h_full()
 7456                                            .child(
 7457                                                div()
 7458                                                    .flex()
 7459                                                    .flex_row()
 7460                                                    .flex_1()
 7461                                                    .overflow_hidden()
 7462                                                    .children(self.render_dock(
 7463                                                        DockPosition::Left,
 7464                                                        &self.left_dock,
 7465                                                        window,
 7466                                                        cx,
 7467                                                    ))
 7468                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7469                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7470                                                            this.when(pane.expanded(cx), |this| {
 7471                                                                this.child(
 7472                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7473                                                                )
 7474                                                            })
 7475                                                        })
 7476                                                    })
 7477                                                    .child(
 7478                                                        div()
 7479                                                            .flex()
 7480                                                            .flex_col()
 7481                                                            .flex_1()
 7482                                                            .overflow_hidden()
 7483                                                            .child(
 7484                                                                h_flex()
 7485                                                                    .flex_1()
 7486                                                                    .when_some(
 7487                                                                        paddings.0,
 7488                                                                        |this, p| {
 7489                                                                            this.child(
 7490                                                                                p.border_r_1(),
 7491                                                                            )
 7492                                                                        },
 7493                                                                    )
 7494                                                                    .child(self.center.render(
 7495                                                                        self.zoomed.as_ref(),
 7496                                                                        &PaneRenderContext {
 7497                                                                            follower_states:
 7498                                                                                &self.follower_states,
 7499                                                                            active_call: self.active_call(),
 7500                                                                            active_pane: &self.active_pane,
 7501                                                                            app_state: &self.app_state,
 7502                                                                            project: &self.project,
 7503                                                                            workspace: &self.weak_self,
 7504                                                                        },
 7505                                                                        window,
 7506                                                                        cx,
 7507                                                                    ))
 7508                                                                    .when_some(
 7509                                                                        paddings.1,
 7510                                                                        |this, p| {
 7511                                                                            this.child(
 7512                                                                                p.border_l_1(),
 7513                                                                            )
 7514                                                                        },
 7515                                                                    ),
 7516                                                            ),
 7517                                                    )
 7518                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7519                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7520                                                            this.when(pane.expanded(cx), |this| {
 7521                                                                this.child(
 7522                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7523                                                                )
 7524                                                            })
 7525                                                        })
 7526                                                    })
 7527                                                    .children(self.render_dock(
 7528                                                        DockPosition::Right,
 7529                                                        &self.right_dock,
 7530                                                        window,
 7531                                                        cx,
 7532                                                    )),
 7533                                            )
 7534                                            .child(div().w_full().children(self.render_dock(
 7535                                                DockPosition::Bottom,
 7536                                                &self.bottom_dock,
 7537                                                window,
 7538                                                cx
 7539                                            ))),
 7540
 7541                                        BottomDockLayout::LeftAligned => div()
 7542                                            .flex()
 7543                                            .flex_row()
 7544                                            .h_full()
 7545                                            .child(
 7546                                                div()
 7547                                                    .flex()
 7548                                                    .flex_col()
 7549                                                    .flex_1()
 7550                                                    .h_full()
 7551                                                    .child(
 7552                                                        div()
 7553                                                            .flex()
 7554                                                            .flex_row()
 7555                                                            .flex_1()
 7556                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7557                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7558                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7559                                                                    this.when(pane.expanded(cx), |this| {
 7560                                                                        this.child(
 7561                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7562                                                                        )
 7563                                                                    })
 7564                                                                })
 7565                                                            })
 7566                                                            .child(
 7567                                                                div()
 7568                                                                    .flex()
 7569                                                                    .flex_col()
 7570                                                                    .flex_1()
 7571                                                                    .overflow_hidden()
 7572                                                                    .child(
 7573                                                                        h_flex()
 7574                                                                            .flex_1()
 7575                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7576                                                                            .child(self.center.render(
 7577                                                                                self.zoomed.as_ref(),
 7578                                                                                &PaneRenderContext {
 7579                                                                                    follower_states:
 7580                                                                                        &self.follower_states,
 7581                                                                                    active_call: self.active_call(),
 7582                                                                                    active_pane: &self.active_pane,
 7583                                                                                    app_state: &self.app_state,
 7584                                                                                    project: &self.project,
 7585                                                                                    workspace: &self.weak_self,
 7586                                                                                },
 7587                                                                                window,
 7588                                                                                cx,
 7589                                                                            ))
 7590                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7591                                                                    )
 7592                                                            )
 7593                                                            .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7594                                                                this.when(pane.expanded(cx), |this| {
 7595                                                                    this.child(
 7596                                                                        UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7597                                                                    )
 7598                                                                })
 7599                                                            })
 7600                                                    )
 7601                                                    .child(
 7602                                                        div()
 7603                                                            .w_full()
 7604                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7605                                                    ),
 7606                                            )
 7607                                            .children(self.render_dock(
 7608                                                DockPosition::Right,
 7609                                                &self.right_dock,
 7610                                                window,
 7611                                                cx,
 7612                                            )),
 7613
 7614                                        BottomDockLayout::RightAligned => div()
 7615                                            .flex()
 7616                                            .flex_row()
 7617                                            .h_full()
 7618                                            .children(self.render_dock(
 7619                                                DockPosition::Left,
 7620                                                &self.left_dock,
 7621                                                window,
 7622                                                cx,
 7623                                            ))
 7624                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7625                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7626                                                    this.when(pane.expanded(cx), |this| {
 7627                                                        this.child(
 7628                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7629                                                        )
 7630                                                    })
 7631                                                })
 7632                                            })
 7633                                            .child(
 7634                                                div()
 7635                                                    .flex()
 7636                                                    .flex_col()
 7637                                                    .flex_1()
 7638                                                    .h_full()
 7639                                                    .child(
 7640                                                        div()
 7641                                                            .flex()
 7642                                                            .flex_row()
 7643                                                            .flex_1()
 7644                                                            .child(
 7645                                                                div()
 7646                                                                    .flex()
 7647                                                                    .flex_col()
 7648                                                                    .flex_1()
 7649                                                                    .overflow_hidden()
 7650                                                                    .child(
 7651                                                                        h_flex()
 7652                                                                            .flex_1()
 7653                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7654                                                                            .child(self.center.render(
 7655                                                                                self.zoomed.as_ref(),
 7656                                                                                &PaneRenderContext {
 7657                                                                                    follower_states:
 7658                                                                                        &self.follower_states,
 7659                                                                                    active_call: self.active_call(),
 7660                                                                                    active_pane: &self.active_pane,
 7661                                                                                    app_state: &self.app_state,
 7662                                                                                    project: &self.project,
 7663                                                                                    workspace: &self.weak_self,
 7664                                                                                },
 7665                                                                                window,
 7666                                                                                cx,
 7667                                                                            ))
 7668                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7669                                                                    )
 7670                                                            )
 7671                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7672                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7673                                                                    this.when(pane.expanded(cx), |this| {
 7674                                                                        this.child(
 7675                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7676                                                                        )
 7677                                                                    })
 7678                                                                })
 7679                                                            })
 7680                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7681                                                    )
 7682                                                    .child(
 7683                                                        div()
 7684                                                            .w_full()
 7685                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7686                                                    ),
 7687                                            ),
 7688
 7689                                        BottomDockLayout::Contained => div()
 7690                                            .flex()
 7691                                            .flex_row()
 7692                                            .h_full()
 7693                                            .children(self.render_dock(
 7694                                                DockPosition::Left,
 7695                                                &self.left_dock,
 7696                                                window,
 7697                                                cx,
 7698                                            ))
 7699                                            .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7700                                                this.when(pane.expanded(cx), |this| {
 7701                                                    this.child(
 7702                                                        UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7703                                                    )
 7704                                                })
 7705                                            })
 7706                                            .child(
 7707                                                div()
 7708                                                    .flex()
 7709                                                    .flex_col()
 7710                                                    .flex_1()
 7711                                                    .overflow_hidden()
 7712                                                    .child(
 7713                                                        h_flex()
 7714                                                            .flex_1()
 7715                                                            .when_some(paddings.0, |this, p| {
 7716                                                                this.child(p.border_r_1())
 7717                                                            })
 7718                                                            .child(self.center.render(
 7719                                                                self.zoomed.as_ref(),
 7720                                                                &PaneRenderContext {
 7721                                                                    follower_states:
 7722                                                                        &self.follower_states,
 7723                                                                    active_call: self.active_call(),
 7724                                                                    active_pane: &self.active_pane,
 7725                                                                    app_state: &self.app_state,
 7726                                                                    project: &self.project,
 7727                                                                    workspace: &self.weak_self,
 7728                                                                },
 7729                                                                window,
 7730                                                                cx,
 7731                                                            ))
 7732                                                            .when_some(paddings.1, |this, p| {
 7733                                                                this.child(p.border_l_1())
 7734                                                            }),
 7735                                                    )
 7736                                                    .children(self.render_dock(
 7737                                                        DockPosition::Bottom,
 7738                                                        &self.bottom_dock,
 7739                                                        window,
 7740                                                        cx,
 7741                                                    )),
 7742                                            )
 7743                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7744                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7745                                                    this.when(pane.expanded(cx), |this| {
 7746                                                        this.child(
 7747                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7748                                                        )
 7749                                                    })
 7750                                                })
 7751                                            })
 7752                                            .children(self.render_dock(
 7753                                                DockPosition::Right,
 7754                                                &self.right_dock,
 7755                                                window,
 7756                                                cx,
 7757                                            )),
 7758                                    }
 7759                                })
 7760                                .children(self.zoomed.as_ref().and_then(|view| {
 7761                                    let zoomed_view = view.upgrade()?;
 7762                                    let div = div()
 7763                                        .occlude()
 7764                                        .absolute()
 7765                                        .overflow_hidden()
 7766                                        .border_color(colors.border)
 7767                                        .bg(colors.background)
 7768                                        .child(zoomed_view)
 7769                                        .inset_0()
 7770                                        .shadow_lg();
 7771
 7772                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7773                                       return Some(div);
 7774                                    }
 7775
 7776                                    Some(match self.zoomed_position {
 7777                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7778                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7779                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7780                                        None => {
 7781                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7782                                        }
 7783                                    })
 7784                                }))
 7785                                .children(self.render_notifications(window, cx)),
 7786                        )
 7787                        .when(self.status_bar_visible(cx), |parent| {
 7788                            parent.child(self.status_bar.clone())
 7789                        })
 7790                        .child(self.modal_layer.clone())
 7791                        .child(self.toast_layer.clone()),
 7792                )
 7793    }
 7794}
 7795
 7796impl WorkspaceStore {
 7797    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7798        Self {
 7799            workspaces: Default::default(),
 7800            _subscriptions: vec![
 7801                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7802                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7803            ],
 7804            client,
 7805        }
 7806    }
 7807
 7808    pub fn update_followers(
 7809        &self,
 7810        project_id: Option<u64>,
 7811        update: proto::update_followers::Variant,
 7812        cx: &App,
 7813    ) -> Option<()> {
 7814        let active_call = ActiveCall::try_global(cx)?;
 7815        let room_id = active_call.read(cx).room()?.read(cx).id();
 7816        self.client
 7817            .send(proto::UpdateFollowers {
 7818                room_id,
 7819                project_id,
 7820                variant: Some(update),
 7821            })
 7822            .log_err()
 7823    }
 7824
 7825    pub async fn handle_follow(
 7826        this: Entity<Self>,
 7827        envelope: TypedEnvelope<proto::Follow>,
 7828        mut cx: AsyncApp,
 7829    ) -> Result<proto::FollowResponse> {
 7830        this.update(&mut cx, |this, cx| {
 7831            let follower = Follower {
 7832                project_id: envelope.payload.project_id,
 7833                peer_id: envelope.original_sender_id()?,
 7834            };
 7835
 7836            let mut response = proto::FollowResponse::default();
 7837
 7838            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7839                let Some(workspace) = weak_workspace.upgrade() else {
 7840                    return false;
 7841                };
 7842                window_handle
 7843                    .update(cx, |_, window, cx| {
 7844                        workspace.update(cx, |workspace, cx| {
 7845                            let handler_response =
 7846                                workspace.handle_follow(follower.project_id, window, cx);
 7847                            if let Some(active_view) = handler_response.active_view
 7848                                && workspace.project.read(cx).remote_id() == follower.project_id
 7849                            {
 7850                                response.active_view = Some(active_view)
 7851                            }
 7852                        });
 7853                    })
 7854                    .is_ok()
 7855            });
 7856
 7857            Ok(response)
 7858        })
 7859    }
 7860
 7861    async fn handle_update_followers(
 7862        this: Entity<Self>,
 7863        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7864        mut cx: AsyncApp,
 7865    ) -> Result<()> {
 7866        let leader_id = envelope.original_sender_id()?;
 7867        let update = envelope.payload;
 7868
 7869        this.update(&mut cx, |this, cx| {
 7870            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7871                let Some(workspace) = weak_workspace.upgrade() else {
 7872                    return false;
 7873                };
 7874                window_handle
 7875                    .update(cx, |_, window, cx| {
 7876                        workspace.update(cx, |workspace, cx| {
 7877                            let project_id = workspace.project.read(cx).remote_id();
 7878                            if update.project_id != project_id && update.project_id.is_some() {
 7879                                return;
 7880                            }
 7881                            workspace.handle_update_followers(
 7882                                leader_id,
 7883                                update.clone(),
 7884                                window,
 7885                                cx,
 7886                            );
 7887                        });
 7888                    })
 7889                    .is_ok()
 7890            });
 7891            Ok(())
 7892        })
 7893    }
 7894
 7895    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 7896        self.workspaces.iter().map(|(_, weak)| weak)
 7897    }
 7898
 7899    pub fn workspaces_with_windows(
 7900        &self,
 7901    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 7902        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 7903    }
 7904}
 7905
 7906impl ViewId {
 7907    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7908        Ok(Self {
 7909            creator: message
 7910                .creator
 7911                .map(CollaboratorId::PeerId)
 7912                .context("creator is missing")?,
 7913            id: message.id,
 7914        })
 7915    }
 7916
 7917    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7918        if let CollaboratorId::PeerId(peer_id) = self.creator {
 7919            Some(proto::ViewId {
 7920                creator: Some(peer_id),
 7921                id: self.id,
 7922            })
 7923        } else {
 7924            None
 7925        }
 7926    }
 7927}
 7928
 7929impl FollowerState {
 7930    fn pane(&self) -> &Entity<Pane> {
 7931        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 7932    }
 7933}
 7934
 7935pub trait WorkspaceHandle {
 7936    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 7937}
 7938
 7939impl WorkspaceHandle for Entity<Workspace> {
 7940    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 7941        self.read(cx)
 7942            .worktrees(cx)
 7943            .flat_map(|worktree| {
 7944                let worktree_id = worktree.read(cx).id();
 7945                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 7946                    worktree_id,
 7947                    path: f.path.clone(),
 7948                })
 7949            })
 7950            .collect::<Vec<_>>()
 7951    }
 7952}
 7953
 7954pub async fn last_opened_workspace_location(
 7955    fs: &dyn fs::Fs,
 7956) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 7957    DB.last_workspace(fs).await.log_err().flatten()
 7958}
 7959
 7960pub async fn last_session_workspace_locations(
 7961    last_session_id: &str,
 7962    last_session_window_stack: Option<Vec<WindowId>>,
 7963    fs: &dyn fs::Fs,
 7964) -> Option<Vec<SessionWorkspace>> {
 7965    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 7966        .await
 7967        .log_err()
 7968}
 7969
 7970pub async fn restore_multiworkspace(
 7971    multi_workspace: SerializedMultiWorkspace,
 7972    app_state: Arc<AppState>,
 7973    cx: &mut AsyncApp,
 7974) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 7975    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 7976    let mut group_iter = workspaces.into_iter();
 7977    let first = group_iter
 7978        .next()
 7979        .context("window group must not be empty")?;
 7980
 7981    let window_handle = if first.paths.is_empty() {
 7982        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 7983            .await?
 7984    } else {
 7985        let (window, _items) = cx
 7986            .update(|cx| {
 7987                Workspace::new_local(
 7988                    first.paths.paths().to_vec(),
 7989                    app_state.clone(),
 7990                    None,
 7991                    None,
 7992                    None,
 7993                    cx,
 7994                )
 7995            })
 7996            .await?;
 7997        window
 7998    };
 7999
 8000    for session_workspace in group_iter {
 8001        if session_workspace.paths.is_empty() {
 8002            cx.update(|cx| {
 8003                open_workspace_by_id(
 8004                    session_workspace.workspace_id,
 8005                    app_state.clone(),
 8006                    Some(window_handle),
 8007                    cx,
 8008                )
 8009            })
 8010            .await?;
 8011        } else {
 8012            cx.update(|cx| {
 8013                Workspace::new_local(
 8014                    session_workspace.paths.paths().to_vec(),
 8015                    app_state.clone(),
 8016                    Some(window_handle),
 8017                    None,
 8018                    None,
 8019                    cx,
 8020                )
 8021            })
 8022            .await?;
 8023        }
 8024    }
 8025
 8026    if let Some(target_id) = state.active_workspace_id {
 8027        window_handle
 8028            .update(cx, |multi_workspace, window, cx| {
 8029                let target_index = multi_workspace
 8030                    .workspaces()
 8031                    .iter()
 8032                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8033                if let Some(index) = target_index {
 8034                    multi_workspace.activate_index(index, window, cx);
 8035                } else if !multi_workspace.workspaces().is_empty() {
 8036                    multi_workspace.activate_index(0, window, cx);
 8037                }
 8038            })
 8039            .ok();
 8040    } else {
 8041        window_handle
 8042            .update(cx, |multi_workspace, window, cx| {
 8043                if !multi_workspace.workspaces().is_empty() {
 8044                    multi_workspace.activate_index(0, window, cx);
 8045                }
 8046            })
 8047            .ok();
 8048    }
 8049
 8050    if state.sidebar_open {
 8051        window_handle
 8052            .update(cx, |multi_workspace, window, cx| {
 8053                multi_workspace.open_sidebar(window, cx);
 8054            })
 8055            .ok();
 8056    }
 8057
 8058    window_handle
 8059        .update(cx, |_, window, _cx| {
 8060            window.activate_window();
 8061        })
 8062        .ok();
 8063
 8064    Ok(window_handle)
 8065}
 8066
 8067actions!(
 8068    collab,
 8069    [
 8070        /// Opens the channel notes for the current call.
 8071        ///
 8072        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8073        /// channel in the collab panel.
 8074        ///
 8075        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8076        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8077        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8078        OpenChannelNotes,
 8079        /// Mutes your microphone.
 8080        Mute,
 8081        /// Deafens yourself (mute both microphone and speakers).
 8082        Deafen,
 8083        /// Leaves the current call.
 8084        LeaveCall,
 8085        /// Shares the current project with collaborators.
 8086        ShareProject,
 8087        /// Shares your screen with collaborators.
 8088        ScreenShare,
 8089        /// Copies the current room name and session id for debugging purposes.
 8090        CopyRoomId,
 8091    ]
 8092);
 8093actions!(
 8094    zed,
 8095    [
 8096        /// Opens the Zed log file.
 8097        OpenLog,
 8098        /// Reveals the Zed log file in the system file manager.
 8099        RevealLogInFileManager
 8100    ]
 8101);
 8102
 8103async fn join_channel_internal(
 8104    channel_id: ChannelId,
 8105    app_state: &Arc<AppState>,
 8106    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8107    requesting_workspace: Option<WeakEntity<Workspace>>,
 8108    active_call: &Entity<ActiveCall>,
 8109    cx: &mut AsyncApp,
 8110) -> Result<bool> {
 8111    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 8112        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 8113            return (false, None);
 8114        };
 8115
 8116        let already_in_channel = room.channel_id() == Some(channel_id);
 8117        let should_prompt = room.is_sharing_project()
 8118            && !room.remote_participants().is_empty()
 8119            && !already_in_channel;
 8120        let open_room = if already_in_channel {
 8121            active_call.room().cloned()
 8122        } else {
 8123            None
 8124        };
 8125        (should_prompt, open_room)
 8126    });
 8127
 8128    if let Some(room) = open_room {
 8129        let task = room.update(cx, |room, cx| {
 8130            if let Some((project, host)) = room.most_active_project(cx) {
 8131                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8132            }
 8133
 8134            None
 8135        });
 8136        if let Some(task) = task {
 8137            task.await?;
 8138        }
 8139        return anyhow::Ok(true);
 8140    }
 8141
 8142    if should_prompt {
 8143        if let Some(multi_workspace) = requesting_window {
 8144            let answer = multi_workspace
 8145                .update(cx, |_, window, cx| {
 8146                    window.prompt(
 8147                        PromptLevel::Warning,
 8148                        "Do you want to switch channels?",
 8149                        Some("Leaving this call will unshare your current project."),
 8150                        &["Yes, Join Channel", "Cancel"],
 8151                        cx,
 8152                    )
 8153                })?
 8154                .await;
 8155
 8156            if answer == Ok(1) {
 8157                return Ok(false);
 8158            }
 8159        } else {
 8160            return Ok(false); // unreachable!() hopefully
 8161        }
 8162    }
 8163
 8164    let client = cx.update(|cx| active_call.read(cx).client());
 8165
 8166    let mut client_status = client.status();
 8167
 8168    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8169    'outer: loop {
 8170        let Some(status) = client_status.recv().await else {
 8171            anyhow::bail!("error connecting");
 8172        };
 8173
 8174        match status {
 8175            Status::Connecting
 8176            | Status::Authenticating
 8177            | Status::Authenticated
 8178            | Status::Reconnecting
 8179            | Status::Reauthenticating
 8180            | Status::Reauthenticated => continue,
 8181            Status::Connected { .. } => break 'outer,
 8182            Status::SignedOut | Status::AuthenticationError => {
 8183                return Err(ErrorCode::SignedOut.into());
 8184            }
 8185            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8186            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8187                return Err(ErrorCode::Disconnected.into());
 8188            }
 8189        }
 8190    }
 8191
 8192    let room = active_call
 8193        .update(cx, |active_call, cx| {
 8194            active_call.join_channel(channel_id, cx)
 8195        })
 8196        .await?;
 8197
 8198    let Some(room) = room else {
 8199        return anyhow::Ok(true);
 8200    };
 8201
 8202    room.update(cx, |room, _| room.room_update_completed())
 8203        .await;
 8204
 8205    let task = room.update(cx, |room, cx| {
 8206        if let Some((project, host)) = room.most_active_project(cx) {
 8207            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8208        }
 8209
 8210        // If you are the first to join a channel, see if you should share your project.
 8211        if room.remote_participants().is_empty()
 8212            && !room.local_participant_is_guest()
 8213            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8214        {
 8215            let project = workspace.update(cx, |workspace, cx| {
 8216                let project = workspace.project.read(cx);
 8217
 8218                if !CallSettings::get_global(cx).share_on_join {
 8219                    return None;
 8220                }
 8221
 8222                if (project.is_local() || project.is_via_remote_server())
 8223                    && project.visible_worktrees(cx).any(|tree| {
 8224                        tree.read(cx)
 8225                            .root_entry()
 8226                            .is_some_and(|entry| entry.is_dir())
 8227                    })
 8228                {
 8229                    Some(workspace.project.clone())
 8230                } else {
 8231                    None
 8232                }
 8233            });
 8234            if let Some(project) = project {
 8235                return Some(cx.spawn(async move |room, cx| {
 8236                    room.update(cx, |room, cx| room.share_project(project, cx))?
 8237                        .await?;
 8238                    Ok(())
 8239                }));
 8240            }
 8241        }
 8242
 8243        None
 8244    });
 8245    if let Some(task) = task {
 8246        task.await?;
 8247        return anyhow::Ok(true);
 8248    }
 8249    anyhow::Ok(false)
 8250}
 8251
 8252pub fn join_channel(
 8253    channel_id: ChannelId,
 8254    app_state: Arc<AppState>,
 8255    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8256    requesting_workspace: Option<WeakEntity<Workspace>>,
 8257    cx: &mut App,
 8258) -> Task<Result<()>> {
 8259    let active_call = ActiveCall::global(cx);
 8260    cx.spawn(async move |cx| {
 8261        let result = join_channel_internal(
 8262            channel_id,
 8263            &app_state,
 8264            requesting_window,
 8265            requesting_workspace,
 8266            &active_call,
 8267            cx,
 8268        )
 8269        .await;
 8270
 8271        // join channel succeeded, and opened a window
 8272        if matches!(result, Ok(true)) {
 8273            return anyhow::Ok(());
 8274        }
 8275
 8276        // find an existing workspace to focus and show call controls
 8277        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8278        if active_window.is_none() {
 8279            // no open workspaces, make one to show the error in (blergh)
 8280            let (window_handle, _) = cx
 8281                .update(|cx| {
 8282                    Workspace::new_local(
 8283                        vec![],
 8284                        app_state.clone(),
 8285                        requesting_window,
 8286                        None,
 8287                        None,
 8288                        cx,
 8289                    )
 8290                })
 8291                .await?;
 8292
 8293            window_handle
 8294                .update(cx, |_, window, _cx| {
 8295                    window.activate_window();
 8296                })
 8297                .ok();
 8298
 8299            if result.is_ok() {
 8300                cx.update(|cx| {
 8301                    cx.dispatch_action(&OpenChannelNotes);
 8302                });
 8303            }
 8304
 8305            active_window = Some(window_handle);
 8306        }
 8307
 8308        if let Err(err) = result {
 8309            log::error!("failed to join channel: {}", err);
 8310            if let Some(active_window) = active_window {
 8311                active_window
 8312                    .update(cx, |_, window, cx| {
 8313                        let detail: SharedString = match err.error_code() {
 8314                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8315                            ErrorCode::UpgradeRequired => concat!(
 8316                                "Your are running an unsupported version of Zed. ",
 8317                                "Please update to continue."
 8318                            )
 8319                            .into(),
 8320                            ErrorCode::NoSuchChannel => concat!(
 8321                                "No matching channel was found. ",
 8322                                "Please check the link and try again."
 8323                            )
 8324                            .into(),
 8325                            ErrorCode::Forbidden => concat!(
 8326                                "This channel is private, and you do not have access. ",
 8327                                "Please ask someone to add you and try again."
 8328                            )
 8329                            .into(),
 8330                            ErrorCode::Disconnected => {
 8331                                "Please check your internet connection and try again.".into()
 8332                            }
 8333                            _ => format!("{}\n\nPlease try again.", err).into(),
 8334                        };
 8335                        window.prompt(
 8336                            PromptLevel::Critical,
 8337                            "Failed to join channel",
 8338                            Some(&detail),
 8339                            &["Ok"],
 8340                            cx,
 8341                        )
 8342                    })?
 8343                    .await
 8344                    .ok();
 8345            }
 8346        }
 8347
 8348        // return ok, we showed the error to the user.
 8349        anyhow::Ok(())
 8350    })
 8351}
 8352
 8353pub async fn get_any_active_multi_workspace(
 8354    app_state: Arc<AppState>,
 8355    mut cx: AsyncApp,
 8356) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8357    // find an existing workspace to focus and show call controls
 8358    let active_window = activate_any_workspace_window(&mut cx);
 8359    if active_window.is_none() {
 8360        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
 8361            .await?;
 8362    }
 8363    activate_any_workspace_window(&mut cx).context("could not open zed")
 8364}
 8365
 8366fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8367    cx.update(|cx| {
 8368        if let Some(workspace_window) = cx
 8369            .active_window()
 8370            .and_then(|window| window.downcast::<MultiWorkspace>())
 8371        {
 8372            return Some(workspace_window);
 8373        }
 8374
 8375        for window in cx.windows() {
 8376            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8377                workspace_window
 8378                    .update(cx, |_, window, _| window.activate_window())
 8379                    .ok();
 8380                return Some(workspace_window);
 8381            }
 8382        }
 8383        None
 8384    })
 8385}
 8386
 8387pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8388    cx.windows()
 8389        .into_iter()
 8390        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8391        .filter(|multi_workspace| {
 8392            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8393                multi_workspace
 8394                    .workspaces()
 8395                    .iter()
 8396                    .any(|workspace| workspace.read(cx).project.read(cx).is_local())
 8397            })
 8398        })
 8399        .collect()
 8400}
 8401
 8402#[derive(Default)]
 8403pub struct OpenOptions {
 8404    pub visible: Option<OpenVisible>,
 8405    pub focus: Option<bool>,
 8406    pub open_new_workspace: Option<bool>,
 8407    pub prefer_focused_window: bool,
 8408    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8409    pub env: Option<HashMap<String, String>>,
 8410}
 8411
 8412/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8413pub fn open_workspace_by_id(
 8414    workspace_id: WorkspaceId,
 8415    app_state: Arc<AppState>,
 8416    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8417    cx: &mut App,
 8418) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8419    let project_handle = Project::local(
 8420        app_state.client.clone(),
 8421        app_state.node_runtime.clone(),
 8422        app_state.user_store.clone(),
 8423        app_state.languages.clone(),
 8424        app_state.fs.clone(),
 8425        None,
 8426        project::LocalProjectFlags {
 8427            init_worktree_trust: true,
 8428            ..project::LocalProjectFlags::default()
 8429        },
 8430        cx,
 8431    );
 8432
 8433    cx.spawn(async move |cx| {
 8434        let serialized_workspace = persistence::DB
 8435            .workspace_for_id(workspace_id)
 8436            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8437
 8438        let centered_layout = serialized_workspace.centered_layout;
 8439
 8440        let (window, workspace) = if let Some(window) = requesting_window {
 8441            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8442                let workspace = cx.new(|cx| {
 8443                    let mut workspace = Workspace::new(
 8444                        Some(workspace_id),
 8445                        project_handle.clone(),
 8446                        app_state.clone(),
 8447                        window,
 8448                        cx,
 8449                    );
 8450                    workspace.centered_layout = centered_layout;
 8451                    workspace
 8452                });
 8453                multi_workspace.add_workspace(workspace.clone(), cx);
 8454                workspace
 8455            })?;
 8456            (window, workspace)
 8457        } else {
 8458            let window_bounds_override = window_bounds_env_override();
 8459
 8460            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8461                (Some(WindowBounds::Windowed(bounds)), None)
 8462            } else if let Some(display) = serialized_workspace.display
 8463                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8464            {
 8465                (Some(bounds.0), Some(display))
 8466            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8467                (Some(bounds), Some(display))
 8468            } else {
 8469                (None, None)
 8470            };
 8471
 8472            let options = cx.update(|cx| {
 8473                let mut options = (app_state.build_window_options)(display, cx);
 8474                options.window_bounds = window_bounds;
 8475                options
 8476            });
 8477
 8478            let window = cx.open_window(options, {
 8479                let app_state = app_state.clone();
 8480                let project_handle = project_handle.clone();
 8481                move |window, cx| {
 8482                    let workspace = cx.new(|cx| {
 8483                        let mut workspace = Workspace::new(
 8484                            Some(workspace_id),
 8485                            project_handle,
 8486                            app_state,
 8487                            window,
 8488                            cx,
 8489                        );
 8490                        workspace.centered_layout = centered_layout;
 8491                        workspace
 8492                    });
 8493                    cx.new(|cx| MultiWorkspace::new(workspace, cx))
 8494                }
 8495            })?;
 8496
 8497            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8498                multi_workspace.workspace().clone()
 8499            })?;
 8500
 8501            (window, workspace)
 8502        };
 8503
 8504        notify_if_database_failed(window, cx);
 8505
 8506        // Restore items from the serialized workspace
 8507        window
 8508            .update(cx, |_, window, cx| {
 8509                workspace.update(cx, |_workspace, cx| {
 8510                    open_items(Some(serialized_workspace), vec![], window, cx)
 8511                })
 8512            })?
 8513            .await?;
 8514
 8515        window.update(cx, |_, window, cx| {
 8516            workspace.update(cx, |workspace, cx| {
 8517                workspace.serialize_workspace(window, cx);
 8518            });
 8519        })?;
 8520
 8521        Ok(window)
 8522    })
 8523}
 8524
 8525#[allow(clippy::type_complexity)]
 8526pub fn open_paths(
 8527    abs_paths: &[PathBuf],
 8528    app_state: Arc<AppState>,
 8529    open_options: OpenOptions,
 8530    cx: &mut App,
 8531) -> Task<
 8532    anyhow::Result<(
 8533        WindowHandle<MultiWorkspace>,
 8534        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8535    )>,
 8536> {
 8537    let abs_paths = abs_paths.to_vec();
 8538    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8539    let mut best_match = None;
 8540    let mut open_visible = OpenVisible::All;
 8541    #[cfg(target_os = "windows")]
 8542    let wsl_path = abs_paths
 8543        .iter()
 8544        .find_map(|p| util::paths::WslPath::from_path(p));
 8545
 8546    cx.spawn(async move |cx| {
 8547        if open_options.open_new_workspace != Some(true) {
 8548            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8549            let all_metadatas = futures::future::join_all(all_paths)
 8550                .await
 8551                .into_iter()
 8552                .filter_map(|result| result.ok().flatten())
 8553                .collect::<Vec<_>>();
 8554
 8555            cx.update(|cx| {
 8556                for window in local_workspace_windows(cx) {
 8557                    if let Ok(multi_workspace) = window.read(cx) {
 8558                        for workspace in multi_workspace.workspaces() {
 8559                            let m = workspace.read(cx).project.read(cx).visibility_for_paths(
 8560                                &abs_paths,
 8561                                &all_metadatas,
 8562                                open_options.open_new_workspace == None,
 8563                                cx,
 8564                            );
 8565                            if m > best_match {
 8566                                existing = Some((window, workspace.clone()));
 8567                                best_match = m;
 8568                            } else if best_match.is_none()
 8569                                && open_options.open_new_workspace == Some(false)
 8570                            {
 8571                                existing = Some((window, workspace.clone()))
 8572                            }
 8573                        }
 8574                    }
 8575                }
 8576            });
 8577
 8578            if open_options.open_new_workspace.is_none()
 8579                && (existing.is_none() || open_options.prefer_focused_window)
 8580                && all_metadatas.iter().all(|file| !file.is_dir)
 8581            {
 8582                cx.update(|cx| {
 8583                    if let Some(window) = cx
 8584                        .active_window()
 8585                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8586                        && let Ok(multi_workspace) = window.read(cx)
 8587                    {
 8588                        let active_workspace = multi_workspace.workspace().clone();
 8589                        let project = active_workspace.read(cx).project().read(cx);
 8590                        if project.is_local() && !project.is_via_collab() {
 8591                            existing = Some((window, active_workspace));
 8592                            open_visible = OpenVisible::None;
 8593                            return;
 8594                        }
 8595                    }
 8596                    'outer: for window in local_workspace_windows(cx) {
 8597                        if let Ok(multi_workspace) = window.read(cx) {
 8598                            for workspace in multi_workspace.workspaces() {
 8599                                let project = workspace.read(cx).project().read(cx);
 8600                                if project.is_via_collab() {
 8601                                    continue;
 8602                                }
 8603                                existing = Some((window, workspace.clone()));
 8604                                open_visible = OpenVisible::None;
 8605                                break 'outer;
 8606                            }
 8607                        }
 8608                    }
 8609                });
 8610            }
 8611        }
 8612
 8613        let result = if let Some((existing, target_workspace)) = existing {
 8614            let open_task = existing
 8615                .update(cx, |multi_workspace, window, cx| {
 8616                    window.activate_window();
 8617                    multi_workspace.activate(target_workspace.clone(), cx);
 8618                    target_workspace.update(cx, |workspace, cx| {
 8619                        workspace.open_paths(
 8620                            abs_paths,
 8621                            OpenOptions {
 8622                                visible: Some(open_visible),
 8623                                ..Default::default()
 8624                            },
 8625                            None,
 8626                            window,
 8627                            cx,
 8628                        )
 8629                    })
 8630                })?
 8631                .await;
 8632
 8633            _ = existing.update(cx, |multi_workspace, _, cx| {
 8634                let workspace = multi_workspace.workspace().clone();
 8635                workspace.update(cx, |workspace, cx| {
 8636                    for item in open_task.iter().flatten() {
 8637                        if let Err(e) = item {
 8638                            workspace.show_error(&e, cx);
 8639                        }
 8640                    }
 8641                });
 8642            });
 8643
 8644            Ok((existing, open_task))
 8645        } else {
 8646            let result = cx
 8647                .update(move |cx| {
 8648                    Workspace::new_local(
 8649                        abs_paths,
 8650                        app_state.clone(),
 8651                        open_options.replace_window,
 8652                        open_options.env,
 8653                        None,
 8654                        cx,
 8655                    )
 8656                })
 8657                .await;
 8658
 8659            if let Ok((ref window_handle, _)) = result {
 8660                window_handle
 8661                    .update(cx, |_, window, _cx| {
 8662                        window.activate_window();
 8663                    })
 8664                    .log_err();
 8665            }
 8666
 8667            result
 8668        };
 8669
 8670        #[cfg(target_os = "windows")]
 8671        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8672            && let Ok((multi_workspace_window, _)) = &result
 8673        {
 8674            multi_workspace_window
 8675                .update(cx, move |multi_workspace, _window, cx| {
 8676                    struct OpenInWsl;
 8677                    let workspace = multi_workspace.workspace().clone();
 8678                    workspace.update(cx, |workspace, cx| {
 8679                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8680                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8681                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8682                            cx.new(move |cx| {
 8683                                MessageNotification::new(msg, cx)
 8684                                    .primary_message("Open in WSL")
 8685                                    .primary_icon(IconName::FolderOpen)
 8686                                    .primary_on_click(move |window, cx| {
 8687                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 8688                                                distro: remote::WslConnectionOptions {
 8689                                                        distro_name: distro.clone(),
 8690                                                    user: None,
 8691                                                },
 8692                                                paths: vec![path.clone().into()],
 8693                                            }), cx)
 8694                                    })
 8695                            })
 8696                        });
 8697                    });
 8698                })
 8699                .unwrap();
 8700        };
 8701        result
 8702    })
 8703}
 8704
 8705pub fn open_new(
 8706    open_options: OpenOptions,
 8707    app_state: Arc<AppState>,
 8708    cx: &mut App,
 8709    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8710) -> Task<anyhow::Result<()>> {
 8711    let task = Workspace::new_local(
 8712        Vec::new(),
 8713        app_state,
 8714        open_options.replace_window,
 8715        open_options.env,
 8716        Some(Box::new(init)),
 8717        cx,
 8718    );
 8719    cx.spawn(async move |cx| {
 8720        let (window, _opened_paths) = task.await?;
 8721        window
 8722            .update(cx, |_, window, _cx| {
 8723                window.activate_window();
 8724            })
 8725            .ok();
 8726        Ok(())
 8727    })
 8728}
 8729
 8730pub fn create_and_open_local_file(
 8731    path: &'static Path,
 8732    window: &mut Window,
 8733    cx: &mut Context<Workspace>,
 8734    default_content: impl 'static + Send + FnOnce() -> Rope,
 8735) -> Task<Result<Box<dyn ItemHandle>>> {
 8736    cx.spawn_in(window, async move |workspace, cx| {
 8737        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8738        if !fs.is_file(path).await {
 8739            fs.create_file(path, Default::default()).await?;
 8740            fs.save(path, &default_content(), Default::default())
 8741                .await?;
 8742        }
 8743
 8744        workspace
 8745            .update_in(cx, |workspace, window, cx| {
 8746                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 8747                    let path = workspace
 8748                        .project
 8749                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 8750                    cx.spawn_in(window, async move |workspace, cx| {
 8751                        let path = path.await?;
 8752                        let mut items = workspace
 8753                            .update_in(cx, |workspace, window, cx| {
 8754                                workspace.open_paths(
 8755                                    vec![path.to_path_buf()],
 8756                                    OpenOptions {
 8757                                        visible: Some(OpenVisible::None),
 8758                                        ..Default::default()
 8759                                    },
 8760                                    None,
 8761                                    window,
 8762                                    cx,
 8763                                )
 8764                            })?
 8765                            .await;
 8766                        let item = items.pop().flatten();
 8767                        item.with_context(|| format!("path {path:?} is not a file"))?
 8768                    })
 8769                })
 8770            })?
 8771            .await?
 8772            .await
 8773    })
 8774}
 8775
 8776pub fn open_remote_project_with_new_connection(
 8777    window: WindowHandle<MultiWorkspace>,
 8778    remote_connection: Arc<dyn RemoteConnection>,
 8779    cancel_rx: oneshot::Receiver<()>,
 8780    delegate: Arc<dyn RemoteClientDelegate>,
 8781    app_state: Arc<AppState>,
 8782    paths: Vec<PathBuf>,
 8783    cx: &mut App,
 8784) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8785    cx.spawn(async move |cx| {
 8786        let (workspace_id, serialized_workspace) =
 8787            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8788                .await?;
 8789
 8790        let session = match cx
 8791            .update(|cx| {
 8792                remote::RemoteClient::new(
 8793                    ConnectionIdentifier::Workspace(workspace_id.0),
 8794                    remote_connection,
 8795                    cancel_rx,
 8796                    delegate,
 8797                    cx,
 8798                )
 8799            })
 8800            .await?
 8801        {
 8802            Some(result) => result,
 8803            None => return Ok(Vec::new()),
 8804        };
 8805
 8806        let project = cx.update(|cx| {
 8807            project::Project::remote(
 8808                session,
 8809                app_state.client.clone(),
 8810                app_state.node_runtime.clone(),
 8811                app_state.user_store.clone(),
 8812                app_state.languages.clone(),
 8813                app_state.fs.clone(),
 8814                true,
 8815                cx,
 8816            )
 8817        });
 8818
 8819        open_remote_project_inner(
 8820            project,
 8821            paths,
 8822            workspace_id,
 8823            serialized_workspace,
 8824            app_state,
 8825            window,
 8826            cx,
 8827        )
 8828        .await
 8829    })
 8830}
 8831
 8832pub fn open_remote_project_with_existing_connection(
 8833    connection_options: RemoteConnectionOptions,
 8834    project: Entity<Project>,
 8835    paths: Vec<PathBuf>,
 8836    app_state: Arc<AppState>,
 8837    window: WindowHandle<MultiWorkspace>,
 8838    cx: &mut AsyncApp,
 8839) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8840    cx.spawn(async move |cx| {
 8841        let (workspace_id, serialized_workspace) =
 8842            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 8843
 8844        open_remote_project_inner(
 8845            project,
 8846            paths,
 8847            workspace_id,
 8848            serialized_workspace,
 8849            app_state,
 8850            window,
 8851            cx,
 8852        )
 8853        .await
 8854    })
 8855}
 8856
 8857async fn open_remote_project_inner(
 8858    project: Entity<Project>,
 8859    paths: Vec<PathBuf>,
 8860    workspace_id: WorkspaceId,
 8861    serialized_workspace: Option<SerializedWorkspace>,
 8862    app_state: Arc<AppState>,
 8863    window: WindowHandle<MultiWorkspace>,
 8864    cx: &mut AsyncApp,
 8865) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 8866    let toolchains = DB.toolchains(workspace_id).await?;
 8867    for (toolchain, worktree_path, path) in toolchains {
 8868        project
 8869            .update(cx, |this, cx| {
 8870                let Some(worktree_id) =
 8871                    this.find_worktree(&worktree_path, cx)
 8872                        .and_then(|(worktree, rel_path)| {
 8873                            if rel_path.is_empty() {
 8874                                Some(worktree.read(cx).id())
 8875                            } else {
 8876                                None
 8877                            }
 8878                        })
 8879                else {
 8880                    return Task::ready(None);
 8881                };
 8882
 8883                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 8884            })
 8885            .await;
 8886    }
 8887    let mut project_paths_to_open = vec![];
 8888    let mut project_path_errors = vec![];
 8889
 8890    for path in paths {
 8891        let result = cx
 8892            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 8893            .await;
 8894        match result {
 8895            Ok((_, project_path)) => {
 8896                project_paths_to_open.push((path.clone(), Some(project_path)));
 8897            }
 8898            Err(error) => {
 8899                project_path_errors.push(error);
 8900            }
 8901        };
 8902    }
 8903
 8904    if project_paths_to_open.is_empty() {
 8905        return Err(project_path_errors.pop().context("no paths given")?);
 8906    }
 8907
 8908    let workspace = window.update(cx, |multi_workspace, window, cx| {
 8909        telemetry::event!("SSH Project Opened");
 8910
 8911        let new_workspace = cx.new(|cx| {
 8912            let mut workspace =
 8913                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 8914            workspace.update_history(cx);
 8915
 8916            if let Some(ref serialized) = serialized_workspace {
 8917                workspace.centered_layout = serialized.centered_layout;
 8918            }
 8919
 8920            workspace
 8921        });
 8922
 8923        multi_workspace.activate(new_workspace.clone(), cx);
 8924        new_workspace
 8925    })?;
 8926
 8927    let items = window
 8928        .update(cx, |_, window, cx| {
 8929            window.activate_window();
 8930            workspace.update(cx, |_workspace, cx| {
 8931                open_items(serialized_workspace, project_paths_to_open, window, cx)
 8932            })
 8933        })?
 8934        .await?;
 8935
 8936    workspace.update(cx, |workspace, cx| {
 8937        for error in project_path_errors {
 8938            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 8939                if let Some(path) = error.error_tag("path") {
 8940                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 8941                }
 8942            } else {
 8943                workspace.show_error(&error, cx)
 8944            }
 8945        }
 8946    });
 8947
 8948    Ok(items.into_iter().map(|item| item?.ok()).collect())
 8949}
 8950
 8951fn deserialize_remote_project(
 8952    connection_options: RemoteConnectionOptions,
 8953    paths: Vec<PathBuf>,
 8954    cx: &AsyncApp,
 8955) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 8956    cx.background_spawn(async move {
 8957        let remote_connection_id = persistence::DB
 8958            .get_or_create_remote_connection(connection_options)
 8959            .await?;
 8960
 8961        let serialized_workspace =
 8962            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8963
 8964        let workspace_id = if let Some(workspace_id) =
 8965            serialized_workspace.as_ref().map(|workspace| workspace.id)
 8966        {
 8967            workspace_id
 8968        } else {
 8969            persistence::DB.next_id().await?
 8970        };
 8971
 8972        Ok((workspace_id, serialized_workspace))
 8973    })
 8974}
 8975
 8976pub fn join_in_room_project(
 8977    project_id: u64,
 8978    follow_user_id: u64,
 8979    app_state: Arc<AppState>,
 8980    cx: &mut App,
 8981) -> Task<Result<()>> {
 8982    let windows = cx.windows();
 8983    cx.spawn(async move |cx| {
 8984        let existing_window_and_workspace: Option<(
 8985            WindowHandle<MultiWorkspace>,
 8986            Entity<Workspace>,
 8987        )> = windows.into_iter().find_map(|window_handle| {
 8988            window_handle
 8989                .downcast::<MultiWorkspace>()
 8990                .and_then(|window_handle| {
 8991                    window_handle
 8992                        .update(cx, |multi_workspace, _window, cx| {
 8993                            for workspace in multi_workspace.workspaces() {
 8994                                if workspace.read(cx).project().read(cx).remote_id()
 8995                                    == Some(project_id)
 8996                                {
 8997                                    return Some((window_handle, workspace.clone()));
 8998                                }
 8999                            }
 9000                            None
 9001                        })
 9002                        .unwrap_or(None)
 9003                })
 9004        });
 9005
 9006        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9007            existing_window_and_workspace
 9008        {
 9009            existing_window
 9010                .update(cx, |multi_workspace, _, cx| {
 9011                    multi_workspace.activate(target_workspace, cx);
 9012                })
 9013                .ok();
 9014            existing_window
 9015        } else {
 9016            let active_call = cx.update(|cx| ActiveCall::global(cx));
 9017            let room = active_call
 9018                .read_with(cx, |call, _| call.room().cloned())
 9019                .context("not in a call")?;
 9020            let project = room
 9021                .update(cx, |room, cx| {
 9022                    room.join_project(
 9023                        project_id,
 9024                        app_state.languages.clone(),
 9025                        app_state.fs.clone(),
 9026                        cx,
 9027                    )
 9028                })
 9029                .await?;
 9030
 9031            let window_bounds_override = window_bounds_env_override();
 9032            cx.update(|cx| {
 9033                let mut options = (app_state.build_window_options)(None, cx);
 9034                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9035                cx.open_window(options, |window, cx| {
 9036                    let workspace = cx.new(|cx| {
 9037                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9038                    });
 9039                    cx.new(|cx| MultiWorkspace::new(workspace, cx))
 9040                })
 9041            })?
 9042        };
 9043
 9044        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9045            cx.activate(true);
 9046            window.activate_window();
 9047
 9048            // We set the active workspace above, so this is the correct workspace.
 9049            let workspace = multi_workspace.workspace().clone();
 9050            workspace.update(cx, |workspace, cx| {
 9051                if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 9052                    let follow_peer_id = room
 9053                        .read(cx)
 9054                        .remote_participants()
 9055                        .iter()
 9056                        .find(|(_, participant)| participant.user.id == follow_user_id)
 9057                        .map(|(_, p)| p.peer_id)
 9058                        .or_else(|| {
 9059                            // If we couldn't follow the given user, follow the host instead.
 9060                            let collaborator = workspace
 9061                                .project()
 9062                                .read(cx)
 9063                                .collaborators()
 9064                                .values()
 9065                                .find(|collaborator| collaborator.is_host)?;
 9066                            Some(collaborator.peer_id)
 9067                        });
 9068
 9069                    if let Some(follow_peer_id) = follow_peer_id {
 9070                        workspace.follow(follow_peer_id, window, cx);
 9071                    }
 9072                }
 9073            });
 9074        })?;
 9075
 9076        anyhow::Ok(())
 9077    })
 9078}
 9079
 9080pub fn reload(cx: &mut App) {
 9081    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9082    let mut workspace_windows = cx
 9083        .windows()
 9084        .into_iter()
 9085        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9086        .collect::<Vec<_>>();
 9087
 9088    // If multiple windows have unsaved changes, and need a save prompt,
 9089    // prompt in the active window before switching to a different window.
 9090    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9091
 9092    let mut prompt = None;
 9093    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9094        prompt = window
 9095            .update(cx, |_, window, cx| {
 9096                window.prompt(
 9097                    PromptLevel::Info,
 9098                    "Are you sure you want to restart?",
 9099                    None,
 9100                    &["Restart", "Cancel"],
 9101                    cx,
 9102                )
 9103            })
 9104            .ok();
 9105    }
 9106
 9107    cx.spawn(async move |cx| {
 9108        if let Some(prompt) = prompt {
 9109            let answer = prompt.await?;
 9110            if answer != 0 {
 9111                return anyhow::Ok(());
 9112            }
 9113        }
 9114
 9115        // If the user cancels any save prompt, then keep the app open.
 9116        for window in workspace_windows {
 9117            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9118                let workspace = multi_workspace.workspace().clone();
 9119                workspace.update(cx, |workspace, cx| {
 9120                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9121                })
 9122            }) && !should_close.await?
 9123            {
 9124                return anyhow::Ok(());
 9125            }
 9126        }
 9127        cx.update(|cx| cx.restart());
 9128        anyhow::Ok(())
 9129    })
 9130    .detach_and_log_err(cx);
 9131}
 9132
 9133fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9134    let mut parts = value.split(',');
 9135    let x: usize = parts.next()?.parse().ok()?;
 9136    let y: usize = parts.next()?.parse().ok()?;
 9137    Some(point(px(x as f32), px(y as f32)))
 9138}
 9139
 9140fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9141    let mut parts = value.split(',');
 9142    let width: usize = parts.next()?.parse().ok()?;
 9143    let height: usize = parts.next()?.parse().ok()?;
 9144    Some(size(px(width as f32), px(height as f32)))
 9145}
 9146
 9147/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9148/// appropriate.
 9149///
 9150/// The `border_radius_tiling` parameter allows overriding which corners get
 9151/// rounded, independently of the actual window tiling state. This is used
 9152/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9153/// we want square corners on the left (so the sidebar appears flush with the
 9154/// window edge) but we still need the shadow padding for proper visual
 9155/// appearance. Unlike actual window tiling, this only affects border radius -
 9156/// not padding or shadows.
 9157pub fn client_side_decorations(
 9158    element: impl IntoElement,
 9159    window: &mut Window,
 9160    cx: &mut App,
 9161    border_radius_tiling: Tiling,
 9162) -> Stateful<Div> {
 9163    const BORDER_SIZE: Pixels = px(1.0);
 9164    let decorations = window.window_decorations();
 9165    let tiling = match decorations {
 9166        Decorations::Server => Tiling::default(),
 9167        Decorations::Client { tiling } => tiling,
 9168    };
 9169
 9170    match decorations {
 9171        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9172        Decorations::Server => window.set_client_inset(px(0.0)),
 9173    }
 9174
 9175    struct GlobalResizeEdge(ResizeEdge);
 9176    impl Global for GlobalResizeEdge {}
 9177
 9178    div()
 9179        .id("window-backdrop")
 9180        .bg(transparent_black())
 9181        .map(|div| match decorations {
 9182            Decorations::Server => div,
 9183            Decorations::Client { .. } => div
 9184                .when(
 9185                    !(tiling.top
 9186                        || tiling.right
 9187                        || border_radius_tiling.top
 9188                        || border_radius_tiling.right),
 9189                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9190                )
 9191                .when(
 9192                    !(tiling.top
 9193                        || tiling.left
 9194                        || border_radius_tiling.top
 9195                        || border_radius_tiling.left),
 9196                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9197                )
 9198                .when(
 9199                    !(tiling.bottom
 9200                        || tiling.right
 9201                        || border_radius_tiling.bottom
 9202                        || border_radius_tiling.right),
 9203                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9204                )
 9205                .when(
 9206                    !(tiling.bottom
 9207                        || tiling.left
 9208                        || border_radius_tiling.bottom
 9209                        || border_radius_tiling.left),
 9210                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9211                )
 9212                .when(!tiling.top, |div| {
 9213                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9214                })
 9215                .when(!tiling.bottom, |div| {
 9216                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9217                })
 9218                .when(!tiling.left, |div| {
 9219                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9220                })
 9221                .when(!tiling.right, |div| {
 9222                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9223                })
 9224                .on_mouse_move(move |e, window, cx| {
 9225                    let size = window.window_bounds().get_bounds().size;
 9226                    let pos = e.position;
 9227
 9228                    let new_edge =
 9229                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9230
 9231                    let edge = cx.try_global::<GlobalResizeEdge>();
 9232                    if new_edge != edge.map(|edge| edge.0) {
 9233                        window
 9234                            .window_handle()
 9235                            .update(cx, |workspace, _, cx| {
 9236                                cx.notify(workspace.entity_id());
 9237                            })
 9238                            .ok();
 9239                    }
 9240                })
 9241                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9242                    let size = window.window_bounds().get_bounds().size;
 9243                    let pos = e.position;
 9244
 9245                    let edge = match resize_edge(
 9246                        pos,
 9247                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9248                        size,
 9249                        tiling,
 9250                    ) {
 9251                        Some(value) => value,
 9252                        None => return,
 9253                    };
 9254
 9255                    window.start_window_resize(edge);
 9256                }),
 9257        })
 9258        .size_full()
 9259        .child(
 9260            div()
 9261                .cursor(CursorStyle::Arrow)
 9262                .map(|div| match decorations {
 9263                    Decorations::Server => div,
 9264                    Decorations::Client { .. } => div
 9265                        .border_color(cx.theme().colors().border)
 9266                        .when(
 9267                            !(tiling.top
 9268                                || tiling.right
 9269                                || border_radius_tiling.top
 9270                                || border_radius_tiling.right),
 9271                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9272                        )
 9273                        .when(
 9274                            !(tiling.top
 9275                                || tiling.left
 9276                                || border_radius_tiling.top
 9277                                || border_radius_tiling.left),
 9278                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9279                        )
 9280                        .when(
 9281                            !(tiling.bottom
 9282                                || tiling.right
 9283                                || border_radius_tiling.bottom
 9284                                || border_radius_tiling.right),
 9285                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9286                        )
 9287                        .when(
 9288                            !(tiling.bottom
 9289                                || tiling.left
 9290                                || border_radius_tiling.bottom
 9291                                || border_radius_tiling.left),
 9292                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9293                        )
 9294                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9295                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9296                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9297                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9298                        .when(!tiling.is_tiled(), |div| {
 9299                            div.shadow(vec![gpui::BoxShadow {
 9300                                color: Hsla {
 9301                                    h: 0.,
 9302                                    s: 0.,
 9303                                    l: 0.,
 9304                                    a: 0.4,
 9305                                },
 9306                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9307                                spread_radius: px(0.),
 9308                                offset: point(px(0.0), px(0.0)),
 9309                            }])
 9310                        }),
 9311                })
 9312                .on_mouse_move(|_e, _, cx| {
 9313                    cx.stop_propagation();
 9314                })
 9315                .size_full()
 9316                .child(element),
 9317        )
 9318        .map(|div| match decorations {
 9319            Decorations::Server => div,
 9320            Decorations::Client { tiling, .. } => div.child(
 9321                canvas(
 9322                    |_bounds, window, _| {
 9323                        window.insert_hitbox(
 9324                            Bounds::new(
 9325                                point(px(0.0), px(0.0)),
 9326                                window.window_bounds().get_bounds().size,
 9327                            ),
 9328                            HitboxBehavior::Normal,
 9329                        )
 9330                    },
 9331                    move |_bounds, hitbox, window, cx| {
 9332                        let mouse = window.mouse_position();
 9333                        let size = window.window_bounds().get_bounds().size;
 9334                        let Some(edge) =
 9335                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9336                        else {
 9337                            return;
 9338                        };
 9339                        cx.set_global(GlobalResizeEdge(edge));
 9340                        window.set_cursor_style(
 9341                            match edge {
 9342                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9343                                ResizeEdge::Left | ResizeEdge::Right => {
 9344                                    CursorStyle::ResizeLeftRight
 9345                                }
 9346                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9347                                    CursorStyle::ResizeUpLeftDownRight
 9348                                }
 9349                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9350                                    CursorStyle::ResizeUpRightDownLeft
 9351                                }
 9352                            },
 9353                            &hitbox,
 9354                        );
 9355                    },
 9356                )
 9357                .size_full()
 9358                .absolute(),
 9359            ),
 9360        })
 9361}
 9362
 9363fn resize_edge(
 9364    pos: Point<Pixels>,
 9365    shadow_size: Pixels,
 9366    window_size: Size<Pixels>,
 9367    tiling: Tiling,
 9368) -> Option<ResizeEdge> {
 9369    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9370    if bounds.contains(&pos) {
 9371        return None;
 9372    }
 9373
 9374    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9375    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9376    if !tiling.top && top_left_bounds.contains(&pos) {
 9377        return Some(ResizeEdge::TopLeft);
 9378    }
 9379
 9380    let top_right_bounds = Bounds::new(
 9381        Point::new(window_size.width - corner_size.width, px(0.)),
 9382        corner_size,
 9383    );
 9384    if !tiling.top && top_right_bounds.contains(&pos) {
 9385        return Some(ResizeEdge::TopRight);
 9386    }
 9387
 9388    let bottom_left_bounds = Bounds::new(
 9389        Point::new(px(0.), window_size.height - corner_size.height),
 9390        corner_size,
 9391    );
 9392    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9393        return Some(ResizeEdge::BottomLeft);
 9394    }
 9395
 9396    let bottom_right_bounds = Bounds::new(
 9397        Point::new(
 9398            window_size.width - corner_size.width,
 9399            window_size.height - corner_size.height,
 9400        ),
 9401        corner_size,
 9402    );
 9403    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9404        return Some(ResizeEdge::BottomRight);
 9405    }
 9406
 9407    if !tiling.top && pos.y < shadow_size {
 9408        Some(ResizeEdge::Top)
 9409    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9410        Some(ResizeEdge::Bottom)
 9411    } else if !tiling.left && pos.x < shadow_size {
 9412        Some(ResizeEdge::Left)
 9413    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9414        Some(ResizeEdge::Right)
 9415    } else {
 9416        None
 9417    }
 9418}
 9419
 9420fn join_pane_into_active(
 9421    active_pane: &Entity<Pane>,
 9422    pane: &Entity<Pane>,
 9423    window: &mut Window,
 9424    cx: &mut App,
 9425) {
 9426    if pane == active_pane {
 9427    } else if pane.read(cx).items_len() == 0 {
 9428        pane.update(cx, |_, cx| {
 9429            cx.emit(pane::Event::Remove {
 9430                focus_on_pane: None,
 9431            });
 9432        })
 9433    } else {
 9434        move_all_items(pane, active_pane, window, cx);
 9435    }
 9436}
 9437
 9438fn move_all_items(
 9439    from_pane: &Entity<Pane>,
 9440    to_pane: &Entity<Pane>,
 9441    window: &mut Window,
 9442    cx: &mut App,
 9443) {
 9444    let destination_is_different = from_pane != to_pane;
 9445    let mut moved_items = 0;
 9446    for (item_ix, item_handle) in from_pane
 9447        .read(cx)
 9448        .items()
 9449        .enumerate()
 9450        .map(|(ix, item)| (ix, item.clone()))
 9451        .collect::<Vec<_>>()
 9452    {
 9453        let ix = item_ix - moved_items;
 9454        if destination_is_different {
 9455            // Close item from previous pane
 9456            from_pane.update(cx, |source, cx| {
 9457                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9458            });
 9459            moved_items += 1;
 9460        }
 9461
 9462        // This automatically removes duplicate items in the pane
 9463        to_pane.update(cx, |destination, cx| {
 9464            destination.add_item(item_handle, true, true, None, window, cx);
 9465            window.focus(&destination.focus_handle(cx), cx)
 9466        });
 9467    }
 9468}
 9469
 9470pub fn move_item(
 9471    source: &Entity<Pane>,
 9472    destination: &Entity<Pane>,
 9473    item_id_to_move: EntityId,
 9474    destination_index: usize,
 9475    activate: bool,
 9476    window: &mut Window,
 9477    cx: &mut App,
 9478) {
 9479    let Some((item_ix, item_handle)) = source
 9480        .read(cx)
 9481        .items()
 9482        .enumerate()
 9483        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9484        .map(|(ix, item)| (ix, item.clone()))
 9485    else {
 9486        // Tab was closed during drag
 9487        return;
 9488    };
 9489
 9490    if source != destination {
 9491        // Close item from previous pane
 9492        source.update(cx, |source, cx| {
 9493            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9494        });
 9495    }
 9496
 9497    // This automatically removes duplicate items in the pane
 9498    destination.update(cx, |destination, cx| {
 9499        destination.add_item_inner(
 9500            item_handle,
 9501            activate,
 9502            activate,
 9503            activate,
 9504            Some(destination_index),
 9505            window,
 9506            cx,
 9507        );
 9508        if activate {
 9509            window.focus(&destination.focus_handle(cx), cx)
 9510        }
 9511    });
 9512}
 9513
 9514pub fn move_active_item(
 9515    source: &Entity<Pane>,
 9516    destination: &Entity<Pane>,
 9517    focus_destination: bool,
 9518    close_if_empty: bool,
 9519    window: &mut Window,
 9520    cx: &mut App,
 9521) {
 9522    if source == destination {
 9523        return;
 9524    }
 9525    let Some(active_item) = source.read(cx).active_item() else {
 9526        return;
 9527    };
 9528    source.update(cx, |source_pane, cx| {
 9529        let item_id = active_item.item_id();
 9530        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9531        destination.update(cx, |target_pane, cx| {
 9532            target_pane.add_item(
 9533                active_item,
 9534                focus_destination,
 9535                focus_destination,
 9536                Some(target_pane.items_len()),
 9537                window,
 9538                cx,
 9539            );
 9540        });
 9541    });
 9542}
 9543
 9544pub fn clone_active_item(
 9545    workspace_id: Option<WorkspaceId>,
 9546    source: &Entity<Pane>,
 9547    destination: &Entity<Pane>,
 9548    focus_destination: bool,
 9549    window: &mut Window,
 9550    cx: &mut App,
 9551) {
 9552    if source == destination {
 9553        return;
 9554    }
 9555    let Some(active_item) = source.read(cx).active_item() else {
 9556        return;
 9557    };
 9558    if !active_item.can_split(cx) {
 9559        return;
 9560    }
 9561    let destination = destination.downgrade();
 9562    let task = active_item.clone_on_split(workspace_id, window, cx);
 9563    window
 9564        .spawn(cx, async move |cx| {
 9565            let Some(clone) = task.await else {
 9566                return;
 9567            };
 9568            destination
 9569                .update_in(cx, |target_pane, window, cx| {
 9570                    target_pane.add_item(
 9571                        clone,
 9572                        focus_destination,
 9573                        focus_destination,
 9574                        Some(target_pane.items_len()),
 9575                        window,
 9576                        cx,
 9577                    );
 9578                })
 9579                .log_err();
 9580        })
 9581        .detach();
 9582}
 9583
 9584#[derive(Debug)]
 9585pub struct WorkspacePosition {
 9586    pub window_bounds: Option<WindowBounds>,
 9587    pub display: Option<Uuid>,
 9588    pub centered_layout: bool,
 9589}
 9590
 9591pub fn remote_workspace_position_from_db(
 9592    connection_options: RemoteConnectionOptions,
 9593    paths_to_open: &[PathBuf],
 9594    cx: &App,
 9595) -> Task<Result<WorkspacePosition>> {
 9596    let paths = paths_to_open.to_vec();
 9597
 9598    cx.background_spawn(async move {
 9599        let remote_connection_id = persistence::DB
 9600            .get_or_create_remote_connection(connection_options)
 9601            .await
 9602            .context("fetching serialized ssh project")?;
 9603        let serialized_workspace =
 9604            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9605
 9606        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9607            (Some(WindowBounds::Windowed(bounds)), None)
 9608        } else {
 9609            let restorable_bounds = serialized_workspace
 9610                .as_ref()
 9611                .and_then(|workspace| {
 9612                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9613                })
 9614                .or_else(|| persistence::read_default_window_bounds());
 9615
 9616            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9617                (Some(serialized_bounds), Some(serialized_display))
 9618            } else {
 9619                (None, None)
 9620            }
 9621        };
 9622
 9623        let centered_layout = serialized_workspace
 9624            .as_ref()
 9625            .map(|w| w.centered_layout)
 9626            .unwrap_or(false);
 9627
 9628        Ok(WorkspacePosition {
 9629            window_bounds,
 9630            display,
 9631            centered_layout,
 9632        })
 9633    })
 9634}
 9635
 9636pub fn with_active_or_new_workspace(
 9637    cx: &mut App,
 9638    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9639) {
 9640    match cx
 9641        .active_window()
 9642        .and_then(|w| w.downcast::<MultiWorkspace>())
 9643    {
 9644        Some(multi_workspace) => {
 9645            cx.defer(move |cx| {
 9646                multi_workspace
 9647                    .update(cx, |multi_workspace, window, cx| {
 9648                        let workspace = multi_workspace.workspace().clone();
 9649                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9650                    })
 9651                    .log_err();
 9652            });
 9653        }
 9654        None => {
 9655            let app_state = AppState::global(cx);
 9656            if let Some(app_state) = app_state.upgrade() {
 9657                open_new(
 9658                    OpenOptions::default(),
 9659                    app_state,
 9660                    cx,
 9661                    move |workspace, window, cx| f(workspace, window, cx),
 9662                )
 9663                .detach_and_log_err(cx);
 9664            }
 9665        }
 9666    }
 9667}
 9668
 9669#[cfg(test)]
 9670mod tests {
 9671    use std::{cell::RefCell, rc::Rc};
 9672
 9673    use super::*;
 9674    use crate::{
 9675        dock::{PanelEvent, test::TestPanel},
 9676        item::{
 9677            ItemBufferKind, ItemEvent,
 9678            test::{TestItem, TestProjectItem},
 9679        },
 9680    };
 9681    use fs::FakeFs;
 9682    use gpui::{
 9683        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9684        UpdateGlobal, VisualTestContext, px,
 9685    };
 9686    use project::{Project, ProjectEntryId};
 9687    use serde_json::json;
 9688    use settings::SettingsStore;
 9689    use util::rel_path::rel_path;
 9690
 9691    #[gpui::test]
 9692    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9693        init_test(cx);
 9694
 9695        let fs = FakeFs::new(cx.executor());
 9696        let project = Project::test(fs, [], cx).await;
 9697        let (workspace, cx) =
 9698            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9699
 9700        // Adding an item with no ambiguity renders the tab without detail.
 9701        let item1 = cx.new(|cx| {
 9702            let mut item = TestItem::new(cx);
 9703            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9704            item
 9705        });
 9706        workspace.update_in(cx, |workspace, window, cx| {
 9707            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9708        });
 9709        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9710
 9711        // Adding an item that creates ambiguity increases the level of detail on
 9712        // both tabs.
 9713        let item2 = cx.new_window_entity(|_window, cx| {
 9714            let mut item = TestItem::new(cx);
 9715            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9716            item
 9717        });
 9718        workspace.update_in(cx, |workspace, window, cx| {
 9719            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9720        });
 9721        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9722        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9723
 9724        // Adding an item that creates ambiguity increases the level of detail only
 9725        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9726        // we stop at the highest detail available.
 9727        let item3 = cx.new(|cx| {
 9728            let mut item = TestItem::new(cx);
 9729            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9730            item
 9731        });
 9732        workspace.update_in(cx, |workspace, window, cx| {
 9733            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9734        });
 9735        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9736        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9737        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9738    }
 9739
 9740    #[gpui::test]
 9741    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9742        init_test(cx);
 9743
 9744        let fs = FakeFs::new(cx.executor());
 9745        fs.insert_tree(
 9746            "/root1",
 9747            json!({
 9748                "one.txt": "",
 9749                "two.txt": "",
 9750            }),
 9751        )
 9752        .await;
 9753        fs.insert_tree(
 9754            "/root2",
 9755            json!({
 9756                "three.txt": "",
 9757            }),
 9758        )
 9759        .await;
 9760
 9761        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9762        let (workspace, cx) =
 9763            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9764        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9765        let worktree_id = project.update(cx, |project, cx| {
 9766            project.worktrees(cx).next().unwrap().read(cx).id()
 9767        });
 9768
 9769        let item1 = cx.new(|cx| {
 9770            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9771        });
 9772        let item2 = cx.new(|cx| {
 9773            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9774        });
 9775
 9776        // Add an item to an empty pane
 9777        workspace.update_in(cx, |workspace, window, cx| {
 9778            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9779        });
 9780        project.update(cx, |project, cx| {
 9781            assert_eq!(
 9782                project.active_entry(),
 9783                project
 9784                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9785                    .map(|e| e.id)
 9786            );
 9787        });
 9788        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9789
 9790        // Add a second item to a non-empty pane
 9791        workspace.update_in(cx, |workspace, window, cx| {
 9792            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9793        });
 9794        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9795        project.update(cx, |project, cx| {
 9796            assert_eq!(
 9797                project.active_entry(),
 9798                project
 9799                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9800                    .map(|e| e.id)
 9801            );
 9802        });
 9803
 9804        // Close the active item
 9805        pane.update_in(cx, |pane, window, cx| {
 9806            pane.close_active_item(&Default::default(), window, cx)
 9807        })
 9808        .await
 9809        .unwrap();
 9810        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9811        project.update(cx, |project, cx| {
 9812            assert_eq!(
 9813                project.active_entry(),
 9814                project
 9815                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9816                    .map(|e| e.id)
 9817            );
 9818        });
 9819
 9820        // Add a project folder
 9821        project
 9822            .update(cx, |project, cx| {
 9823                project.find_or_create_worktree("root2", true, cx)
 9824            })
 9825            .await
 9826            .unwrap();
 9827        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 9828
 9829        // Remove a project folder
 9830        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 9831        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 9832    }
 9833
 9834    #[gpui::test]
 9835    async fn test_close_window(cx: &mut TestAppContext) {
 9836        init_test(cx);
 9837
 9838        let fs = FakeFs::new(cx.executor());
 9839        fs.insert_tree("/root", json!({ "one": "" })).await;
 9840
 9841        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9842        let (workspace, cx) =
 9843            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9844
 9845        // When there are no dirty items, there's nothing to do.
 9846        let item1 = cx.new(TestItem::new);
 9847        workspace.update_in(cx, |w, window, cx| {
 9848            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 9849        });
 9850        let task = workspace.update_in(cx, |w, window, cx| {
 9851            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9852        });
 9853        assert!(task.await.unwrap());
 9854
 9855        // When there are dirty untitled items, prompt to save each one. If the user
 9856        // cancels any prompt, then abort.
 9857        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 9858        let item3 = cx.new(|cx| {
 9859            TestItem::new(cx)
 9860                .with_dirty(true)
 9861                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9862        });
 9863        workspace.update_in(cx, |w, window, cx| {
 9864            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9865            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9866        });
 9867        let task = workspace.update_in(cx, |w, window, cx| {
 9868            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9869        });
 9870        cx.executor().run_until_parked();
 9871        cx.simulate_prompt_answer("Cancel"); // cancel save all
 9872        cx.executor().run_until_parked();
 9873        assert!(!cx.has_pending_prompt());
 9874        assert!(!task.await.unwrap());
 9875    }
 9876
 9877    #[gpui::test]
 9878    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 9879        init_test(cx);
 9880
 9881        // Register TestItem as a serializable item
 9882        cx.update(|cx| {
 9883            register_serializable_item::<TestItem>(cx);
 9884        });
 9885
 9886        let fs = FakeFs::new(cx.executor());
 9887        fs.insert_tree("/root", json!({ "one": "" })).await;
 9888
 9889        let project = Project::test(fs, ["root".as_ref()], cx).await;
 9890        let (workspace, cx) =
 9891            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9892
 9893        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 9894        let item1 = cx.new(|cx| {
 9895            TestItem::new(cx)
 9896                .with_dirty(true)
 9897                .with_serialize(|| Some(Task::ready(Ok(()))))
 9898        });
 9899        let item2 = cx.new(|cx| {
 9900            TestItem::new(cx)
 9901                .with_dirty(true)
 9902                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9903                .with_serialize(|| Some(Task::ready(Ok(()))))
 9904        });
 9905        workspace.update_in(cx, |w, window, cx| {
 9906            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9907            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9908        });
 9909        let task = workspace.update_in(cx, |w, window, cx| {
 9910            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 9911        });
 9912        assert!(task.await.unwrap());
 9913    }
 9914
 9915    #[gpui::test]
 9916    async fn test_close_pane_items(cx: &mut TestAppContext) {
 9917        init_test(cx);
 9918
 9919        let fs = FakeFs::new(cx.executor());
 9920
 9921        let project = Project::test(fs, None, cx).await;
 9922        let (workspace, cx) =
 9923            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9924
 9925        let item1 = cx.new(|cx| {
 9926            TestItem::new(cx)
 9927                .with_dirty(true)
 9928                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9929        });
 9930        let item2 = cx.new(|cx| {
 9931            TestItem::new(cx)
 9932                .with_dirty(true)
 9933                .with_conflict(true)
 9934                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9935        });
 9936        let item3 = cx.new(|cx| {
 9937            TestItem::new(cx)
 9938                .with_dirty(true)
 9939                .with_conflict(true)
 9940                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 9941        });
 9942        let item4 = cx.new(|cx| {
 9943            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 9944                let project_item = TestProjectItem::new_untitled(cx);
 9945                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9946                project_item
 9947            }])
 9948        });
 9949        let pane = workspace.update_in(cx, |workspace, window, cx| {
 9950            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9951            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9952            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9953            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 9954            workspace.active_pane().clone()
 9955        });
 9956
 9957        let close_items = pane.update_in(cx, |pane, window, cx| {
 9958            pane.activate_item(1, true, true, window, cx);
 9959            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9960            let item1_id = item1.item_id();
 9961            let item3_id = item3.item_id();
 9962            let item4_id = item4.item_id();
 9963            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 9964                [item1_id, item3_id, item4_id].contains(&id)
 9965            })
 9966        });
 9967        cx.executor().run_until_parked();
 9968
 9969        assert!(cx.has_pending_prompt());
 9970        cx.simulate_prompt_answer("Save all");
 9971
 9972        cx.executor().run_until_parked();
 9973
 9974        // Item 1 is saved. There's a prompt to save item 3.
 9975        pane.update(cx, |pane, cx| {
 9976            assert_eq!(item1.read(cx).save_count, 1);
 9977            assert_eq!(item1.read(cx).save_as_count, 0);
 9978            assert_eq!(item1.read(cx).reload_count, 0);
 9979            assert_eq!(pane.items_len(), 3);
 9980            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 9981        });
 9982        assert!(cx.has_pending_prompt());
 9983
 9984        // Cancel saving item 3.
 9985        cx.simulate_prompt_answer("Discard");
 9986        cx.executor().run_until_parked();
 9987
 9988        // Item 3 is reloaded. There's a prompt to save item 4.
 9989        pane.update(cx, |pane, cx| {
 9990            assert_eq!(item3.read(cx).save_count, 0);
 9991            assert_eq!(item3.read(cx).save_as_count, 0);
 9992            assert_eq!(item3.read(cx).reload_count, 1);
 9993            assert_eq!(pane.items_len(), 2);
 9994            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 9995        });
 9996
 9997        // There's a prompt for a path for item 4.
 9998        cx.simulate_new_path_selection(|_| Some(Default::default()));
 9999        close_items.await.unwrap();
10000
10001        // The requested items are closed.
10002        pane.update(cx, |pane, cx| {
10003            assert_eq!(item4.read(cx).save_count, 0);
10004            assert_eq!(item4.read(cx).save_as_count, 1);
10005            assert_eq!(item4.read(cx).reload_count, 0);
10006            assert_eq!(pane.items_len(), 1);
10007            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10008        });
10009    }
10010
10011    #[gpui::test]
10012    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10013        init_test(cx);
10014
10015        let fs = FakeFs::new(cx.executor());
10016        let project = Project::test(fs, [], cx).await;
10017        let (workspace, cx) =
10018            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10019
10020        // Create several workspace items with single project entries, and two
10021        // workspace items with multiple project entries.
10022        let single_entry_items = (0..=4)
10023            .map(|project_entry_id| {
10024                cx.new(|cx| {
10025                    TestItem::new(cx)
10026                        .with_dirty(true)
10027                        .with_project_items(&[dirty_project_item(
10028                            project_entry_id,
10029                            &format!("{project_entry_id}.txt"),
10030                            cx,
10031                        )])
10032                })
10033            })
10034            .collect::<Vec<_>>();
10035        let item_2_3 = cx.new(|cx| {
10036            TestItem::new(cx)
10037                .with_dirty(true)
10038                .with_buffer_kind(ItemBufferKind::Multibuffer)
10039                .with_project_items(&[
10040                    single_entry_items[2].read(cx).project_items[0].clone(),
10041                    single_entry_items[3].read(cx).project_items[0].clone(),
10042                ])
10043        });
10044        let item_3_4 = cx.new(|cx| {
10045            TestItem::new(cx)
10046                .with_dirty(true)
10047                .with_buffer_kind(ItemBufferKind::Multibuffer)
10048                .with_project_items(&[
10049                    single_entry_items[3].read(cx).project_items[0].clone(),
10050                    single_entry_items[4].read(cx).project_items[0].clone(),
10051                ])
10052        });
10053
10054        // Create two panes that contain the following project entries:
10055        //   left pane:
10056        //     multi-entry items:   (2, 3)
10057        //     single-entry items:  0, 2, 3, 4
10058        //   right pane:
10059        //     single-entry items:  4, 1
10060        //     multi-entry items:   (3, 4)
10061        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10062            let left_pane = workspace.active_pane().clone();
10063            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10064            workspace.add_item_to_active_pane(
10065                single_entry_items[0].boxed_clone(),
10066                None,
10067                true,
10068                window,
10069                cx,
10070            );
10071            workspace.add_item_to_active_pane(
10072                single_entry_items[2].boxed_clone(),
10073                None,
10074                true,
10075                window,
10076                cx,
10077            );
10078            workspace.add_item_to_active_pane(
10079                single_entry_items[3].boxed_clone(),
10080                None,
10081                true,
10082                window,
10083                cx,
10084            );
10085            workspace.add_item_to_active_pane(
10086                single_entry_items[4].boxed_clone(),
10087                None,
10088                true,
10089                window,
10090                cx,
10091            );
10092
10093            let right_pane =
10094                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10095
10096            let boxed_clone = single_entry_items[1].boxed_clone();
10097            let right_pane = window.spawn(cx, async move |cx| {
10098                right_pane.await.inspect(|right_pane| {
10099                    right_pane
10100                        .update_in(cx, |pane, window, cx| {
10101                            pane.add_item(boxed_clone, true, true, None, window, cx);
10102                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10103                        })
10104                        .unwrap();
10105                })
10106            });
10107
10108            (left_pane, right_pane)
10109        });
10110        let right_pane = right_pane.await.unwrap();
10111        cx.focus(&right_pane);
10112
10113        let close = right_pane.update_in(cx, |pane, window, cx| {
10114            pane.close_all_items(&CloseAllItems::default(), window, cx)
10115                .unwrap()
10116        });
10117        cx.executor().run_until_parked();
10118
10119        let msg = cx.pending_prompt().unwrap().0;
10120        assert!(msg.contains("1.txt"));
10121        assert!(!msg.contains("2.txt"));
10122        assert!(!msg.contains("3.txt"));
10123        assert!(!msg.contains("4.txt"));
10124
10125        // With best-effort close, cancelling item 1 keeps it open but items 4
10126        // and (3,4) still close since their entries exist in left pane.
10127        cx.simulate_prompt_answer("Cancel");
10128        close.await;
10129
10130        right_pane.read_with(cx, |pane, _| {
10131            assert_eq!(pane.items_len(), 1);
10132        });
10133
10134        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10135        left_pane
10136            .update_in(cx, |left_pane, window, cx| {
10137                left_pane.close_item_by_id(
10138                    single_entry_items[3].entity_id(),
10139                    SaveIntent::Skip,
10140                    window,
10141                    cx,
10142                )
10143            })
10144            .await
10145            .unwrap();
10146
10147        let close = left_pane.update_in(cx, |pane, window, cx| {
10148            pane.close_all_items(&CloseAllItems::default(), window, cx)
10149                .unwrap()
10150        });
10151        cx.executor().run_until_parked();
10152
10153        let details = cx.pending_prompt().unwrap().1;
10154        assert!(details.contains("0.txt"));
10155        assert!(details.contains("3.txt"));
10156        assert!(details.contains("4.txt"));
10157        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10158        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10159        // assert!(!details.contains("2.txt"));
10160
10161        cx.simulate_prompt_answer("Save all");
10162        cx.executor().run_until_parked();
10163        close.await;
10164
10165        left_pane.read_with(cx, |pane, _| {
10166            assert_eq!(pane.items_len(), 0);
10167        });
10168    }
10169
10170    #[gpui::test]
10171    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10172        init_test(cx);
10173
10174        let fs = FakeFs::new(cx.executor());
10175        let project = Project::test(fs, [], cx).await;
10176        let (workspace, cx) =
10177            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10178        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10179
10180        let item = cx.new(|cx| {
10181            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10182        });
10183        let item_id = item.entity_id();
10184        workspace.update_in(cx, |workspace, window, cx| {
10185            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10186        });
10187
10188        // Autosave on window change.
10189        item.update(cx, |item, cx| {
10190            SettingsStore::update_global(cx, |settings, cx| {
10191                settings.update_user_settings(cx, |settings| {
10192                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10193                })
10194            });
10195            item.is_dirty = true;
10196        });
10197
10198        // Deactivating the window saves the file.
10199        cx.deactivate_window();
10200        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10201
10202        // Re-activating the window doesn't save the file.
10203        cx.update(|window, _| window.activate_window());
10204        cx.executor().run_until_parked();
10205        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10206
10207        // Autosave on focus change.
10208        item.update_in(cx, |item, window, cx| {
10209            cx.focus_self(window);
10210            SettingsStore::update_global(cx, |settings, cx| {
10211                settings.update_user_settings(cx, |settings| {
10212                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10213                })
10214            });
10215            item.is_dirty = true;
10216        });
10217        // Blurring the item saves the file.
10218        item.update_in(cx, |_, window, _| window.blur());
10219        cx.executor().run_until_parked();
10220        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10221
10222        // Deactivating the window still saves the file.
10223        item.update_in(cx, |item, window, cx| {
10224            cx.focus_self(window);
10225            item.is_dirty = true;
10226        });
10227        cx.deactivate_window();
10228        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10229
10230        // Autosave after delay.
10231        item.update(cx, |item, cx| {
10232            SettingsStore::update_global(cx, |settings, cx| {
10233                settings.update_user_settings(cx, |settings| {
10234                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10235                        milliseconds: 500.into(),
10236                    });
10237                })
10238            });
10239            item.is_dirty = true;
10240            cx.emit(ItemEvent::Edit);
10241        });
10242
10243        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10244        cx.executor().advance_clock(Duration::from_millis(250));
10245        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10246
10247        // After delay expires, the file is saved.
10248        cx.executor().advance_clock(Duration::from_millis(250));
10249        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10250
10251        // Autosave after delay, should save earlier than delay if tab is closed
10252        item.update(cx, |item, cx| {
10253            item.is_dirty = true;
10254            cx.emit(ItemEvent::Edit);
10255        });
10256        cx.executor().advance_clock(Duration::from_millis(250));
10257        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10258
10259        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10260        pane.update_in(cx, |pane, window, cx| {
10261            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10262        })
10263        .await
10264        .unwrap();
10265        assert!(!cx.has_pending_prompt());
10266        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10267
10268        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10269        workspace.update_in(cx, |workspace, window, cx| {
10270            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10271        });
10272        item.update_in(cx, |item, _window, cx| {
10273            item.is_dirty = true;
10274            for project_item in &mut item.project_items {
10275                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10276            }
10277        });
10278        cx.run_until_parked();
10279        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10280
10281        // Autosave on focus change, ensuring closing the tab counts as such.
10282        item.update(cx, |item, cx| {
10283            SettingsStore::update_global(cx, |settings, cx| {
10284                settings.update_user_settings(cx, |settings| {
10285                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10286                })
10287            });
10288            item.is_dirty = true;
10289            for project_item in &mut item.project_items {
10290                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10291            }
10292        });
10293
10294        pane.update_in(cx, |pane, window, cx| {
10295            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10296        })
10297        .await
10298        .unwrap();
10299        assert!(!cx.has_pending_prompt());
10300        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10301
10302        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10303        workspace.update_in(cx, |workspace, window, cx| {
10304            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10305        });
10306        item.update_in(cx, |item, window, cx| {
10307            item.project_items[0].update(cx, |item, _| {
10308                item.entry_id = None;
10309            });
10310            item.is_dirty = true;
10311            window.blur();
10312        });
10313        cx.run_until_parked();
10314        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10315
10316        // Ensure autosave is prevented for deleted files also when closing the buffer.
10317        let _close_items = pane.update_in(cx, |pane, window, cx| {
10318            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10319        });
10320        cx.run_until_parked();
10321        assert!(cx.has_pending_prompt());
10322        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10323    }
10324
10325    #[gpui::test]
10326    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10327        init_test(cx);
10328
10329        let fs = FakeFs::new(cx.executor());
10330
10331        let project = Project::test(fs, [], cx).await;
10332        let (workspace, cx) =
10333            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10334
10335        let item = cx.new(|cx| {
10336            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10337        });
10338        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10339        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10340        let toolbar_notify_count = Rc::new(RefCell::new(0));
10341
10342        workspace.update_in(cx, |workspace, window, cx| {
10343            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10344            let toolbar_notification_count = toolbar_notify_count.clone();
10345            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10346                *toolbar_notification_count.borrow_mut() += 1
10347            })
10348            .detach();
10349        });
10350
10351        pane.read_with(cx, |pane, _| {
10352            assert!(!pane.can_navigate_backward());
10353            assert!(!pane.can_navigate_forward());
10354        });
10355
10356        item.update_in(cx, |item, _, cx| {
10357            item.set_state("one".to_string(), cx);
10358        });
10359
10360        // Toolbar must be notified to re-render the navigation buttons
10361        assert_eq!(*toolbar_notify_count.borrow(), 1);
10362
10363        pane.read_with(cx, |pane, _| {
10364            assert!(pane.can_navigate_backward());
10365            assert!(!pane.can_navigate_forward());
10366        });
10367
10368        workspace
10369            .update_in(cx, |workspace, window, cx| {
10370                workspace.go_back(pane.downgrade(), window, cx)
10371            })
10372            .await
10373            .unwrap();
10374
10375        assert_eq!(*toolbar_notify_count.borrow(), 2);
10376        pane.read_with(cx, |pane, _| {
10377            assert!(!pane.can_navigate_backward());
10378            assert!(pane.can_navigate_forward());
10379        });
10380    }
10381
10382    #[gpui::test]
10383    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10384        init_test(cx);
10385        let fs = FakeFs::new(cx.executor());
10386
10387        let project = Project::test(fs, [], cx).await;
10388        let (workspace, cx) =
10389            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10390
10391        let panel = workspace.update_in(cx, |workspace, window, cx| {
10392            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10393            workspace.add_panel(panel.clone(), window, cx);
10394
10395            workspace
10396                .right_dock()
10397                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10398
10399            panel
10400        });
10401
10402        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10403        pane.update_in(cx, |pane, window, cx| {
10404            let item = cx.new(TestItem::new);
10405            pane.add_item(Box::new(item), true, true, None, window, cx);
10406        });
10407
10408        // Transfer focus from center to panel
10409        workspace.update_in(cx, |workspace, window, cx| {
10410            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10411        });
10412
10413        workspace.update_in(cx, |workspace, window, cx| {
10414            assert!(workspace.right_dock().read(cx).is_open());
10415            assert!(!panel.is_zoomed(window, cx));
10416            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10417        });
10418
10419        // Transfer focus from panel to center
10420        workspace.update_in(cx, |workspace, window, cx| {
10421            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10422        });
10423
10424        workspace.update_in(cx, |workspace, window, cx| {
10425            assert!(workspace.right_dock().read(cx).is_open());
10426            assert!(!panel.is_zoomed(window, cx));
10427            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10428        });
10429
10430        // Close the dock
10431        workspace.update_in(cx, |workspace, window, cx| {
10432            workspace.toggle_dock(DockPosition::Right, window, cx);
10433        });
10434
10435        workspace.update_in(cx, |workspace, window, cx| {
10436            assert!(!workspace.right_dock().read(cx).is_open());
10437            assert!(!panel.is_zoomed(window, cx));
10438            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10439        });
10440
10441        // Open the dock
10442        workspace.update_in(cx, |workspace, window, cx| {
10443            workspace.toggle_dock(DockPosition::Right, window, cx);
10444        });
10445
10446        workspace.update_in(cx, |workspace, window, cx| {
10447            assert!(workspace.right_dock().read(cx).is_open());
10448            assert!(!panel.is_zoomed(window, cx));
10449            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10450        });
10451
10452        // Focus and zoom panel
10453        panel.update_in(cx, |panel, window, cx| {
10454            cx.focus_self(window);
10455            panel.set_zoomed(true, window, cx)
10456        });
10457
10458        workspace.update_in(cx, |workspace, window, cx| {
10459            assert!(workspace.right_dock().read(cx).is_open());
10460            assert!(panel.is_zoomed(window, cx));
10461            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10462        });
10463
10464        // Transfer focus to the center closes the dock
10465        workspace.update_in(cx, |workspace, window, cx| {
10466            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10467        });
10468
10469        workspace.update_in(cx, |workspace, window, cx| {
10470            assert!(!workspace.right_dock().read(cx).is_open());
10471            assert!(panel.is_zoomed(window, cx));
10472            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10473        });
10474
10475        // Transferring focus back to the panel keeps it zoomed
10476        workspace.update_in(cx, |workspace, window, cx| {
10477            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10478        });
10479
10480        workspace.update_in(cx, |workspace, window, cx| {
10481            assert!(workspace.right_dock().read(cx).is_open());
10482            assert!(panel.is_zoomed(window, cx));
10483            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10484        });
10485
10486        // Close the dock while it is zoomed
10487        workspace.update_in(cx, |workspace, window, cx| {
10488            workspace.toggle_dock(DockPosition::Right, window, cx)
10489        });
10490
10491        workspace.update_in(cx, |workspace, window, cx| {
10492            assert!(!workspace.right_dock().read(cx).is_open());
10493            assert!(panel.is_zoomed(window, cx));
10494            assert!(workspace.zoomed.is_none());
10495            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10496        });
10497
10498        // Opening the dock, when it's zoomed, retains focus
10499        workspace.update_in(cx, |workspace, window, cx| {
10500            workspace.toggle_dock(DockPosition::Right, window, cx)
10501        });
10502
10503        workspace.update_in(cx, |workspace, window, cx| {
10504            assert!(workspace.right_dock().read(cx).is_open());
10505            assert!(panel.is_zoomed(window, cx));
10506            assert!(workspace.zoomed.is_some());
10507            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10508        });
10509
10510        // Unzoom and close the panel, zoom the active pane.
10511        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10512        workspace.update_in(cx, |workspace, window, cx| {
10513            workspace.toggle_dock(DockPosition::Right, window, cx)
10514        });
10515        pane.update_in(cx, |pane, window, cx| {
10516            pane.toggle_zoom(&Default::default(), window, cx)
10517        });
10518
10519        // Opening a dock unzooms the pane.
10520        workspace.update_in(cx, |workspace, window, cx| {
10521            workspace.toggle_dock(DockPosition::Right, window, cx)
10522        });
10523        workspace.update_in(cx, |workspace, window, cx| {
10524            let pane = pane.read(cx);
10525            assert!(!pane.is_zoomed());
10526            assert!(!pane.focus_handle(cx).is_focused(window));
10527            assert!(workspace.right_dock().read(cx).is_open());
10528            assert!(workspace.zoomed.is_none());
10529        });
10530    }
10531
10532    #[gpui::test]
10533    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10534        init_test(cx);
10535        let fs = FakeFs::new(cx.executor());
10536
10537        let project = Project::test(fs, [], cx).await;
10538        let (workspace, cx) =
10539            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10540
10541        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10542            workspace.active_pane().clone()
10543        });
10544
10545        // Add an item to the pane so it can be zoomed
10546        workspace.update_in(cx, |workspace, window, cx| {
10547            let item = cx.new(TestItem::new);
10548            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10549        });
10550
10551        // Initially not zoomed
10552        workspace.update_in(cx, |workspace, _window, cx| {
10553            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10554            assert!(
10555                workspace.zoomed.is_none(),
10556                "Workspace should track no zoomed pane"
10557            );
10558            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10559        });
10560
10561        // Zoom In
10562        pane.update_in(cx, |pane, window, cx| {
10563            pane.zoom_in(&crate::ZoomIn, window, cx);
10564        });
10565
10566        workspace.update_in(cx, |workspace, window, cx| {
10567            assert!(
10568                pane.read(cx).is_zoomed(),
10569                "Pane should be zoomed after ZoomIn"
10570            );
10571            assert!(
10572                workspace.zoomed.is_some(),
10573                "Workspace should track the zoomed pane"
10574            );
10575            assert!(
10576                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10577                "ZoomIn should focus the pane"
10578            );
10579        });
10580
10581        // Zoom In again is a no-op
10582        pane.update_in(cx, |pane, window, cx| {
10583            pane.zoom_in(&crate::ZoomIn, window, cx);
10584        });
10585
10586        workspace.update_in(cx, |workspace, window, cx| {
10587            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10588            assert!(
10589                workspace.zoomed.is_some(),
10590                "Workspace still tracks zoomed pane"
10591            );
10592            assert!(
10593                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10594                "Pane remains focused after repeated ZoomIn"
10595            );
10596        });
10597
10598        // Zoom Out
10599        pane.update_in(cx, |pane, window, cx| {
10600            pane.zoom_out(&crate::ZoomOut, window, cx);
10601        });
10602
10603        workspace.update_in(cx, |workspace, _window, cx| {
10604            assert!(
10605                !pane.read(cx).is_zoomed(),
10606                "Pane should unzoom after ZoomOut"
10607            );
10608            assert!(
10609                workspace.zoomed.is_none(),
10610                "Workspace clears zoom tracking after ZoomOut"
10611            );
10612        });
10613
10614        // Zoom Out again is a no-op
10615        pane.update_in(cx, |pane, window, cx| {
10616            pane.zoom_out(&crate::ZoomOut, window, cx);
10617        });
10618
10619        workspace.update_in(cx, |workspace, _window, cx| {
10620            assert!(
10621                !pane.read(cx).is_zoomed(),
10622                "Second ZoomOut keeps pane unzoomed"
10623            );
10624            assert!(
10625                workspace.zoomed.is_none(),
10626                "Workspace remains without zoomed pane"
10627            );
10628        });
10629    }
10630
10631    #[gpui::test]
10632    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10633        init_test(cx);
10634        let fs = FakeFs::new(cx.executor());
10635
10636        let project = Project::test(fs, [], cx).await;
10637        let (workspace, cx) =
10638            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10639        workspace.update_in(cx, |workspace, window, cx| {
10640            // Open two docks
10641            let left_dock = workspace.dock_at_position(DockPosition::Left);
10642            let right_dock = workspace.dock_at_position(DockPosition::Right);
10643
10644            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10645            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10646
10647            assert!(left_dock.read(cx).is_open());
10648            assert!(right_dock.read(cx).is_open());
10649        });
10650
10651        workspace.update_in(cx, |workspace, window, cx| {
10652            // Toggle all docks - should close both
10653            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10654
10655            let left_dock = workspace.dock_at_position(DockPosition::Left);
10656            let right_dock = workspace.dock_at_position(DockPosition::Right);
10657            assert!(!left_dock.read(cx).is_open());
10658            assert!(!right_dock.read(cx).is_open());
10659        });
10660
10661        workspace.update_in(cx, |workspace, window, cx| {
10662            // Toggle again - should reopen both
10663            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10664
10665            let left_dock = workspace.dock_at_position(DockPosition::Left);
10666            let right_dock = workspace.dock_at_position(DockPosition::Right);
10667            assert!(left_dock.read(cx).is_open());
10668            assert!(right_dock.read(cx).is_open());
10669        });
10670    }
10671
10672    #[gpui::test]
10673    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10674        init_test(cx);
10675        let fs = FakeFs::new(cx.executor());
10676
10677        let project = Project::test(fs, [], cx).await;
10678        let (workspace, cx) =
10679            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10680        workspace.update_in(cx, |workspace, window, cx| {
10681            // Open two docks
10682            let left_dock = workspace.dock_at_position(DockPosition::Left);
10683            let right_dock = workspace.dock_at_position(DockPosition::Right);
10684
10685            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10686            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10687
10688            assert!(left_dock.read(cx).is_open());
10689            assert!(right_dock.read(cx).is_open());
10690        });
10691
10692        workspace.update_in(cx, |workspace, window, cx| {
10693            // Close them manually
10694            workspace.toggle_dock(DockPosition::Left, window, cx);
10695            workspace.toggle_dock(DockPosition::Right, window, cx);
10696
10697            let left_dock = workspace.dock_at_position(DockPosition::Left);
10698            let right_dock = workspace.dock_at_position(DockPosition::Right);
10699            assert!(!left_dock.read(cx).is_open());
10700            assert!(!right_dock.read(cx).is_open());
10701        });
10702
10703        workspace.update_in(cx, |workspace, window, cx| {
10704            // Toggle all docks - only last closed (right dock) should reopen
10705            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10706
10707            let left_dock = workspace.dock_at_position(DockPosition::Left);
10708            let right_dock = workspace.dock_at_position(DockPosition::Right);
10709            assert!(!left_dock.read(cx).is_open());
10710            assert!(right_dock.read(cx).is_open());
10711        });
10712    }
10713
10714    #[gpui::test]
10715    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10716        init_test(cx);
10717        let fs = FakeFs::new(cx.executor());
10718        let project = Project::test(fs, [], cx).await;
10719        let (workspace, cx) =
10720            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10721
10722        // Open two docks (left and right) with one panel each
10723        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10724            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10725            workspace.add_panel(left_panel.clone(), window, cx);
10726
10727            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10728            workspace.add_panel(right_panel.clone(), window, cx);
10729
10730            workspace.toggle_dock(DockPosition::Left, window, cx);
10731            workspace.toggle_dock(DockPosition::Right, window, cx);
10732
10733            // Verify initial state
10734            assert!(
10735                workspace.left_dock().read(cx).is_open(),
10736                "Left dock should be open"
10737            );
10738            assert_eq!(
10739                workspace
10740                    .left_dock()
10741                    .read(cx)
10742                    .visible_panel()
10743                    .unwrap()
10744                    .panel_id(),
10745                left_panel.panel_id(),
10746                "Left panel should be visible in left dock"
10747            );
10748            assert!(
10749                workspace.right_dock().read(cx).is_open(),
10750                "Right dock should be open"
10751            );
10752            assert_eq!(
10753                workspace
10754                    .right_dock()
10755                    .read(cx)
10756                    .visible_panel()
10757                    .unwrap()
10758                    .panel_id(),
10759                right_panel.panel_id(),
10760                "Right panel should be visible in right dock"
10761            );
10762            assert!(
10763                !workspace.bottom_dock().read(cx).is_open(),
10764                "Bottom dock should be closed"
10765            );
10766
10767            (left_panel, right_panel)
10768        });
10769
10770        // Focus the left panel and move it to the next position (bottom dock)
10771        workspace.update_in(cx, |workspace, window, cx| {
10772            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10773            assert!(
10774                left_panel.read(cx).focus_handle(cx).is_focused(window),
10775                "Left panel should be focused"
10776            );
10777        });
10778
10779        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10780
10781        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10782        workspace.update(cx, |workspace, cx| {
10783            assert!(
10784                !workspace.left_dock().read(cx).is_open(),
10785                "Left dock should be closed"
10786            );
10787            assert!(
10788                workspace.bottom_dock().read(cx).is_open(),
10789                "Bottom dock should now be open"
10790            );
10791            assert_eq!(
10792                left_panel.read(cx).position,
10793                DockPosition::Bottom,
10794                "Left panel should now be in the bottom dock"
10795            );
10796            assert_eq!(
10797                workspace
10798                    .bottom_dock()
10799                    .read(cx)
10800                    .visible_panel()
10801                    .unwrap()
10802                    .panel_id(),
10803                left_panel.panel_id(),
10804                "Left panel should be the visible panel in the bottom dock"
10805            );
10806        });
10807
10808        // Toggle all docks off
10809        workspace.update_in(cx, |workspace, window, cx| {
10810            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10811            assert!(
10812                !workspace.left_dock().read(cx).is_open(),
10813                "Left dock should be closed"
10814            );
10815            assert!(
10816                !workspace.right_dock().read(cx).is_open(),
10817                "Right dock should be closed"
10818            );
10819            assert!(
10820                !workspace.bottom_dock().read(cx).is_open(),
10821                "Bottom dock should be closed"
10822            );
10823        });
10824
10825        // Toggle all docks back on and verify positions are restored
10826        workspace.update_in(cx, |workspace, window, cx| {
10827            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10828            assert!(
10829                !workspace.left_dock().read(cx).is_open(),
10830                "Left dock should remain closed"
10831            );
10832            assert!(
10833                workspace.right_dock().read(cx).is_open(),
10834                "Right dock should remain open"
10835            );
10836            assert!(
10837                workspace.bottom_dock().read(cx).is_open(),
10838                "Bottom dock should remain open"
10839            );
10840            assert_eq!(
10841                left_panel.read(cx).position,
10842                DockPosition::Bottom,
10843                "Left panel should remain in the bottom dock"
10844            );
10845            assert_eq!(
10846                right_panel.read(cx).position,
10847                DockPosition::Right,
10848                "Right panel should remain in the right dock"
10849            );
10850            assert_eq!(
10851                workspace
10852                    .bottom_dock()
10853                    .read(cx)
10854                    .visible_panel()
10855                    .unwrap()
10856                    .panel_id(),
10857                left_panel.panel_id(),
10858                "Left panel should be the visible panel in the right dock"
10859            );
10860        });
10861    }
10862
10863    #[gpui::test]
10864    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10865        init_test(cx);
10866
10867        let fs = FakeFs::new(cx.executor());
10868
10869        let project = Project::test(fs, None, cx).await;
10870        let (workspace, cx) =
10871            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10872
10873        // Let's arrange the panes like this:
10874        //
10875        // +-----------------------+
10876        // |         top           |
10877        // +------+--------+-------+
10878        // | left | center | right |
10879        // +------+--------+-------+
10880        // |        bottom         |
10881        // +-----------------------+
10882
10883        let top_item = cx.new(|cx| {
10884            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10885        });
10886        let bottom_item = cx.new(|cx| {
10887            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10888        });
10889        let left_item = cx.new(|cx| {
10890            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10891        });
10892        let right_item = cx.new(|cx| {
10893            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10894        });
10895        let center_item = cx.new(|cx| {
10896            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10897        });
10898
10899        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10900            let top_pane_id = workspace.active_pane().entity_id();
10901            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10902            workspace.split_pane(
10903                workspace.active_pane().clone(),
10904                SplitDirection::Down,
10905                window,
10906                cx,
10907            );
10908            top_pane_id
10909        });
10910        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10911            let bottom_pane_id = workspace.active_pane().entity_id();
10912            workspace.add_item_to_active_pane(
10913                Box::new(bottom_item.clone()),
10914                None,
10915                false,
10916                window,
10917                cx,
10918            );
10919            workspace.split_pane(
10920                workspace.active_pane().clone(),
10921                SplitDirection::Up,
10922                window,
10923                cx,
10924            );
10925            bottom_pane_id
10926        });
10927        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10928            let left_pane_id = workspace.active_pane().entity_id();
10929            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10930            workspace.split_pane(
10931                workspace.active_pane().clone(),
10932                SplitDirection::Right,
10933                window,
10934                cx,
10935            );
10936            left_pane_id
10937        });
10938        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10939            let right_pane_id = workspace.active_pane().entity_id();
10940            workspace.add_item_to_active_pane(
10941                Box::new(right_item.clone()),
10942                None,
10943                false,
10944                window,
10945                cx,
10946            );
10947            workspace.split_pane(
10948                workspace.active_pane().clone(),
10949                SplitDirection::Left,
10950                window,
10951                cx,
10952            );
10953            right_pane_id
10954        });
10955        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10956            let center_pane_id = workspace.active_pane().entity_id();
10957            workspace.add_item_to_active_pane(
10958                Box::new(center_item.clone()),
10959                None,
10960                false,
10961                window,
10962                cx,
10963            );
10964            center_pane_id
10965        });
10966        cx.executor().run_until_parked();
10967
10968        workspace.update_in(cx, |workspace, window, cx| {
10969            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10970
10971            // Join into next from center pane into right
10972            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10973        });
10974
10975        workspace.update_in(cx, |workspace, window, cx| {
10976            let active_pane = workspace.active_pane();
10977            assert_eq!(right_pane_id, active_pane.entity_id());
10978            assert_eq!(2, active_pane.read(cx).items_len());
10979            let item_ids_in_pane =
10980                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10981            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10982            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10983
10984            // Join into next from right pane into bottom
10985            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10986        });
10987
10988        workspace.update_in(cx, |workspace, window, cx| {
10989            let active_pane = workspace.active_pane();
10990            assert_eq!(bottom_pane_id, active_pane.entity_id());
10991            assert_eq!(3, active_pane.read(cx).items_len());
10992            let item_ids_in_pane =
10993                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10994            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10995            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10996            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10997
10998            // Join into next from bottom pane into left
10999            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11000        });
11001
11002        workspace.update_in(cx, |workspace, window, cx| {
11003            let active_pane = workspace.active_pane();
11004            assert_eq!(left_pane_id, active_pane.entity_id());
11005            assert_eq!(4, active_pane.read(cx).items_len());
11006            let item_ids_in_pane =
11007                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11008            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11009            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11010            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11011            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11012
11013            // Join into next from left pane into top
11014            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11015        });
11016
11017        workspace.update_in(cx, |workspace, window, cx| {
11018            let active_pane = workspace.active_pane();
11019            assert_eq!(top_pane_id, active_pane.entity_id());
11020            assert_eq!(5, active_pane.read(cx).items_len());
11021            let item_ids_in_pane =
11022                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11023            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11024            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11025            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11026            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11027            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11028
11029            // Single pane left: no-op
11030            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11031        });
11032
11033        workspace.update(cx, |workspace, _cx| {
11034            let active_pane = workspace.active_pane();
11035            assert_eq!(top_pane_id, active_pane.entity_id());
11036        });
11037    }
11038
11039    fn add_an_item_to_active_pane(
11040        cx: &mut VisualTestContext,
11041        workspace: &Entity<Workspace>,
11042        item_id: u64,
11043    ) -> Entity<TestItem> {
11044        let item = cx.new(|cx| {
11045            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11046                item_id,
11047                "item{item_id}.txt",
11048                cx,
11049            )])
11050        });
11051        workspace.update_in(cx, |workspace, window, cx| {
11052            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11053        });
11054        item
11055    }
11056
11057    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11058        workspace.update_in(cx, |workspace, window, cx| {
11059            workspace.split_pane(
11060                workspace.active_pane().clone(),
11061                SplitDirection::Right,
11062                window,
11063                cx,
11064            )
11065        })
11066    }
11067
11068    #[gpui::test]
11069    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11070        init_test(cx);
11071        let fs = FakeFs::new(cx.executor());
11072        let project = Project::test(fs, None, cx).await;
11073        let (workspace, cx) =
11074            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11075
11076        add_an_item_to_active_pane(cx, &workspace, 1);
11077        split_pane(cx, &workspace);
11078        add_an_item_to_active_pane(cx, &workspace, 2);
11079        split_pane(cx, &workspace); // empty pane
11080        split_pane(cx, &workspace);
11081        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11082
11083        cx.executor().run_until_parked();
11084
11085        workspace.update(cx, |workspace, cx| {
11086            let num_panes = workspace.panes().len();
11087            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11088            let active_item = workspace
11089                .active_pane()
11090                .read(cx)
11091                .active_item()
11092                .expect("item is in focus");
11093
11094            assert_eq!(num_panes, 4);
11095            assert_eq!(num_items_in_current_pane, 1);
11096            assert_eq!(active_item.item_id(), last_item.item_id());
11097        });
11098
11099        workspace.update_in(cx, |workspace, window, cx| {
11100            workspace.join_all_panes(window, cx);
11101        });
11102
11103        workspace.update(cx, |workspace, cx| {
11104            let num_panes = workspace.panes().len();
11105            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11106            let active_item = workspace
11107                .active_pane()
11108                .read(cx)
11109                .active_item()
11110                .expect("item is in focus");
11111
11112            assert_eq!(num_panes, 1);
11113            assert_eq!(num_items_in_current_pane, 3);
11114            assert_eq!(active_item.item_id(), last_item.item_id());
11115        });
11116    }
11117    struct TestModal(FocusHandle);
11118
11119    impl TestModal {
11120        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11121            Self(cx.focus_handle())
11122        }
11123    }
11124
11125    impl EventEmitter<DismissEvent> for TestModal {}
11126
11127    impl Focusable for TestModal {
11128        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11129            self.0.clone()
11130        }
11131    }
11132
11133    impl ModalView for TestModal {}
11134
11135    impl Render for TestModal {
11136        fn render(
11137            &mut self,
11138            _window: &mut Window,
11139            _cx: &mut Context<TestModal>,
11140        ) -> impl IntoElement {
11141            div().track_focus(&self.0)
11142        }
11143    }
11144
11145    #[gpui::test]
11146    async fn test_panels(cx: &mut gpui::TestAppContext) {
11147        init_test(cx);
11148        let fs = FakeFs::new(cx.executor());
11149
11150        let project = Project::test(fs, [], cx).await;
11151        let (workspace, cx) =
11152            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11153
11154        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11155            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11156            workspace.add_panel(panel_1.clone(), window, cx);
11157            workspace.toggle_dock(DockPosition::Left, window, cx);
11158            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11159            workspace.add_panel(panel_2.clone(), window, cx);
11160            workspace.toggle_dock(DockPosition::Right, window, cx);
11161
11162            let left_dock = workspace.left_dock();
11163            assert_eq!(
11164                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11165                panel_1.panel_id()
11166            );
11167            assert_eq!(
11168                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11169                panel_1.size(window, cx)
11170            );
11171
11172            left_dock.update(cx, |left_dock, cx| {
11173                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11174            });
11175            assert_eq!(
11176                workspace
11177                    .right_dock()
11178                    .read(cx)
11179                    .visible_panel()
11180                    .unwrap()
11181                    .panel_id(),
11182                panel_2.panel_id(),
11183            );
11184
11185            (panel_1, panel_2)
11186        });
11187
11188        // Move panel_1 to the right
11189        panel_1.update_in(cx, |panel_1, window, cx| {
11190            panel_1.set_position(DockPosition::Right, window, cx)
11191        });
11192
11193        workspace.update_in(cx, |workspace, window, cx| {
11194            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11195            // Since it was the only panel on the left, the left dock should now be closed.
11196            assert!(!workspace.left_dock().read(cx).is_open());
11197            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11198            let right_dock = workspace.right_dock();
11199            assert_eq!(
11200                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11201                panel_1.panel_id()
11202            );
11203            assert_eq!(
11204                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11205                px(1337.)
11206            );
11207
11208            // Now we move panel_2 to the left
11209            panel_2.set_position(DockPosition::Left, window, cx);
11210        });
11211
11212        workspace.update(cx, |workspace, cx| {
11213            // Since panel_2 was not visible on the right, we don't open the left dock.
11214            assert!(!workspace.left_dock().read(cx).is_open());
11215            // And the right dock is unaffected in its displaying of panel_1
11216            assert!(workspace.right_dock().read(cx).is_open());
11217            assert_eq!(
11218                workspace
11219                    .right_dock()
11220                    .read(cx)
11221                    .visible_panel()
11222                    .unwrap()
11223                    .panel_id(),
11224                panel_1.panel_id(),
11225            );
11226        });
11227
11228        // Move panel_1 back to the left
11229        panel_1.update_in(cx, |panel_1, window, cx| {
11230            panel_1.set_position(DockPosition::Left, window, cx)
11231        });
11232
11233        workspace.update_in(cx, |workspace, window, cx| {
11234            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11235            let left_dock = workspace.left_dock();
11236            assert!(left_dock.read(cx).is_open());
11237            assert_eq!(
11238                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11239                panel_1.panel_id()
11240            );
11241            assert_eq!(
11242                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11243                px(1337.)
11244            );
11245            // And the right dock should be closed as it no longer has any panels.
11246            assert!(!workspace.right_dock().read(cx).is_open());
11247
11248            // Now we move panel_1 to the bottom
11249            panel_1.set_position(DockPosition::Bottom, window, cx);
11250        });
11251
11252        workspace.update_in(cx, |workspace, window, cx| {
11253            // Since panel_1 was visible on the left, we close the left dock.
11254            assert!(!workspace.left_dock().read(cx).is_open());
11255            // The bottom dock is sized based on the panel's default size,
11256            // since the panel orientation changed from vertical to horizontal.
11257            let bottom_dock = workspace.bottom_dock();
11258            assert_eq!(
11259                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11260                panel_1.size(window, cx),
11261            );
11262            // Close bottom dock and move panel_1 back to the left.
11263            bottom_dock.update(cx, |bottom_dock, cx| {
11264                bottom_dock.set_open(false, window, cx)
11265            });
11266            panel_1.set_position(DockPosition::Left, window, cx);
11267        });
11268
11269        // Emit activated event on panel 1
11270        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11271
11272        // Now the left dock is open and panel_1 is active and focused.
11273        workspace.update_in(cx, |workspace, window, cx| {
11274            let left_dock = workspace.left_dock();
11275            assert!(left_dock.read(cx).is_open());
11276            assert_eq!(
11277                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11278                panel_1.panel_id(),
11279            );
11280            assert!(panel_1.focus_handle(cx).is_focused(window));
11281        });
11282
11283        // Emit closed event on panel 2, which is not active
11284        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11285
11286        // Wo don't close the left dock, because panel_2 wasn't the active panel
11287        workspace.update(cx, |workspace, cx| {
11288            let left_dock = workspace.left_dock();
11289            assert!(left_dock.read(cx).is_open());
11290            assert_eq!(
11291                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11292                panel_1.panel_id(),
11293            );
11294        });
11295
11296        // Emitting a ZoomIn event shows the panel as zoomed.
11297        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11298        workspace.read_with(cx, |workspace, _| {
11299            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11300            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11301        });
11302
11303        // Move panel to another dock while it is zoomed
11304        panel_1.update_in(cx, |panel, window, cx| {
11305            panel.set_position(DockPosition::Right, window, cx)
11306        });
11307        workspace.read_with(cx, |workspace, _| {
11308            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11309
11310            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11311        });
11312
11313        // This is a helper for getting a:
11314        // - valid focus on an element,
11315        // - that isn't a part of the panes and panels system of the Workspace,
11316        // - and doesn't trigger the 'on_focus_lost' API.
11317        let focus_other_view = {
11318            let workspace = workspace.clone();
11319            move |cx: &mut VisualTestContext| {
11320                workspace.update_in(cx, |workspace, window, cx| {
11321                    if workspace.active_modal::<TestModal>(cx).is_some() {
11322                        workspace.toggle_modal(window, cx, TestModal::new);
11323                        workspace.toggle_modal(window, cx, TestModal::new);
11324                    } else {
11325                        workspace.toggle_modal(window, cx, TestModal::new);
11326                    }
11327                })
11328            }
11329        };
11330
11331        // If focus is transferred to another view that's not a panel or another pane, we still show
11332        // the panel as zoomed.
11333        focus_other_view(cx);
11334        workspace.read_with(cx, |workspace, _| {
11335            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11336            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11337        });
11338
11339        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11340        workspace.update_in(cx, |_workspace, window, cx| {
11341            cx.focus_self(window);
11342        });
11343        workspace.read_with(cx, |workspace, _| {
11344            assert_eq!(workspace.zoomed, None);
11345            assert_eq!(workspace.zoomed_position, None);
11346        });
11347
11348        // If focus is transferred again to another view that's not a panel or a pane, we won't
11349        // show the panel as zoomed because it wasn't zoomed before.
11350        focus_other_view(cx);
11351        workspace.read_with(cx, |workspace, _| {
11352            assert_eq!(workspace.zoomed, None);
11353            assert_eq!(workspace.zoomed_position, None);
11354        });
11355
11356        // When the panel is activated, it is zoomed again.
11357        cx.dispatch_action(ToggleRightDock);
11358        workspace.read_with(cx, |workspace, _| {
11359            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11360            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11361        });
11362
11363        // Emitting a ZoomOut event unzooms the panel.
11364        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11365        workspace.read_with(cx, |workspace, _| {
11366            assert_eq!(workspace.zoomed, None);
11367            assert_eq!(workspace.zoomed_position, None);
11368        });
11369
11370        // Emit closed event on panel 1, which is active
11371        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11372
11373        // Now the left dock is closed, because panel_1 was the active panel
11374        workspace.update(cx, |workspace, cx| {
11375            let right_dock = workspace.right_dock();
11376            assert!(!right_dock.read(cx).is_open());
11377        });
11378    }
11379
11380    #[gpui::test]
11381    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11382        init_test(cx);
11383
11384        let fs = FakeFs::new(cx.background_executor.clone());
11385        let project = Project::test(fs, [], cx).await;
11386        let (workspace, cx) =
11387            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11388        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11389
11390        let dirty_regular_buffer = cx.new(|cx| {
11391            TestItem::new(cx)
11392                .with_dirty(true)
11393                .with_label("1.txt")
11394                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11395        });
11396        let dirty_regular_buffer_2 = cx.new(|cx| {
11397            TestItem::new(cx)
11398                .with_dirty(true)
11399                .with_label("2.txt")
11400                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11401        });
11402        let dirty_multi_buffer_with_both = cx.new(|cx| {
11403            TestItem::new(cx)
11404                .with_dirty(true)
11405                .with_buffer_kind(ItemBufferKind::Multibuffer)
11406                .with_label("Fake Project Search")
11407                .with_project_items(&[
11408                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11409                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11410                ])
11411        });
11412        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11413        workspace.update_in(cx, |workspace, window, cx| {
11414            workspace.add_item(
11415                pane.clone(),
11416                Box::new(dirty_regular_buffer.clone()),
11417                None,
11418                false,
11419                false,
11420                window,
11421                cx,
11422            );
11423            workspace.add_item(
11424                pane.clone(),
11425                Box::new(dirty_regular_buffer_2.clone()),
11426                None,
11427                false,
11428                false,
11429                window,
11430                cx,
11431            );
11432            workspace.add_item(
11433                pane.clone(),
11434                Box::new(dirty_multi_buffer_with_both.clone()),
11435                None,
11436                false,
11437                false,
11438                window,
11439                cx,
11440            );
11441        });
11442
11443        pane.update_in(cx, |pane, window, cx| {
11444            pane.activate_item(2, true, true, window, cx);
11445            assert_eq!(
11446                pane.active_item().unwrap().item_id(),
11447                multi_buffer_with_both_files_id,
11448                "Should select the multi buffer in the pane"
11449            );
11450        });
11451        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11452            pane.close_other_items(
11453                &CloseOtherItems {
11454                    save_intent: Some(SaveIntent::Save),
11455                    close_pinned: true,
11456                },
11457                None,
11458                window,
11459                cx,
11460            )
11461        });
11462        cx.background_executor.run_until_parked();
11463        assert!(!cx.has_pending_prompt());
11464        close_all_but_multi_buffer_task
11465            .await
11466            .expect("Closing all buffers but the multi buffer failed");
11467        pane.update(cx, |pane, cx| {
11468            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11469            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11470            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11471            assert_eq!(pane.items_len(), 1);
11472            assert_eq!(
11473                pane.active_item().unwrap().item_id(),
11474                multi_buffer_with_both_files_id,
11475                "Should have only the multi buffer left in the pane"
11476            );
11477            assert!(
11478                dirty_multi_buffer_with_both.read(cx).is_dirty,
11479                "The multi buffer containing the unsaved buffer should still be dirty"
11480            );
11481        });
11482
11483        dirty_regular_buffer.update(cx, |buffer, cx| {
11484            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11485        });
11486
11487        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11488            pane.close_active_item(
11489                &CloseActiveItem {
11490                    save_intent: Some(SaveIntent::Close),
11491                    close_pinned: false,
11492                },
11493                window,
11494                cx,
11495            )
11496        });
11497        cx.background_executor.run_until_parked();
11498        assert!(
11499            cx.has_pending_prompt(),
11500            "Dirty multi buffer should prompt a save dialog"
11501        );
11502        cx.simulate_prompt_answer("Save");
11503        cx.background_executor.run_until_parked();
11504        close_multi_buffer_task
11505            .await
11506            .expect("Closing the multi buffer failed");
11507        pane.update(cx, |pane, cx| {
11508            assert_eq!(
11509                dirty_multi_buffer_with_both.read(cx).save_count,
11510                1,
11511                "Multi buffer item should get be saved"
11512            );
11513            // Test impl does not save inner items, so we do not assert them
11514            assert_eq!(
11515                pane.items_len(),
11516                0,
11517                "No more items should be left in the pane"
11518            );
11519            assert!(pane.active_item().is_none());
11520        });
11521    }
11522
11523    #[gpui::test]
11524    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11525        cx: &mut TestAppContext,
11526    ) {
11527        init_test(cx);
11528
11529        let fs = FakeFs::new(cx.background_executor.clone());
11530        let project = Project::test(fs, [], cx).await;
11531        let (workspace, cx) =
11532            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11533        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11534
11535        let dirty_regular_buffer = cx.new(|cx| {
11536            TestItem::new(cx)
11537                .with_dirty(true)
11538                .with_label("1.txt")
11539                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11540        });
11541        let dirty_regular_buffer_2 = cx.new(|cx| {
11542            TestItem::new(cx)
11543                .with_dirty(true)
11544                .with_label("2.txt")
11545                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11546        });
11547        let clear_regular_buffer = cx.new(|cx| {
11548            TestItem::new(cx)
11549                .with_label("3.txt")
11550                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11551        });
11552
11553        let dirty_multi_buffer_with_both = cx.new(|cx| {
11554            TestItem::new(cx)
11555                .with_dirty(true)
11556                .with_buffer_kind(ItemBufferKind::Multibuffer)
11557                .with_label("Fake Project Search")
11558                .with_project_items(&[
11559                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11560                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11561                    clear_regular_buffer.read(cx).project_items[0].clone(),
11562                ])
11563        });
11564        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11565        workspace.update_in(cx, |workspace, window, cx| {
11566            workspace.add_item(
11567                pane.clone(),
11568                Box::new(dirty_regular_buffer.clone()),
11569                None,
11570                false,
11571                false,
11572                window,
11573                cx,
11574            );
11575            workspace.add_item(
11576                pane.clone(),
11577                Box::new(dirty_multi_buffer_with_both.clone()),
11578                None,
11579                false,
11580                false,
11581                window,
11582                cx,
11583            );
11584        });
11585
11586        pane.update_in(cx, |pane, window, cx| {
11587            pane.activate_item(1, true, true, window, cx);
11588            assert_eq!(
11589                pane.active_item().unwrap().item_id(),
11590                multi_buffer_with_both_files_id,
11591                "Should select the multi buffer in the pane"
11592            );
11593        });
11594        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11595            pane.close_active_item(
11596                &CloseActiveItem {
11597                    save_intent: None,
11598                    close_pinned: false,
11599                },
11600                window,
11601                cx,
11602            )
11603        });
11604        cx.background_executor.run_until_parked();
11605        assert!(
11606            cx.has_pending_prompt(),
11607            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11608        );
11609    }
11610
11611    /// Tests that when `close_on_file_delete` is enabled, files are automatically
11612    /// closed when they are deleted from disk.
11613    #[gpui::test]
11614    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11615        init_test(cx);
11616
11617        // Enable the close_on_disk_deletion setting
11618        cx.update_global(|store: &mut SettingsStore, cx| {
11619            store.update_user_settings(cx, |settings| {
11620                settings.workspace.close_on_file_delete = Some(true);
11621            });
11622        });
11623
11624        let fs = FakeFs::new(cx.background_executor.clone());
11625        let project = Project::test(fs, [], cx).await;
11626        let (workspace, cx) =
11627            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11628        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11629
11630        // Create a test item that simulates a file
11631        let item = cx.new(|cx| {
11632            TestItem::new(cx)
11633                .with_label("test.txt")
11634                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11635        });
11636
11637        // Add item to workspace
11638        workspace.update_in(cx, |workspace, window, cx| {
11639            workspace.add_item(
11640                pane.clone(),
11641                Box::new(item.clone()),
11642                None,
11643                false,
11644                false,
11645                window,
11646                cx,
11647            );
11648        });
11649
11650        // Verify the item is in the pane
11651        pane.read_with(cx, |pane, _| {
11652            assert_eq!(pane.items().count(), 1);
11653        });
11654
11655        // Simulate file deletion by setting the item's deleted state
11656        item.update(cx, |item, _| {
11657            item.set_has_deleted_file(true);
11658        });
11659
11660        // Emit UpdateTab event to trigger the close behavior
11661        cx.run_until_parked();
11662        item.update(cx, |_, cx| {
11663            cx.emit(ItemEvent::UpdateTab);
11664        });
11665
11666        // Allow the close operation to complete
11667        cx.run_until_parked();
11668
11669        // Verify the item was automatically closed
11670        pane.read_with(cx, |pane, _| {
11671            assert_eq!(
11672                pane.items().count(),
11673                0,
11674                "Item should be automatically closed when file is deleted"
11675            );
11676        });
11677    }
11678
11679    /// Tests that when `close_on_file_delete` is disabled (default), files remain
11680    /// open with a strikethrough when they are deleted from disk.
11681    #[gpui::test]
11682    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11683        init_test(cx);
11684
11685        // Ensure close_on_disk_deletion is disabled (default)
11686        cx.update_global(|store: &mut SettingsStore, cx| {
11687            store.update_user_settings(cx, |settings| {
11688                settings.workspace.close_on_file_delete = Some(false);
11689            });
11690        });
11691
11692        let fs = FakeFs::new(cx.background_executor.clone());
11693        let project = Project::test(fs, [], cx).await;
11694        let (workspace, cx) =
11695            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11696        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11697
11698        // Create a test item that simulates a file
11699        let item = cx.new(|cx| {
11700            TestItem::new(cx)
11701                .with_label("test.txt")
11702                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11703        });
11704
11705        // Add item to workspace
11706        workspace.update_in(cx, |workspace, window, cx| {
11707            workspace.add_item(
11708                pane.clone(),
11709                Box::new(item.clone()),
11710                None,
11711                false,
11712                false,
11713                window,
11714                cx,
11715            );
11716        });
11717
11718        // Verify the item is in the pane
11719        pane.read_with(cx, |pane, _| {
11720            assert_eq!(pane.items().count(), 1);
11721        });
11722
11723        // Simulate file deletion
11724        item.update(cx, |item, _| {
11725            item.set_has_deleted_file(true);
11726        });
11727
11728        // Emit UpdateTab event
11729        cx.run_until_parked();
11730        item.update(cx, |_, cx| {
11731            cx.emit(ItemEvent::UpdateTab);
11732        });
11733
11734        // Allow any potential close operation to complete
11735        cx.run_until_parked();
11736
11737        // Verify the item remains open (with strikethrough)
11738        pane.read_with(cx, |pane, _| {
11739            assert_eq!(
11740                pane.items().count(),
11741                1,
11742                "Item should remain open when close_on_disk_deletion is disabled"
11743            );
11744        });
11745
11746        // Verify the item shows as deleted
11747        item.read_with(cx, |item, _| {
11748            assert!(
11749                item.has_deleted_file,
11750                "Item should be marked as having deleted file"
11751            );
11752        });
11753    }
11754
11755    /// Tests that dirty files are not automatically closed when deleted from disk,
11756    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11757    /// unsaved changes without being prompted.
11758    #[gpui::test]
11759    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11760        init_test(cx);
11761
11762        // Enable the close_on_file_delete setting
11763        cx.update_global(|store: &mut SettingsStore, cx| {
11764            store.update_user_settings(cx, |settings| {
11765                settings.workspace.close_on_file_delete = Some(true);
11766            });
11767        });
11768
11769        let fs = FakeFs::new(cx.background_executor.clone());
11770        let project = Project::test(fs, [], cx).await;
11771        let (workspace, cx) =
11772            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11773        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11774
11775        // Create a dirty test item
11776        let item = cx.new(|cx| {
11777            TestItem::new(cx)
11778                .with_dirty(true)
11779                .with_label("test.txt")
11780                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11781        });
11782
11783        // Add item to workspace
11784        workspace.update_in(cx, |workspace, window, cx| {
11785            workspace.add_item(
11786                pane.clone(),
11787                Box::new(item.clone()),
11788                None,
11789                false,
11790                false,
11791                window,
11792                cx,
11793            );
11794        });
11795
11796        // Simulate file deletion
11797        item.update(cx, |item, _| {
11798            item.set_has_deleted_file(true);
11799        });
11800
11801        // Emit UpdateTab event to trigger the close behavior
11802        cx.run_until_parked();
11803        item.update(cx, |_, cx| {
11804            cx.emit(ItemEvent::UpdateTab);
11805        });
11806
11807        // Allow any potential close operation to complete
11808        cx.run_until_parked();
11809
11810        // Verify the item remains open (dirty files are not auto-closed)
11811        pane.read_with(cx, |pane, _| {
11812            assert_eq!(
11813                pane.items().count(),
11814                1,
11815                "Dirty items should not be automatically closed even when file is deleted"
11816            );
11817        });
11818
11819        // Verify the item is marked as deleted and still dirty
11820        item.read_with(cx, |item, _| {
11821            assert!(
11822                item.has_deleted_file,
11823                "Item should be marked as having deleted file"
11824            );
11825            assert!(item.is_dirty, "Item should still be dirty");
11826        });
11827    }
11828
11829    /// Tests that navigation history is cleaned up when files are auto-closed
11830    /// due to deletion from disk.
11831    #[gpui::test]
11832    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11833        init_test(cx);
11834
11835        // Enable the close_on_file_delete setting
11836        cx.update_global(|store: &mut SettingsStore, cx| {
11837            store.update_user_settings(cx, |settings| {
11838                settings.workspace.close_on_file_delete = Some(true);
11839            });
11840        });
11841
11842        let fs = FakeFs::new(cx.background_executor.clone());
11843        let project = Project::test(fs, [], cx).await;
11844        let (workspace, cx) =
11845            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11846        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11847
11848        // Create test items
11849        let item1 = cx.new(|cx| {
11850            TestItem::new(cx)
11851                .with_label("test1.txt")
11852                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11853        });
11854        let item1_id = item1.item_id();
11855
11856        let item2 = cx.new(|cx| {
11857            TestItem::new(cx)
11858                .with_label("test2.txt")
11859                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11860        });
11861
11862        // Add items to workspace
11863        workspace.update_in(cx, |workspace, window, cx| {
11864            workspace.add_item(
11865                pane.clone(),
11866                Box::new(item1.clone()),
11867                None,
11868                false,
11869                false,
11870                window,
11871                cx,
11872            );
11873            workspace.add_item(
11874                pane.clone(),
11875                Box::new(item2.clone()),
11876                None,
11877                false,
11878                false,
11879                window,
11880                cx,
11881            );
11882        });
11883
11884        // Activate item1 to ensure it gets navigation entries
11885        pane.update_in(cx, |pane, window, cx| {
11886            pane.activate_item(0, true, true, window, cx);
11887        });
11888
11889        // Switch to item2 and back to create navigation history
11890        pane.update_in(cx, |pane, window, cx| {
11891            pane.activate_item(1, true, true, window, cx);
11892        });
11893        cx.run_until_parked();
11894
11895        pane.update_in(cx, |pane, window, cx| {
11896            pane.activate_item(0, true, true, window, cx);
11897        });
11898        cx.run_until_parked();
11899
11900        // Simulate file deletion for item1
11901        item1.update(cx, |item, _| {
11902            item.set_has_deleted_file(true);
11903        });
11904
11905        // Emit UpdateTab event to trigger the close behavior
11906        item1.update(cx, |_, cx| {
11907            cx.emit(ItemEvent::UpdateTab);
11908        });
11909        cx.run_until_parked();
11910
11911        // Verify item1 was closed
11912        pane.read_with(cx, |pane, _| {
11913            assert_eq!(
11914                pane.items().count(),
11915                1,
11916                "Should have 1 item remaining after auto-close"
11917            );
11918        });
11919
11920        // Check navigation history after close
11921        let has_item = pane.read_with(cx, |pane, cx| {
11922            let mut has_item = false;
11923            pane.nav_history().for_each_entry(cx, |entry, _| {
11924                if entry.item.id() == item1_id {
11925                    has_item = true;
11926                }
11927            });
11928            has_item
11929        });
11930
11931        assert!(
11932            !has_item,
11933            "Navigation history should not contain closed item entries"
11934        );
11935    }
11936
11937    #[gpui::test]
11938    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11939        cx: &mut TestAppContext,
11940    ) {
11941        init_test(cx);
11942
11943        let fs = FakeFs::new(cx.background_executor.clone());
11944        let project = Project::test(fs, [], cx).await;
11945        let (workspace, cx) =
11946            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11947        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11948
11949        let dirty_regular_buffer = cx.new(|cx| {
11950            TestItem::new(cx)
11951                .with_dirty(true)
11952                .with_label("1.txt")
11953                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11954        });
11955        let dirty_regular_buffer_2 = cx.new(|cx| {
11956            TestItem::new(cx)
11957                .with_dirty(true)
11958                .with_label("2.txt")
11959                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11960        });
11961        let clear_regular_buffer = cx.new(|cx| {
11962            TestItem::new(cx)
11963                .with_label("3.txt")
11964                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11965        });
11966
11967        let dirty_multi_buffer = cx.new(|cx| {
11968            TestItem::new(cx)
11969                .with_dirty(true)
11970                .with_buffer_kind(ItemBufferKind::Multibuffer)
11971                .with_label("Fake Project Search")
11972                .with_project_items(&[
11973                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11974                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11975                    clear_regular_buffer.read(cx).project_items[0].clone(),
11976                ])
11977        });
11978        workspace.update_in(cx, |workspace, window, cx| {
11979            workspace.add_item(
11980                pane.clone(),
11981                Box::new(dirty_regular_buffer.clone()),
11982                None,
11983                false,
11984                false,
11985                window,
11986                cx,
11987            );
11988            workspace.add_item(
11989                pane.clone(),
11990                Box::new(dirty_regular_buffer_2.clone()),
11991                None,
11992                false,
11993                false,
11994                window,
11995                cx,
11996            );
11997            workspace.add_item(
11998                pane.clone(),
11999                Box::new(dirty_multi_buffer.clone()),
12000                None,
12001                false,
12002                false,
12003                window,
12004                cx,
12005            );
12006        });
12007
12008        pane.update_in(cx, |pane, window, cx| {
12009            pane.activate_item(2, true, true, window, cx);
12010            assert_eq!(
12011                pane.active_item().unwrap().item_id(),
12012                dirty_multi_buffer.item_id(),
12013                "Should select the multi buffer in the pane"
12014            );
12015        });
12016        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12017            pane.close_active_item(
12018                &CloseActiveItem {
12019                    save_intent: None,
12020                    close_pinned: false,
12021                },
12022                window,
12023                cx,
12024            )
12025        });
12026        cx.background_executor.run_until_parked();
12027        assert!(
12028            !cx.has_pending_prompt(),
12029            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12030        );
12031        close_multi_buffer_task
12032            .await
12033            .expect("Closing multi buffer failed");
12034        pane.update(cx, |pane, cx| {
12035            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12036            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12037            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12038            assert_eq!(
12039                pane.items()
12040                    .map(|item| item.item_id())
12041                    .sorted()
12042                    .collect::<Vec<_>>(),
12043                vec![
12044                    dirty_regular_buffer.item_id(),
12045                    dirty_regular_buffer_2.item_id(),
12046                ],
12047                "Should have no multi buffer left in the pane"
12048            );
12049            assert!(dirty_regular_buffer.read(cx).is_dirty);
12050            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12051        });
12052    }
12053
12054    #[gpui::test]
12055    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12056        init_test(cx);
12057        let fs = FakeFs::new(cx.executor());
12058        let project = Project::test(fs, [], cx).await;
12059        let (workspace, cx) =
12060            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12061
12062        // Add a new panel to the right dock, opening the dock and setting the
12063        // focus to the new panel.
12064        let panel = workspace.update_in(cx, |workspace, window, cx| {
12065            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12066            workspace.add_panel(panel.clone(), window, cx);
12067
12068            workspace
12069                .right_dock()
12070                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12071
12072            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12073
12074            panel
12075        });
12076
12077        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12078        // panel to the next valid position which, in this case, is the left
12079        // dock.
12080        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12081        workspace.update(cx, |workspace, cx| {
12082            assert!(workspace.left_dock().read(cx).is_open());
12083            assert_eq!(panel.read(cx).position, DockPosition::Left);
12084        });
12085
12086        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12087        // panel to the next valid position which, in this case, is the bottom
12088        // dock.
12089        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12090        workspace.update(cx, |workspace, cx| {
12091            assert!(workspace.bottom_dock().read(cx).is_open());
12092            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12093        });
12094
12095        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12096        // around moving the panel to its initial position, the right dock.
12097        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12098        workspace.update(cx, |workspace, cx| {
12099            assert!(workspace.right_dock().read(cx).is_open());
12100            assert_eq!(panel.read(cx).position, DockPosition::Right);
12101        });
12102
12103        // Remove focus from the panel, ensuring that, if the panel is not
12104        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12105        // the panel's position, so the panel is still in the right dock.
12106        workspace.update_in(cx, |workspace, window, cx| {
12107            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12108        });
12109
12110        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12111        workspace.update(cx, |workspace, cx| {
12112            assert!(workspace.right_dock().read(cx).is_open());
12113            assert_eq!(panel.read(cx).position, DockPosition::Right);
12114        });
12115    }
12116
12117    #[gpui::test]
12118    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12119        init_test(cx);
12120
12121        let fs = FakeFs::new(cx.executor());
12122        let project = Project::test(fs, [], cx).await;
12123        let (workspace, cx) =
12124            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12125
12126        let item_1 = cx.new(|cx| {
12127            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12128        });
12129        workspace.update_in(cx, |workspace, window, cx| {
12130            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12131            workspace.move_item_to_pane_in_direction(
12132                &MoveItemToPaneInDirection {
12133                    direction: SplitDirection::Right,
12134                    focus: true,
12135                    clone: false,
12136                },
12137                window,
12138                cx,
12139            );
12140            workspace.move_item_to_pane_at_index(
12141                &MoveItemToPane {
12142                    destination: 3,
12143                    focus: true,
12144                    clone: false,
12145                },
12146                window,
12147                cx,
12148            );
12149
12150            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12151            assert_eq!(
12152                pane_items_paths(&workspace.active_pane, cx),
12153                vec!["first.txt".to_string()],
12154                "Single item was not moved anywhere"
12155            );
12156        });
12157
12158        let item_2 = cx.new(|cx| {
12159            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12160        });
12161        workspace.update_in(cx, |workspace, window, cx| {
12162            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12163            assert_eq!(
12164                pane_items_paths(&workspace.panes[0], cx),
12165                vec!["first.txt".to_string(), "second.txt".to_string()],
12166            );
12167            workspace.move_item_to_pane_in_direction(
12168                &MoveItemToPaneInDirection {
12169                    direction: SplitDirection::Right,
12170                    focus: true,
12171                    clone: false,
12172                },
12173                window,
12174                cx,
12175            );
12176
12177            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12178            assert_eq!(
12179                pane_items_paths(&workspace.panes[0], cx),
12180                vec!["first.txt".to_string()],
12181                "After moving, one item should be left in the original pane"
12182            );
12183            assert_eq!(
12184                pane_items_paths(&workspace.panes[1], cx),
12185                vec!["second.txt".to_string()],
12186                "New item should have been moved to the new pane"
12187            );
12188        });
12189
12190        let item_3 = cx.new(|cx| {
12191            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12192        });
12193        workspace.update_in(cx, |workspace, window, cx| {
12194            let original_pane = workspace.panes[0].clone();
12195            workspace.set_active_pane(&original_pane, window, cx);
12196            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12197            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12198            assert_eq!(
12199                pane_items_paths(&workspace.active_pane, cx),
12200                vec!["first.txt".to_string(), "third.txt".to_string()],
12201                "New pane should be ready to move one item out"
12202            );
12203
12204            workspace.move_item_to_pane_at_index(
12205                &MoveItemToPane {
12206                    destination: 3,
12207                    focus: true,
12208                    clone: false,
12209                },
12210                window,
12211                cx,
12212            );
12213            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12214            assert_eq!(
12215                pane_items_paths(&workspace.active_pane, cx),
12216                vec!["first.txt".to_string()],
12217                "After moving, one item should be left in the original pane"
12218            );
12219            assert_eq!(
12220                pane_items_paths(&workspace.panes[1], cx),
12221                vec!["second.txt".to_string()],
12222                "Previously created pane should be unchanged"
12223            );
12224            assert_eq!(
12225                pane_items_paths(&workspace.panes[2], cx),
12226                vec!["third.txt".to_string()],
12227                "New item should have been moved to the new pane"
12228            );
12229        });
12230    }
12231
12232    #[gpui::test]
12233    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12234        init_test(cx);
12235
12236        let fs = FakeFs::new(cx.executor());
12237        let project = Project::test(fs, [], cx).await;
12238        let (workspace, cx) =
12239            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12240
12241        let item_1 = cx.new(|cx| {
12242            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12243        });
12244        workspace.update_in(cx, |workspace, window, cx| {
12245            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12246            workspace.move_item_to_pane_in_direction(
12247                &MoveItemToPaneInDirection {
12248                    direction: SplitDirection::Right,
12249                    focus: true,
12250                    clone: true,
12251                },
12252                window,
12253                cx,
12254            );
12255        });
12256        cx.run_until_parked();
12257        workspace.update_in(cx, |workspace, window, cx| {
12258            workspace.move_item_to_pane_at_index(
12259                &MoveItemToPane {
12260                    destination: 3,
12261                    focus: true,
12262                    clone: true,
12263                },
12264                window,
12265                cx,
12266            );
12267        });
12268        cx.run_until_parked();
12269
12270        workspace.update(cx, |workspace, cx| {
12271            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12272            for pane in workspace.panes() {
12273                assert_eq!(
12274                    pane_items_paths(pane, cx),
12275                    vec!["first.txt".to_string()],
12276                    "Single item exists in all panes"
12277                );
12278            }
12279        });
12280
12281        // verify that the active pane has been updated after waiting for the
12282        // pane focus event to fire and resolve
12283        workspace.read_with(cx, |workspace, _app| {
12284            assert_eq!(
12285                workspace.active_pane(),
12286                &workspace.panes[2],
12287                "The third pane should be the active one: {:?}",
12288                workspace.panes
12289            );
12290        })
12291    }
12292
12293    mod register_project_item_tests {
12294
12295        use super::*;
12296
12297        // View
12298        struct TestPngItemView {
12299            focus_handle: FocusHandle,
12300        }
12301        // Model
12302        struct TestPngItem {}
12303
12304        impl project::ProjectItem for TestPngItem {
12305            fn try_open(
12306                _project: &Entity<Project>,
12307                path: &ProjectPath,
12308                cx: &mut App,
12309            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12310                if path.path.extension().unwrap() == "png" {
12311                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12312                } else {
12313                    None
12314                }
12315            }
12316
12317            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12318                None
12319            }
12320
12321            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12322                None
12323            }
12324
12325            fn is_dirty(&self) -> bool {
12326                false
12327            }
12328        }
12329
12330        impl Item for TestPngItemView {
12331            type Event = ();
12332            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12333                "".into()
12334            }
12335        }
12336        impl EventEmitter<()> for TestPngItemView {}
12337        impl Focusable for TestPngItemView {
12338            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12339                self.focus_handle.clone()
12340            }
12341        }
12342
12343        impl Render for TestPngItemView {
12344            fn render(
12345                &mut self,
12346                _window: &mut Window,
12347                _cx: &mut Context<Self>,
12348            ) -> impl IntoElement {
12349                Empty
12350            }
12351        }
12352
12353        impl ProjectItem for TestPngItemView {
12354            type Item = TestPngItem;
12355
12356            fn for_project_item(
12357                _project: Entity<Project>,
12358                _pane: Option<&Pane>,
12359                _item: Entity<Self::Item>,
12360                _: &mut Window,
12361                cx: &mut Context<Self>,
12362            ) -> Self
12363            where
12364                Self: Sized,
12365            {
12366                Self {
12367                    focus_handle: cx.focus_handle(),
12368                }
12369            }
12370        }
12371
12372        // View
12373        struct TestIpynbItemView {
12374            focus_handle: FocusHandle,
12375        }
12376        // Model
12377        struct TestIpynbItem {}
12378
12379        impl project::ProjectItem for TestIpynbItem {
12380            fn try_open(
12381                _project: &Entity<Project>,
12382                path: &ProjectPath,
12383                cx: &mut App,
12384            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12385                if path.path.extension().unwrap() == "ipynb" {
12386                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12387                } else {
12388                    None
12389                }
12390            }
12391
12392            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12393                None
12394            }
12395
12396            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12397                None
12398            }
12399
12400            fn is_dirty(&self) -> bool {
12401                false
12402            }
12403        }
12404
12405        impl Item for TestIpynbItemView {
12406            type Event = ();
12407            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12408                "".into()
12409            }
12410        }
12411        impl EventEmitter<()> for TestIpynbItemView {}
12412        impl Focusable for TestIpynbItemView {
12413            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12414                self.focus_handle.clone()
12415            }
12416        }
12417
12418        impl Render for TestIpynbItemView {
12419            fn render(
12420                &mut self,
12421                _window: &mut Window,
12422                _cx: &mut Context<Self>,
12423            ) -> impl IntoElement {
12424                Empty
12425            }
12426        }
12427
12428        impl ProjectItem for TestIpynbItemView {
12429            type Item = TestIpynbItem;
12430
12431            fn for_project_item(
12432                _project: Entity<Project>,
12433                _pane: Option<&Pane>,
12434                _item: Entity<Self::Item>,
12435                _: &mut Window,
12436                cx: &mut Context<Self>,
12437            ) -> Self
12438            where
12439                Self: Sized,
12440            {
12441                Self {
12442                    focus_handle: cx.focus_handle(),
12443                }
12444            }
12445        }
12446
12447        struct TestAlternatePngItemView {
12448            focus_handle: FocusHandle,
12449        }
12450
12451        impl Item for TestAlternatePngItemView {
12452            type Event = ();
12453            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12454                "".into()
12455            }
12456        }
12457
12458        impl EventEmitter<()> for TestAlternatePngItemView {}
12459        impl Focusable for TestAlternatePngItemView {
12460            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12461                self.focus_handle.clone()
12462            }
12463        }
12464
12465        impl Render for TestAlternatePngItemView {
12466            fn render(
12467                &mut self,
12468                _window: &mut Window,
12469                _cx: &mut Context<Self>,
12470            ) -> impl IntoElement {
12471                Empty
12472            }
12473        }
12474
12475        impl ProjectItem for TestAlternatePngItemView {
12476            type Item = TestPngItem;
12477
12478            fn for_project_item(
12479                _project: Entity<Project>,
12480                _pane: Option<&Pane>,
12481                _item: Entity<Self::Item>,
12482                _: &mut Window,
12483                cx: &mut Context<Self>,
12484            ) -> Self
12485            where
12486                Self: Sized,
12487            {
12488                Self {
12489                    focus_handle: cx.focus_handle(),
12490                }
12491            }
12492        }
12493
12494        #[gpui::test]
12495        async fn test_register_project_item(cx: &mut TestAppContext) {
12496            init_test(cx);
12497
12498            cx.update(|cx| {
12499                register_project_item::<TestPngItemView>(cx);
12500                register_project_item::<TestIpynbItemView>(cx);
12501            });
12502
12503            let fs = FakeFs::new(cx.executor());
12504            fs.insert_tree(
12505                "/root1",
12506                json!({
12507                    "one.png": "BINARYDATAHERE",
12508                    "two.ipynb": "{ totally a notebook }",
12509                    "three.txt": "editing text, sure why not?"
12510                }),
12511            )
12512            .await;
12513
12514            let project = Project::test(fs, ["root1".as_ref()], cx).await;
12515            let (workspace, cx) =
12516                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12517
12518            let worktree_id = project.update(cx, |project, cx| {
12519                project.worktrees(cx).next().unwrap().read(cx).id()
12520            });
12521
12522            let handle = workspace
12523                .update_in(cx, |workspace, window, cx| {
12524                    let project_path = (worktree_id, rel_path("one.png"));
12525                    workspace.open_path(project_path, None, true, window, cx)
12526                })
12527                .await
12528                .unwrap();
12529
12530            // Now we can check if the handle we got back errored or not
12531            assert_eq!(
12532                handle.to_any_view().entity_type(),
12533                TypeId::of::<TestPngItemView>()
12534            );
12535
12536            let handle = workspace
12537                .update_in(cx, |workspace, window, cx| {
12538                    let project_path = (worktree_id, rel_path("two.ipynb"));
12539                    workspace.open_path(project_path, None, true, window, cx)
12540                })
12541                .await
12542                .unwrap();
12543
12544            assert_eq!(
12545                handle.to_any_view().entity_type(),
12546                TypeId::of::<TestIpynbItemView>()
12547            );
12548
12549            let handle = workspace
12550                .update_in(cx, |workspace, window, cx| {
12551                    let project_path = (worktree_id, rel_path("three.txt"));
12552                    workspace.open_path(project_path, None, true, window, cx)
12553                })
12554                .await;
12555            assert!(handle.is_err());
12556        }
12557
12558        #[gpui::test]
12559        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12560            init_test(cx);
12561
12562            cx.update(|cx| {
12563                register_project_item::<TestPngItemView>(cx);
12564                register_project_item::<TestAlternatePngItemView>(cx);
12565            });
12566
12567            let fs = FakeFs::new(cx.executor());
12568            fs.insert_tree(
12569                "/root1",
12570                json!({
12571                    "one.png": "BINARYDATAHERE",
12572                    "two.ipynb": "{ totally a notebook }",
12573                    "three.txt": "editing text, sure why not?"
12574                }),
12575            )
12576            .await;
12577            let project = Project::test(fs, ["root1".as_ref()], cx).await;
12578            let (workspace, cx) =
12579                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12580            let worktree_id = project.update(cx, |project, cx| {
12581                project.worktrees(cx).next().unwrap().read(cx).id()
12582            });
12583
12584            let handle = workspace
12585                .update_in(cx, |workspace, window, cx| {
12586                    let project_path = (worktree_id, rel_path("one.png"));
12587                    workspace.open_path(project_path, None, true, window, cx)
12588                })
12589                .await
12590                .unwrap();
12591
12592            // This _must_ be the second item registered
12593            assert_eq!(
12594                handle.to_any_view().entity_type(),
12595                TypeId::of::<TestAlternatePngItemView>()
12596            );
12597
12598            let handle = workspace
12599                .update_in(cx, |workspace, window, cx| {
12600                    let project_path = (worktree_id, rel_path("three.txt"));
12601                    workspace.open_path(project_path, None, true, window, cx)
12602                })
12603                .await;
12604            assert!(handle.is_err());
12605        }
12606    }
12607
12608    #[gpui::test]
12609    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12610        init_test(cx);
12611
12612        let fs = FakeFs::new(cx.executor());
12613        let project = Project::test(fs, [], cx).await;
12614        let (workspace, _cx) =
12615            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12616
12617        // Test with status bar shown (default)
12618        workspace.read_with(cx, |workspace, cx| {
12619            let visible = workspace.status_bar_visible(cx);
12620            assert!(visible, "Status bar should be visible by default");
12621        });
12622
12623        // Test with status bar hidden
12624        cx.update_global(|store: &mut SettingsStore, cx| {
12625            store.update_user_settings(cx, |settings| {
12626                settings.status_bar.get_or_insert_default().show = Some(false);
12627            });
12628        });
12629
12630        workspace.read_with(cx, |workspace, cx| {
12631            let visible = workspace.status_bar_visible(cx);
12632            assert!(!visible, "Status bar should be hidden when show is false");
12633        });
12634
12635        // Test with status bar shown explicitly
12636        cx.update_global(|store: &mut SettingsStore, cx| {
12637            store.update_user_settings(cx, |settings| {
12638                settings.status_bar.get_or_insert_default().show = Some(true);
12639            });
12640        });
12641
12642        workspace.read_with(cx, |workspace, cx| {
12643            let visible = workspace.status_bar_visible(cx);
12644            assert!(visible, "Status bar should be visible when show is true");
12645        });
12646    }
12647
12648    #[gpui::test]
12649    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12650        init_test(cx);
12651
12652        let fs = FakeFs::new(cx.executor());
12653        let project = Project::test(fs, [], cx).await;
12654        let (workspace, cx) =
12655            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12656        let panel = workspace.update_in(cx, |workspace, window, cx| {
12657            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12658            workspace.add_panel(panel.clone(), window, cx);
12659
12660            workspace
12661                .right_dock()
12662                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12663
12664            panel
12665        });
12666
12667        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12668        let item_a = cx.new(TestItem::new);
12669        let item_b = cx.new(TestItem::new);
12670        let item_a_id = item_a.entity_id();
12671        let item_b_id = item_b.entity_id();
12672
12673        pane.update_in(cx, |pane, window, cx| {
12674            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12675            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12676        });
12677
12678        pane.read_with(cx, |pane, _| {
12679            assert_eq!(pane.items_len(), 2);
12680            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12681        });
12682
12683        workspace.update_in(cx, |workspace, window, cx| {
12684            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12685        });
12686
12687        workspace.update_in(cx, |_, window, cx| {
12688            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12689        });
12690
12691        // Assert that the `pane::CloseActiveItem` action is handled at the
12692        // workspace level when one of the dock panels is focused and, in that
12693        // case, the center pane's active item is closed but the focus is not
12694        // moved.
12695        cx.dispatch_action(pane::CloseActiveItem::default());
12696        cx.run_until_parked();
12697
12698        pane.read_with(cx, |pane, _| {
12699            assert_eq!(pane.items_len(), 1);
12700            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12701        });
12702
12703        workspace.update_in(cx, |workspace, window, cx| {
12704            assert!(workspace.right_dock().read(cx).is_open());
12705            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12706        });
12707    }
12708
12709    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
12710        pane.read(cx)
12711            .items()
12712            .flat_map(|item| {
12713                item.project_paths(cx)
12714                    .into_iter()
12715                    .map(|path| path.path.display(PathStyle::local()).into_owned())
12716            })
12717            .collect()
12718    }
12719
12720    pub fn init_test(cx: &mut TestAppContext) {
12721        cx.update(|cx| {
12722            let settings_store = SettingsStore::test(cx);
12723            cx.set_global(settings_store);
12724            theme::init(theme::LoadThemes::JustBase, cx);
12725        });
12726    }
12727
12728    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
12729        let item = TestProjectItem::new(id, path, cx);
12730        item.update(cx, |item, _| {
12731            item.is_dirty = true;
12732        });
12733        item
12734    }
12735}