workspace.rs

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