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