workspace.rs

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