workspace.rs

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