workspace.rs

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