workspace.rs

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