workspace.rs

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