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