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