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