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