workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6mod multi_workspace;
    7pub mod notifications;
    8pub mod pane;
    9pub mod pane_group;
   10pub mod path_list {
   11    pub use util::path_list::{PathList, SerializedPathList};
   12}
   13mod persistence;
   14pub mod searchable;
   15mod security_modal;
   16pub mod shared_screen;
   17use db::smol::future::yield_now;
   18pub use shared_screen::SharedScreen;
   19mod status_bar;
   20pub mod tasks;
   21mod theme_preview;
   22mod toast_layer;
   23mod toolbar;
   24pub mod welcome;
   25mod workspace_settings;
   26
   27pub use crate::notifications::NotificationFrame;
   28pub use dock::Panel;
   29pub use multi_workspace::{
   30    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
   31    NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
   32    ToggleWorkspaceSidebar,
   33};
   34pub use path_list::{PathList, SerializedPathList};
   35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   36
   37use anyhow::{Context as _, Result, anyhow};
   38use client::{
   39    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   40    proto::{self, ErrorCode, PanelId, PeerId},
   41};
   42use collections::{HashMap, HashSet, hash_map};
   43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   44use fs::Fs;
   45use futures::{
   46    Future, FutureExt, StreamExt,
   47    channel::{
   48        mpsc::{self, UnboundedReceiver, UnboundedSender},
   49        oneshot,
   50    },
   51    future::{Shared, try_join_all},
   52};
   53use gpui::{
   54    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   55    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   56    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   57    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   58    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   59    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   60};
   61pub use history_manager::*;
   62pub use item::{
   63    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   64    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   65};
   66use itertools::Itertools;
   67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   68pub use modal_layer::*;
   69use node_runtime::NodeRuntime;
   70use notifications::{
   71    DetachAndPromptErr, Notifications, dismiss_app_notification,
   72    simple_message_notification::MessageNotification,
   73};
   74pub use pane::*;
   75pub use pane_group::{
   76    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   77    SplitDirection,
   78};
   79use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   80pub use persistence::{
   81    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   82    model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
   83    read_serialized_multi_workspaces,
   84};
   85use postage::stream::Stream;
   86use project::{
   87    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   88    WorktreeSettings,
   89    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   90    project_settings::ProjectSettings,
   91    toolchain_store::ToolchainStoreEvent,
   92    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   93};
   94use remote::{
   95    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   96    remote_client::ConnectionIdentifier,
   97};
   98use schemars::JsonSchema;
   99use serde::Deserialize;
  100use session::AppSession;
  101use settings::{
  102    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  103};
  104
  105use sqlez::{
  106    bindable::{Bind, Column, StaticColumnCount},
  107    statement::Statement,
  108};
  109use status_bar::StatusBar;
  110pub use status_bar::StatusItemView;
  111use std::{
  112    any::TypeId,
  113    borrow::Cow,
  114    cell::RefCell,
  115    cmp,
  116    collections::VecDeque,
  117    env,
  118    hash::Hash,
  119    path::{Path, PathBuf},
  120    process::ExitStatus,
  121    rc::Rc,
  122    sync::{
  123        Arc, LazyLock, Weak,
  124        atomic::{AtomicBool, AtomicUsize},
  125    },
  126    time::Duration,
  127};
  128use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  129use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  130pub use toolbar::{
  131    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  132};
  133pub use ui;
  134use ui::{Window, prelude::*};
  135use util::{
  136    ResultExt, TryFutureExt,
  137    paths::{PathStyle, SanitizedPath},
  138    rel_path::RelPath,
  139    serde::default_true,
  140};
  141use uuid::Uuid;
  142pub use workspace_settings::{
  143    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  144    WorkspaceSettings,
  145};
  146use zed_actions::{Spawn, feedback::FileBugReport};
  147
  148use crate::{item::ItemBufferKind, notifications::NotificationId};
  149use crate::{
  150    persistence::{
  151        SerializedAxis,
  152        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  153    },
  154    security_modal::SecurityModal,
  155};
  156
  157pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  158
  159static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  160    env::var("ZED_WINDOW_SIZE")
  161        .ok()
  162        .as_deref()
  163        .and_then(parse_pixel_size_env_var)
  164});
  165
  166static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  167    env::var("ZED_WINDOW_POSITION")
  168        .ok()
  169        .as_deref()
  170        .and_then(parse_pixel_position_env_var)
  171});
  172
  173pub trait TerminalProvider {
  174    fn spawn(
  175        &self,
  176        task: SpawnInTerminal,
  177        window: &mut Window,
  178        cx: &mut App,
  179    ) -> Task<Option<Result<ExitStatus>>>;
  180}
  181
  182pub trait DebuggerProvider {
  183    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  184    fn start_session(
  185        &self,
  186        definition: DebugScenario,
  187        task_context: SharedTaskContext,
  188        active_buffer: Option<Entity<Buffer>>,
  189        worktree_id: Option<WorktreeId>,
  190        window: &mut Window,
  191        cx: &mut App,
  192    );
  193
  194    fn spawn_task_or_modal(
  195        &self,
  196        workspace: &mut Workspace,
  197        action: &Spawn,
  198        window: &mut Window,
  199        cx: &mut Context<Workspace>,
  200    );
  201
  202    fn task_scheduled(&self, cx: &mut App);
  203    fn debug_scenario_scheduled(&self, cx: &mut App);
  204    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  205
  206    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  207}
  208
  209actions!(
  210    workspace,
  211    [
  212        /// Activates the next pane in the workspace.
  213        ActivateNextPane,
  214        /// Activates the previous pane in the workspace.
  215        ActivatePreviousPane,
  216        /// Activates the last pane in the workspace.
  217        ActivateLastPane,
  218        /// Switches to the next window.
  219        ActivateNextWindow,
  220        /// Switches to the previous window.
  221        ActivatePreviousWindow,
  222        /// Adds a folder to the current project.
  223        AddFolderToProject,
  224        /// Clears all notifications.
  225        ClearAllNotifications,
  226        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  227        ClearNavigationHistory,
  228        /// Closes the active dock.
  229        CloseActiveDock,
  230        /// Closes all docks.
  231        CloseAllDocks,
  232        /// Toggles all docks.
  233        ToggleAllDocks,
  234        /// Closes the current window.
  235        CloseWindow,
  236        /// Closes the current project.
  237        CloseProject,
  238        /// Opens the feedback dialog.
  239        Feedback,
  240        /// Follows the next collaborator in the session.
  241        FollowNextCollaborator,
  242        /// Moves the focused panel to the next position.
  243        MoveFocusedPanelToNextPosition,
  244        /// Creates a new file.
  245        NewFile,
  246        /// Creates a new file in a vertical split.
  247        NewFileSplitVertical,
  248        /// Creates a new file in a horizontal split.
  249        NewFileSplitHorizontal,
  250        /// Opens a new search.
  251        NewSearch,
  252        /// Opens a new window.
  253        NewWindow,
  254        /// Opens a file or directory.
  255        Open,
  256        /// Opens multiple files.
  257        OpenFiles,
  258        /// Opens the current location in terminal.
  259        OpenInTerminal,
  260        /// Opens the component preview.
  261        OpenComponentPreview,
  262        /// Reloads the active item.
  263        ReloadActiveItem,
  264        /// Resets the active dock to its default size.
  265        ResetActiveDockSize,
  266        /// Resets all open docks to their default sizes.
  267        ResetOpenDocksSize,
  268        /// Reloads the application
  269        Reload,
  270        /// Saves the current file with a new name.
  271        SaveAs,
  272        /// Saves without formatting.
  273        SaveWithoutFormat,
  274        /// Shuts down all debug adapters.
  275        ShutdownDebugAdapters,
  276        /// Suppresses the current notification.
  277        SuppressNotification,
  278        /// Toggles the bottom dock.
  279        ToggleBottomDock,
  280        /// Toggles centered layout mode.
  281        ToggleCenteredLayout,
  282        /// Toggles edit prediction feature globally for all files.
  283        ToggleEditPrediction,
  284        /// Toggles the left dock.
  285        ToggleLeftDock,
  286        /// Toggles the right dock.
  287        ToggleRightDock,
  288        /// Toggles zoom on the active pane.
  289        ToggleZoom,
  290        /// Toggles read-only mode for the active item (if supported by that item).
  291        ToggleReadOnlyFile,
  292        /// Zooms in on the active pane.
  293        ZoomIn,
  294        /// Zooms out of the active pane.
  295        ZoomOut,
  296        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  297        /// If the modal is shown already, closes it without trusting any worktree.
  298        ToggleWorktreeSecurity,
  299        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  300        /// Requires restart to take effect on already opened projects.
  301        ClearTrustedWorktrees,
  302        /// Stops following a collaborator.
  303        Unfollow,
  304        /// Restores the banner.
  305        RestoreBanner,
  306        /// Toggles expansion of the selected item.
  307        ToggleExpandItem,
  308    ]
  309);
  310
  311/// Activates a specific pane by its index.
  312#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  313#[action(namespace = workspace)]
  314pub struct ActivatePane(pub usize);
  315
  316/// Moves an item to a specific pane by index.
  317#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  318#[action(namespace = workspace)]
  319#[serde(deny_unknown_fields)]
  320pub struct MoveItemToPane {
  321    #[serde(default = "default_1")]
  322    pub destination: usize,
  323    #[serde(default = "default_true")]
  324    pub focus: bool,
  325    #[serde(default)]
  326    pub clone: bool,
  327}
  328
  329fn default_1() -> usize {
  330    1
  331}
  332
  333/// Moves an item to a pane in the specified direction.
  334#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  335#[action(namespace = workspace)]
  336#[serde(deny_unknown_fields)]
  337pub struct MoveItemToPaneInDirection {
  338    #[serde(default = "default_right")]
  339    pub direction: SplitDirection,
  340    #[serde(default = "default_true")]
  341    pub focus: bool,
  342    #[serde(default)]
  343    pub clone: bool,
  344}
  345
  346/// Creates a new file in a split of the desired direction.
  347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  348#[action(namespace = workspace)]
  349#[serde(deny_unknown_fields)]
  350pub struct NewFileSplit(pub SplitDirection);
  351
  352fn default_right() -> SplitDirection {
  353    SplitDirection::Right
  354}
  355
  356/// Saves all open files in the workspace.
  357#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  358#[action(namespace = workspace)]
  359#[serde(deny_unknown_fields)]
  360pub struct SaveAll {
  361    #[serde(default)]
  362    pub save_intent: Option<SaveIntent>,
  363}
  364
  365/// Saves the current file with the specified options.
  366#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  367#[action(namespace = workspace)]
  368#[serde(deny_unknown_fields)]
  369pub struct Save {
  370    #[serde(default)]
  371    pub save_intent: Option<SaveIntent>,
  372}
  373
  374/// Closes all items and panes in the workspace.
  375#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  376#[action(namespace = workspace)]
  377#[serde(deny_unknown_fields)]
  378pub struct CloseAllItemsAndPanes {
  379    #[serde(default)]
  380    pub save_intent: Option<SaveIntent>,
  381}
  382
  383/// Closes all inactive tabs and panes in the workspace.
  384#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  385#[action(namespace = workspace)]
  386#[serde(deny_unknown_fields)]
  387pub struct CloseInactiveTabsAndPanes {
  388    #[serde(default)]
  389    pub save_intent: Option<SaveIntent>,
  390}
  391
  392/// Closes the active item across all panes.
  393#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  394#[action(namespace = workspace)]
  395#[serde(deny_unknown_fields)]
  396pub struct CloseItemInAllPanes {
  397    #[serde(default)]
  398    pub save_intent: Option<SaveIntent>,
  399    #[serde(default)]
  400    pub close_pinned: bool,
  401}
  402
  403/// Sends a sequence of keystrokes to the active element.
  404#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  405#[action(namespace = workspace)]
  406pub struct SendKeystrokes(pub String);
  407
  408actions!(
  409    project_symbols,
  410    [
  411        /// Toggles the project symbols search.
  412        #[action(name = "Toggle")]
  413        ToggleProjectSymbols
  414    ]
  415);
  416
  417/// Toggles the file finder interface.
  418#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  419#[action(namespace = file_finder, name = "Toggle")]
  420#[serde(deny_unknown_fields)]
  421pub struct ToggleFileFinder {
  422    #[serde(default)]
  423    pub separate_history: bool,
  424}
  425
  426/// Opens a new terminal in the center.
  427#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  428#[action(namespace = workspace)]
  429#[serde(deny_unknown_fields)]
  430pub struct NewCenterTerminal {
  431    /// If true, creates a local terminal even in remote projects.
  432    #[serde(default)]
  433    pub local: bool,
  434}
  435
  436/// Opens a new terminal.
  437#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  438#[action(namespace = workspace)]
  439#[serde(deny_unknown_fields)]
  440pub struct NewTerminal {
  441    /// If true, creates a local terminal even in remote projects.
  442    #[serde(default)]
  443    pub local: bool,
  444}
  445
  446/// Increases size of a currently focused dock by a given amount of pixels.
  447#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  448#[action(namespace = workspace)]
  449#[serde(deny_unknown_fields)]
  450pub struct IncreaseActiveDockSize {
  451    /// For 0px parameter, uses UI font size value.
  452    #[serde(default)]
  453    pub px: u32,
  454}
  455
  456/// Decreases size of a currently focused dock by a given amount of pixels.
  457#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  458#[action(namespace = workspace)]
  459#[serde(deny_unknown_fields)]
  460pub struct DecreaseActiveDockSize {
  461    /// For 0px parameter, uses UI font size value.
  462    #[serde(default)]
  463    pub px: u32,
  464}
  465
  466/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  467#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  468#[action(namespace = workspace)]
  469#[serde(deny_unknown_fields)]
  470pub struct IncreaseOpenDocksSize {
  471    /// For 0px parameter, uses UI font size value.
  472    #[serde(default)]
  473    pub px: u32,
  474}
  475
  476/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  477#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  478#[action(namespace = workspace)]
  479#[serde(deny_unknown_fields)]
  480pub struct DecreaseOpenDocksSize {
  481    /// For 0px parameter, uses UI font size value.
  482    #[serde(default)]
  483    pub px: u32,
  484}
  485
  486actions!(
  487    workspace,
  488    [
  489        /// Activates the pane to the left.
  490        ActivatePaneLeft,
  491        /// Activates the pane to the right.
  492        ActivatePaneRight,
  493        /// Activates the pane above.
  494        ActivatePaneUp,
  495        /// Activates the pane below.
  496        ActivatePaneDown,
  497        /// Swaps the current pane with the one to the left.
  498        SwapPaneLeft,
  499        /// Swaps the current pane with the one to the right.
  500        SwapPaneRight,
  501        /// Swaps the current pane with the one above.
  502        SwapPaneUp,
  503        /// Swaps the current pane with the one below.
  504        SwapPaneDown,
  505        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  506        SwapPaneAdjacent,
  507        /// Move the current pane to be at the far left.
  508        MovePaneLeft,
  509        /// Move the current pane to be at the far right.
  510        MovePaneRight,
  511        /// Move the current pane to be at the very top.
  512        MovePaneUp,
  513        /// Move the current pane to be at the very bottom.
  514        MovePaneDown,
  515    ]
  516);
  517
  518#[derive(PartialEq, Eq, Debug)]
  519pub enum CloseIntent {
  520    /// Quit the program entirely.
  521    Quit,
  522    /// Close a window.
  523    CloseWindow,
  524    /// Replace the workspace in an existing window.
  525    ReplaceWindow,
  526}
  527
  528#[derive(Clone)]
  529pub struct Toast {
  530    id: NotificationId,
  531    msg: Cow<'static, str>,
  532    autohide: bool,
  533    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  534}
  535
  536impl Toast {
  537    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  538        Toast {
  539            id,
  540            msg: msg.into(),
  541            on_click: None,
  542            autohide: false,
  543        }
  544    }
  545
  546    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  547    where
  548        M: Into<Cow<'static, str>>,
  549        F: Fn(&mut Window, &mut App) + 'static,
  550    {
  551        self.on_click = Some((message.into(), Arc::new(on_click)));
  552        self
  553    }
  554
  555    pub fn autohide(mut self) -> Self {
  556        self.autohide = true;
  557        self
  558    }
  559}
  560
  561impl PartialEq for Toast {
  562    fn eq(&self, other: &Self) -> bool {
  563        self.id == other.id
  564            && self.msg == other.msg
  565            && self.on_click.is_some() == other.on_click.is_some()
  566    }
  567}
  568
  569/// Opens a new terminal with the specified working directory.
  570#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  571#[action(namespace = workspace)]
  572#[serde(deny_unknown_fields)]
  573pub struct OpenTerminal {
  574    pub working_directory: PathBuf,
  575    /// If true, creates a local terminal even in remote projects.
  576    #[serde(default)]
  577    pub local: bool,
  578}
  579
  580#[derive(
  581    Clone,
  582    Copy,
  583    Debug,
  584    Default,
  585    Hash,
  586    PartialEq,
  587    Eq,
  588    PartialOrd,
  589    Ord,
  590    serde::Serialize,
  591    serde::Deserialize,
  592)]
  593pub struct WorkspaceId(i64);
  594
  595impl WorkspaceId {
  596    pub fn from_i64(value: i64) -> Self {
  597        Self(value)
  598    }
  599}
  600
  601impl StaticColumnCount for WorkspaceId {}
  602impl Bind for WorkspaceId {
  603    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  604        self.0.bind(statement, start_index)
  605    }
  606}
  607impl Column for WorkspaceId {
  608    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  609        i64::column(statement, start_index)
  610            .map(|(i, next_index)| (Self(i), next_index))
  611            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  612    }
  613}
  614impl From<WorkspaceId> for i64 {
  615    fn from(val: WorkspaceId) -> Self {
  616        val.0
  617    }
  618}
  619
  620fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  621    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  622        workspace_window
  623            .update(cx, |multi_workspace, window, cx| {
  624                let workspace = multi_workspace.workspace().clone();
  625                workspace.update(cx, |workspace, cx| {
  626                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  627                });
  628            })
  629            .ok();
  630    } else {
  631        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, cx);
  632        cx.spawn(async move |cx| {
  633            let (window, _) = task.await?;
  634            window.update(cx, |multi_workspace, window, cx| {
  635                window.activate_window();
  636                let workspace = multi_workspace.workspace().clone();
  637                workspace.update(cx, |workspace, cx| {
  638                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  639                });
  640            })?;
  641            anyhow::Ok(())
  642        })
  643        .detach_and_log_err(cx);
  644    }
  645}
  646
  647pub fn prompt_for_open_path_and_open(
  648    workspace: &mut Workspace,
  649    app_state: Arc<AppState>,
  650    options: PathPromptOptions,
  651    window: &mut Window,
  652    cx: &mut Context<Workspace>,
  653) {
  654    let paths = workspace.prompt_for_open_path(
  655        options,
  656        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  657        window,
  658        cx,
  659    );
  660    cx.spawn_in(window, async move |this, cx| {
  661        let Some(paths) = paths.await.log_err().flatten() else {
  662            return;
  663        };
  664        if let Some(task) = this
  665            .update_in(cx, |this, window, cx| {
  666                this.open_workspace_for_paths(false, paths, window, cx)
  667            })
  668            .log_err()
  669        {
  670            task.await.log_err();
  671        }
  672    })
  673    .detach();
  674}
  675
  676pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  677    component::init();
  678    theme_preview::init(cx);
  679    toast_layer::init(cx);
  680    history_manager::init(app_state.fs.clone(), cx);
  681
  682    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  683        .on_action(|_: &Reload, cx| reload(cx))
  684        .on_action({
  685            let app_state = Arc::downgrade(&app_state);
  686            move |_: &Open, cx: &mut App| {
  687                if let Some(app_state) = app_state.upgrade() {
  688                    prompt_and_open_paths(
  689                        app_state,
  690                        PathPromptOptions {
  691                            files: true,
  692                            directories: true,
  693                            multiple: true,
  694                            prompt: None,
  695                        },
  696                        cx,
  697                    );
  698                }
  699            }
  700        })
  701        .on_action({
  702            let app_state = Arc::downgrade(&app_state);
  703            move |_: &OpenFiles, cx: &mut App| {
  704                let directories = cx.can_select_mixed_files_and_dirs();
  705                if let Some(app_state) = app_state.upgrade() {
  706                    prompt_and_open_paths(
  707                        app_state,
  708                        PathPromptOptions {
  709                            files: true,
  710                            directories,
  711                            multiple: true,
  712                            prompt: None,
  713                        },
  714                        cx,
  715                    );
  716                }
  717            }
  718        });
  719}
  720
  721type BuildProjectItemFn =
  722    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  723
  724type BuildProjectItemForPathFn =
  725    fn(
  726        &Entity<Project>,
  727        &ProjectPath,
  728        &mut Window,
  729        &mut App,
  730    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  731
  732#[derive(Clone, Default)]
  733struct ProjectItemRegistry {
  734    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  735    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  736}
  737
  738impl ProjectItemRegistry {
  739    fn register<T: ProjectItem>(&mut self) {
  740        self.build_project_item_fns_by_type.insert(
  741            TypeId::of::<T::Item>(),
  742            |item, project, pane, window, cx| {
  743                let item = item.downcast().unwrap();
  744                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  745                    as Box<dyn ItemHandle>
  746            },
  747        );
  748        self.build_project_item_for_path_fns
  749            .push(|project, project_path, window, cx| {
  750                let project_path = project_path.clone();
  751                let is_file = project
  752                    .read(cx)
  753                    .entry_for_path(&project_path, cx)
  754                    .is_some_and(|entry| entry.is_file());
  755                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  756                let is_local = project.read(cx).is_local();
  757                let project_item =
  758                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  759                let project = project.clone();
  760                Some(window.spawn(cx, async move |cx| {
  761                    match project_item.await.with_context(|| {
  762                        format!(
  763                            "opening project path {:?}",
  764                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  765                        )
  766                    }) {
  767                        Ok(project_item) => {
  768                            let project_item = project_item;
  769                            let project_entry_id: Option<ProjectEntryId> =
  770                                project_item.read_with(cx, project::ProjectItem::entry_id);
  771                            let build_workspace_item = Box::new(
  772                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  773                                    Box::new(cx.new(|cx| {
  774                                        T::for_project_item(
  775                                            project,
  776                                            Some(pane),
  777                                            project_item,
  778                                            window,
  779                                            cx,
  780                                        )
  781                                    })) as Box<dyn ItemHandle>
  782                                },
  783                            ) as Box<_>;
  784                            Ok((project_entry_id, build_workspace_item))
  785                        }
  786                        Err(e) => {
  787                            log::warn!("Failed to open a project item: {e:#}");
  788                            if e.error_code() == ErrorCode::Internal {
  789                                if let Some(abs_path) =
  790                                    entry_abs_path.as_deref().filter(|_| is_file)
  791                                {
  792                                    if let Some(broken_project_item_view) =
  793                                        cx.update(|window, cx| {
  794                                            T::for_broken_project_item(
  795                                                abs_path, is_local, &e, window, cx,
  796                                            )
  797                                        })?
  798                                    {
  799                                        let build_workspace_item = Box::new(
  800                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  801                                                cx.new(|_| broken_project_item_view).boxed_clone()
  802                                            },
  803                                        )
  804                                        as Box<_>;
  805                                        return Ok((None, build_workspace_item));
  806                                    }
  807                                }
  808                            }
  809                            Err(e)
  810                        }
  811                    }
  812                }))
  813            });
  814    }
  815
  816    fn open_path(
  817        &self,
  818        project: &Entity<Project>,
  819        path: &ProjectPath,
  820        window: &mut Window,
  821        cx: &mut App,
  822    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  823        let Some(open_project_item) = self
  824            .build_project_item_for_path_fns
  825            .iter()
  826            .rev()
  827            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  828        else {
  829            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  830        };
  831        open_project_item
  832    }
  833
  834    fn build_item<T: project::ProjectItem>(
  835        &self,
  836        item: Entity<T>,
  837        project: Entity<Project>,
  838        pane: Option<&Pane>,
  839        window: &mut Window,
  840        cx: &mut App,
  841    ) -> Option<Box<dyn ItemHandle>> {
  842        let build = self
  843            .build_project_item_fns_by_type
  844            .get(&TypeId::of::<T>())?;
  845        Some(build(item.into_any(), project, pane, window, cx))
  846    }
  847}
  848
  849type WorkspaceItemBuilder =
  850    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  851
  852impl Global for ProjectItemRegistry {}
  853
  854/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  855/// items will get a chance to open the file, starting from the project item that
  856/// was added last.
  857pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  858    cx.default_global::<ProjectItemRegistry>().register::<I>();
  859}
  860
  861#[derive(Default)]
  862pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  863
  864struct FollowableViewDescriptor {
  865    from_state_proto: fn(
  866        Entity<Workspace>,
  867        ViewId,
  868        &mut Option<proto::view::Variant>,
  869        &mut Window,
  870        &mut App,
  871    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  872    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  873}
  874
  875impl Global for FollowableViewRegistry {}
  876
  877impl FollowableViewRegistry {
  878    pub fn register<I: FollowableItem>(cx: &mut App) {
  879        cx.default_global::<Self>().0.insert(
  880            TypeId::of::<I>(),
  881            FollowableViewDescriptor {
  882                from_state_proto: |workspace, id, state, window, cx| {
  883                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  884                        cx.foreground_executor()
  885                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  886                    })
  887                },
  888                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  889            },
  890        );
  891    }
  892
  893    pub fn from_state_proto(
  894        workspace: Entity<Workspace>,
  895        view_id: ViewId,
  896        mut state: Option<proto::view::Variant>,
  897        window: &mut Window,
  898        cx: &mut App,
  899    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  900        cx.update_default_global(|this: &mut Self, cx| {
  901            this.0.values().find_map(|descriptor| {
  902                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  903            })
  904        })
  905    }
  906
  907    pub fn to_followable_view(
  908        view: impl Into<AnyView>,
  909        cx: &App,
  910    ) -> Option<Box<dyn FollowableItemHandle>> {
  911        let this = cx.try_global::<Self>()?;
  912        let view = view.into();
  913        let descriptor = this.0.get(&view.entity_type())?;
  914        Some((descriptor.to_followable_view)(&view))
  915    }
  916}
  917
  918#[derive(Copy, Clone)]
  919struct SerializableItemDescriptor {
  920    deserialize: fn(
  921        Entity<Project>,
  922        WeakEntity<Workspace>,
  923        WorkspaceId,
  924        ItemId,
  925        &mut Window,
  926        &mut Context<Pane>,
  927    ) -> Task<Result<Box<dyn ItemHandle>>>,
  928    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  929    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  930}
  931
  932#[derive(Default)]
  933struct SerializableItemRegistry {
  934    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  935    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  936}
  937
  938impl Global for SerializableItemRegistry {}
  939
  940impl SerializableItemRegistry {
  941    fn deserialize(
  942        item_kind: &str,
  943        project: Entity<Project>,
  944        workspace: WeakEntity<Workspace>,
  945        workspace_id: WorkspaceId,
  946        item_item: ItemId,
  947        window: &mut Window,
  948        cx: &mut Context<Pane>,
  949    ) -> Task<Result<Box<dyn ItemHandle>>> {
  950        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  951            return Task::ready(Err(anyhow!(
  952                "cannot deserialize {}, descriptor not found",
  953                item_kind
  954            )));
  955        };
  956
  957        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  958    }
  959
  960    fn cleanup(
  961        item_kind: &str,
  962        workspace_id: WorkspaceId,
  963        loaded_items: Vec<ItemId>,
  964        window: &mut Window,
  965        cx: &mut App,
  966    ) -> Task<Result<()>> {
  967        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  968            return Task::ready(Err(anyhow!(
  969                "cannot cleanup {}, descriptor not found",
  970                item_kind
  971            )));
  972        };
  973
  974        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  975    }
  976
  977    fn view_to_serializable_item_handle(
  978        view: AnyView,
  979        cx: &App,
  980    ) -> Option<Box<dyn SerializableItemHandle>> {
  981        let this = cx.try_global::<Self>()?;
  982        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  983        Some((descriptor.view_to_serializable_item)(view))
  984    }
  985
  986    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  987        let this = cx.try_global::<Self>()?;
  988        this.descriptors_by_kind.get(item_kind).copied()
  989    }
  990}
  991
  992pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  993    let serialized_item_kind = I::serialized_item_kind();
  994
  995    let registry = cx.default_global::<SerializableItemRegistry>();
  996    let descriptor = SerializableItemDescriptor {
  997        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  998            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  999            cx.foreground_executor()
 1000                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1001        },
 1002        cleanup: |workspace_id, loaded_items, window, cx| {
 1003            I::cleanup(workspace_id, loaded_items, window, cx)
 1004        },
 1005        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1006    };
 1007    registry
 1008        .descriptors_by_kind
 1009        .insert(Arc::from(serialized_item_kind), descriptor);
 1010    registry
 1011        .descriptors_by_type
 1012        .insert(TypeId::of::<I>(), descriptor);
 1013}
 1014
 1015pub struct AppState {
 1016    pub languages: Arc<LanguageRegistry>,
 1017    pub client: Arc<Client>,
 1018    pub user_store: Entity<UserStore>,
 1019    pub workspace_store: Entity<WorkspaceStore>,
 1020    pub fs: Arc<dyn fs::Fs>,
 1021    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1022    pub node_runtime: NodeRuntime,
 1023    pub session: Entity<AppSession>,
 1024}
 1025
 1026struct GlobalAppState(Weak<AppState>);
 1027
 1028impl Global for GlobalAppState {}
 1029
 1030pub struct WorkspaceStore {
 1031    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1032    client: Arc<Client>,
 1033    _subscriptions: Vec<client::Subscription>,
 1034}
 1035
 1036#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1037pub enum CollaboratorId {
 1038    PeerId(PeerId),
 1039    Agent,
 1040}
 1041
 1042impl From<PeerId> for CollaboratorId {
 1043    fn from(peer_id: PeerId) -> Self {
 1044        CollaboratorId::PeerId(peer_id)
 1045    }
 1046}
 1047
 1048impl From<&PeerId> for CollaboratorId {
 1049    fn from(peer_id: &PeerId) -> Self {
 1050        CollaboratorId::PeerId(*peer_id)
 1051    }
 1052}
 1053
 1054#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1055struct Follower {
 1056    project_id: Option<u64>,
 1057    peer_id: PeerId,
 1058}
 1059
 1060impl AppState {
 1061    #[track_caller]
 1062    pub fn global(cx: &App) -> Weak<Self> {
 1063        cx.global::<GlobalAppState>().0.clone()
 1064    }
 1065    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1066        cx.try_global::<GlobalAppState>()
 1067            .map(|state| state.0.clone())
 1068    }
 1069    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1070        cx.set_global(GlobalAppState(state));
 1071    }
 1072
 1073    #[cfg(any(test, feature = "test-support"))]
 1074    pub fn test(cx: &mut App) -> Arc<Self> {
 1075        use fs::Fs;
 1076        use node_runtime::NodeRuntime;
 1077        use session::Session;
 1078        use settings::SettingsStore;
 1079
 1080        if !cx.has_global::<SettingsStore>() {
 1081            let settings_store = SettingsStore::test(cx);
 1082            cx.set_global(settings_store);
 1083        }
 1084
 1085        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1086        <dyn Fs>::set_global(fs.clone(), cx);
 1087        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1088        let clock = Arc::new(clock::FakeSystemClock::new());
 1089        let http_client = http_client::FakeHttpClient::with_404_response();
 1090        let client = Client::new(clock, http_client, cx);
 1091        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1092        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1093        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1094
 1095        theme::init(theme::LoadThemes::JustBase, cx);
 1096        client::init(&client, cx);
 1097
 1098        Arc::new(Self {
 1099            client,
 1100            fs,
 1101            languages,
 1102            user_store,
 1103            workspace_store,
 1104            node_runtime: NodeRuntime::unavailable(),
 1105            build_window_options: |_, _| Default::default(),
 1106            session,
 1107        })
 1108    }
 1109}
 1110
 1111struct DelayedDebouncedEditAction {
 1112    task: Option<Task<()>>,
 1113    cancel_channel: Option<oneshot::Sender<()>>,
 1114}
 1115
 1116impl DelayedDebouncedEditAction {
 1117    fn new() -> DelayedDebouncedEditAction {
 1118        DelayedDebouncedEditAction {
 1119            task: None,
 1120            cancel_channel: None,
 1121        }
 1122    }
 1123
 1124    fn fire_new<F>(
 1125        &mut self,
 1126        delay: Duration,
 1127        window: &mut Window,
 1128        cx: &mut Context<Workspace>,
 1129        func: F,
 1130    ) where
 1131        F: 'static
 1132            + Send
 1133            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1134    {
 1135        if let Some(channel) = self.cancel_channel.take() {
 1136            _ = channel.send(());
 1137        }
 1138
 1139        let (sender, mut receiver) = oneshot::channel::<()>();
 1140        self.cancel_channel = Some(sender);
 1141
 1142        let previous_task = self.task.take();
 1143        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1144            let mut timer = cx.background_executor().timer(delay).fuse();
 1145            if let Some(previous_task) = previous_task {
 1146                previous_task.await;
 1147            }
 1148
 1149            futures::select_biased! {
 1150                _ = receiver => return,
 1151                    _ = timer => {}
 1152            }
 1153
 1154            if let Some(result) = workspace
 1155                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1156                .log_err()
 1157            {
 1158                result.await.log_err();
 1159            }
 1160        }));
 1161    }
 1162}
 1163
 1164pub enum Event {
 1165    PaneAdded(Entity<Pane>),
 1166    PaneRemoved,
 1167    ItemAdded {
 1168        item: Box<dyn ItemHandle>,
 1169    },
 1170    ActiveItemChanged,
 1171    ItemRemoved {
 1172        item_id: EntityId,
 1173    },
 1174    UserSavedItem {
 1175        pane: WeakEntity<Pane>,
 1176        item: Box<dyn WeakItemHandle>,
 1177        save_intent: SaveIntent,
 1178    },
 1179    ContactRequestedJoin(u64),
 1180    WorkspaceCreated(WeakEntity<Workspace>),
 1181    OpenBundledFile {
 1182        text: Cow<'static, str>,
 1183        title: &'static str,
 1184        language: &'static str,
 1185    },
 1186    ZoomChanged,
 1187    ModalOpened,
 1188    Activate,
 1189}
 1190
 1191#[derive(Debug, Clone)]
 1192pub enum OpenVisible {
 1193    All,
 1194    None,
 1195    OnlyFiles,
 1196    OnlyDirectories,
 1197}
 1198
 1199enum WorkspaceLocation {
 1200    // Valid local paths or SSH project to serialize
 1201    Location(SerializedWorkspaceLocation, PathList),
 1202    // No valid location found hence clear session id
 1203    DetachFromSession,
 1204    // No valid location found to serialize
 1205    None,
 1206}
 1207
 1208type PromptForNewPath = Box<
 1209    dyn Fn(
 1210        &mut Workspace,
 1211        DirectoryLister,
 1212        Option<String>,
 1213        &mut Window,
 1214        &mut Context<Workspace>,
 1215    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1216>;
 1217
 1218type PromptForOpenPath = Box<
 1219    dyn Fn(
 1220        &mut Workspace,
 1221        DirectoryLister,
 1222        &mut Window,
 1223        &mut Context<Workspace>,
 1224    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1225>;
 1226
 1227#[derive(Default)]
 1228struct DispatchingKeystrokes {
 1229    dispatched: HashSet<Vec<Keystroke>>,
 1230    queue: VecDeque<Keystroke>,
 1231    task: Option<Shared<Task<()>>>,
 1232}
 1233
 1234/// Collects everything project-related for a certain window opened.
 1235/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1236///
 1237/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1238/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1239/// that can be used to register a global action to be triggered from any place in the window.
 1240pub struct Workspace {
 1241    weak_self: WeakEntity<Self>,
 1242    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1243    zoomed: Option<AnyWeakView>,
 1244    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1245    zoomed_position: Option<DockPosition>,
 1246    center: PaneGroup,
 1247    left_dock: Entity<Dock>,
 1248    bottom_dock: Entity<Dock>,
 1249    right_dock: Entity<Dock>,
 1250    panes: Vec<Entity<Pane>>,
 1251    active_worktree_override: Option<WorktreeId>,
 1252    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1253    active_pane: Entity<Pane>,
 1254    last_active_center_pane: Option<WeakEntity<Pane>>,
 1255    last_active_view_id: Option<proto::ViewId>,
 1256    status_bar: Entity<StatusBar>,
 1257    pub(crate) modal_layer: Entity<ModalLayer>,
 1258    toast_layer: Entity<ToastLayer>,
 1259    titlebar_item: Option<AnyView>,
 1260    notifications: Notifications,
 1261    suppressed_notifications: HashSet<NotificationId>,
 1262    project: Entity<Project>,
 1263    follower_states: HashMap<CollaboratorId, FollowerState>,
 1264    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1265    window_edited: bool,
 1266    last_window_title: Option<String>,
 1267    dirty_items: HashMap<EntityId, Subscription>,
 1268    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1269    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1270    database_id: Option<WorkspaceId>,
 1271    app_state: Arc<AppState>,
 1272    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1273    _subscriptions: Vec<Subscription>,
 1274    _apply_leader_updates: Task<Result<()>>,
 1275    _observe_current_user: Task<Result<()>>,
 1276    _schedule_serialize_workspace: Option<Task<()>>,
 1277    _serialize_workspace_task: Option<Task<()>>,
 1278    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1279    pane_history_timestamp: Arc<AtomicUsize>,
 1280    bounds: Bounds<Pixels>,
 1281    pub centered_layout: bool,
 1282    bounds_save_task_queued: Option<Task<()>>,
 1283    on_prompt_for_new_path: Option<PromptForNewPath>,
 1284    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1285    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1286    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1287    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1288    _items_serializer: Task<Result<()>>,
 1289    session_id: Option<String>,
 1290    scheduled_tasks: Vec<Task<()>>,
 1291    last_open_dock_positions: Vec<DockPosition>,
 1292    removing: bool,
 1293}
 1294
 1295impl EventEmitter<Event> for Workspace {}
 1296
 1297#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1298pub struct ViewId {
 1299    pub creator: CollaboratorId,
 1300    pub id: u64,
 1301}
 1302
 1303pub struct FollowerState {
 1304    center_pane: Entity<Pane>,
 1305    dock_pane: Option<Entity<Pane>>,
 1306    active_view_id: Option<ViewId>,
 1307    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1308}
 1309
 1310struct FollowerView {
 1311    view: Box<dyn FollowableItemHandle>,
 1312    location: Option<proto::PanelId>,
 1313}
 1314
 1315impl Workspace {
 1316    pub fn new(
 1317        workspace_id: Option<WorkspaceId>,
 1318        project: Entity<Project>,
 1319        app_state: Arc<AppState>,
 1320        window: &mut Window,
 1321        cx: &mut Context<Self>,
 1322    ) -> Self {
 1323        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1324            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1325                if let TrustedWorktreesEvent::Trusted(..) = e {
 1326                    // Do not persist auto trusted worktrees
 1327                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1328                        worktrees_store.update(cx, |worktrees_store, cx| {
 1329                            worktrees_store.schedule_serialization(
 1330                                cx,
 1331                                |new_trusted_worktrees, cx| {
 1332                                    let timeout =
 1333                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1334                                    cx.background_spawn(async move {
 1335                                        timeout.await;
 1336                                        persistence::DB
 1337                                            .save_trusted_worktrees(new_trusted_worktrees)
 1338                                            .await
 1339                                            .log_err();
 1340                                    })
 1341                                },
 1342                            )
 1343                        });
 1344                    }
 1345                }
 1346            })
 1347            .detach();
 1348
 1349            cx.observe_global::<SettingsStore>(|_, cx| {
 1350                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1351                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1352                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1353                            trusted_worktrees.auto_trust_all(cx);
 1354                        })
 1355                    }
 1356                }
 1357            })
 1358            .detach();
 1359        }
 1360
 1361        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1362            match event {
 1363                project::Event::RemoteIdChanged(_) => {
 1364                    this.update_window_title(window, cx);
 1365                }
 1366
 1367                project::Event::CollaboratorLeft(peer_id) => {
 1368                    this.collaborator_left(*peer_id, window, cx);
 1369                }
 1370
 1371                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1372                    this.update_window_title(window, cx);
 1373                    if this
 1374                        .project()
 1375                        .read(cx)
 1376                        .worktree_for_id(id, cx)
 1377                        .is_some_and(|wt| wt.read(cx).is_visible())
 1378                    {
 1379                        this.serialize_workspace(window, cx);
 1380                        this.update_history(cx);
 1381                    }
 1382                }
 1383                project::Event::WorktreeUpdatedEntries(..) => {
 1384                    this.update_window_title(window, cx);
 1385                    this.serialize_workspace(window, cx);
 1386                }
 1387
 1388                project::Event::DisconnectedFromHost => {
 1389                    this.update_window_edited(window, cx);
 1390                    let leaders_to_unfollow =
 1391                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1392                    for leader_id in leaders_to_unfollow {
 1393                        this.unfollow(leader_id, window, cx);
 1394                    }
 1395                }
 1396
 1397                project::Event::DisconnectedFromRemote {
 1398                    server_not_running: _,
 1399                } => {
 1400                    this.update_window_edited(window, cx);
 1401                }
 1402
 1403                project::Event::Closed => {
 1404                    window.remove_window();
 1405                }
 1406
 1407                project::Event::DeletedEntry(_, entry_id) => {
 1408                    for pane in this.panes.iter() {
 1409                        pane.update(cx, |pane, cx| {
 1410                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1411                        });
 1412                    }
 1413                }
 1414
 1415                project::Event::Toast {
 1416                    notification_id,
 1417                    message,
 1418                    link,
 1419                } => this.show_notification(
 1420                    NotificationId::named(notification_id.clone()),
 1421                    cx,
 1422                    |cx| {
 1423                        let mut notification = MessageNotification::new(message.clone(), cx);
 1424                        if let Some(link) = link {
 1425                            notification = notification
 1426                                .more_info_message(link.label)
 1427                                .more_info_url(link.url);
 1428                        }
 1429
 1430                        cx.new(|_| notification)
 1431                    },
 1432                ),
 1433
 1434                project::Event::HideToast { notification_id } => {
 1435                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1436                }
 1437
 1438                project::Event::LanguageServerPrompt(request) => {
 1439                    struct LanguageServerPrompt;
 1440
 1441                    this.show_notification(
 1442                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1443                        cx,
 1444                        |cx| {
 1445                            cx.new(|cx| {
 1446                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1447                            })
 1448                        },
 1449                    );
 1450                }
 1451
 1452                project::Event::AgentLocationChanged => {
 1453                    this.handle_agent_location_changed(window, cx)
 1454                }
 1455
 1456                _ => {}
 1457            }
 1458            cx.notify()
 1459        })
 1460        .detach();
 1461
 1462        cx.subscribe_in(
 1463            &project.read(cx).breakpoint_store(),
 1464            window,
 1465            |workspace, _, event, window, cx| match event {
 1466                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1467                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1468                    workspace.serialize_workspace(window, cx);
 1469                }
 1470                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1471            },
 1472        )
 1473        .detach();
 1474        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1475            cx.subscribe_in(
 1476                &toolchain_store,
 1477                window,
 1478                |workspace, _, event, window, cx| match event {
 1479                    ToolchainStoreEvent::CustomToolchainsModified => {
 1480                        workspace.serialize_workspace(window, cx);
 1481                    }
 1482                    _ => {}
 1483                },
 1484            )
 1485            .detach();
 1486        }
 1487
 1488        cx.on_focus_lost(window, |this, window, cx| {
 1489            let focus_handle = this.focus_handle(cx);
 1490            window.focus(&focus_handle, cx);
 1491        })
 1492        .detach();
 1493
 1494        let weak_handle = cx.entity().downgrade();
 1495        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1496
 1497        let center_pane = cx.new(|cx| {
 1498            let mut center_pane = Pane::new(
 1499                weak_handle.clone(),
 1500                project.clone(),
 1501                pane_history_timestamp.clone(),
 1502                None,
 1503                NewFile.boxed_clone(),
 1504                true,
 1505                window,
 1506                cx,
 1507            );
 1508            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1509            center_pane.set_should_display_welcome_page(true);
 1510            center_pane
 1511        });
 1512        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1513            .detach();
 1514
 1515        window.focus(&center_pane.focus_handle(cx), cx);
 1516
 1517        cx.emit(Event::PaneAdded(center_pane.clone()));
 1518
 1519        let any_window_handle = window.window_handle();
 1520        app_state.workspace_store.update(cx, |store, _| {
 1521            store
 1522                .workspaces
 1523                .insert((any_window_handle, weak_handle.clone()));
 1524        });
 1525
 1526        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1527        let mut connection_status = app_state.client.status();
 1528        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1529            current_user.next().await;
 1530            connection_status.next().await;
 1531            let mut stream =
 1532                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1533
 1534            while stream.recv().await.is_some() {
 1535                this.update(cx, |_, cx| cx.notify())?;
 1536            }
 1537            anyhow::Ok(())
 1538        });
 1539
 1540        // All leader updates are enqueued and then processed in a single task, so
 1541        // that each asynchronous operation can be run in order.
 1542        let (leader_updates_tx, mut leader_updates_rx) =
 1543            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1544        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1545            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1546                Self::process_leader_update(&this, leader_id, update, cx)
 1547                    .await
 1548                    .log_err();
 1549            }
 1550
 1551            Ok(())
 1552        });
 1553
 1554        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1555        let modal_layer = cx.new(|_| ModalLayer::new());
 1556        let toast_layer = cx.new(|_| ToastLayer::new());
 1557        cx.subscribe(
 1558            &modal_layer,
 1559            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1560                cx.emit(Event::ModalOpened);
 1561            },
 1562        )
 1563        .detach();
 1564
 1565        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1566        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1567        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1568        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1569        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1570        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1571        let status_bar = cx.new(|cx| {
 1572            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1573            status_bar.add_left_item(left_dock_buttons, window, cx);
 1574            status_bar.add_right_item(right_dock_buttons, window, cx);
 1575            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1576            status_bar
 1577        });
 1578
 1579        let session_id = app_state.session.read(cx).id().to_owned();
 1580
 1581        let mut active_call = None;
 1582        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1583            let subscriptions =
 1584                vec![
 1585                    call.0
 1586                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1587                ];
 1588            active_call = Some((call, subscriptions));
 1589        }
 1590
 1591        let (serializable_items_tx, serializable_items_rx) =
 1592            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1593        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1594            Self::serialize_items(&this, serializable_items_rx, cx).await
 1595        });
 1596
 1597        let subscriptions = vec![
 1598            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1599            cx.observe_window_bounds(window, move |this, window, cx| {
 1600                if this.bounds_save_task_queued.is_some() {
 1601                    return;
 1602                }
 1603                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1604                    cx.background_executor()
 1605                        .timer(Duration::from_millis(100))
 1606                        .await;
 1607                    this.update_in(cx, |this, window, cx| {
 1608                        this.save_window_bounds(window, cx).detach();
 1609                        this.bounds_save_task_queued.take();
 1610                    })
 1611                    .ok();
 1612                }));
 1613                cx.notify();
 1614            }),
 1615            cx.observe_window_appearance(window, |_, window, cx| {
 1616                let window_appearance = window.appearance();
 1617
 1618                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1619
 1620                GlobalTheme::reload_theme(cx);
 1621                GlobalTheme::reload_icon_theme(cx);
 1622            }),
 1623            cx.on_release({
 1624                let weak_handle = weak_handle.clone();
 1625                move |this, cx| {
 1626                    this.app_state.workspace_store.update(cx, move |store, _| {
 1627                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1628                    })
 1629                }
 1630            }),
 1631        ];
 1632
 1633        cx.defer_in(window, move |this, window, cx| {
 1634            this.update_window_title(window, cx);
 1635            this.show_initial_notifications(cx);
 1636        });
 1637
 1638        let mut center = PaneGroup::new(center_pane.clone());
 1639        center.set_is_center(true);
 1640        center.mark_positions(cx);
 1641
 1642        Workspace {
 1643            weak_self: weak_handle.clone(),
 1644            zoomed: None,
 1645            zoomed_position: None,
 1646            previous_dock_drag_coordinates: None,
 1647            center,
 1648            panes: vec![center_pane.clone()],
 1649            panes_by_item: Default::default(),
 1650            active_pane: center_pane.clone(),
 1651            last_active_center_pane: Some(center_pane.downgrade()),
 1652            last_active_view_id: None,
 1653            status_bar,
 1654            modal_layer,
 1655            toast_layer,
 1656            titlebar_item: None,
 1657            active_worktree_override: None,
 1658            notifications: Notifications::default(),
 1659            suppressed_notifications: HashSet::default(),
 1660            left_dock,
 1661            bottom_dock,
 1662            right_dock,
 1663            project: project.clone(),
 1664            follower_states: Default::default(),
 1665            last_leaders_by_pane: Default::default(),
 1666            dispatching_keystrokes: Default::default(),
 1667            window_edited: false,
 1668            last_window_title: None,
 1669            dirty_items: Default::default(),
 1670            active_call,
 1671            database_id: workspace_id,
 1672            app_state,
 1673            _observe_current_user,
 1674            _apply_leader_updates,
 1675            _schedule_serialize_workspace: None,
 1676            _serialize_workspace_task: None,
 1677            _schedule_serialize_ssh_paths: None,
 1678            leader_updates_tx,
 1679            _subscriptions: subscriptions,
 1680            pane_history_timestamp,
 1681            workspace_actions: Default::default(),
 1682            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1683            bounds: Default::default(),
 1684            centered_layout: false,
 1685            bounds_save_task_queued: None,
 1686            on_prompt_for_new_path: None,
 1687            on_prompt_for_open_path: None,
 1688            terminal_provider: None,
 1689            debugger_provider: None,
 1690            serializable_items_tx,
 1691            _items_serializer,
 1692            session_id: Some(session_id),
 1693
 1694            scheduled_tasks: Vec::new(),
 1695            last_open_dock_positions: Vec::new(),
 1696            removing: false,
 1697        }
 1698    }
 1699
 1700    pub fn new_local(
 1701        abs_paths: Vec<PathBuf>,
 1702        app_state: Arc<AppState>,
 1703        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1704        env: Option<HashMap<String, String>>,
 1705        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1706        cx: &mut App,
 1707    ) -> Task<
 1708        anyhow::Result<(
 1709            WindowHandle<MultiWorkspace>,
 1710            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1711        )>,
 1712    > {
 1713        let project_handle = Project::local(
 1714            app_state.client.clone(),
 1715            app_state.node_runtime.clone(),
 1716            app_state.user_store.clone(),
 1717            app_state.languages.clone(),
 1718            app_state.fs.clone(),
 1719            env,
 1720            Default::default(),
 1721            cx,
 1722        );
 1723
 1724        cx.spawn(async move |cx| {
 1725            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1726            for path in abs_paths.into_iter() {
 1727                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1728                    paths_to_open.push(canonical)
 1729                } else {
 1730                    paths_to_open.push(path)
 1731                }
 1732            }
 1733
 1734            let serialized_workspace =
 1735                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1736
 1737            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1738                paths_to_open = paths.ordered_paths().cloned().collect();
 1739                if !paths.is_lexicographically_ordered() {
 1740                    project_handle.update(cx, |project, cx| {
 1741                        project.set_worktrees_reordered(true, cx);
 1742                    });
 1743                }
 1744            }
 1745
 1746            // Get project paths for all of the abs_paths
 1747            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1748                Vec::with_capacity(paths_to_open.len());
 1749
 1750            for path in paths_to_open.into_iter() {
 1751                if let Some((_, project_entry)) = cx
 1752                    .update(|cx| {
 1753                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1754                    })
 1755                    .await
 1756                    .log_err()
 1757                {
 1758                    project_paths.push((path, Some(project_entry)));
 1759                } else {
 1760                    project_paths.push((path, None));
 1761                }
 1762            }
 1763
 1764            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1765                serialized_workspace.id
 1766            } else {
 1767                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1768            };
 1769
 1770            let toolchains = DB.toolchains(workspace_id).await?;
 1771
 1772            for (toolchain, worktree_path, path) in toolchains {
 1773                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1774                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1775                    this.find_worktree(&worktree_path, cx)
 1776                        .and_then(|(worktree, rel_path)| {
 1777                            if rel_path.is_empty() {
 1778                                Some(worktree.read(cx).id())
 1779                            } else {
 1780                                None
 1781                            }
 1782                        })
 1783                }) else {
 1784                    // We did not find a worktree with a given path, but that's whatever.
 1785                    continue;
 1786                };
 1787                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1788                    continue;
 1789                }
 1790
 1791                project_handle
 1792                    .update(cx, |this, cx| {
 1793                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1794                    })
 1795                    .await;
 1796            }
 1797            if let Some(workspace) = serialized_workspace.as_ref() {
 1798                project_handle.update(cx, |this, cx| {
 1799                    for (scope, toolchains) in &workspace.user_toolchains {
 1800                        for toolchain in toolchains {
 1801                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1802                        }
 1803                    }
 1804                });
 1805            }
 1806
 1807            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1808                if let Some(window) = requesting_window {
 1809                    let centered_layout = serialized_workspace
 1810                        .as_ref()
 1811                        .map(|w| w.centered_layout)
 1812                        .unwrap_or(false);
 1813
 1814                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1815                        let workspace = cx.new(|cx| {
 1816                            let mut workspace = Workspace::new(
 1817                                Some(workspace_id),
 1818                                project_handle.clone(),
 1819                                app_state.clone(),
 1820                                window,
 1821                                cx,
 1822                            );
 1823
 1824                            workspace.centered_layout = centered_layout;
 1825
 1826                            // Call init callback to add items before window renders
 1827                            if let Some(init) = init {
 1828                                init(&mut workspace, window, cx);
 1829                            }
 1830
 1831                            workspace
 1832                        });
 1833                        multi_workspace.activate(workspace.clone(), cx);
 1834                        workspace
 1835                    })?;
 1836                    (window, workspace)
 1837                } else {
 1838                    let window_bounds_override = window_bounds_env_override();
 1839
 1840                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1841                        (Some(WindowBounds::Windowed(bounds)), None)
 1842                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1843                        && let Some(display) = workspace.display
 1844                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1845                    {
 1846                        // Reopening an existing workspace - restore its saved bounds
 1847                        (Some(bounds.0), Some(display))
 1848                    } else if let Some((display, bounds)) =
 1849                        persistence::read_default_window_bounds()
 1850                    {
 1851                        // New or empty workspace - use the last known window bounds
 1852                        (Some(bounds), Some(display))
 1853                    } else {
 1854                        // New window - let GPUI's default_bounds() handle cascading
 1855                        (None, None)
 1856                    };
 1857
 1858                    // Use the serialized workspace to construct the new window
 1859                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1860                    options.window_bounds = window_bounds;
 1861                    let centered_layout = serialized_workspace
 1862                        .as_ref()
 1863                        .map(|w| w.centered_layout)
 1864                        .unwrap_or(false);
 1865                    let window = cx.open_window(options, {
 1866                        let app_state = app_state.clone();
 1867                        let project_handle = project_handle.clone();
 1868                        move |window, cx| {
 1869                            let workspace = cx.new(|cx| {
 1870                                let mut workspace = Workspace::new(
 1871                                    Some(workspace_id),
 1872                                    project_handle,
 1873                                    app_state,
 1874                                    window,
 1875                                    cx,
 1876                                );
 1877                                workspace.centered_layout = centered_layout;
 1878
 1879                                // Call init callback to add items before window renders
 1880                                if let Some(init) = init {
 1881                                    init(&mut workspace, window, cx);
 1882                                }
 1883
 1884                                workspace
 1885                            });
 1886                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1887                        }
 1888                    })?;
 1889                    let workspace =
 1890                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1891                            multi_workspace.workspace().clone()
 1892                        })?;
 1893                    (window, workspace)
 1894                };
 1895
 1896            notify_if_database_failed(window, cx);
 1897            // Check if this is an empty workspace (no paths to open)
 1898            // An empty workspace is one where project_paths is empty
 1899            let is_empty_workspace = project_paths.is_empty();
 1900            // Check if serialized workspace has paths before it's moved
 1901            let serialized_workspace_has_paths = serialized_workspace
 1902                .as_ref()
 1903                .map(|ws| !ws.paths.is_empty())
 1904                .unwrap_or(false);
 1905
 1906            let opened_items = window
 1907                .update(cx, |_, window, cx| {
 1908                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1909                        open_items(serialized_workspace, project_paths, window, cx)
 1910                    })
 1911                })?
 1912                .await
 1913                .unwrap_or_default();
 1914
 1915            // Restore default dock state for empty workspaces
 1916            // Only restore if:
 1917            // 1. This is an empty workspace (no paths), AND
 1918            // 2. The serialized workspace either doesn't exist or has no paths
 1919            if is_empty_workspace && !serialized_workspace_has_paths {
 1920                if let Some(default_docks) = persistence::read_default_dock_state() {
 1921                    window
 1922                        .update(cx, |_, window, cx| {
 1923                            workspace.update(cx, |workspace, cx| {
 1924                                for (dock, serialized_dock) in [
 1925                                    (&workspace.right_dock, &default_docks.right),
 1926                                    (&workspace.left_dock, &default_docks.left),
 1927                                    (&workspace.bottom_dock, &default_docks.bottom),
 1928                                ] {
 1929                                    dock.update(cx, |dock, cx| {
 1930                                        dock.serialized_dock = Some(serialized_dock.clone());
 1931                                        dock.restore_state(window, cx);
 1932                                    });
 1933                                }
 1934                                cx.notify();
 1935                            });
 1936                        })
 1937                        .log_err();
 1938                }
 1939            }
 1940
 1941            window
 1942                .update(cx, |_, _window, cx| {
 1943                    workspace.update(cx, |this: &mut Workspace, cx| {
 1944                        this.update_history(cx);
 1945                    });
 1946                })
 1947                .log_err();
 1948            Ok((window, opened_items))
 1949        })
 1950    }
 1951
 1952    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1953        self.weak_self.clone()
 1954    }
 1955
 1956    pub fn left_dock(&self) -> &Entity<Dock> {
 1957        &self.left_dock
 1958    }
 1959
 1960    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1961        &self.bottom_dock
 1962    }
 1963
 1964    pub fn set_bottom_dock_layout(
 1965        &mut self,
 1966        layout: BottomDockLayout,
 1967        window: &mut Window,
 1968        cx: &mut Context<Self>,
 1969    ) {
 1970        let fs = self.project().read(cx).fs();
 1971        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1972            content.workspace.bottom_dock_layout = Some(layout);
 1973        });
 1974
 1975        cx.notify();
 1976        self.serialize_workspace(window, cx);
 1977    }
 1978
 1979    pub fn right_dock(&self) -> &Entity<Dock> {
 1980        &self.right_dock
 1981    }
 1982
 1983    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1984        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1985    }
 1986
 1987    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1988        match position {
 1989            DockPosition::Left => &self.left_dock,
 1990            DockPosition::Bottom => &self.bottom_dock,
 1991            DockPosition::Right => &self.right_dock,
 1992        }
 1993    }
 1994
 1995    pub fn is_edited(&self) -> bool {
 1996        self.window_edited
 1997    }
 1998
 1999    pub fn add_panel<T: Panel>(
 2000        &mut self,
 2001        panel: Entity<T>,
 2002        window: &mut Window,
 2003        cx: &mut Context<Self>,
 2004    ) {
 2005        let focus_handle = panel.panel_focus_handle(cx);
 2006        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2007            .detach();
 2008
 2009        let dock_position = panel.position(window, cx);
 2010        let dock = self.dock_at_position(dock_position);
 2011
 2012        dock.update(cx, |dock, cx| {
 2013            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2014        });
 2015    }
 2016
 2017    pub fn remove_panel<T: Panel>(
 2018        &mut self,
 2019        panel: &Entity<T>,
 2020        window: &mut Window,
 2021        cx: &mut Context<Self>,
 2022    ) {
 2023        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2024            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2025        }
 2026    }
 2027
 2028    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2029        &self.status_bar
 2030    }
 2031
 2032    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2033        self.status_bar.update(cx, |status_bar, cx| {
 2034            status_bar.set_workspace_sidebar_open(open, cx);
 2035        });
 2036    }
 2037
 2038    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2039        StatusBarSettings::get_global(cx).show
 2040    }
 2041
 2042    pub fn app_state(&self) -> &Arc<AppState> {
 2043        &self.app_state
 2044    }
 2045
 2046    pub fn user_store(&self) -> &Entity<UserStore> {
 2047        &self.app_state.user_store
 2048    }
 2049
 2050    pub fn project(&self) -> &Entity<Project> {
 2051        &self.project
 2052    }
 2053
 2054    pub fn path_style(&self, cx: &App) -> PathStyle {
 2055        self.project.read(cx).path_style(cx)
 2056    }
 2057
 2058    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2059        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2060
 2061        for pane_handle in &self.panes {
 2062            let pane = pane_handle.read(cx);
 2063
 2064            for entry in pane.activation_history() {
 2065                history.insert(
 2066                    entry.entity_id,
 2067                    history
 2068                        .get(&entry.entity_id)
 2069                        .cloned()
 2070                        .unwrap_or(0)
 2071                        .max(entry.timestamp),
 2072                );
 2073            }
 2074        }
 2075
 2076        history
 2077    }
 2078
 2079    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2080        let mut recent_item: Option<Entity<T>> = None;
 2081        let mut recent_timestamp = 0;
 2082        for pane_handle in &self.panes {
 2083            let pane = pane_handle.read(cx);
 2084            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2085                pane.items().map(|item| (item.item_id(), item)).collect();
 2086            for entry in pane.activation_history() {
 2087                if entry.timestamp > recent_timestamp
 2088                    && let Some(&item) = item_map.get(&entry.entity_id)
 2089                    && let Some(typed_item) = item.act_as::<T>(cx)
 2090                {
 2091                    recent_timestamp = entry.timestamp;
 2092                    recent_item = Some(typed_item);
 2093                }
 2094            }
 2095        }
 2096        recent_item
 2097    }
 2098
 2099    pub fn recent_navigation_history_iter(
 2100        &self,
 2101        cx: &App,
 2102    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2103        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2104        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2105
 2106        for pane in &self.panes {
 2107            let pane = pane.read(cx);
 2108
 2109            pane.nav_history()
 2110                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2111                    if let Some(fs_path) = &fs_path {
 2112                        abs_paths_opened
 2113                            .entry(fs_path.clone())
 2114                            .or_default()
 2115                            .insert(project_path.clone());
 2116                    }
 2117                    let timestamp = entry.timestamp;
 2118                    match history.entry(project_path) {
 2119                        hash_map::Entry::Occupied(mut entry) => {
 2120                            let (_, old_timestamp) = entry.get();
 2121                            if &timestamp > old_timestamp {
 2122                                entry.insert((fs_path, timestamp));
 2123                            }
 2124                        }
 2125                        hash_map::Entry::Vacant(entry) => {
 2126                            entry.insert((fs_path, timestamp));
 2127                        }
 2128                    }
 2129                });
 2130
 2131            if let Some(item) = pane.active_item()
 2132                && let Some(project_path) = item.project_path(cx)
 2133            {
 2134                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2135
 2136                if let Some(fs_path) = &fs_path {
 2137                    abs_paths_opened
 2138                        .entry(fs_path.clone())
 2139                        .or_default()
 2140                        .insert(project_path.clone());
 2141                }
 2142
 2143                history.insert(project_path, (fs_path, std::usize::MAX));
 2144            }
 2145        }
 2146
 2147        history
 2148            .into_iter()
 2149            .sorted_by_key(|(_, (_, order))| *order)
 2150            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2151            .rev()
 2152            .filter(move |(history_path, abs_path)| {
 2153                let latest_project_path_opened = abs_path
 2154                    .as_ref()
 2155                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2156                    .and_then(|project_paths| {
 2157                        project_paths
 2158                            .iter()
 2159                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2160                    });
 2161
 2162                latest_project_path_opened.is_none_or(|path| path == history_path)
 2163            })
 2164    }
 2165
 2166    pub fn recent_navigation_history(
 2167        &self,
 2168        limit: Option<usize>,
 2169        cx: &App,
 2170    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2171        self.recent_navigation_history_iter(cx)
 2172            .take(limit.unwrap_or(usize::MAX))
 2173            .collect()
 2174    }
 2175
 2176    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2177        for pane in &self.panes {
 2178            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2179        }
 2180    }
 2181
 2182    fn navigate_history(
 2183        &mut self,
 2184        pane: WeakEntity<Pane>,
 2185        mode: NavigationMode,
 2186        window: &mut Window,
 2187        cx: &mut Context<Workspace>,
 2188    ) -> Task<Result<()>> {
 2189        self.navigate_history_impl(
 2190            pane,
 2191            mode,
 2192            window,
 2193            &mut |history, cx| history.pop(mode, cx),
 2194            cx,
 2195        )
 2196    }
 2197
 2198    fn navigate_tag_history(
 2199        &mut self,
 2200        pane: WeakEntity<Pane>,
 2201        mode: TagNavigationMode,
 2202        window: &mut Window,
 2203        cx: &mut Context<Workspace>,
 2204    ) -> Task<Result<()>> {
 2205        self.navigate_history_impl(
 2206            pane,
 2207            NavigationMode::Normal,
 2208            window,
 2209            &mut |history, _cx| history.pop_tag(mode),
 2210            cx,
 2211        )
 2212    }
 2213
 2214    fn navigate_history_impl(
 2215        &mut self,
 2216        pane: WeakEntity<Pane>,
 2217        mode: NavigationMode,
 2218        window: &mut Window,
 2219        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2220        cx: &mut Context<Workspace>,
 2221    ) -> Task<Result<()>> {
 2222        let to_load = if let Some(pane) = pane.upgrade() {
 2223            pane.update(cx, |pane, cx| {
 2224                window.focus(&pane.focus_handle(cx), cx);
 2225                loop {
 2226                    // Retrieve the weak item handle from the history.
 2227                    let entry = cb(pane.nav_history_mut(), cx)?;
 2228
 2229                    // If the item is still present in this pane, then activate it.
 2230                    if let Some(index) = entry
 2231                        .item
 2232                        .upgrade()
 2233                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2234                    {
 2235                        let prev_active_item_index = pane.active_item_index();
 2236                        pane.nav_history_mut().set_mode(mode);
 2237                        pane.activate_item(index, true, true, window, cx);
 2238                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2239
 2240                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2241                        if let Some(data) = entry.data {
 2242                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2243                        }
 2244
 2245                        if navigated {
 2246                            break None;
 2247                        }
 2248                    } else {
 2249                        // If the item is no longer present in this pane, then retrieve its
 2250                        // path info in order to reopen it.
 2251                        break pane
 2252                            .nav_history()
 2253                            .path_for_item(entry.item.id())
 2254                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2255                    }
 2256                }
 2257            })
 2258        } else {
 2259            None
 2260        };
 2261
 2262        if let Some((project_path, abs_path, entry)) = to_load {
 2263            // If the item was no longer present, then load it again from its previous path, first try the local path
 2264            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2265
 2266            cx.spawn_in(window, async move  |workspace, cx| {
 2267                let open_by_project_path = open_by_project_path.await;
 2268                let mut navigated = false;
 2269                match open_by_project_path
 2270                    .with_context(|| format!("Navigating to {project_path:?}"))
 2271                {
 2272                    Ok((project_entry_id, build_item)) => {
 2273                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2274                            pane.nav_history_mut().set_mode(mode);
 2275                            pane.active_item().map(|p| p.item_id())
 2276                        })?;
 2277
 2278                        pane.update_in(cx, |pane, window, cx| {
 2279                            let item = pane.open_item(
 2280                                project_entry_id,
 2281                                project_path,
 2282                                true,
 2283                                entry.is_preview,
 2284                                true,
 2285                                None,
 2286                                window, cx,
 2287                                build_item,
 2288                            );
 2289                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2290                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2291                            if let Some(data) = entry.data {
 2292                                navigated |= item.navigate(data, window, cx);
 2293                            }
 2294                        })?;
 2295                    }
 2296                    Err(open_by_project_path_e) => {
 2297                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2298                        // and its worktree is now dropped
 2299                        if let Some(abs_path) = abs_path {
 2300                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2301                                pane.nav_history_mut().set_mode(mode);
 2302                                pane.active_item().map(|p| p.item_id())
 2303                            })?;
 2304                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2305                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2306                            })?;
 2307                            match open_by_abs_path
 2308                                .await
 2309                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2310                            {
 2311                                Ok(item) => {
 2312                                    pane.update_in(cx, |pane, window, cx| {
 2313                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2314                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2315                                        if let Some(data) = entry.data {
 2316                                            navigated |= item.navigate(data, window, cx);
 2317                                        }
 2318                                    })?;
 2319                                }
 2320                                Err(open_by_abs_path_e) => {
 2321                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2322                                }
 2323                            }
 2324                        }
 2325                    }
 2326                }
 2327
 2328                if !navigated {
 2329                    workspace
 2330                        .update_in(cx, |workspace, window, cx| {
 2331                            Self::navigate_history(workspace, pane, mode, window, cx)
 2332                        })?
 2333                        .await?;
 2334                }
 2335
 2336                Ok(())
 2337            })
 2338        } else {
 2339            Task::ready(Ok(()))
 2340        }
 2341    }
 2342
 2343    pub fn go_back(
 2344        &mut self,
 2345        pane: WeakEntity<Pane>,
 2346        window: &mut Window,
 2347        cx: &mut Context<Workspace>,
 2348    ) -> Task<Result<()>> {
 2349        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2350    }
 2351
 2352    pub fn go_forward(
 2353        &mut self,
 2354        pane: WeakEntity<Pane>,
 2355        window: &mut Window,
 2356        cx: &mut Context<Workspace>,
 2357    ) -> Task<Result<()>> {
 2358        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2359    }
 2360
 2361    pub fn reopen_closed_item(
 2362        &mut self,
 2363        window: &mut Window,
 2364        cx: &mut Context<Workspace>,
 2365    ) -> Task<Result<()>> {
 2366        self.navigate_history(
 2367            self.active_pane().downgrade(),
 2368            NavigationMode::ReopeningClosedItem,
 2369            window,
 2370            cx,
 2371        )
 2372    }
 2373
 2374    pub fn client(&self) -> &Arc<Client> {
 2375        &self.app_state.client
 2376    }
 2377
 2378    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2379        self.titlebar_item = Some(item);
 2380        cx.notify();
 2381    }
 2382
 2383    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2384        self.on_prompt_for_new_path = Some(prompt)
 2385    }
 2386
 2387    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2388        self.on_prompt_for_open_path = Some(prompt)
 2389    }
 2390
 2391    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2392        self.terminal_provider = Some(Box::new(provider));
 2393    }
 2394
 2395    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2396        self.debugger_provider = Some(Arc::new(provider));
 2397    }
 2398
 2399    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2400        self.debugger_provider.clone()
 2401    }
 2402
 2403    pub fn prompt_for_open_path(
 2404        &mut self,
 2405        path_prompt_options: PathPromptOptions,
 2406        lister: DirectoryLister,
 2407        window: &mut Window,
 2408        cx: &mut Context<Self>,
 2409    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2410        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2411            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2412            let rx = prompt(self, lister, window, cx);
 2413            self.on_prompt_for_open_path = Some(prompt);
 2414            rx
 2415        } else {
 2416            let (tx, rx) = oneshot::channel();
 2417            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2418
 2419            cx.spawn_in(window, async move |workspace, cx| {
 2420                let Ok(result) = abs_path.await else {
 2421                    return Ok(());
 2422                };
 2423
 2424                match result {
 2425                    Ok(result) => {
 2426                        tx.send(result).ok();
 2427                    }
 2428                    Err(err) => {
 2429                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2430                            workspace.show_portal_error(err.to_string(), cx);
 2431                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2432                            let rx = prompt(workspace, lister, window, cx);
 2433                            workspace.on_prompt_for_open_path = Some(prompt);
 2434                            rx
 2435                        })?;
 2436                        if let Ok(path) = rx.await {
 2437                            tx.send(path).ok();
 2438                        }
 2439                    }
 2440                };
 2441                anyhow::Ok(())
 2442            })
 2443            .detach();
 2444
 2445            rx
 2446        }
 2447    }
 2448
 2449    pub fn prompt_for_new_path(
 2450        &mut self,
 2451        lister: DirectoryLister,
 2452        suggested_name: Option<String>,
 2453        window: &mut Window,
 2454        cx: &mut Context<Self>,
 2455    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2456        if self.project.read(cx).is_via_collab()
 2457            || self.project.read(cx).is_via_remote_server()
 2458            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2459        {
 2460            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2461            let rx = prompt(self, lister, suggested_name, window, cx);
 2462            self.on_prompt_for_new_path = Some(prompt);
 2463            return rx;
 2464        }
 2465
 2466        let (tx, rx) = oneshot::channel();
 2467        cx.spawn_in(window, async move |workspace, cx| {
 2468            let abs_path = workspace.update(cx, |workspace, cx| {
 2469                let relative_to = workspace
 2470                    .most_recent_active_path(cx)
 2471                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2472                    .or_else(|| {
 2473                        let project = workspace.project.read(cx);
 2474                        project.visible_worktrees(cx).find_map(|worktree| {
 2475                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2476                        })
 2477                    })
 2478                    .or_else(std::env::home_dir)
 2479                    .unwrap_or_else(|| PathBuf::from(""));
 2480                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2481            })?;
 2482            let abs_path = match abs_path.await? {
 2483                Ok(path) => path,
 2484                Err(err) => {
 2485                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2486                        workspace.show_portal_error(err.to_string(), cx);
 2487
 2488                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2489                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2490                        workspace.on_prompt_for_new_path = Some(prompt);
 2491                        rx
 2492                    })?;
 2493                    if let Ok(path) = rx.await {
 2494                        tx.send(path).ok();
 2495                    }
 2496                    return anyhow::Ok(());
 2497                }
 2498            };
 2499
 2500            tx.send(abs_path.map(|path| vec![path])).ok();
 2501            anyhow::Ok(())
 2502        })
 2503        .detach();
 2504
 2505        rx
 2506    }
 2507
 2508    pub fn titlebar_item(&self) -> Option<AnyView> {
 2509        self.titlebar_item.clone()
 2510    }
 2511
 2512    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2513    /// When set, git-related operations should use this worktree instead of deriving
 2514    /// the active worktree from the focused file.
 2515    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2516        self.active_worktree_override
 2517    }
 2518
 2519    pub fn set_active_worktree_override(
 2520        &mut self,
 2521        worktree_id: Option<WorktreeId>,
 2522        cx: &mut Context<Self>,
 2523    ) {
 2524        self.active_worktree_override = worktree_id;
 2525        cx.notify();
 2526    }
 2527
 2528    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2529        self.active_worktree_override = None;
 2530        cx.notify();
 2531    }
 2532
 2533    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2534    ///
 2535    /// If the given workspace has a local project, then it will be passed
 2536    /// to the callback. Otherwise, a new empty window will be created.
 2537    pub fn with_local_workspace<T, F>(
 2538        &mut self,
 2539        window: &mut Window,
 2540        cx: &mut Context<Self>,
 2541        callback: F,
 2542    ) -> Task<Result<T>>
 2543    where
 2544        T: 'static,
 2545        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2546    {
 2547        if self.project.read(cx).is_local() {
 2548            Task::ready(Ok(callback(self, window, cx)))
 2549        } else {
 2550            let env = self.project.read(cx).cli_environment(cx);
 2551            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2552            cx.spawn_in(window, async move |_vh, cx| {
 2553                let (multi_workspace_window, _) = task.await?;
 2554                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2555                    let workspace = multi_workspace.workspace().clone();
 2556                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2557                })
 2558            })
 2559        }
 2560    }
 2561
 2562    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2563    ///
 2564    /// If the given workspace has a local project, then it will be passed
 2565    /// to the callback. Otherwise, a new empty window will be created.
 2566    pub fn with_local_or_wsl_workspace<T, F>(
 2567        &mut self,
 2568        window: &mut Window,
 2569        cx: &mut Context<Self>,
 2570        callback: F,
 2571    ) -> Task<Result<T>>
 2572    where
 2573        T: 'static,
 2574        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2575    {
 2576        let project = self.project.read(cx);
 2577        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2578            Task::ready(Ok(callback(self, window, cx)))
 2579        } else {
 2580            let env = self.project.read(cx).cli_environment(cx);
 2581            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2582            cx.spawn_in(window, async move |_vh, cx| {
 2583                let (multi_workspace_window, _) = task.await?;
 2584                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2585                    let workspace = multi_workspace.workspace().clone();
 2586                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2587                })
 2588            })
 2589        }
 2590    }
 2591
 2592    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2593        self.project.read(cx).worktrees(cx)
 2594    }
 2595
 2596    pub fn visible_worktrees<'a>(
 2597        &self,
 2598        cx: &'a App,
 2599    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2600        self.project.read(cx).visible_worktrees(cx)
 2601    }
 2602
 2603    #[cfg(any(test, feature = "test-support"))]
 2604    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2605        let futures = self
 2606            .worktrees(cx)
 2607            .filter_map(|worktree| worktree.read(cx).as_local())
 2608            .map(|worktree| worktree.scan_complete())
 2609            .collect::<Vec<_>>();
 2610        async move {
 2611            for future in futures {
 2612                future.await;
 2613            }
 2614        }
 2615    }
 2616
 2617    pub fn close_global(cx: &mut App) {
 2618        cx.defer(|cx| {
 2619            cx.windows().iter().find(|window| {
 2620                window
 2621                    .update(cx, |_, window, _| {
 2622                        if window.is_window_active() {
 2623                            //This can only get called when the window's project connection has been lost
 2624                            //so we don't need to prompt the user for anything and instead just close the window
 2625                            window.remove_window();
 2626                            true
 2627                        } else {
 2628                            false
 2629                        }
 2630                    })
 2631                    .unwrap_or(false)
 2632            });
 2633        });
 2634    }
 2635
 2636    pub fn move_focused_panel_to_next_position(
 2637        &mut self,
 2638        _: &MoveFocusedPanelToNextPosition,
 2639        window: &mut Window,
 2640        cx: &mut Context<Self>,
 2641    ) {
 2642        let docks = self.all_docks();
 2643        let active_dock = docks
 2644            .into_iter()
 2645            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2646
 2647        if let Some(dock) = active_dock {
 2648            dock.update(cx, |dock, cx| {
 2649                let active_panel = dock
 2650                    .active_panel()
 2651                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2652
 2653                if let Some(panel) = active_panel {
 2654                    panel.move_to_next_position(window, cx);
 2655                }
 2656            })
 2657        }
 2658    }
 2659
 2660    pub fn prepare_to_close(
 2661        &mut self,
 2662        close_intent: CloseIntent,
 2663        window: &mut Window,
 2664        cx: &mut Context<Self>,
 2665    ) -> Task<Result<bool>> {
 2666        let active_call = self.active_global_call();
 2667
 2668        cx.spawn_in(window, async move |this, cx| {
 2669            this.update(cx, |this, _| {
 2670                if close_intent == CloseIntent::CloseWindow {
 2671                    this.removing = true;
 2672                }
 2673            })?;
 2674
 2675            let workspace_count = cx.update(|_window, cx| {
 2676                cx.windows()
 2677                    .iter()
 2678                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2679                    .count()
 2680            })?;
 2681
 2682            #[cfg(target_os = "macos")]
 2683            let save_last_workspace = false;
 2684
 2685            // On Linux and Windows, closing the last window should restore the last workspace.
 2686            #[cfg(not(target_os = "macos"))]
 2687            let save_last_workspace = {
 2688                let remaining_workspaces = cx.update(|_window, cx| {
 2689                    cx.windows()
 2690                        .iter()
 2691                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2692                        .filter_map(|multi_workspace| {
 2693                            multi_workspace
 2694                                .update(cx, |multi_workspace, _, cx| {
 2695                                    multi_workspace.workspace().read(cx).removing
 2696                                })
 2697                                .ok()
 2698                        })
 2699                        .filter(|removing| !removing)
 2700                        .count()
 2701                })?;
 2702
 2703                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2704            };
 2705
 2706            if let Some(active_call) = active_call
 2707                && workspace_count == 1
 2708                && cx
 2709                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2710                    .unwrap_or(false)
 2711            {
 2712                if close_intent == CloseIntent::CloseWindow {
 2713                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2714                    let answer = cx.update(|window, cx| {
 2715                        window.prompt(
 2716                            PromptLevel::Warning,
 2717                            "Do you want to leave the current call?",
 2718                            None,
 2719                            &["Close window and hang up", "Cancel"],
 2720                            cx,
 2721                        )
 2722                    })?;
 2723
 2724                    if answer.await.log_err() == Some(1) {
 2725                        return anyhow::Ok(false);
 2726                    } else {
 2727                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2728                            task.await.log_err();
 2729                        }
 2730                    }
 2731                }
 2732                if close_intent == CloseIntent::ReplaceWindow {
 2733                    _ = cx.update(|_window, cx| {
 2734                        let multi_workspace = cx
 2735                            .windows()
 2736                            .iter()
 2737                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2738                            .next()
 2739                            .unwrap();
 2740                        let project = multi_workspace
 2741                            .read(cx)?
 2742                            .workspace()
 2743                            .read(cx)
 2744                            .project
 2745                            .clone();
 2746                        if project.read(cx).is_shared() {
 2747                            active_call.0.unshare_project(project, cx)?;
 2748                        }
 2749                        Ok::<_, anyhow::Error>(())
 2750                    });
 2751                }
 2752            }
 2753
 2754            let save_result = this
 2755                .update_in(cx, |this, window, cx| {
 2756                    this.save_all_internal(SaveIntent::Close, window, cx)
 2757                })?
 2758                .await;
 2759
 2760            // If we're not quitting, but closing, we remove the workspace from
 2761            // the current session.
 2762            if close_intent != CloseIntent::Quit
 2763                && !save_last_workspace
 2764                && save_result.as_ref().is_ok_and(|&res| res)
 2765            {
 2766                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2767                    .await;
 2768            }
 2769
 2770            save_result
 2771        })
 2772    }
 2773
 2774    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2775        self.save_all_internal(
 2776            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2777            window,
 2778            cx,
 2779        )
 2780        .detach_and_log_err(cx);
 2781    }
 2782
 2783    fn send_keystrokes(
 2784        &mut self,
 2785        action: &SendKeystrokes,
 2786        window: &mut Window,
 2787        cx: &mut Context<Self>,
 2788    ) {
 2789        let keystrokes: Vec<Keystroke> = action
 2790            .0
 2791            .split(' ')
 2792            .flat_map(|k| Keystroke::parse(k).log_err())
 2793            .map(|k| {
 2794                cx.keyboard_mapper()
 2795                    .map_key_equivalent(k, false)
 2796                    .inner()
 2797                    .clone()
 2798            })
 2799            .collect();
 2800        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2801    }
 2802
 2803    pub fn send_keystrokes_impl(
 2804        &mut self,
 2805        keystrokes: Vec<Keystroke>,
 2806        window: &mut Window,
 2807        cx: &mut Context<Self>,
 2808    ) -> Shared<Task<()>> {
 2809        let mut state = self.dispatching_keystrokes.borrow_mut();
 2810        if !state.dispatched.insert(keystrokes.clone()) {
 2811            cx.propagate();
 2812            return state.task.clone().unwrap();
 2813        }
 2814
 2815        state.queue.extend(keystrokes);
 2816
 2817        let keystrokes = self.dispatching_keystrokes.clone();
 2818        if state.task.is_none() {
 2819            state.task = Some(
 2820                window
 2821                    .spawn(cx, async move |cx| {
 2822                        // limit to 100 keystrokes to avoid infinite recursion.
 2823                        for _ in 0..100 {
 2824                            let keystroke = {
 2825                                let mut state = keystrokes.borrow_mut();
 2826                                let Some(keystroke) = state.queue.pop_front() else {
 2827                                    state.dispatched.clear();
 2828                                    state.task.take();
 2829                                    return;
 2830                                };
 2831                                keystroke
 2832                            };
 2833                            cx.update(|window, cx| {
 2834                                let focused = window.focused(cx);
 2835                                window.dispatch_keystroke(keystroke.clone(), cx);
 2836                                if window.focused(cx) != focused {
 2837                                    // dispatch_keystroke may cause the focus to change.
 2838                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2839                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2840                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2841                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2842                                    // )
 2843                                    window.draw(cx).clear();
 2844                                }
 2845                            })
 2846                            .ok();
 2847
 2848                            // Yield between synthetic keystrokes so deferred focus and
 2849                            // other effects can settle before dispatching the next key.
 2850                            yield_now().await;
 2851                        }
 2852
 2853                        *keystrokes.borrow_mut() = Default::default();
 2854                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2855                    })
 2856                    .shared(),
 2857            );
 2858        }
 2859        state.task.clone().unwrap()
 2860    }
 2861
 2862    fn save_all_internal(
 2863        &mut self,
 2864        mut save_intent: SaveIntent,
 2865        window: &mut Window,
 2866        cx: &mut Context<Self>,
 2867    ) -> Task<Result<bool>> {
 2868        if self.project.read(cx).is_disconnected(cx) {
 2869            return Task::ready(Ok(true));
 2870        }
 2871        let dirty_items = self
 2872            .panes
 2873            .iter()
 2874            .flat_map(|pane| {
 2875                pane.read(cx).items().filter_map(|item| {
 2876                    if item.is_dirty(cx) {
 2877                        item.tab_content_text(0, cx);
 2878                        Some((pane.downgrade(), item.boxed_clone()))
 2879                    } else {
 2880                        None
 2881                    }
 2882                })
 2883            })
 2884            .collect::<Vec<_>>();
 2885
 2886        let project = self.project.clone();
 2887        cx.spawn_in(window, async move |workspace, cx| {
 2888            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2889                let (serialize_tasks, remaining_dirty_items) =
 2890                    workspace.update_in(cx, |workspace, window, cx| {
 2891                        let mut remaining_dirty_items = Vec::new();
 2892                        let mut serialize_tasks = Vec::new();
 2893                        for (pane, item) in dirty_items {
 2894                            if let Some(task) = item
 2895                                .to_serializable_item_handle(cx)
 2896                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2897                            {
 2898                                serialize_tasks.push(task);
 2899                            } else {
 2900                                remaining_dirty_items.push((pane, item));
 2901                            }
 2902                        }
 2903                        (serialize_tasks, remaining_dirty_items)
 2904                    })?;
 2905
 2906                futures::future::try_join_all(serialize_tasks).await?;
 2907
 2908                if !remaining_dirty_items.is_empty() {
 2909                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2910                }
 2911
 2912                if remaining_dirty_items.len() > 1 {
 2913                    let answer = workspace.update_in(cx, |_, window, cx| {
 2914                        let detail = Pane::file_names_for_prompt(
 2915                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2916                            cx,
 2917                        );
 2918                        window.prompt(
 2919                            PromptLevel::Warning,
 2920                            "Do you want to save all changes in the following files?",
 2921                            Some(&detail),
 2922                            &["Save all", "Discard all", "Cancel"],
 2923                            cx,
 2924                        )
 2925                    })?;
 2926                    match answer.await.log_err() {
 2927                        Some(0) => save_intent = SaveIntent::SaveAll,
 2928                        Some(1) => save_intent = SaveIntent::Skip,
 2929                        Some(2) => return Ok(false),
 2930                        _ => {}
 2931                    }
 2932                }
 2933
 2934                remaining_dirty_items
 2935            } else {
 2936                dirty_items
 2937            };
 2938
 2939            for (pane, item) in dirty_items {
 2940                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2941                    (
 2942                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2943                        item.project_entry_ids(cx),
 2944                    )
 2945                })?;
 2946                if (singleton || !project_entry_ids.is_empty())
 2947                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2948                {
 2949                    return Ok(false);
 2950                }
 2951            }
 2952            Ok(true)
 2953        })
 2954    }
 2955
 2956    pub fn open_workspace_for_paths(
 2957        &mut self,
 2958        replace_current_window: bool,
 2959        paths: Vec<PathBuf>,
 2960        window: &mut Window,
 2961        cx: &mut Context<Self>,
 2962    ) -> Task<Result<()>> {
 2963        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 2964        let is_remote = self.project.read(cx).is_via_collab();
 2965        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2966        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2967
 2968        let window_to_replace = if replace_current_window {
 2969            window_handle
 2970        } else if is_remote || has_worktree || has_dirty_items {
 2971            None
 2972        } else {
 2973            window_handle
 2974        };
 2975        let app_state = self.app_state.clone();
 2976
 2977        cx.spawn(async move |_, cx| {
 2978            cx.update(|cx| {
 2979                open_paths(
 2980                    &paths,
 2981                    app_state,
 2982                    OpenOptions {
 2983                        replace_window: window_to_replace,
 2984                        ..Default::default()
 2985                    },
 2986                    cx,
 2987                )
 2988            })
 2989            .await?;
 2990            Ok(())
 2991        })
 2992    }
 2993
 2994    #[allow(clippy::type_complexity)]
 2995    pub fn open_paths(
 2996        &mut self,
 2997        mut abs_paths: Vec<PathBuf>,
 2998        options: OpenOptions,
 2999        pane: Option<WeakEntity<Pane>>,
 3000        window: &mut Window,
 3001        cx: &mut Context<Self>,
 3002    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3003        let fs = self.app_state.fs.clone();
 3004
 3005        let caller_ordered_abs_paths = abs_paths.clone();
 3006
 3007        // Sort the paths to ensure we add worktrees for parents before their children.
 3008        abs_paths.sort_unstable();
 3009        cx.spawn_in(window, async move |this, cx| {
 3010            let mut tasks = Vec::with_capacity(abs_paths.len());
 3011
 3012            for abs_path in &abs_paths {
 3013                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3014                    OpenVisible::All => Some(true),
 3015                    OpenVisible::None => Some(false),
 3016                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3017                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3018                        Some(None) => Some(true),
 3019                        None => None,
 3020                    },
 3021                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3022                        Some(Some(metadata)) => Some(metadata.is_dir),
 3023                        Some(None) => Some(false),
 3024                        None => None,
 3025                    },
 3026                };
 3027                let project_path = match visible {
 3028                    Some(visible) => match this
 3029                        .update(cx, |this, cx| {
 3030                            Workspace::project_path_for_path(
 3031                                this.project.clone(),
 3032                                abs_path,
 3033                                visible,
 3034                                cx,
 3035                            )
 3036                        })
 3037                        .log_err()
 3038                    {
 3039                        Some(project_path) => project_path.await.log_err(),
 3040                        None => None,
 3041                    },
 3042                    None => None,
 3043                };
 3044
 3045                let this = this.clone();
 3046                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3047                let fs = fs.clone();
 3048                let pane = pane.clone();
 3049                let task = cx.spawn(async move |cx| {
 3050                    let (_worktree, project_path) = project_path?;
 3051                    if fs.is_dir(&abs_path).await {
 3052                        // Opening a directory should not race to update the active entry.
 3053                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3054                        None
 3055                    } else {
 3056                        Some(
 3057                            this.update_in(cx, |this, window, cx| {
 3058                                this.open_path(
 3059                                    project_path,
 3060                                    pane,
 3061                                    options.focus.unwrap_or(true),
 3062                                    window,
 3063                                    cx,
 3064                                )
 3065                            })
 3066                            .ok()?
 3067                            .await,
 3068                        )
 3069                    }
 3070                });
 3071                tasks.push(task);
 3072            }
 3073
 3074            let results = futures::future::join_all(tasks).await;
 3075
 3076            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3077            let mut winner: Option<(PathBuf, bool)> = None;
 3078            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3079                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3080                    if !metadata.is_dir {
 3081                        winner = Some((abs_path, false));
 3082                        break;
 3083                    }
 3084                    if winner.is_none() {
 3085                        winner = Some((abs_path, true));
 3086                    }
 3087                } else if winner.is_none() {
 3088                    winner = Some((abs_path, false));
 3089                }
 3090            }
 3091
 3092            // Compute the winner entry id on the foreground thread and emit once, after all
 3093            // paths finish opening. This avoids races between concurrently-opening paths
 3094            // (directories in particular) and makes the resulting project panel selection
 3095            // deterministic.
 3096            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3097                'emit_winner: {
 3098                    let winner_abs_path: Arc<Path> =
 3099                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3100
 3101                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3102                        OpenVisible::All => true,
 3103                        OpenVisible::None => false,
 3104                        OpenVisible::OnlyFiles => !winner_is_dir,
 3105                        OpenVisible::OnlyDirectories => winner_is_dir,
 3106                    };
 3107
 3108                    let Some(worktree_task) = this
 3109                        .update(cx, |workspace, cx| {
 3110                            workspace.project.update(cx, |project, cx| {
 3111                                project.find_or_create_worktree(
 3112                                    winner_abs_path.as_ref(),
 3113                                    visible,
 3114                                    cx,
 3115                                )
 3116                            })
 3117                        })
 3118                        .ok()
 3119                    else {
 3120                        break 'emit_winner;
 3121                    };
 3122
 3123                    let Ok((worktree, _)) = worktree_task.await else {
 3124                        break 'emit_winner;
 3125                    };
 3126
 3127                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3128                        let worktree = worktree.read(cx);
 3129                        let worktree_abs_path = worktree.abs_path();
 3130                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3131                            worktree.root_entry()
 3132                        } else {
 3133                            winner_abs_path
 3134                                .strip_prefix(worktree_abs_path.as_ref())
 3135                                .ok()
 3136                                .and_then(|relative_path| {
 3137                                    let relative_path =
 3138                                        RelPath::new(relative_path, PathStyle::local())
 3139                                            .log_err()?;
 3140                                    worktree.entry_for_path(&relative_path)
 3141                                })
 3142                        }?;
 3143                        Some(entry.id)
 3144                    }) else {
 3145                        break 'emit_winner;
 3146                    };
 3147
 3148                    this.update(cx, |workspace, cx| {
 3149                        workspace.project.update(cx, |_, cx| {
 3150                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3151                        });
 3152                    })
 3153                    .ok();
 3154                }
 3155            }
 3156
 3157            results
 3158        })
 3159    }
 3160
 3161    pub fn open_resolved_path(
 3162        &mut self,
 3163        path: ResolvedPath,
 3164        window: &mut Window,
 3165        cx: &mut Context<Self>,
 3166    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3167        match path {
 3168            ResolvedPath::ProjectPath { project_path, .. } => {
 3169                self.open_path(project_path, None, true, window, cx)
 3170            }
 3171            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3172                PathBuf::from(path),
 3173                OpenOptions {
 3174                    visible: Some(OpenVisible::None),
 3175                    ..Default::default()
 3176                },
 3177                window,
 3178                cx,
 3179            ),
 3180        }
 3181    }
 3182
 3183    pub fn absolute_path_of_worktree(
 3184        &self,
 3185        worktree_id: WorktreeId,
 3186        cx: &mut Context<Self>,
 3187    ) -> Option<PathBuf> {
 3188        self.project
 3189            .read(cx)
 3190            .worktree_for_id(worktree_id, cx)
 3191            // TODO: use `abs_path` or `root_dir`
 3192            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3193    }
 3194
 3195    fn add_folder_to_project(
 3196        &mut self,
 3197        _: &AddFolderToProject,
 3198        window: &mut Window,
 3199        cx: &mut Context<Self>,
 3200    ) {
 3201        let project = self.project.read(cx);
 3202        if project.is_via_collab() {
 3203            self.show_error(
 3204                &anyhow!("You cannot add folders to someone else's project"),
 3205                cx,
 3206            );
 3207            return;
 3208        }
 3209        let paths = self.prompt_for_open_path(
 3210            PathPromptOptions {
 3211                files: false,
 3212                directories: true,
 3213                multiple: true,
 3214                prompt: None,
 3215            },
 3216            DirectoryLister::Project(self.project.clone()),
 3217            window,
 3218            cx,
 3219        );
 3220        cx.spawn_in(window, async move |this, cx| {
 3221            if let Some(paths) = paths.await.log_err().flatten() {
 3222                let results = this
 3223                    .update_in(cx, |this, window, cx| {
 3224                        this.open_paths(
 3225                            paths,
 3226                            OpenOptions {
 3227                                visible: Some(OpenVisible::All),
 3228                                ..Default::default()
 3229                            },
 3230                            None,
 3231                            window,
 3232                            cx,
 3233                        )
 3234                    })?
 3235                    .await;
 3236                for result in results.into_iter().flatten() {
 3237                    result.log_err();
 3238                }
 3239            }
 3240            anyhow::Ok(())
 3241        })
 3242        .detach_and_log_err(cx);
 3243    }
 3244
 3245    pub fn project_path_for_path(
 3246        project: Entity<Project>,
 3247        abs_path: &Path,
 3248        visible: bool,
 3249        cx: &mut App,
 3250    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3251        let entry = project.update(cx, |project, cx| {
 3252            project.find_or_create_worktree(abs_path, visible, cx)
 3253        });
 3254        cx.spawn(async move |cx| {
 3255            let (worktree, path) = entry.await?;
 3256            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3257            Ok((worktree, ProjectPath { worktree_id, path }))
 3258        })
 3259    }
 3260
 3261    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3262        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3263    }
 3264
 3265    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3266        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3267    }
 3268
 3269    pub fn items_of_type<'a, T: Item>(
 3270        &'a self,
 3271        cx: &'a App,
 3272    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3273        self.panes
 3274            .iter()
 3275            .flat_map(|pane| pane.read(cx).items_of_type())
 3276    }
 3277
 3278    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3279        self.active_pane().read(cx).active_item()
 3280    }
 3281
 3282    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3283        let item = self.active_item(cx)?;
 3284        item.to_any_view().downcast::<I>().ok()
 3285    }
 3286
 3287    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3288        self.active_item(cx).and_then(|item| item.project_path(cx))
 3289    }
 3290
 3291    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3292        self.recent_navigation_history_iter(cx)
 3293            .filter_map(|(path, abs_path)| {
 3294                let worktree = self
 3295                    .project
 3296                    .read(cx)
 3297                    .worktree_for_id(path.worktree_id, cx)?;
 3298                if worktree.read(cx).is_visible() {
 3299                    abs_path
 3300                } else {
 3301                    None
 3302                }
 3303            })
 3304            .next()
 3305    }
 3306
 3307    pub fn save_active_item(
 3308        &mut self,
 3309        save_intent: SaveIntent,
 3310        window: &mut Window,
 3311        cx: &mut App,
 3312    ) -> Task<Result<()>> {
 3313        let project = self.project.clone();
 3314        let pane = self.active_pane();
 3315        let item = pane.read(cx).active_item();
 3316        let pane = pane.downgrade();
 3317
 3318        window.spawn(cx, async move |cx| {
 3319            if let Some(item) = item {
 3320                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3321                    .await
 3322                    .map(|_| ())
 3323            } else {
 3324                Ok(())
 3325            }
 3326        })
 3327    }
 3328
 3329    pub fn close_inactive_items_and_panes(
 3330        &mut self,
 3331        action: &CloseInactiveTabsAndPanes,
 3332        window: &mut Window,
 3333        cx: &mut Context<Self>,
 3334    ) {
 3335        if let Some(task) = self.close_all_internal(
 3336            true,
 3337            action.save_intent.unwrap_or(SaveIntent::Close),
 3338            window,
 3339            cx,
 3340        ) {
 3341            task.detach_and_log_err(cx)
 3342        }
 3343    }
 3344
 3345    pub fn close_all_items_and_panes(
 3346        &mut self,
 3347        action: &CloseAllItemsAndPanes,
 3348        window: &mut Window,
 3349        cx: &mut Context<Self>,
 3350    ) {
 3351        if let Some(task) = self.close_all_internal(
 3352            false,
 3353            action.save_intent.unwrap_or(SaveIntent::Close),
 3354            window,
 3355            cx,
 3356        ) {
 3357            task.detach_and_log_err(cx)
 3358        }
 3359    }
 3360
 3361    /// Closes the active item across all panes.
 3362    pub fn close_item_in_all_panes(
 3363        &mut self,
 3364        action: &CloseItemInAllPanes,
 3365        window: &mut Window,
 3366        cx: &mut Context<Self>,
 3367    ) {
 3368        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3369            return;
 3370        };
 3371
 3372        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3373        let close_pinned = action.close_pinned;
 3374
 3375        if let Some(project_path) = active_item.project_path(cx) {
 3376            self.close_items_with_project_path(
 3377                &project_path,
 3378                save_intent,
 3379                close_pinned,
 3380                window,
 3381                cx,
 3382            );
 3383        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3384            let item_id = active_item.item_id();
 3385            self.active_pane().update(cx, |pane, cx| {
 3386                pane.close_item_by_id(item_id, save_intent, window, cx)
 3387                    .detach_and_log_err(cx);
 3388            });
 3389        }
 3390    }
 3391
 3392    /// Closes all items with the given project path across all panes.
 3393    pub fn close_items_with_project_path(
 3394        &mut self,
 3395        project_path: &ProjectPath,
 3396        save_intent: SaveIntent,
 3397        close_pinned: bool,
 3398        window: &mut Window,
 3399        cx: &mut Context<Self>,
 3400    ) {
 3401        let panes = self.panes().to_vec();
 3402        for pane in panes {
 3403            pane.update(cx, |pane, cx| {
 3404                pane.close_items_for_project_path(
 3405                    project_path,
 3406                    save_intent,
 3407                    close_pinned,
 3408                    window,
 3409                    cx,
 3410                )
 3411                .detach_and_log_err(cx);
 3412            });
 3413        }
 3414    }
 3415
 3416    fn close_all_internal(
 3417        &mut self,
 3418        retain_active_pane: bool,
 3419        save_intent: SaveIntent,
 3420        window: &mut Window,
 3421        cx: &mut Context<Self>,
 3422    ) -> Option<Task<Result<()>>> {
 3423        let current_pane = self.active_pane();
 3424
 3425        let mut tasks = Vec::new();
 3426
 3427        if retain_active_pane {
 3428            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3429                pane.close_other_items(
 3430                    &CloseOtherItems {
 3431                        save_intent: None,
 3432                        close_pinned: false,
 3433                    },
 3434                    None,
 3435                    window,
 3436                    cx,
 3437                )
 3438            });
 3439
 3440            tasks.push(current_pane_close);
 3441        }
 3442
 3443        for pane in self.panes() {
 3444            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3445                continue;
 3446            }
 3447
 3448            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3449                pane.close_all_items(
 3450                    &CloseAllItems {
 3451                        save_intent: Some(save_intent),
 3452                        close_pinned: false,
 3453                    },
 3454                    window,
 3455                    cx,
 3456                )
 3457            });
 3458
 3459            tasks.push(close_pane_items)
 3460        }
 3461
 3462        if tasks.is_empty() {
 3463            None
 3464        } else {
 3465            Some(cx.spawn_in(window, async move |_, _| {
 3466                for task in tasks {
 3467                    task.await?
 3468                }
 3469                Ok(())
 3470            }))
 3471        }
 3472    }
 3473
 3474    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3475        self.dock_at_position(position).read(cx).is_open()
 3476    }
 3477
 3478    pub fn toggle_dock(
 3479        &mut self,
 3480        dock_side: DockPosition,
 3481        window: &mut Window,
 3482        cx: &mut Context<Self>,
 3483    ) {
 3484        let mut focus_center = false;
 3485        let mut reveal_dock = false;
 3486
 3487        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3488        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3489
 3490        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3491            telemetry::event!(
 3492                "Panel Button Clicked",
 3493                name = panel.persistent_name(),
 3494                toggle_state = !was_visible
 3495            );
 3496        }
 3497        if was_visible {
 3498            self.save_open_dock_positions(cx);
 3499        }
 3500
 3501        let dock = self.dock_at_position(dock_side);
 3502        dock.update(cx, |dock, cx| {
 3503            dock.set_open(!was_visible, window, cx);
 3504
 3505            if dock.active_panel().is_none() {
 3506                let Some(panel_ix) = dock
 3507                    .first_enabled_panel_idx(cx)
 3508                    .log_with_level(log::Level::Info)
 3509                else {
 3510                    return;
 3511                };
 3512                dock.activate_panel(panel_ix, window, cx);
 3513            }
 3514
 3515            if let Some(active_panel) = dock.active_panel() {
 3516                if was_visible {
 3517                    if active_panel
 3518                        .panel_focus_handle(cx)
 3519                        .contains_focused(window, cx)
 3520                    {
 3521                        focus_center = true;
 3522                    }
 3523                } else {
 3524                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3525                    window.focus(focus_handle, cx);
 3526                    reveal_dock = true;
 3527                }
 3528            }
 3529        });
 3530
 3531        if reveal_dock {
 3532            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3533        }
 3534
 3535        if focus_center {
 3536            self.active_pane
 3537                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3538        }
 3539
 3540        cx.notify();
 3541        self.serialize_workspace(window, cx);
 3542    }
 3543
 3544    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3545        self.all_docks().into_iter().find(|&dock| {
 3546            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3547        })
 3548    }
 3549
 3550    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3551        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3552            self.save_open_dock_positions(cx);
 3553            dock.update(cx, |dock, cx| {
 3554                dock.set_open(false, window, cx);
 3555            });
 3556            return true;
 3557        }
 3558        false
 3559    }
 3560
 3561    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3562        self.save_open_dock_positions(cx);
 3563        for dock in self.all_docks() {
 3564            dock.update(cx, |dock, cx| {
 3565                dock.set_open(false, window, cx);
 3566            });
 3567        }
 3568
 3569        cx.focus_self(window);
 3570        cx.notify();
 3571        self.serialize_workspace(window, cx);
 3572    }
 3573
 3574    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3575        self.all_docks()
 3576            .into_iter()
 3577            .filter_map(|dock| {
 3578                let dock_ref = dock.read(cx);
 3579                if dock_ref.is_open() {
 3580                    Some(dock_ref.position())
 3581                } else {
 3582                    None
 3583                }
 3584            })
 3585            .collect()
 3586    }
 3587
 3588    /// Saves the positions of currently open docks.
 3589    ///
 3590    /// Updates `last_open_dock_positions` with positions of all currently open
 3591    /// docks, to later be restored by the 'Toggle All Docks' action.
 3592    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3593        let open_dock_positions = self.get_open_dock_positions(cx);
 3594        if !open_dock_positions.is_empty() {
 3595            self.last_open_dock_positions = open_dock_positions;
 3596        }
 3597    }
 3598
 3599    /// Toggles all docks between open and closed states.
 3600    ///
 3601    /// If any docks are open, closes all and remembers their positions. If all
 3602    /// docks are closed, restores the last remembered dock configuration.
 3603    fn toggle_all_docks(
 3604        &mut self,
 3605        _: &ToggleAllDocks,
 3606        window: &mut Window,
 3607        cx: &mut Context<Self>,
 3608    ) {
 3609        let open_dock_positions = self.get_open_dock_positions(cx);
 3610
 3611        if !open_dock_positions.is_empty() {
 3612            self.close_all_docks(window, cx);
 3613        } else if !self.last_open_dock_positions.is_empty() {
 3614            self.restore_last_open_docks(window, cx);
 3615        }
 3616    }
 3617
 3618    /// Reopens docks from the most recently remembered configuration.
 3619    ///
 3620    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3621    /// and clears the stored positions.
 3622    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3623        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3624
 3625        for position in positions_to_open {
 3626            let dock = self.dock_at_position(position);
 3627            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3628        }
 3629
 3630        cx.focus_self(window);
 3631        cx.notify();
 3632        self.serialize_workspace(window, cx);
 3633    }
 3634
 3635    /// Transfer focus to the panel of the given type.
 3636    pub fn focus_panel<T: Panel>(
 3637        &mut self,
 3638        window: &mut Window,
 3639        cx: &mut Context<Self>,
 3640    ) -> Option<Entity<T>> {
 3641        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3642        panel.to_any().downcast().ok()
 3643    }
 3644
 3645    /// Focus the panel of the given type if it isn't already focused. If it is
 3646    /// already focused, then transfer focus back to the workspace center.
 3647    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3648    /// panel when transferring focus back to the center.
 3649    pub fn toggle_panel_focus<T: Panel>(
 3650        &mut self,
 3651        window: &mut Window,
 3652        cx: &mut Context<Self>,
 3653    ) -> bool {
 3654        let mut did_focus_panel = false;
 3655        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3656            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3657            did_focus_panel
 3658        });
 3659
 3660        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3661            self.close_panel::<T>(window, cx);
 3662        }
 3663
 3664        telemetry::event!(
 3665            "Panel Button Clicked",
 3666            name = T::persistent_name(),
 3667            toggle_state = did_focus_panel
 3668        );
 3669
 3670        did_focus_panel
 3671    }
 3672
 3673    pub fn activate_panel_for_proto_id(
 3674        &mut self,
 3675        panel_id: PanelId,
 3676        window: &mut Window,
 3677        cx: &mut Context<Self>,
 3678    ) -> Option<Arc<dyn PanelHandle>> {
 3679        let mut panel = None;
 3680        for dock in self.all_docks() {
 3681            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3682                panel = dock.update(cx, |dock, cx| {
 3683                    dock.activate_panel(panel_index, window, cx);
 3684                    dock.set_open(true, window, cx);
 3685                    dock.active_panel().cloned()
 3686                });
 3687                break;
 3688            }
 3689        }
 3690
 3691        if panel.is_some() {
 3692            cx.notify();
 3693            self.serialize_workspace(window, cx);
 3694        }
 3695
 3696        panel
 3697    }
 3698
 3699    /// Focus or unfocus the given panel type, depending on the given callback.
 3700    fn focus_or_unfocus_panel<T: Panel>(
 3701        &mut self,
 3702        window: &mut Window,
 3703        cx: &mut Context<Self>,
 3704        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3705    ) -> Option<Arc<dyn PanelHandle>> {
 3706        let mut result_panel = None;
 3707        let mut serialize = false;
 3708        for dock in self.all_docks() {
 3709            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3710                let mut focus_center = false;
 3711                let panel = dock.update(cx, |dock, cx| {
 3712                    dock.activate_panel(panel_index, window, cx);
 3713
 3714                    let panel = dock.active_panel().cloned();
 3715                    if let Some(panel) = panel.as_ref() {
 3716                        if should_focus(&**panel, window, cx) {
 3717                            dock.set_open(true, window, cx);
 3718                            panel.panel_focus_handle(cx).focus(window, cx);
 3719                        } else {
 3720                            focus_center = true;
 3721                        }
 3722                    }
 3723                    panel
 3724                });
 3725
 3726                if focus_center {
 3727                    self.active_pane
 3728                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3729                }
 3730
 3731                result_panel = panel;
 3732                serialize = true;
 3733                break;
 3734            }
 3735        }
 3736
 3737        if serialize {
 3738            self.serialize_workspace(window, cx);
 3739        }
 3740
 3741        cx.notify();
 3742        result_panel
 3743    }
 3744
 3745    /// Open the panel of the given type
 3746    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3747        for dock in self.all_docks() {
 3748            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3749                dock.update(cx, |dock, cx| {
 3750                    dock.activate_panel(panel_index, window, cx);
 3751                    dock.set_open(true, window, cx);
 3752                });
 3753            }
 3754        }
 3755    }
 3756
 3757    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3758        for dock in self.all_docks().iter() {
 3759            dock.update(cx, |dock, cx| {
 3760                if dock.panel::<T>().is_some() {
 3761                    dock.set_open(false, window, cx)
 3762                }
 3763            })
 3764        }
 3765    }
 3766
 3767    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3768        self.all_docks()
 3769            .iter()
 3770            .find_map(|dock| dock.read(cx).panel::<T>())
 3771    }
 3772
 3773    fn dismiss_zoomed_items_to_reveal(
 3774        &mut self,
 3775        dock_to_reveal: Option<DockPosition>,
 3776        window: &mut Window,
 3777        cx: &mut Context<Self>,
 3778    ) {
 3779        // If a center pane is zoomed, unzoom it.
 3780        for pane in &self.panes {
 3781            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3782                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3783            }
 3784        }
 3785
 3786        // If another dock is zoomed, hide it.
 3787        let mut focus_center = false;
 3788        for dock in self.all_docks() {
 3789            dock.update(cx, |dock, cx| {
 3790                if Some(dock.position()) != dock_to_reveal
 3791                    && let Some(panel) = dock.active_panel()
 3792                    && panel.is_zoomed(window, cx)
 3793                {
 3794                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3795                    dock.set_open(false, window, cx);
 3796                }
 3797            });
 3798        }
 3799
 3800        if focus_center {
 3801            self.active_pane
 3802                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3803        }
 3804
 3805        if self.zoomed_position != dock_to_reveal {
 3806            self.zoomed = None;
 3807            self.zoomed_position = None;
 3808            cx.emit(Event::ZoomChanged);
 3809        }
 3810
 3811        cx.notify();
 3812    }
 3813
 3814    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3815        let pane = cx.new(|cx| {
 3816            let mut pane = Pane::new(
 3817                self.weak_handle(),
 3818                self.project.clone(),
 3819                self.pane_history_timestamp.clone(),
 3820                None,
 3821                NewFile.boxed_clone(),
 3822                true,
 3823                window,
 3824                cx,
 3825            );
 3826            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3827            pane
 3828        });
 3829        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3830            .detach();
 3831        self.panes.push(pane.clone());
 3832
 3833        window.focus(&pane.focus_handle(cx), cx);
 3834
 3835        cx.emit(Event::PaneAdded(pane.clone()));
 3836        pane
 3837    }
 3838
 3839    pub fn add_item_to_center(
 3840        &mut self,
 3841        item: Box<dyn ItemHandle>,
 3842        window: &mut Window,
 3843        cx: &mut Context<Self>,
 3844    ) -> bool {
 3845        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3846            if let Some(center_pane) = center_pane.upgrade() {
 3847                center_pane.update(cx, |pane, cx| {
 3848                    pane.add_item(item, true, true, None, window, cx)
 3849                });
 3850                true
 3851            } else {
 3852                false
 3853            }
 3854        } else {
 3855            false
 3856        }
 3857    }
 3858
 3859    pub fn add_item_to_active_pane(
 3860        &mut self,
 3861        item: Box<dyn ItemHandle>,
 3862        destination_index: Option<usize>,
 3863        focus_item: bool,
 3864        window: &mut Window,
 3865        cx: &mut App,
 3866    ) {
 3867        self.add_item(
 3868            self.active_pane.clone(),
 3869            item,
 3870            destination_index,
 3871            false,
 3872            focus_item,
 3873            window,
 3874            cx,
 3875        )
 3876    }
 3877
 3878    pub fn add_item(
 3879        &mut self,
 3880        pane: Entity<Pane>,
 3881        item: Box<dyn ItemHandle>,
 3882        destination_index: Option<usize>,
 3883        activate_pane: bool,
 3884        focus_item: bool,
 3885        window: &mut Window,
 3886        cx: &mut App,
 3887    ) {
 3888        pane.update(cx, |pane, cx| {
 3889            pane.add_item(
 3890                item,
 3891                activate_pane,
 3892                focus_item,
 3893                destination_index,
 3894                window,
 3895                cx,
 3896            )
 3897        });
 3898    }
 3899
 3900    pub fn split_item(
 3901        &mut self,
 3902        split_direction: SplitDirection,
 3903        item: Box<dyn ItemHandle>,
 3904        window: &mut Window,
 3905        cx: &mut Context<Self>,
 3906    ) {
 3907        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3908        self.add_item(new_pane, item, None, true, true, window, cx);
 3909    }
 3910
 3911    pub fn open_abs_path(
 3912        &mut self,
 3913        abs_path: PathBuf,
 3914        options: OpenOptions,
 3915        window: &mut Window,
 3916        cx: &mut Context<Self>,
 3917    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3918        cx.spawn_in(window, async move |workspace, cx| {
 3919            let open_paths_task_result = workspace
 3920                .update_in(cx, |workspace, window, cx| {
 3921                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3922                })
 3923                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3924                .await;
 3925            anyhow::ensure!(
 3926                open_paths_task_result.len() == 1,
 3927                "open abs path {abs_path:?} task returned incorrect number of results"
 3928            );
 3929            match open_paths_task_result
 3930                .into_iter()
 3931                .next()
 3932                .expect("ensured single task result")
 3933            {
 3934                Some(open_result) => {
 3935                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3936                }
 3937                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3938            }
 3939        })
 3940    }
 3941
 3942    pub fn split_abs_path(
 3943        &mut self,
 3944        abs_path: PathBuf,
 3945        visible: bool,
 3946        window: &mut Window,
 3947        cx: &mut Context<Self>,
 3948    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3949        let project_path_task =
 3950            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3951        cx.spawn_in(window, async move |this, cx| {
 3952            let (_, path) = project_path_task.await?;
 3953            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3954                .await
 3955        })
 3956    }
 3957
 3958    pub fn open_path(
 3959        &mut self,
 3960        path: impl Into<ProjectPath>,
 3961        pane: Option<WeakEntity<Pane>>,
 3962        focus_item: bool,
 3963        window: &mut Window,
 3964        cx: &mut App,
 3965    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3966        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3967    }
 3968
 3969    pub fn open_path_preview(
 3970        &mut self,
 3971        path: impl Into<ProjectPath>,
 3972        pane: Option<WeakEntity<Pane>>,
 3973        focus_item: bool,
 3974        allow_preview: bool,
 3975        activate: bool,
 3976        window: &mut Window,
 3977        cx: &mut App,
 3978    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3979        let pane = pane.unwrap_or_else(|| {
 3980            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3981                self.panes
 3982                    .first()
 3983                    .expect("There must be an active pane")
 3984                    .downgrade()
 3985            })
 3986        });
 3987
 3988        let project_path = path.into();
 3989        let task = self.load_path(project_path.clone(), window, cx);
 3990        window.spawn(cx, async move |cx| {
 3991            let (project_entry_id, build_item) = task.await?;
 3992
 3993            pane.update_in(cx, |pane, window, cx| {
 3994                pane.open_item(
 3995                    project_entry_id,
 3996                    project_path,
 3997                    focus_item,
 3998                    allow_preview,
 3999                    activate,
 4000                    None,
 4001                    window,
 4002                    cx,
 4003                    build_item,
 4004                )
 4005            })
 4006        })
 4007    }
 4008
 4009    pub fn split_path(
 4010        &mut self,
 4011        path: impl Into<ProjectPath>,
 4012        window: &mut Window,
 4013        cx: &mut Context<Self>,
 4014    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4015        self.split_path_preview(path, false, None, window, cx)
 4016    }
 4017
 4018    pub fn split_path_preview(
 4019        &mut self,
 4020        path: impl Into<ProjectPath>,
 4021        allow_preview: bool,
 4022        split_direction: Option<SplitDirection>,
 4023        window: &mut Window,
 4024        cx: &mut Context<Self>,
 4025    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4026        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4027            self.panes
 4028                .first()
 4029                .expect("There must be an active pane")
 4030                .downgrade()
 4031        });
 4032
 4033        if let Member::Pane(center_pane) = &self.center.root
 4034            && center_pane.read(cx).items_len() == 0
 4035        {
 4036            return self.open_path(path, Some(pane), true, window, cx);
 4037        }
 4038
 4039        let project_path = path.into();
 4040        let task = self.load_path(project_path.clone(), window, cx);
 4041        cx.spawn_in(window, async move |this, cx| {
 4042            let (project_entry_id, build_item) = task.await?;
 4043            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4044                let pane = pane.upgrade()?;
 4045                let new_pane = this.split_pane(
 4046                    pane,
 4047                    split_direction.unwrap_or(SplitDirection::Right),
 4048                    window,
 4049                    cx,
 4050                );
 4051                new_pane.update(cx, |new_pane, cx| {
 4052                    Some(new_pane.open_item(
 4053                        project_entry_id,
 4054                        project_path,
 4055                        true,
 4056                        allow_preview,
 4057                        true,
 4058                        None,
 4059                        window,
 4060                        cx,
 4061                        build_item,
 4062                    ))
 4063                })
 4064            })
 4065            .map(|option| option.context("pane was dropped"))?
 4066        })
 4067    }
 4068
 4069    fn load_path(
 4070        &mut self,
 4071        path: ProjectPath,
 4072        window: &mut Window,
 4073        cx: &mut App,
 4074    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4075        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4076        registry.open_path(self.project(), &path, window, cx)
 4077    }
 4078
 4079    pub fn find_project_item<T>(
 4080        &self,
 4081        pane: &Entity<Pane>,
 4082        project_item: &Entity<T::Item>,
 4083        cx: &App,
 4084    ) -> Option<Entity<T>>
 4085    where
 4086        T: ProjectItem,
 4087    {
 4088        use project::ProjectItem as _;
 4089        let project_item = project_item.read(cx);
 4090        let entry_id = project_item.entry_id(cx);
 4091        let project_path = project_item.project_path(cx);
 4092
 4093        let mut item = None;
 4094        if let Some(entry_id) = entry_id {
 4095            item = pane.read(cx).item_for_entry(entry_id, cx);
 4096        }
 4097        if item.is_none()
 4098            && let Some(project_path) = project_path
 4099        {
 4100            item = pane.read(cx).item_for_path(project_path, cx);
 4101        }
 4102
 4103        item.and_then(|item| item.downcast::<T>())
 4104    }
 4105
 4106    pub fn is_project_item_open<T>(
 4107        &self,
 4108        pane: &Entity<Pane>,
 4109        project_item: &Entity<T::Item>,
 4110        cx: &App,
 4111    ) -> bool
 4112    where
 4113        T: ProjectItem,
 4114    {
 4115        self.find_project_item::<T>(pane, project_item, cx)
 4116            .is_some()
 4117    }
 4118
 4119    pub fn open_project_item<T>(
 4120        &mut self,
 4121        pane: Entity<Pane>,
 4122        project_item: Entity<T::Item>,
 4123        activate_pane: bool,
 4124        focus_item: bool,
 4125        keep_old_preview: bool,
 4126        allow_new_preview: bool,
 4127        window: &mut Window,
 4128        cx: &mut Context<Self>,
 4129    ) -> Entity<T>
 4130    where
 4131        T: ProjectItem,
 4132    {
 4133        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4134
 4135        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4136            if !keep_old_preview
 4137                && let Some(old_id) = old_item_id
 4138                && old_id != item.item_id()
 4139            {
 4140                // switching to a different item, so unpreview old active item
 4141                pane.update(cx, |pane, _| {
 4142                    pane.unpreview_item_if_preview(old_id);
 4143                });
 4144            }
 4145
 4146            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4147            if !allow_new_preview {
 4148                pane.update(cx, |pane, _| {
 4149                    pane.unpreview_item_if_preview(item.item_id());
 4150                });
 4151            }
 4152            return item;
 4153        }
 4154
 4155        let item = pane.update(cx, |pane, cx| {
 4156            cx.new(|cx| {
 4157                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4158            })
 4159        });
 4160        let mut destination_index = None;
 4161        pane.update(cx, |pane, cx| {
 4162            if !keep_old_preview && let Some(old_id) = old_item_id {
 4163                pane.unpreview_item_if_preview(old_id);
 4164            }
 4165            if allow_new_preview {
 4166                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4167            }
 4168        });
 4169
 4170        self.add_item(
 4171            pane,
 4172            Box::new(item.clone()),
 4173            destination_index,
 4174            activate_pane,
 4175            focus_item,
 4176            window,
 4177            cx,
 4178        );
 4179        item
 4180    }
 4181
 4182    pub fn open_shared_screen(
 4183        &mut self,
 4184        peer_id: PeerId,
 4185        window: &mut Window,
 4186        cx: &mut Context<Self>,
 4187    ) {
 4188        if let Some(shared_screen) =
 4189            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4190        {
 4191            self.active_pane.update(cx, |pane, cx| {
 4192                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4193            });
 4194        }
 4195    }
 4196
 4197    pub fn activate_item(
 4198        &mut self,
 4199        item: &dyn ItemHandle,
 4200        activate_pane: bool,
 4201        focus_item: bool,
 4202        window: &mut Window,
 4203        cx: &mut App,
 4204    ) -> bool {
 4205        let result = self.panes.iter().find_map(|pane| {
 4206            pane.read(cx)
 4207                .index_for_item(item)
 4208                .map(|ix| (pane.clone(), ix))
 4209        });
 4210        if let Some((pane, ix)) = result {
 4211            pane.update(cx, |pane, cx| {
 4212                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4213            });
 4214            true
 4215        } else {
 4216            false
 4217        }
 4218    }
 4219
 4220    fn activate_pane_at_index(
 4221        &mut self,
 4222        action: &ActivatePane,
 4223        window: &mut Window,
 4224        cx: &mut Context<Self>,
 4225    ) {
 4226        let panes = self.center.panes();
 4227        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4228            window.focus(&pane.focus_handle(cx), cx);
 4229        } else {
 4230            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4231                .detach();
 4232        }
 4233    }
 4234
 4235    fn move_item_to_pane_at_index(
 4236        &mut self,
 4237        action: &MoveItemToPane,
 4238        window: &mut Window,
 4239        cx: &mut Context<Self>,
 4240    ) {
 4241        let panes = self.center.panes();
 4242        let destination = match panes.get(action.destination) {
 4243            Some(&destination) => destination.clone(),
 4244            None => {
 4245                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4246                    return;
 4247                }
 4248                let direction = SplitDirection::Right;
 4249                let split_off_pane = self
 4250                    .find_pane_in_direction(direction, cx)
 4251                    .unwrap_or_else(|| self.active_pane.clone());
 4252                let new_pane = self.add_pane(window, cx);
 4253                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4254                new_pane
 4255            }
 4256        };
 4257
 4258        if action.clone {
 4259            if self
 4260                .active_pane
 4261                .read(cx)
 4262                .active_item()
 4263                .is_some_and(|item| item.can_split(cx))
 4264            {
 4265                clone_active_item(
 4266                    self.database_id(),
 4267                    &self.active_pane,
 4268                    &destination,
 4269                    action.focus,
 4270                    window,
 4271                    cx,
 4272                );
 4273                return;
 4274            }
 4275        }
 4276        move_active_item(
 4277            &self.active_pane,
 4278            &destination,
 4279            action.focus,
 4280            true,
 4281            window,
 4282            cx,
 4283        )
 4284    }
 4285
 4286    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4287        let panes = self.center.panes();
 4288        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4289            let next_ix = (ix + 1) % panes.len();
 4290            let next_pane = panes[next_ix].clone();
 4291            window.focus(&next_pane.focus_handle(cx), cx);
 4292        }
 4293    }
 4294
 4295    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4296        let panes = self.center.panes();
 4297        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4298            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4299            let prev_pane = panes[prev_ix].clone();
 4300            window.focus(&prev_pane.focus_handle(cx), cx);
 4301        }
 4302    }
 4303
 4304    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4305        let last_pane = self.center.last_pane();
 4306        window.focus(&last_pane.focus_handle(cx), cx);
 4307    }
 4308
 4309    pub fn activate_pane_in_direction(
 4310        &mut self,
 4311        direction: SplitDirection,
 4312        window: &mut Window,
 4313        cx: &mut App,
 4314    ) {
 4315        use ActivateInDirectionTarget as Target;
 4316        enum Origin {
 4317            LeftDock,
 4318            RightDock,
 4319            BottomDock,
 4320            Center,
 4321        }
 4322
 4323        let origin: Origin = [
 4324            (&self.left_dock, Origin::LeftDock),
 4325            (&self.right_dock, Origin::RightDock),
 4326            (&self.bottom_dock, Origin::BottomDock),
 4327        ]
 4328        .into_iter()
 4329        .find_map(|(dock, origin)| {
 4330            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4331                Some(origin)
 4332            } else {
 4333                None
 4334            }
 4335        })
 4336        .unwrap_or(Origin::Center);
 4337
 4338        let get_last_active_pane = || {
 4339            let pane = self
 4340                .last_active_center_pane
 4341                .clone()
 4342                .unwrap_or_else(|| {
 4343                    self.panes
 4344                        .first()
 4345                        .expect("There must be an active pane")
 4346                        .downgrade()
 4347                })
 4348                .upgrade()?;
 4349            (pane.read(cx).items_len() != 0).then_some(pane)
 4350        };
 4351
 4352        let try_dock =
 4353            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4354
 4355        let target = match (origin, direction) {
 4356            // We're in the center, so we first try to go to a different pane,
 4357            // otherwise try to go to a dock.
 4358            (Origin::Center, direction) => {
 4359                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4360                    Some(Target::Pane(pane))
 4361                } else {
 4362                    match direction {
 4363                        SplitDirection::Up => None,
 4364                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4365                        SplitDirection::Left => try_dock(&self.left_dock),
 4366                        SplitDirection::Right => try_dock(&self.right_dock),
 4367                    }
 4368                }
 4369            }
 4370
 4371            (Origin::LeftDock, SplitDirection::Right) => {
 4372                if let Some(last_active_pane) = get_last_active_pane() {
 4373                    Some(Target::Pane(last_active_pane))
 4374                } else {
 4375                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4376                }
 4377            }
 4378
 4379            (Origin::LeftDock, SplitDirection::Down)
 4380            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4381
 4382            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4383            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4384            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4385
 4386            (Origin::RightDock, SplitDirection::Left) => {
 4387                if let Some(last_active_pane) = get_last_active_pane() {
 4388                    Some(Target::Pane(last_active_pane))
 4389                } else {
 4390                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4391                }
 4392            }
 4393
 4394            _ => None,
 4395        };
 4396
 4397        match target {
 4398            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4399                let pane = pane.read(cx);
 4400                if let Some(item) = pane.active_item() {
 4401                    item.item_focus_handle(cx).focus(window, cx);
 4402                } else {
 4403                    log::error!(
 4404                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4405                    );
 4406                }
 4407            }
 4408            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4409                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4410                window.defer(cx, move |window, cx| {
 4411                    let dock = dock.read(cx);
 4412                    if let Some(panel) = dock.active_panel() {
 4413                        panel.panel_focus_handle(cx).focus(window, cx);
 4414                    } else {
 4415                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4416                    }
 4417                })
 4418            }
 4419            None => {}
 4420        }
 4421    }
 4422
 4423    pub fn move_item_to_pane_in_direction(
 4424        &mut self,
 4425        action: &MoveItemToPaneInDirection,
 4426        window: &mut Window,
 4427        cx: &mut Context<Self>,
 4428    ) {
 4429        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4430            Some(destination) => destination,
 4431            None => {
 4432                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4433                    return;
 4434                }
 4435                let new_pane = self.add_pane(window, cx);
 4436                self.center
 4437                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4438                new_pane
 4439            }
 4440        };
 4441
 4442        if action.clone {
 4443            if self
 4444                .active_pane
 4445                .read(cx)
 4446                .active_item()
 4447                .is_some_and(|item| item.can_split(cx))
 4448            {
 4449                clone_active_item(
 4450                    self.database_id(),
 4451                    &self.active_pane,
 4452                    &destination,
 4453                    action.focus,
 4454                    window,
 4455                    cx,
 4456                );
 4457                return;
 4458            }
 4459        }
 4460        move_active_item(
 4461            &self.active_pane,
 4462            &destination,
 4463            action.focus,
 4464            true,
 4465            window,
 4466            cx,
 4467        );
 4468    }
 4469
 4470    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4471        self.center.bounding_box_for_pane(pane)
 4472    }
 4473
 4474    pub fn find_pane_in_direction(
 4475        &mut self,
 4476        direction: SplitDirection,
 4477        cx: &App,
 4478    ) -> Option<Entity<Pane>> {
 4479        self.center
 4480            .find_pane_in_direction(&self.active_pane, direction, cx)
 4481            .cloned()
 4482    }
 4483
 4484    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4485        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4486            self.center.swap(&self.active_pane, &to, cx);
 4487            cx.notify();
 4488        }
 4489    }
 4490
 4491    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4492        if self
 4493            .center
 4494            .move_to_border(&self.active_pane, direction, cx)
 4495            .unwrap()
 4496        {
 4497            cx.notify();
 4498        }
 4499    }
 4500
 4501    pub fn resize_pane(
 4502        &mut self,
 4503        axis: gpui::Axis,
 4504        amount: Pixels,
 4505        window: &mut Window,
 4506        cx: &mut Context<Self>,
 4507    ) {
 4508        let docks = self.all_docks();
 4509        let active_dock = docks
 4510            .into_iter()
 4511            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4512
 4513        if let Some(dock) = active_dock {
 4514            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4515                return;
 4516            };
 4517            match dock.read(cx).position() {
 4518                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4519                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4520                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4521            }
 4522        } else {
 4523            self.center
 4524                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4525        }
 4526        cx.notify();
 4527    }
 4528
 4529    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4530        self.center.reset_pane_sizes(cx);
 4531        cx.notify();
 4532    }
 4533
 4534    fn handle_pane_focused(
 4535        &mut self,
 4536        pane: Entity<Pane>,
 4537        window: &mut Window,
 4538        cx: &mut Context<Self>,
 4539    ) {
 4540        // This is explicitly hoisted out of the following check for pane identity as
 4541        // terminal panel panes are not registered as a center panes.
 4542        self.status_bar.update(cx, |status_bar, cx| {
 4543            status_bar.set_active_pane(&pane, window, cx);
 4544        });
 4545        if self.active_pane != pane {
 4546            self.set_active_pane(&pane, window, cx);
 4547        }
 4548
 4549        if self.last_active_center_pane.is_none() {
 4550            self.last_active_center_pane = Some(pane.downgrade());
 4551        }
 4552
 4553        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4554        // This prevents the dock from closing when focus events fire during window activation.
 4555        // We also preserve any dock whose active panel itself has focus — this covers
 4556        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4557        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4558            let dock_read = dock.read(cx);
 4559            if let Some(panel) = dock_read.active_panel() {
 4560                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4561                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4562                {
 4563                    return Some(dock_read.position());
 4564                }
 4565            }
 4566            None
 4567        });
 4568
 4569        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4570        if pane.read(cx).is_zoomed() {
 4571            self.zoomed = Some(pane.downgrade().into());
 4572        } else {
 4573            self.zoomed = None;
 4574        }
 4575        self.zoomed_position = None;
 4576        cx.emit(Event::ZoomChanged);
 4577        self.update_active_view_for_followers(window, cx);
 4578        pane.update(cx, |pane, _| {
 4579            pane.track_alternate_file_items();
 4580        });
 4581
 4582        cx.notify();
 4583    }
 4584
 4585    fn set_active_pane(
 4586        &mut self,
 4587        pane: &Entity<Pane>,
 4588        window: &mut Window,
 4589        cx: &mut Context<Self>,
 4590    ) {
 4591        self.active_pane = pane.clone();
 4592        self.active_item_path_changed(true, window, cx);
 4593        self.last_active_center_pane = Some(pane.downgrade());
 4594    }
 4595
 4596    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4597        self.update_active_view_for_followers(window, cx);
 4598    }
 4599
 4600    fn handle_pane_event(
 4601        &mut self,
 4602        pane: &Entity<Pane>,
 4603        event: &pane::Event,
 4604        window: &mut Window,
 4605        cx: &mut Context<Self>,
 4606    ) {
 4607        let mut serialize_workspace = true;
 4608        match event {
 4609            pane::Event::AddItem { item } => {
 4610                item.added_to_pane(self, pane.clone(), window, cx);
 4611                cx.emit(Event::ItemAdded {
 4612                    item: item.boxed_clone(),
 4613                });
 4614            }
 4615            pane::Event::Split { direction, mode } => {
 4616                match mode {
 4617                    SplitMode::ClonePane => {
 4618                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4619                            .detach();
 4620                    }
 4621                    SplitMode::EmptyPane => {
 4622                        self.split_pane(pane.clone(), *direction, window, cx);
 4623                    }
 4624                    SplitMode::MovePane => {
 4625                        self.split_and_move(pane.clone(), *direction, window, cx);
 4626                    }
 4627                };
 4628            }
 4629            pane::Event::JoinIntoNext => {
 4630                self.join_pane_into_next(pane.clone(), window, cx);
 4631            }
 4632            pane::Event::JoinAll => {
 4633                self.join_all_panes(window, cx);
 4634            }
 4635            pane::Event::Remove { focus_on_pane } => {
 4636                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4637            }
 4638            pane::Event::ActivateItem {
 4639                local,
 4640                focus_changed,
 4641            } => {
 4642                window.invalidate_character_coordinates();
 4643
 4644                pane.update(cx, |pane, _| {
 4645                    pane.track_alternate_file_items();
 4646                });
 4647                if *local {
 4648                    self.unfollow_in_pane(pane, window, cx);
 4649                }
 4650                serialize_workspace = *focus_changed || pane != self.active_pane();
 4651                if pane == self.active_pane() {
 4652                    self.active_item_path_changed(*focus_changed, window, cx);
 4653                    self.update_active_view_for_followers(window, cx);
 4654                } else if *local {
 4655                    self.set_active_pane(pane, window, cx);
 4656                }
 4657            }
 4658            pane::Event::UserSavedItem { item, save_intent } => {
 4659                cx.emit(Event::UserSavedItem {
 4660                    pane: pane.downgrade(),
 4661                    item: item.boxed_clone(),
 4662                    save_intent: *save_intent,
 4663                });
 4664                serialize_workspace = false;
 4665            }
 4666            pane::Event::ChangeItemTitle => {
 4667                if *pane == self.active_pane {
 4668                    self.active_item_path_changed(false, window, cx);
 4669                }
 4670                serialize_workspace = false;
 4671            }
 4672            pane::Event::RemovedItem { item } => {
 4673                cx.emit(Event::ActiveItemChanged);
 4674                self.update_window_edited(window, cx);
 4675                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4676                    && entry.get().entity_id() == pane.entity_id()
 4677                {
 4678                    entry.remove();
 4679                }
 4680                cx.emit(Event::ItemRemoved {
 4681                    item_id: item.item_id(),
 4682                });
 4683            }
 4684            pane::Event::Focus => {
 4685                window.invalidate_character_coordinates();
 4686                self.handle_pane_focused(pane.clone(), window, cx);
 4687            }
 4688            pane::Event::ZoomIn => {
 4689                if *pane == self.active_pane {
 4690                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4691                    if pane.read(cx).has_focus(window, cx) {
 4692                        self.zoomed = Some(pane.downgrade().into());
 4693                        self.zoomed_position = None;
 4694                        cx.emit(Event::ZoomChanged);
 4695                    }
 4696                    cx.notify();
 4697                }
 4698            }
 4699            pane::Event::ZoomOut => {
 4700                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4701                if self.zoomed_position.is_none() {
 4702                    self.zoomed = None;
 4703                    cx.emit(Event::ZoomChanged);
 4704                }
 4705                cx.notify();
 4706            }
 4707            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4708        }
 4709
 4710        if serialize_workspace {
 4711            self.serialize_workspace(window, cx);
 4712        }
 4713    }
 4714
 4715    pub fn unfollow_in_pane(
 4716        &mut self,
 4717        pane: &Entity<Pane>,
 4718        window: &mut Window,
 4719        cx: &mut Context<Workspace>,
 4720    ) -> Option<CollaboratorId> {
 4721        let leader_id = self.leader_for_pane(pane)?;
 4722        self.unfollow(leader_id, window, cx);
 4723        Some(leader_id)
 4724    }
 4725
 4726    pub fn split_pane(
 4727        &mut self,
 4728        pane_to_split: Entity<Pane>,
 4729        split_direction: SplitDirection,
 4730        window: &mut Window,
 4731        cx: &mut Context<Self>,
 4732    ) -> Entity<Pane> {
 4733        let new_pane = self.add_pane(window, cx);
 4734        self.center
 4735            .split(&pane_to_split, &new_pane, split_direction, cx);
 4736        cx.notify();
 4737        new_pane
 4738    }
 4739
 4740    pub fn split_and_move(
 4741        &mut self,
 4742        pane: Entity<Pane>,
 4743        direction: SplitDirection,
 4744        window: &mut Window,
 4745        cx: &mut Context<Self>,
 4746    ) {
 4747        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4748            return;
 4749        };
 4750        let new_pane = self.add_pane(window, cx);
 4751        new_pane.update(cx, |pane, cx| {
 4752            pane.add_item(item, true, true, None, window, cx)
 4753        });
 4754        self.center.split(&pane, &new_pane, direction, cx);
 4755        cx.notify();
 4756    }
 4757
 4758    pub fn split_and_clone(
 4759        &mut self,
 4760        pane: Entity<Pane>,
 4761        direction: SplitDirection,
 4762        window: &mut Window,
 4763        cx: &mut Context<Self>,
 4764    ) -> Task<Option<Entity<Pane>>> {
 4765        let Some(item) = pane.read(cx).active_item() else {
 4766            return Task::ready(None);
 4767        };
 4768        if !item.can_split(cx) {
 4769            return Task::ready(None);
 4770        }
 4771        let task = item.clone_on_split(self.database_id(), window, cx);
 4772        cx.spawn_in(window, async move |this, cx| {
 4773            if let Some(clone) = task.await {
 4774                this.update_in(cx, |this, window, cx| {
 4775                    let new_pane = this.add_pane(window, cx);
 4776                    let nav_history = pane.read(cx).fork_nav_history();
 4777                    new_pane.update(cx, |pane, cx| {
 4778                        pane.set_nav_history(nav_history, cx);
 4779                        pane.add_item(clone, true, true, None, window, cx)
 4780                    });
 4781                    this.center.split(&pane, &new_pane, direction, cx);
 4782                    cx.notify();
 4783                    new_pane
 4784                })
 4785                .ok()
 4786            } else {
 4787                None
 4788            }
 4789        })
 4790    }
 4791
 4792    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4793        let active_item = self.active_pane.read(cx).active_item();
 4794        for pane in &self.panes {
 4795            join_pane_into_active(&self.active_pane, pane, window, cx);
 4796        }
 4797        if let Some(active_item) = active_item {
 4798            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4799        }
 4800        cx.notify();
 4801    }
 4802
 4803    pub fn join_pane_into_next(
 4804        &mut self,
 4805        pane: Entity<Pane>,
 4806        window: &mut Window,
 4807        cx: &mut Context<Self>,
 4808    ) {
 4809        let next_pane = self
 4810            .find_pane_in_direction(SplitDirection::Right, cx)
 4811            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4812            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4813            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4814        let Some(next_pane) = next_pane else {
 4815            return;
 4816        };
 4817        move_all_items(&pane, &next_pane, window, cx);
 4818        cx.notify();
 4819    }
 4820
 4821    fn remove_pane(
 4822        &mut self,
 4823        pane: Entity<Pane>,
 4824        focus_on: Option<Entity<Pane>>,
 4825        window: &mut Window,
 4826        cx: &mut Context<Self>,
 4827    ) {
 4828        if self.center.remove(&pane, cx).unwrap() {
 4829            self.force_remove_pane(&pane, &focus_on, window, cx);
 4830            self.unfollow_in_pane(&pane, window, cx);
 4831            self.last_leaders_by_pane.remove(&pane.downgrade());
 4832            for removed_item in pane.read(cx).items() {
 4833                self.panes_by_item.remove(&removed_item.item_id());
 4834            }
 4835
 4836            cx.notify();
 4837        } else {
 4838            self.active_item_path_changed(true, window, cx);
 4839        }
 4840        cx.emit(Event::PaneRemoved);
 4841    }
 4842
 4843    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4844        &mut self.panes
 4845    }
 4846
 4847    pub fn panes(&self) -> &[Entity<Pane>] {
 4848        &self.panes
 4849    }
 4850
 4851    pub fn active_pane(&self) -> &Entity<Pane> {
 4852        &self.active_pane
 4853    }
 4854
 4855    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4856        for dock in self.all_docks() {
 4857            if dock.focus_handle(cx).contains_focused(window, cx)
 4858                && let Some(pane) = dock
 4859                    .read(cx)
 4860                    .active_panel()
 4861                    .and_then(|panel| panel.pane(cx))
 4862            {
 4863                return pane;
 4864            }
 4865        }
 4866        self.active_pane().clone()
 4867    }
 4868
 4869    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4870        self.find_pane_in_direction(SplitDirection::Right, cx)
 4871            .unwrap_or_else(|| {
 4872                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4873            })
 4874    }
 4875
 4876    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4877        self.pane_for_item_id(handle.item_id())
 4878    }
 4879
 4880    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 4881        let weak_pane = self.panes_by_item.get(&item_id)?;
 4882        weak_pane.upgrade()
 4883    }
 4884
 4885    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 4886        self.panes
 4887            .iter()
 4888            .find(|pane| pane.entity_id() == entity_id)
 4889            .cloned()
 4890    }
 4891
 4892    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4893        self.follower_states.retain(|leader_id, state| {
 4894            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4895                for item in state.items_by_leader_view_id.values() {
 4896                    item.view.set_leader_id(None, window, cx);
 4897                }
 4898                false
 4899            } else {
 4900                true
 4901            }
 4902        });
 4903        cx.notify();
 4904    }
 4905
 4906    pub fn start_following(
 4907        &mut self,
 4908        leader_id: impl Into<CollaboratorId>,
 4909        window: &mut Window,
 4910        cx: &mut Context<Self>,
 4911    ) -> Option<Task<Result<()>>> {
 4912        let leader_id = leader_id.into();
 4913        let pane = self.active_pane().clone();
 4914
 4915        self.last_leaders_by_pane
 4916            .insert(pane.downgrade(), leader_id);
 4917        self.unfollow(leader_id, window, cx);
 4918        self.unfollow_in_pane(&pane, window, cx);
 4919        self.follower_states.insert(
 4920            leader_id,
 4921            FollowerState {
 4922                center_pane: pane.clone(),
 4923                dock_pane: None,
 4924                active_view_id: None,
 4925                items_by_leader_view_id: Default::default(),
 4926            },
 4927        );
 4928        cx.notify();
 4929
 4930        match leader_id {
 4931            CollaboratorId::PeerId(leader_peer_id) => {
 4932                let room_id = self.active_call()?.room_id(cx)?;
 4933                let project_id = self.project.read(cx).remote_id();
 4934                let request = self.app_state.client.request(proto::Follow {
 4935                    room_id,
 4936                    project_id,
 4937                    leader_id: Some(leader_peer_id),
 4938                });
 4939
 4940                Some(cx.spawn_in(window, async move |this, cx| {
 4941                    let response = request.await?;
 4942                    this.update(cx, |this, _| {
 4943                        let state = this
 4944                            .follower_states
 4945                            .get_mut(&leader_id)
 4946                            .context("following interrupted")?;
 4947                        state.active_view_id = response
 4948                            .active_view
 4949                            .as_ref()
 4950                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4951                        anyhow::Ok(())
 4952                    })??;
 4953                    if let Some(view) = response.active_view {
 4954                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4955                    }
 4956                    this.update_in(cx, |this, window, cx| {
 4957                        this.leader_updated(leader_id, window, cx)
 4958                    })?;
 4959                    Ok(())
 4960                }))
 4961            }
 4962            CollaboratorId::Agent => {
 4963                self.leader_updated(leader_id, window, cx)?;
 4964                Some(Task::ready(Ok(())))
 4965            }
 4966        }
 4967    }
 4968
 4969    pub fn follow_next_collaborator(
 4970        &mut self,
 4971        _: &FollowNextCollaborator,
 4972        window: &mut Window,
 4973        cx: &mut Context<Self>,
 4974    ) {
 4975        let collaborators = self.project.read(cx).collaborators();
 4976        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4977            let mut collaborators = collaborators.keys().copied();
 4978            for peer_id in collaborators.by_ref() {
 4979                if CollaboratorId::PeerId(peer_id) == leader_id {
 4980                    break;
 4981                }
 4982            }
 4983            collaborators.next().map(CollaboratorId::PeerId)
 4984        } else if let Some(last_leader_id) =
 4985            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4986        {
 4987            match last_leader_id {
 4988                CollaboratorId::PeerId(peer_id) => {
 4989                    if collaborators.contains_key(peer_id) {
 4990                        Some(*last_leader_id)
 4991                    } else {
 4992                        None
 4993                    }
 4994                }
 4995                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4996            }
 4997        } else {
 4998            None
 4999        };
 5000
 5001        let pane = self.active_pane.clone();
 5002        let Some(leader_id) = next_leader_id.or_else(|| {
 5003            Some(CollaboratorId::PeerId(
 5004                collaborators.keys().copied().next()?,
 5005            ))
 5006        }) else {
 5007            return;
 5008        };
 5009        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5010            return;
 5011        }
 5012        if let Some(task) = self.start_following(leader_id, window, cx) {
 5013            task.detach_and_log_err(cx)
 5014        }
 5015    }
 5016
 5017    pub fn follow(
 5018        &mut self,
 5019        leader_id: impl Into<CollaboratorId>,
 5020        window: &mut Window,
 5021        cx: &mut Context<Self>,
 5022    ) {
 5023        let leader_id = leader_id.into();
 5024
 5025        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5026            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5027                return;
 5028            };
 5029            let Some(remote_participant) =
 5030                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5031            else {
 5032                return;
 5033            };
 5034
 5035            let project = self.project.read(cx);
 5036
 5037            let other_project_id = match remote_participant.location {
 5038                ParticipantLocation::External => None,
 5039                ParticipantLocation::UnsharedProject => None,
 5040                ParticipantLocation::SharedProject { project_id } => {
 5041                    if Some(project_id) == project.remote_id() {
 5042                        None
 5043                    } else {
 5044                        Some(project_id)
 5045                    }
 5046                }
 5047            };
 5048
 5049            // if they are active in another project, follow there.
 5050            if let Some(project_id) = other_project_id {
 5051                let app_state = self.app_state.clone();
 5052                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5053                    .detach_and_log_err(cx);
 5054            }
 5055        }
 5056
 5057        // if you're already following, find the right pane and focus it.
 5058        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5059            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5060
 5061            return;
 5062        }
 5063
 5064        // Otherwise, follow.
 5065        if let Some(task) = self.start_following(leader_id, window, cx) {
 5066            task.detach_and_log_err(cx)
 5067        }
 5068    }
 5069
 5070    pub fn unfollow(
 5071        &mut self,
 5072        leader_id: impl Into<CollaboratorId>,
 5073        window: &mut Window,
 5074        cx: &mut Context<Self>,
 5075    ) -> Option<()> {
 5076        cx.notify();
 5077
 5078        let leader_id = leader_id.into();
 5079        let state = self.follower_states.remove(&leader_id)?;
 5080        for (_, item) in state.items_by_leader_view_id {
 5081            item.view.set_leader_id(None, window, cx);
 5082        }
 5083
 5084        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5085            let project_id = self.project.read(cx).remote_id();
 5086            let room_id = self.active_call()?.room_id(cx)?;
 5087            self.app_state
 5088                .client
 5089                .send(proto::Unfollow {
 5090                    room_id,
 5091                    project_id,
 5092                    leader_id: Some(leader_peer_id),
 5093                })
 5094                .log_err();
 5095        }
 5096
 5097        Some(())
 5098    }
 5099
 5100    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5101        self.follower_states.contains_key(&id.into())
 5102    }
 5103
 5104    fn active_item_path_changed(
 5105        &mut self,
 5106        focus_changed: bool,
 5107        window: &mut Window,
 5108        cx: &mut Context<Self>,
 5109    ) {
 5110        cx.emit(Event::ActiveItemChanged);
 5111        let active_entry = self.active_project_path(cx);
 5112        self.project.update(cx, |project, cx| {
 5113            project.set_active_path(active_entry.clone(), cx)
 5114        });
 5115
 5116        if focus_changed && let Some(project_path) = &active_entry {
 5117            let git_store_entity = self.project.read(cx).git_store().clone();
 5118            git_store_entity.update(cx, |git_store, cx| {
 5119                git_store.set_active_repo_for_path(project_path, cx);
 5120            });
 5121        }
 5122
 5123        self.update_window_title(window, cx);
 5124    }
 5125
 5126    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5127        let project = self.project().read(cx);
 5128        let mut title = String::new();
 5129
 5130        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5131            let name = {
 5132                let settings_location = SettingsLocation {
 5133                    worktree_id: worktree.read(cx).id(),
 5134                    path: RelPath::empty(),
 5135                };
 5136
 5137                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5138                match &settings.project_name {
 5139                    Some(name) => name.as_str(),
 5140                    None => worktree.read(cx).root_name_str(),
 5141                }
 5142            };
 5143            if i > 0 {
 5144                title.push_str(", ");
 5145            }
 5146            title.push_str(name);
 5147        }
 5148
 5149        if title.is_empty() {
 5150            title = "empty project".to_string();
 5151        }
 5152
 5153        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5154            let filename = path.path.file_name().or_else(|| {
 5155                Some(
 5156                    project
 5157                        .worktree_for_id(path.worktree_id, cx)?
 5158                        .read(cx)
 5159                        .root_name_str(),
 5160                )
 5161            });
 5162
 5163            if let Some(filename) = filename {
 5164                title.push_str("");
 5165                title.push_str(filename.as_ref());
 5166            }
 5167        }
 5168
 5169        if project.is_via_collab() {
 5170            title.push_str("");
 5171        } else if project.is_shared() {
 5172            title.push_str("");
 5173        }
 5174
 5175        if let Some(last_title) = self.last_window_title.as_ref()
 5176            && &title == last_title
 5177        {
 5178            return;
 5179        }
 5180        window.set_window_title(&title);
 5181        SystemWindowTabController::update_tab_title(
 5182            cx,
 5183            window.window_handle().window_id(),
 5184            SharedString::from(&title),
 5185        );
 5186        self.last_window_title = Some(title);
 5187    }
 5188
 5189    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5190        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5191        if is_edited != self.window_edited {
 5192            self.window_edited = is_edited;
 5193            window.set_window_edited(self.window_edited)
 5194        }
 5195    }
 5196
 5197    fn update_item_dirty_state(
 5198        &mut self,
 5199        item: &dyn ItemHandle,
 5200        window: &mut Window,
 5201        cx: &mut App,
 5202    ) {
 5203        let is_dirty = item.is_dirty(cx);
 5204        let item_id = item.item_id();
 5205        let was_dirty = self.dirty_items.contains_key(&item_id);
 5206        if is_dirty == was_dirty {
 5207            return;
 5208        }
 5209        if was_dirty {
 5210            self.dirty_items.remove(&item_id);
 5211            self.update_window_edited(window, cx);
 5212            return;
 5213        }
 5214
 5215        let workspace = self.weak_handle();
 5216        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5217            return;
 5218        };
 5219        let on_release_callback = Box::new(move |cx: &mut App| {
 5220            window_handle
 5221                .update(cx, |_, window, cx| {
 5222                    workspace
 5223                        .update(cx, |workspace, cx| {
 5224                            workspace.dirty_items.remove(&item_id);
 5225                            workspace.update_window_edited(window, cx)
 5226                        })
 5227                        .ok();
 5228                })
 5229                .ok();
 5230        });
 5231
 5232        let s = item.on_release(cx, on_release_callback);
 5233        self.dirty_items.insert(item_id, s);
 5234        self.update_window_edited(window, cx);
 5235    }
 5236
 5237    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5238        if self.notifications.is_empty() {
 5239            None
 5240        } else {
 5241            Some(
 5242                div()
 5243                    .absolute()
 5244                    .right_3()
 5245                    .bottom_3()
 5246                    .w_112()
 5247                    .h_full()
 5248                    .flex()
 5249                    .flex_col()
 5250                    .justify_end()
 5251                    .gap_2()
 5252                    .children(
 5253                        self.notifications
 5254                            .iter()
 5255                            .map(|(_, notification)| notification.clone().into_any()),
 5256                    ),
 5257            )
 5258        }
 5259    }
 5260
 5261    // RPC handlers
 5262
 5263    fn active_view_for_follower(
 5264        &self,
 5265        follower_project_id: Option<u64>,
 5266        window: &mut Window,
 5267        cx: &mut Context<Self>,
 5268    ) -> Option<proto::View> {
 5269        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5270        let item = item?;
 5271        let leader_id = self
 5272            .pane_for(&*item)
 5273            .and_then(|pane| self.leader_for_pane(&pane));
 5274        let leader_peer_id = match leader_id {
 5275            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5276            Some(CollaboratorId::Agent) | None => None,
 5277        };
 5278
 5279        let item_handle = item.to_followable_item_handle(cx)?;
 5280        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5281        let variant = item_handle.to_state_proto(window, cx)?;
 5282
 5283        if item_handle.is_project_item(window, cx)
 5284            && (follower_project_id.is_none()
 5285                || follower_project_id != self.project.read(cx).remote_id())
 5286        {
 5287            return None;
 5288        }
 5289
 5290        Some(proto::View {
 5291            id: id.to_proto(),
 5292            leader_id: leader_peer_id,
 5293            variant: Some(variant),
 5294            panel_id: panel_id.map(|id| id as i32),
 5295        })
 5296    }
 5297
 5298    fn handle_follow(
 5299        &mut self,
 5300        follower_project_id: Option<u64>,
 5301        window: &mut Window,
 5302        cx: &mut Context<Self>,
 5303    ) -> proto::FollowResponse {
 5304        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5305
 5306        cx.notify();
 5307        proto::FollowResponse {
 5308            views: active_view.iter().cloned().collect(),
 5309            active_view,
 5310        }
 5311    }
 5312
 5313    fn handle_update_followers(
 5314        &mut self,
 5315        leader_id: PeerId,
 5316        message: proto::UpdateFollowers,
 5317        _window: &mut Window,
 5318        _cx: &mut Context<Self>,
 5319    ) {
 5320        self.leader_updates_tx
 5321            .unbounded_send((leader_id, message))
 5322            .ok();
 5323    }
 5324
 5325    async fn process_leader_update(
 5326        this: &WeakEntity<Self>,
 5327        leader_id: PeerId,
 5328        update: proto::UpdateFollowers,
 5329        cx: &mut AsyncWindowContext,
 5330    ) -> Result<()> {
 5331        match update.variant.context("invalid update")? {
 5332            proto::update_followers::Variant::CreateView(view) => {
 5333                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5334                let should_add_view = this.update(cx, |this, _| {
 5335                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5336                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5337                    } else {
 5338                        anyhow::Ok(false)
 5339                    }
 5340                })??;
 5341
 5342                if should_add_view {
 5343                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5344                }
 5345            }
 5346            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5347                let should_add_view = this.update(cx, |this, _| {
 5348                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5349                        state.active_view_id = update_active_view
 5350                            .view
 5351                            .as_ref()
 5352                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5353
 5354                        if state.active_view_id.is_some_and(|view_id| {
 5355                            !state.items_by_leader_view_id.contains_key(&view_id)
 5356                        }) {
 5357                            anyhow::Ok(true)
 5358                        } else {
 5359                            anyhow::Ok(false)
 5360                        }
 5361                    } else {
 5362                        anyhow::Ok(false)
 5363                    }
 5364                })??;
 5365
 5366                if should_add_view && let Some(view) = update_active_view.view {
 5367                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5368                }
 5369            }
 5370            proto::update_followers::Variant::UpdateView(update_view) => {
 5371                let variant = update_view.variant.context("missing update view variant")?;
 5372                let id = update_view.id.context("missing update view id")?;
 5373                let mut tasks = Vec::new();
 5374                this.update_in(cx, |this, window, cx| {
 5375                    let project = this.project.clone();
 5376                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5377                        let view_id = ViewId::from_proto(id.clone())?;
 5378                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5379                            tasks.push(item.view.apply_update_proto(
 5380                                &project,
 5381                                variant.clone(),
 5382                                window,
 5383                                cx,
 5384                            ));
 5385                        }
 5386                    }
 5387                    anyhow::Ok(())
 5388                })??;
 5389                try_join_all(tasks).await.log_err();
 5390            }
 5391        }
 5392        this.update_in(cx, |this, window, cx| {
 5393            this.leader_updated(leader_id, window, cx)
 5394        })?;
 5395        Ok(())
 5396    }
 5397
 5398    async fn add_view_from_leader(
 5399        this: WeakEntity<Self>,
 5400        leader_id: PeerId,
 5401        view: &proto::View,
 5402        cx: &mut AsyncWindowContext,
 5403    ) -> Result<()> {
 5404        let this = this.upgrade().context("workspace dropped")?;
 5405
 5406        let Some(id) = view.id.clone() else {
 5407            anyhow::bail!("no id for view");
 5408        };
 5409        let id = ViewId::from_proto(id)?;
 5410        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5411
 5412        let pane = this.update(cx, |this, _cx| {
 5413            let state = this
 5414                .follower_states
 5415                .get(&leader_id.into())
 5416                .context("stopped following")?;
 5417            anyhow::Ok(state.pane().clone())
 5418        })?;
 5419        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5420            let client = this.read(cx).client().clone();
 5421            pane.items().find_map(|item| {
 5422                let item = item.to_followable_item_handle(cx)?;
 5423                if item.remote_id(&client, window, cx) == Some(id) {
 5424                    Some(item)
 5425                } else {
 5426                    None
 5427                }
 5428            })
 5429        })?;
 5430        let item = if let Some(existing_item) = existing_item {
 5431            existing_item
 5432        } else {
 5433            let variant = view.variant.clone();
 5434            anyhow::ensure!(variant.is_some(), "missing view variant");
 5435
 5436            let task = cx.update(|window, cx| {
 5437                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5438            })?;
 5439
 5440            let Some(task) = task else {
 5441                anyhow::bail!(
 5442                    "failed to construct view from leader (maybe from a different version of zed?)"
 5443                );
 5444            };
 5445
 5446            let mut new_item = task.await?;
 5447            pane.update_in(cx, |pane, window, cx| {
 5448                let mut item_to_remove = None;
 5449                for (ix, item) in pane.items().enumerate() {
 5450                    if let Some(item) = item.to_followable_item_handle(cx) {
 5451                        match new_item.dedup(item.as_ref(), window, cx) {
 5452                            Some(item::Dedup::KeepExisting) => {
 5453                                new_item =
 5454                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5455                                break;
 5456                            }
 5457                            Some(item::Dedup::ReplaceExisting) => {
 5458                                item_to_remove = Some((ix, item.item_id()));
 5459                                break;
 5460                            }
 5461                            None => {}
 5462                        }
 5463                    }
 5464                }
 5465
 5466                if let Some((ix, id)) = item_to_remove {
 5467                    pane.remove_item(id, false, false, window, cx);
 5468                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5469                }
 5470            })?;
 5471
 5472            new_item
 5473        };
 5474
 5475        this.update_in(cx, |this, window, cx| {
 5476            let state = this.follower_states.get_mut(&leader_id.into())?;
 5477            item.set_leader_id(Some(leader_id.into()), window, cx);
 5478            state.items_by_leader_view_id.insert(
 5479                id,
 5480                FollowerView {
 5481                    view: item,
 5482                    location: panel_id,
 5483                },
 5484            );
 5485
 5486            Some(())
 5487        })
 5488        .context("no follower state")?;
 5489
 5490        Ok(())
 5491    }
 5492
 5493    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5494        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5495            return;
 5496        };
 5497
 5498        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5499            let buffer_entity_id = agent_location.buffer.entity_id();
 5500            let view_id = ViewId {
 5501                creator: CollaboratorId::Agent,
 5502                id: buffer_entity_id.as_u64(),
 5503            };
 5504            follower_state.active_view_id = Some(view_id);
 5505
 5506            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5507                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5508                hash_map::Entry::Vacant(entry) => {
 5509                    let existing_view =
 5510                        follower_state
 5511                            .center_pane
 5512                            .read(cx)
 5513                            .items()
 5514                            .find_map(|item| {
 5515                                let item = item.to_followable_item_handle(cx)?;
 5516                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5517                                    && item.project_item_model_ids(cx).as_slice()
 5518                                        == [buffer_entity_id]
 5519                                {
 5520                                    Some(item)
 5521                                } else {
 5522                                    None
 5523                                }
 5524                            });
 5525                    let view = existing_view.or_else(|| {
 5526                        agent_location.buffer.upgrade().and_then(|buffer| {
 5527                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5528                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5529                            })?
 5530                            .to_followable_item_handle(cx)
 5531                        })
 5532                    });
 5533
 5534                    view.map(|view| {
 5535                        entry.insert(FollowerView {
 5536                            view,
 5537                            location: None,
 5538                        })
 5539                    })
 5540                }
 5541            };
 5542
 5543            if let Some(item) = item {
 5544                item.view
 5545                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5546                item.view
 5547                    .update_agent_location(agent_location.position, window, cx);
 5548            }
 5549        } else {
 5550            follower_state.active_view_id = None;
 5551        }
 5552
 5553        self.leader_updated(CollaboratorId::Agent, window, cx);
 5554    }
 5555
 5556    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5557        let mut is_project_item = true;
 5558        let mut update = proto::UpdateActiveView::default();
 5559        if window.is_window_active() {
 5560            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5561
 5562            if let Some(item) = active_item
 5563                && item.item_focus_handle(cx).contains_focused(window, cx)
 5564            {
 5565                let leader_id = self
 5566                    .pane_for(&*item)
 5567                    .and_then(|pane| self.leader_for_pane(&pane));
 5568                let leader_peer_id = match leader_id {
 5569                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5570                    Some(CollaboratorId::Agent) | None => None,
 5571                };
 5572
 5573                if let Some(item) = item.to_followable_item_handle(cx) {
 5574                    let id = item
 5575                        .remote_id(&self.app_state.client, window, cx)
 5576                        .map(|id| id.to_proto());
 5577
 5578                    if let Some(id) = id
 5579                        && let Some(variant) = item.to_state_proto(window, cx)
 5580                    {
 5581                        let view = Some(proto::View {
 5582                            id,
 5583                            leader_id: leader_peer_id,
 5584                            variant: Some(variant),
 5585                            panel_id: panel_id.map(|id| id as i32),
 5586                        });
 5587
 5588                        is_project_item = item.is_project_item(window, cx);
 5589                        update = proto::UpdateActiveView { view };
 5590                    };
 5591                }
 5592            }
 5593        }
 5594
 5595        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5596        if active_view_id != self.last_active_view_id.as_ref() {
 5597            self.last_active_view_id = active_view_id.cloned();
 5598            self.update_followers(
 5599                is_project_item,
 5600                proto::update_followers::Variant::UpdateActiveView(update),
 5601                window,
 5602                cx,
 5603            );
 5604        }
 5605    }
 5606
 5607    fn active_item_for_followers(
 5608        &self,
 5609        window: &mut Window,
 5610        cx: &mut App,
 5611    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5612        let mut active_item = None;
 5613        let mut panel_id = None;
 5614        for dock in self.all_docks() {
 5615            if dock.focus_handle(cx).contains_focused(window, cx)
 5616                && let Some(panel) = dock.read(cx).active_panel()
 5617                && let Some(pane) = panel.pane(cx)
 5618                && let Some(item) = pane.read(cx).active_item()
 5619            {
 5620                active_item = Some(item);
 5621                panel_id = panel.remote_id();
 5622                break;
 5623            }
 5624        }
 5625
 5626        if active_item.is_none() {
 5627            active_item = self.active_pane().read(cx).active_item();
 5628        }
 5629        (active_item, panel_id)
 5630    }
 5631
 5632    fn update_followers(
 5633        &self,
 5634        project_only: bool,
 5635        update: proto::update_followers::Variant,
 5636        _: &mut Window,
 5637        cx: &mut App,
 5638    ) -> Option<()> {
 5639        // If this update only applies to for followers in the current project,
 5640        // then skip it unless this project is shared. If it applies to all
 5641        // followers, regardless of project, then set `project_id` to none,
 5642        // indicating that it goes to all followers.
 5643        let project_id = if project_only {
 5644            Some(self.project.read(cx).remote_id()?)
 5645        } else {
 5646            None
 5647        };
 5648        self.app_state().workspace_store.update(cx, |store, cx| {
 5649            store.update_followers(project_id, update, cx)
 5650        })
 5651    }
 5652
 5653    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5654        self.follower_states.iter().find_map(|(leader_id, state)| {
 5655            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5656                Some(*leader_id)
 5657            } else {
 5658                None
 5659            }
 5660        })
 5661    }
 5662
 5663    fn leader_updated(
 5664        &mut self,
 5665        leader_id: impl Into<CollaboratorId>,
 5666        window: &mut Window,
 5667        cx: &mut Context<Self>,
 5668    ) -> Option<Box<dyn ItemHandle>> {
 5669        cx.notify();
 5670
 5671        let leader_id = leader_id.into();
 5672        let (panel_id, item) = match leader_id {
 5673            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5674            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5675        };
 5676
 5677        let state = self.follower_states.get(&leader_id)?;
 5678        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5679        let pane;
 5680        if let Some(panel_id) = panel_id {
 5681            pane = self
 5682                .activate_panel_for_proto_id(panel_id, window, cx)?
 5683                .pane(cx)?;
 5684            let state = self.follower_states.get_mut(&leader_id)?;
 5685            state.dock_pane = Some(pane.clone());
 5686        } else {
 5687            pane = state.center_pane.clone();
 5688            let state = self.follower_states.get_mut(&leader_id)?;
 5689            if let Some(dock_pane) = state.dock_pane.take() {
 5690                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5691            }
 5692        }
 5693
 5694        pane.update(cx, |pane, cx| {
 5695            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5696            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5697                pane.activate_item(index, false, false, window, cx);
 5698            } else {
 5699                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5700            }
 5701
 5702            if focus_active_item {
 5703                pane.focus_active_item(window, cx)
 5704            }
 5705        });
 5706
 5707        Some(item)
 5708    }
 5709
 5710    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5711        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5712        let active_view_id = state.active_view_id?;
 5713        Some(
 5714            state
 5715                .items_by_leader_view_id
 5716                .get(&active_view_id)?
 5717                .view
 5718                .boxed_clone(),
 5719        )
 5720    }
 5721
 5722    fn active_item_for_peer(
 5723        &self,
 5724        peer_id: PeerId,
 5725        window: &mut Window,
 5726        cx: &mut Context<Self>,
 5727    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5728        let call = self.active_call()?;
 5729        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5730        let leader_in_this_app;
 5731        let leader_in_this_project;
 5732        match participant.location {
 5733            ParticipantLocation::SharedProject { project_id } => {
 5734                leader_in_this_app = true;
 5735                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5736            }
 5737            ParticipantLocation::UnsharedProject => {
 5738                leader_in_this_app = true;
 5739                leader_in_this_project = false;
 5740            }
 5741            ParticipantLocation::External => {
 5742                leader_in_this_app = false;
 5743                leader_in_this_project = false;
 5744            }
 5745        };
 5746        let state = self.follower_states.get(&peer_id.into())?;
 5747        let mut item_to_activate = None;
 5748        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5749            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5750                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5751            {
 5752                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5753            }
 5754        } else if let Some(shared_screen) =
 5755            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5756        {
 5757            item_to_activate = Some((None, Box::new(shared_screen)));
 5758        }
 5759        item_to_activate
 5760    }
 5761
 5762    fn shared_screen_for_peer(
 5763        &self,
 5764        peer_id: PeerId,
 5765        pane: &Entity<Pane>,
 5766        window: &mut Window,
 5767        cx: &mut App,
 5768    ) -> Option<Entity<SharedScreen>> {
 5769        self.active_call()?
 5770            .create_shared_screen(peer_id, pane, window, cx)
 5771    }
 5772
 5773    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5774        if window.is_window_active() {
 5775            self.update_active_view_for_followers(window, cx);
 5776
 5777            if let Some(database_id) = self.database_id {
 5778                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5779                    .detach();
 5780            }
 5781        } else {
 5782            for pane in &self.panes {
 5783                pane.update(cx, |pane, cx| {
 5784                    if let Some(item) = pane.active_item() {
 5785                        item.workspace_deactivated(window, cx);
 5786                    }
 5787                    for item in pane.items() {
 5788                        if matches!(
 5789                            item.workspace_settings(cx).autosave,
 5790                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5791                        ) {
 5792                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5793                                .detach_and_log_err(cx);
 5794                        }
 5795                    }
 5796                });
 5797            }
 5798        }
 5799    }
 5800
 5801    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5802        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5803    }
 5804
 5805    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5806        self.active_call.as_ref().map(|(call, _)| call.clone())
 5807    }
 5808
 5809    fn on_active_call_event(
 5810        &mut self,
 5811        event: &ActiveCallEvent,
 5812        window: &mut Window,
 5813        cx: &mut Context<Self>,
 5814    ) {
 5815        match event {
 5816            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 5817            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 5818                self.leader_updated(participant_id, window, cx);
 5819            }
 5820        }
 5821    }
 5822
 5823    pub fn database_id(&self) -> Option<WorkspaceId> {
 5824        self.database_id
 5825    }
 5826
 5827    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 5828        self.database_id = Some(id);
 5829    }
 5830
 5831    pub fn session_id(&self) -> Option<String> {
 5832        self.session_id.clone()
 5833    }
 5834
 5835    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5836        let Some(display) = window.display(cx) else {
 5837            return Task::ready(());
 5838        };
 5839        let Ok(display_uuid) = display.uuid() else {
 5840            return Task::ready(());
 5841        };
 5842
 5843        let window_bounds = window.inner_window_bounds();
 5844        let database_id = self.database_id;
 5845        let has_paths = !self.root_paths(cx).is_empty();
 5846
 5847        cx.background_executor().spawn(async move {
 5848            if !has_paths {
 5849                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5850                    .await
 5851                    .log_err();
 5852            }
 5853            if let Some(database_id) = database_id {
 5854                DB.set_window_open_status(
 5855                    database_id,
 5856                    SerializedWindowBounds(window_bounds),
 5857                    display_uuid,
 5858                )
 5859                .await
 5860                .log_err();
 5861            } else {
 5862                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5863                    .await
 5864                    .log_err();
 5865            }
 5866        })
 5867    }
 5868
 5869    /// Bypass the 200ms serialization throttle and write workspace state to
 5870    /// the DB immediately. Returns a task the caller can await to ensure the
 5871    /// write completes. Used by the quit handler so the most recent state
 5872    /// isn't lost to a pending throttle timer when the process exits.
 5873    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5874        self._schedule_serialize_workspace.take();
 5875        self._serialize_workspace_task.take();
 5876        self.bounds_save_task_queued.take();
 5877
 5878        let bounds_task = self.save_window_bounds(window, cx);
 5879        let serialize_task = self.serialize_workspace_internal(window, cx);
 5880        cx.spawn(async move |_| {
 5881            bounds_task.await;
 5882            serialize_task.await;
 5883        })
 5884    }
 5885
 5886    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5887        let project = self.project().read(cx);
 5888        project
 5889            .visible_worktrees(cx)
 5890            .map(|worktree| worktree.read(cx).abs_path())
 5891            .collect::<Vec<_>>()
 5892    }
 5893
 5894    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5895        match member {
 5896            Member::Axis(PaneAxis { members, .. }) => {
 5897                for child in members.iter() {
 5898                    self.remove_panes(child.clone(), window, cx)
 5899                }
 5900            }
 5901            Member::Pane(pane) => {
 5902                self.force_remove_pane(&pane, &None, window, cx);
 5903            }
 5904        }
 5905    }
 5906
 5907    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5908        self.session_id.take();
 5909        self.serialize_workspace_internal(window, cx)
 5910    }
 5911
 5912    fn force_remove_pane(
 5913        &mut self,
 5914        pane: &Entity<Pane>,
 5915        focus_on: &Option<Entity<Pane>>,
 5916        window: &mut Window,
 5917        cx: &mut Context<Workspace>,
 5918    ) {
 5919        self.panes.retain(|p| p != pane);
 5920        if let Some(focus_on) = focus_on {
 5921            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5922        } else if self.active_pane() == pane {
 5923            self.panes
 5924                .last()
 5925                .unwrap()
 5926                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5927        }
 5928        if self.last_active_center_pane == Some(pane.downgrade()) {
 5929            self.last_active_center_pane = None;
 5930        }
 5931        cx.notify();
 5932    }
 5933
 5934    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5935        if self._schedule_serialize_workspace.is_none() {
 5936            self._schedule_serialize_workspace =
 5937                Some(cx.spawn_in(window, async move |this, cx| {
 5938                    cx.background_executor()
 5939                        .timer(SERIALIZATION_THROTTLE_TIME)
 5940                        .await;
 5941                    this.update_in(cx, |this, window, cx| {
 5942                        this._serialize_workspace_task =
 5943                            Some(this.serialize_workspace_internal(window, cx));
 5944                        this._schedule_serialize_workspace.take();
 5945                    })
 5946                    .log_err();
 5947                }));
 5948        }
 5949    }
 5950
 5951    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5952        let Some(database_id) = self.database_id() else {
 5953            return Task::ready(());
 5954        };
 5955
 5956        fn serialize_pane_handle(
 5957            pane_handle: &Entity<Pane>,
 5958            window: &mut Window,
 5959            cx: &mut App,
 5960        ) -> SerializedPane {
 5961            let (items, active, pinned_count) = {
 5962                let pane = pane_handle.read(cx);
 5963                let active_item_id = pane.active_item().map(|item| item.item_id());
 5964                (
 5965                    pane.items()
 5966                        .filter_map(|handle| {
 5967                            let handle = handle.to_serializable_item_handle(cx)?;
 5968
 5969                            Some(SerializedItem {
 5970                                kind: Arc::from(handle.serialized_item_kind()),
 5971                                item_id: handle.item_id().as_u64(),
 5972                                active: Some(handle.item_id()) == active_item_id,
 5973                                preview: pane.is_active_preview_item(handle.item_id()),
 5974                            })
 5975                        })
 5976                        .collect::<Vec<_>>(),
 5977                    pane.has_focus(window, cx),
 5978                    pane.pinned_count(),
 5979                )
 5980            };
 5981
 5982            SerializedPane::new(items, active, pinned_count)
 5983        }
 5984
 5985        fn build_serialized_pane_group(
 5986            pane_group: &Member,
 5987            window: &mut Window,
 5988            cx: &mut App,
 5989        ) -> SerializedPaneGroup {
 5990            match pane_group {
 5991                Member::Axis(PaneAxis {
 5992                    axis,
 5993                    members,
 5994                    flexes,
 5995                    bounding_boxes: _,
 5996                }) => SerializedPaneGroup::Group {
 5997                    axis: SerializedAxis(*axis),
 5998                    children: members
 5999                        .iter()
 6000                        .map(|member| build_serialized_pane_group(member, window, cx))
 6001                        .collect::<Vec<_>>(),
 6002                    flexes: Some(flexes.lock().clone()),
 6003                },
 6004                Member::Pane(pane_handle) => {
 6005                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6006                }
 6007            }
 6008        }
 6009
 6010        fn build_serialized_docks(
 6011            this: &Workspace,
 6012            window: &mut Window,
 6013            cx: &mut App,
 6014        ) -> DockStructure {
 6015            let left_dock = this.left_dock.read(cx);
 6016            let left_visible = left_dock.is_open();
 6017            let left_active_panel = left_dock
 6018                .active_panel()
 6019                .map(|panel| panel.persistent_name().to_string());
 6020            let left_dock_zoom = left_dock
 6021                .active_panel()
 6022                .map(|panel| panel.is_zoomed(window, cx))
 6023                .unwrap_or(false);
 6024
 6025            let right_dock = this.right_dock.read(cx);
 6026            let right_visible = right_dock.is_open();
 6027            let right_active_panel = right_dock
 6028                .active_panel()
 6029                .map(|panel| panel.persistent_name().to_string());
 6030            let right_dock_zoom = right_dock
 6031                .active_panel()
 6032                .map(|panel| panel.is_zoomed(window, cx))
 6033                .unwrap_or(false);
 6034
 6035            let bottom_dock = this.bottom_dock.read(cx);
 6036            let bottom_visible = bottom_dock.is_open();
 6037            let bottom_active_panel = bottom_dock
 6038                .active_panel()
 6039                .map(|panel| panel.persistent_name().to_string());
 6040            let bottom_dock_zoom = bottom_dock
 6041                .active_panel()
 6042                .map(|panel| panel.is_zoomed(window, cx))
 6043                .unwrap_or(false);
 6044
 6045            DockStructure {
 6046                left: DockData {
 6047                    visible: left_visible,
 6048                    active_panel: left_active_panel,
 6049                    zoom: left_dock_zoom,
 6050                },
 6051                right: DockData {
 6052                    visible: right_visible,
 6053                    active_panel: right_active_panel,
 6054                    zoom: right_dock_zoom,
 6055                },
 6056                bottom: DockData {
 6057                    visible: bottom_visible,
 6058                    active_panel: bottom_active_panel,
 6059                    zoom: bottom_dock_zoom,
 6060                },
 6061            }
 6062        }
 6063
 6064        match self.workspace_location(cx) {
 6065            WorkspaceLocation::Location(location, paths) => {
 6066                let breakpoints = self.project.update(cx, |project, cx| {
 6067                    project
 6068                        .breakpoint_store()
 6069                        .read(cx)
 6070                        .all_source_breakpoints(cx)
 6071                });
 6072                let user_toolchains = self
 6073                    .project
 6074                    .read(cx)
 6075                    .user_toolchains(cx)
 6076                    .unwrap_or_default();
 6077
 6078                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6079                let docks = build_serialized_docks(self, window, cx);
 6080                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6081
 6082                let serialized_workspace = SerializedWorkspace {
 6083                    id: database_id,
 6084                    location,
 6085                    paths,
 6086                    center_group,
 6087                    window_bounds,
 6088                    display: Default::default(),
 6089                    docks,
 6090                    centered_layout: self.centered_layout,
 6091                    session_id: self.session_id.clone(),
 6092                    breakpoints,
 6093                    window_id: Some(window.window_handle().window_id().as_u64()),
 6094                    user_toolchains,
 6095                };
 6096
 6097                window.spawn(cx, async move |_| {
 6098                    persistence::DB.save_workspace(serialized_workspace).await;
 6099                })
 6100            }
 6101            WorkspaceLocation::DetachFromSession => {
 6102                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6103                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6104                // Save dock state for empty local workspaces
 6105                let docks = build_serialized_docks(self, window, cx);
 6106                window.spawn(cx, async move |_| {
 6107                    persistence::DB
 6108                        .set_window_open_status(
 6109                            database_id,
 6110                            window_bounds,
 6111                            display.unwrap_or_default(),
 6112                        )
 6113                        .await
 6114                        .log_err();
 6115                    persistence::DB
 6116                        .set_session_id(database_id, None)
 6117                        .await
 6118                        .log_err();
 6119                    persistence::write_default_dock_state(docks).await.log_err();
 6120                })
 6121            }
 6122            WorkspaceLocation::None => {
 6123                // Save dock state for empty non-local workspaces
 6124                let docks = build_serialized_docks(self, window, cx);
 6125                window.spawn(cx, async move |_| {
 6126                    persistence::write_default_dock_state(docks).await.log_err();
 6127                })
 6128            }
 6129        }
 6130    }
 6131
 6132    fn has_any_items_open(&self, cx: &App) -> bool {
 6133        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6134    }
 6135
 6136    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6137        let paths = PathList::new(&self.root_paths(cx));
 6138        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6139            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6140        } else if self.project.read(cx).is_local() {
 6141            if !paths.is_empty() || self.has_any_items_open(cx) {
 6142                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6143            } else {
 6144                WorkspaceLocation::DetachFromSession
 6145            }
 6146        } else {
 6147            WorkspaceLocation::None
 6148        }
 6149    }
 6150
 6151    fn update_history(&self, cx: &mut App) {
 6152        let Some(id) = self.database_id() else {
 6153            return;
 6154        };
 6155        if !self.project.read(cx).is_local() {
 6156            return;
 6157        }
 6158        if let Some(manager) = HistoryManager::global(cx) {
 6159            let paths = PathList::new(&self.root_paths(cx));
 6160            manager.update(cx, |this, cx| {
 6161                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6162            });
 6163        }
 6164    }
 6165
 6166    async fn serialize_items(
 6167        this: &WeakEntity<Self>,
 6168        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6169        cx: &mut AsyncWindowContext,
 6170    ) -> Result<()> {
 6171        const CHUNK_SIZE: usize = 200;
 6172
 6173        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6174
 6175        while let Some(items_received) = serializable_items.next().await {
 6176            let unique_items =
 6177                items_received
 6178                    .into_iter()
 6179                    .fold(HashMap::default(), |mut acc, item| {
 6180                        acc.entry(item.item_id()).or_insert(item);
 6181                        acc
 6182                    });
 6183
 6184            // We use into_iter() here so that the references to the items are moved into
 6185            // the tasks and not kept alive while we're sleeping.
 6186            for (_, item) in unique_items.into_iter() {
 6187                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6188                    item.serialize(workspace, false, window, cx)
 6189                }) {
 6190                    cx.background_spawn(async move { task.await.log_err() })
 6191                        .detach();
 6192                }
 6193            }
 6194
 6195            cx.background_executor()
 6196                .timer(SERIALIZATION_THROTTLE_TIME)
 6197                .await;
 6198        }
 6199
 6200        Ok(())
 6201    }
 6202
 6203    pub(crate) fn enqueue_item_serialization(
 6204        &mut self,
 6205        item: Box<dyn SerializableItemHandle>,
 6206    ) -> Result<()> {
 6207        self.serializable_items_tx
 6208            .unbounded_send(item)
 6209            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6210    }
 6211
 6212    pub(crate) fn load_workspace(
 6213        serialized_workspace: SerializedWorkspace,
 6214        paths_to_open: Vec<Option<ProjectPath>>,
 6215        window: &mut Window,
 6216        cx: &mut Context<Workspace>,
 6217    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6218        cx.spawn_in(window, async move |workspace, cx| {
 6219            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6220
 6221            let mut center_group = None;
 6222            let mut center_items = None;
 6223
 6224            // Traverse the splits tree and add to things
 6225            if let Some((group, active_pane, items)) = serialized_workspace
 6226                .center_group
 6227                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6228                .await
 6229            {
 6230                center_items = Some(items);
 6231                center_group = Some((group, active_pane))
 6232            }
 6233
 6234            let mut items_by_project_path = HashMap::default();
 6235            let mut item_ids_by_kind = HashMap::default();
 6236            let mut all_deserialized_items = Vec::default();
 6237            cx.update(|_, cx| {
 6238                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6239                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6240                        item_ids_by_kind
 6241                            .entry(serializable_item_handle.serialized_item_kind())
 6242                            .or_insert(Vec::new())
 6243                            .push(item.item_id().as_u64() as ItemId);
 6244                    }
 6245
 6246                    if let Some(project_path) = item.project_path(cx) {
 6247                        items_by_project_path.insert(project_path, item.clone());
 6248                    }
 6249                    all_deserialized_items.push(item);
 6250                }
 6251            })?;
 6252
 6253            let opened_items = paths_to_open
 6254                .into_iter()
 6255                .map(|path_to_open| {
 6256                    path_to_open
 6257                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6258                })
 6259                .collect::<Vec<_>>();
 6260
 6261            // Remove old panes from workspace panes list
 6262            workspace.update_in(cx, |workspace, window, cx| {
 6263                if let Some((center_group, active_pane)) = center_group {
 6264                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6265
 6266                    // Swap workspace center group
 6267                    workspace.center = PaneGroup::with_root(center_group);
 6268                    workspace.center.set_is_center(true);
 6269                    workspace.center.mark_positions(cx);
 6270
 6271                    if let Some(active_pane) = active_pane {
 6272                        workspace.set_active_pane(&active_pane, window, cx);
 6273                        cx.focus_self(window);
 6274                    } else {
 6275                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6276                    }
 6277                }
 6278
 6279                let docks = serialized_workspace.docks;
 6280
 6281                for (dock, serialized_dock) in [
 6282                    (&mut workspace.right_dock, docks.right),
 6283                    (&mut workspace.left_dock, docks.left),
 6284                    (&mut workspace.bottom_dock, docks.bottom),
 6285                ]
 6286                .iter_mut()
 6287                {
 6288                    dock.update(cx, |dock, cx| {
 6289                        dock.serialized_dock = Some(serialized_dock.clone());
 6290                        dock.restore_state(window, cx);
 6291                    });
 6292                }
 6293
 6294                cx.notify();
 6295            })?;
 6296
 6297            let _ = project
 6298                .update(cx, |project, cx| {
 6299                    project
 6300                        .breakpoint_store()
 6301                        .update(cx, |breakpoint_store, cx| {
 6302                            breakpoint_store
 6303                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6304                        })
 6305                })
 6306                .await;
 6307
 6308            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6309            // after loading the items, we might have different items and in order to avoid
 6310            // the database filling up, we delete items that haven't been loaded now.
 6311            //
 6312            // The items that have been loaded, have been saved after they've been added to the workspace.
 6313            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6314                item_ids_by_kind
 6315                    .into_iter()
 6316                    .map(|(item_kind, loaded_items)| {
 6317                        SerializableItemRegistry::cleanup(
 6318                            item_kind,
 6319                            serialized_workspace.id,
 6320                            loaded_items,
 6321                            window,
 6322                            cx,
 6323                        )
 6324                        .log_err()
 6325                    })
 6326                    .collect::<Vec<_>>()
 6327            })?;
 6328
 6329            futures::future::join_all(clean_up_tasks).await;
 6330
 6331            workspace
 6332                .update_in(cx, |workspace, window, cx| {
 6333                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6334                    workspace.serialize_workspace_internal(window, cx).detach();
 6335
 6336                    // Ensure that we mark the window as edited if we did load dirty items
 6337                    workspace.update_window_edited(window, cx);
 6338                })
 6339                .ok();
 6340
 6341            Ok(opened_items)
 6342        })
 6343    }
 6344
 6345    pub fn key_context(&self, cx: &App) -> KeyContext {
 6346        let mut context = KeyContext::new_with_defaults();
 6347        context.add("Workspace");
 6348        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6349        if let Some(status) = self
 6350            .debugger_provider
 6351            .as_ref()
 6352            .and_then(|provider| provider.active_thread_state(cx))
 6353        {
 6354            match status {
 6355                ThreadStatus::Running | ThreadStatus::Stepping => {
 6356                    context.add("debugger_running");
 6357                }
 6358                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6359                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6360            }
 6361        }
 6362
 6363        if self.left_dock.read(cx).is_open() {
 6364            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6365                context.set("left_dock", active_panel.panel_key());
 6366            }
 6367        }
 6368
 6369        if self.right_dock.read(cx).is_open() {
 6370            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6371                context.set("right_dock", active_panel.panel_key());
 6372            }
 6373        }
 6374
 6375        if self.bottom_dock.read(cx).is_open() {
 6376            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6377                context.set("bottom_dock", active_panel.panel_key());
 6378            }
 6379        }
 6380
 6381        context
 6382    }
 6383
 6384    /// Multiworkspace uses this to add workspace action handling to itself
 6385    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6386        self.add_workspace_actions_listeners(div, window, cx)
 6387            .on_action(cx.listener(
 6388                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6389                    for action in &action_sequence.0 {
 6390                        window.dispatch_action(action.boxed_clone(), cx);
 6391                    }
 6392                },
 6393            ))
 6394            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6395            .on_action(cx.listener(Self::close_all_items_and_panes))
 6396            .on_action(cx.listener(Self::close_item_in_all_panes))
 6397            .on_action(cx.listener(Self::save_all))
 6398            .on_action(cx.listener(Self::send_keystrokes))
 6399            .on_action(cx.listener(Self::add_folder_to_project))
 6400            .on_action(cx.listener(Self::follow_next_collaborator))
 6401            .on_action(cx.listener(Self::activate_pane_at_index))
 6402            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6403            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6404            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6405            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6406                let pane = workspace.active_pane().clone();
 6407                workspace.unfollow_in_pane(&pane, window, cx);
 6408            }))
 6409            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6410                workspace
 6411                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6412                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6413            }))
 6414            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6415                workspace
 6416                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6417                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6418            }))
 6419            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6420                workspace
 6421                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6422                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6423            }))
 6424            .on_action(
 6425                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6426                    workspace.activate_previous_pane(window, cx)
 6427                }),
 6428            )
 6429            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6430                workspace.activate_next_pane(window, cx)
 6431            }))
 6432            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6433                workspace.activate_last_pane(window, cx)
 6434            }))
 6435            .on_action(
 6436                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6437                    workspace.activate_next_window(cx)
 6438                }),
 6439            )
 6440            .on_action(
 6441                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6442                    workspace.activate_previous_window(cx)
 6443                }),
 6444            )
 6445            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6446                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6447            }))
 6448            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6449                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6450            }))
 6451            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6452                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6453            }))
 6454            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6455                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6456            }))
 6457            .on_action(cx.listener(
 6458                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6459                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6460                },
 6461            ))
 6462            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6463                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6464            }))
 6465            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6466                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6467            }))
 6468            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6469                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6470            }))
 6471            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6472                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6473            }))
 6474            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6475                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6476                    SplitDirection::Down,
 6477                    SplitDirection::Up,
 6478                    SplitDirection::Right,
 6479                    SplitDirection::Left,
 6480                ];
 6481                for dir in DIRECTION_PRIORITY {
 6482                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6483                        workspace.swap_pane_in_direction(dir, cx);
 6484                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6485                        break;
 6486                    }
 6487                }
 6488            }))
 6489            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6490                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6491            }))
 6492            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6493                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6494            }))
 6495            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6496                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6497            }))
 6498            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6499                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6500            }))
 6501            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6502                this.toggle_dock(DockPosition::Left, window, cx);
 6503            }))
 6504            .on_action(cx.listener(
 6505                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6506                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6507                },
 6508            ))
 6509            .on_action(cx.listener(
 6510                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6511                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6512                },
 6513            ))
 6514            .on_action(cx.listener(
 6515                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6516                    if !workspace.close_active_dock(window, cx) {
 6517                        cx.propagate();
 6518                    }
 6519                },
 6520            ))
 6521            .on_action(
 6522                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6523                    workspace.close_all_docks(window, cx);
 6524                }),
 6525            )
 6526            .on_action(cx.listener(Self::toggle_all_docks))
 6527            .on_action(cx.listener(
 6528                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6529                    workspace.clear_all_notifications(cx);
 6530                },
 6531            ))
 6532            .on_action(cx.listener(
 6533                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6534                    workspace.clear_navigation_history(window, cx);
 6535                },
 6536            ))
 6537            .on_action(cx.listener(
 6538                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6539                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6540                        workspace.suppress_notification(&notification_id, cx);
 6541                    }
 6542                },
 6543            ))
 6544            .on_action(cx.listener(
 6545                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6546                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6547                },
 6548            ))
 6549            .on_action(
 6550                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6551                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6552                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6553                            trusted_worktrees.clear_trusted_paths()
 6554                        });
 6555                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6556                        cx.spawn(async move |_, cx| {
 6557                            if clear_task.await.log_err().is_some() {
 6558                                cx.update(|cx| reload(cx));
 6559                            }
 6560                        })
 6561                        .detach();
 6562                    }
 6563                }),
 6564            )
 6565            .on_action(cx.listener(
 6566                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6567                    workspace.reopen_closed_item(window, cx).detach();
 6568                },
 6569            ))
 6570            .on_action(cx.listener(
 6571                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6572                    for dock in workspace.all_docks() {
 6573                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6574                            let Some(panel) = dock.read(cx).active_panel() else {
 6575                                return;
 6576                            };
 6577
 6578                            // Set to `None`, then the size will fall back to the default.
 6579                            panel.clone().set_size(None, window, cx);
 6580
 6581                            return;
 6582                        }
 6583                    }
 6584                },
 6585            ))
 6586            .on_action(cx.listener(
 6587                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6588                    for dock in workspace.all_docks() {
 6589                        if let Some(panel) = dock.read(cx).visible_panel() {
 6590                            // Set to `None`, then the size will fall back to the default.
 6591                            panel.clone().set_size(None, window, cx);
 6592                        }
 6593                    }
 6594                },
 6595            ))
 6596            .on_action(cx.listener(
 6597                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6598                    adjust_active_dock_size_by_px(
 6599                        px_with_ui_font_fallback(act.px, cx),
 6600                        workspace,
 6601                        window,
 6602                        cx,
 6603                    );
 6604                },
 6605            ))
 6606            .on_action(cx.listener(
 6607                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6608                    adjust_active_dock_size_by_px(
 6609                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6610                        workspace,
 6611                        window,
 6612                        cx,
 6613                    );
 6614                },
 6615            ))
 6616            .on_action(cx.listener(
 6617                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6618                    adjust_open_docks_size_by_px(
 6619                        px_with_ui_font_fallback(act.px, cx),
 6620                        workspace,
 6621                        window,
 6622                        cx,
 6623                    );
 6624                },
 6625            ))
 6626            .on_action(cx.listener(
 6627                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6628                    adjust_open_docks_size_by_px(
 6629                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6630                        workspace,
 6631                        window,
 6632                        cx,
 6633                    );
 6634                },
 6635            ))
 6636            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6637            .on_action(cx.listener(
 6638                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6639                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6640                        let dock = active_dock.read(cx);
 6641                        if let Some(active_panel) = dock.active_panel() {
 6642                            if active_panel.pane(cx).is_none() {
 6643                                let mut recent_pane: Option<Entity<Pane>> = None;
 6644                                let mut recent_timestamp = 0;
 6645                                for pane_handle in workspace.panes() {
 6646                                    let pane = pane_handle.read(cx);
 6647                                    for entry in pane.activation_history() {
 6648                                        if entry.timestamp > recent_timestamp {
 6649                                            recent_timestamp = entry.timestamp;
 6650                                            recent_pane = Some(pane_handle.clone());
 6651                                        }
 6652                                    }
 6653                                }
 6654
 6655                                if let Some(pane) = recent_pane {
 6656                                    pane.update(cx, |pane, cx| {
 6657                                        let current_index = pane.active_item_index();
 6658                                        let items_len = pane.items_len();
 6659                                        if items_len > 0 {
 6660                                            let next_index = if current_index + 1 < items_len {
 6661                                                current_index + 1
 6662                                            } else {
 6663                                                0
 6664                                            };
 6665                                            pane.activate_item(
 6666                                                next_index, false, false, window, cx,
 6667                                            );
 6668                                        }
 6669                                    });
 6670                                    return;
 6671                                }
 6672                            }
 6673                        }
 6674                    }
 6675                    cx.propagate();
 6676                },
 6677            ))
 6678            .on_action(cx.listener(
 6679                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6680                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6681                        let dock = active_dock.read(cx);
 6682                        if let Some(active_panel) = dock.active_panel() {
 6683                            if active_panel.pane(cx).is_none() {
 6684                                let mut recent_pane: Option<Entity<Pane>> = None;
 6685                                let mut recent_timestamp = 0;
 6686                                for pane_handle in workspace.panes() {
 6687                                    let pane = pane_handle.read(cx);
 6688                                    for entry in pane.activation_history() {
 6689                                        if entry.timestamp > recent_timestamp {
 6690                                            recent_timestamp = entry.timestamp;
 6691                                            recent_pane = Some(pane_handle.clone());
 6692                                        }
 6693                                    }
 6694                                }
 6695
 6696                                if let Some(pane) = recent_pane {
 6697                                    pane.update(cx, |pane, cx| {
 6698                                        let current_index = pane.active_item_index();
 6699                                        let items_len = pane.items_len();
 6700                                        if items_len > 0 {
 6701                                            let prev_index = if current_index > 0 {
 6702                                                current_index - 1
 6703                                            } else {
 6704                                                items_len.saturating_sub(1)
 6705                                            };
 6706                                            pane.activate_item(
 6707                                                prev_index, false, false, window, cx,
 6708                                            );
 6709                                        }
 6710                                    });
 6711                                    return;
 6712                                }
 6713                            }
 6714                        }
 6715                    }
 6716                    cx.propagate();
 6717                },
 6718            ))
 6719            .on_action(cx.listener(
 6720                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6721                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6722                        let dock = active_dock.read(cx);
 6723                        if let Some(active_panel) = dock.active_panel() {
 6724                            if active_panel.pane(cx).is_none() {
 6725                                let active_pane = workspace.active_pane().clone();
 6726                                active_pane.update(cx, |pane, cx| {
 6727                                    pane.close_active_item(action, window, cx)
 6728                                        .detach_and_log_err(cx);
 6729                                });
 6730                                return;
 6731                            }
 6732                        }
 6733                    }
 6734                    cx.propagate();
 6735                },
 6736            ))
 6737            .on_action(
 6738                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6739                    let pane = workspace.active_pane().clone();
 6740                    if let Some(item) = pane.read(cx).active_item() {
 6741                        item.toggle_read_only(window, cx);
 6742                    }
 6743                }),
 6744            )
 6745            .on_action(cx.listener(Workspace::cancel))
 6746    }
 6747
 6748    #[cfg(any(test, feature = "test-support"))]
 6749    pub fn set_random_database_id(&mut self) {
 6750        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6751    }
 6752
 6753    #[cfg(any(test, feature = "test-support"))]
 6754    pub(crate) fn test_new(
 6755        project: Entity<Project>,
 6756        window: &mut Window,
 6757        cx: &mut Context<Self>,
 6758    ) -> Self {
 6759        use node_runtime::NodeRuntime;
 6760        use session::Session;
 6761
 6762        let client = project.read(cx).client();
 6763        let user_store = project.read(cx).user_store();
 6764        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6765        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6766        window.activate_window();
 6767        let app_state = Arc::new(AppState {
 6768            languages: project.read(cx).languages().clone(),
 6769            workspace_store,
 6770            client,
 6771            user_store,
 6772            fs: project.read(cx).fs().clone(),
 6773            build_window_options: |_, _| Default::default(),
 6774            node_runtime: NodeRuntime::unavailable(),
 6775            session,
 6776        });
 6777        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6778        workspace
 6779            .active_pane
 6780            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6781        workspace
 6782    }
 6783
 6784    pub fn register_action<A: Action>(
 6785        &mut self,
 6786        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6787    ) -> &mut Self {
 6788        let callback = Arc::new(callback);
 6789
 6790        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6791            let callback = callback.clone();
 6792            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6793                (callback)(workspace, event, window, cx)
 6794            }))
 6795        }));
 6796        self
 6797    }
 6798    pub fn register_action_renderer(
 6799        &mut self,
 6800        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6801    ) -> &mut Self {
 6802        self.workspace_actions.push(Box::new(callback));
 6803        self
 6804    }
 6805
 6806    fn add_workspace_actions_listeners(
 6807        &self,
 6808        mut div: Div,
 6809        window: &mut Window,
 6810        cx: &mut Context<Self>,
 6811    ) -> Div {
 6812        for action in self.workspace_actions.iter() {
 6813            div = (action)(div, self, window, cx)
 6814        }
 6815        div
 6816    }
 6817
 6818    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6819        self.modal_layer.read(cx).has_active_modal()
 6820    }
 6821
 6822    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6823        self.modal_layer.read(cx).active_modal()
 6824    }
 6825
 6826    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6827    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6828    /// If no modal is active, the new modal will be shown.
 6829    ///
 6830    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6831    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6832    /// will not be shown.
 6833    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6834    where
 6835        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6836    {
 6837        self.modal_layer.update(cx, |modal_layer, cx| {
 6838            modal_layer.toggle_modal(window, cx, build)
 6839        })
 6840    }
 6841
 6842    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6843        self.modal_layer
 6844            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6845    }
 6846
 6847    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6848        self.toast_layer
 6849            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6850    }
 6851
 6852    pub fn toggle_centered_layout(
 6853        &mut self,
 6854        _: &ToggleCenteredLayout,
 6855        _: &mut Window,
 6856        cx: &mut Context<Self>,
 6857    ) {
 6858        self.centered_layout = !self.centered_layout;
 6859        if let Some(database_id) = self.database_id() {
 6860            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6861                .detach_and_log_err(cx);
 6862        }
 6863        cx.notify();
 6864    }
 6865
 6866    fn adjust_padding(padding: Option<f32>) -> f32 {
 6867        padding
 6868            .unwrap_or(CenteredPaddingSettings::default().0)
 6869            .clamp(
 6870                CenteredPaddingSettings::MIN_PADDING,
 6871                CenteredPaddingSettings::MAX_PADDING,
 6872            )
 6873    }
 6874
 6875    fn render_dock(
 6876        &self,
 6877        position: DockPosition,
 6878        dock: &Entity<Dock>,
 6879        window: &mut Window,
 6880        cx: &mut App,
 6881    ) -> Option<Div> {
 6882        if self.zoomed_position == Some(position) {
 6883            return None;
 6884        }
 6885
 6886        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6887            let pane = panel.pane(cx)?;
 6888            let follower_states = &self.follower_states;
 6889            leader_border_for_pane(follower_states, &pane, window, cx)
 6890        });
 6891
 6892        Some(
 6893            div()
 6894                .flex()
 6895                .flex_none()
 6896                .overflow_hidden()
 6897                .child(dock.clone())
 6898                .children(leader_border),
 6899        )
 6900    }
 6901
 6902    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 6903        window
 6904            .root::<MultiWorkspace>()
 6905            .flatten()
 6906            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 6907    }
 6908
 6909    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6910        self.zoomed.as_ref()
 6911    }
 6912
 6913    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6914        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6915            return;
 6916        };
 6917        let windows = cx.windows();
 6918        let next_window =
 6919            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6920                || {
 6921                    windows
 6922                        .iter()
 6923                        .cycle()
 6924                        .skip_while(|window| window.window_id() != current_window_id)
 6925                        .nth(1)
 6926                },
 6927            );
 6928
 6929        if let Some(window) = next_window {
 6930            window
 6931                .update(cx, |_, window, _| window.activate_window())
 6932                .ok();
 6933        }
 6934    }
 6935
 6936    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6937        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6938            return;
 6939        };
 6940        let windows = cx.windows();
 6941        let prev_window =
 6942            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6943                || {
 6944                    windows
 6945                        .iter()
 6946                        .rev()
 6947                        .cycle()
 6948                        .skip_while(|window| window.window_id() != current_window_id)
 6949                        .nth(1)
 6950                },
 6951            );
 6952
 6953        if let Some(window) = prev_window {
 6954            window
 6955                .update(cx, |_, window, _| window.activate_window())
 6956                .ok();
 6957        }
 6958    }
 6959
 6960    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6961        if cx.stop_active_drag(window) {
 6962        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6963            dismiss_app_notification(&notification_id, cx);
 6964        } else {
 6965            cx.propagate();
 6966        }
 6967    }
 6968
 6969    fn adjust_dock_size_by_px(
 6970        &mut self,
 6971        panel_size: Pixels,
 6972        dock_pos: DockPosition,
 6973        px: Pixels,
 6974        window: &mut Window,
 6975        cx: &mut Context<Self>,
 6976    ) {
 6977        match dock_pos {
 6978            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6979            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6980            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6981        }
 6982    }
 6983
 6984    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6985        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6986
 6987        self.left_dock.update(cx, |left_dock, cx| {
 6988            if WorkspaceSettings::get_global(cx)
 6989                .resize_all_panels_in_dock
 6990                .contains(&DockPosition::Left)
 6991            {
 6992                left_dock.resize_all_panels(Some(size), window, cx);
 6993            } else {
 6994                left_dock.resize_active_panel(Some(size), window, cx);
 6995            }
 6996        });
 6997    }
 6998
 6999    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7000        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 7001        self.left_dock.read_with(cx, |left_dock, cx| {
 7002            let left_dock_size = left_dock
 7003                .active_panel_size(window, cx)
 7004                .unwrap_or(Pixels::ZERO);
 7005            if left_dock_size + size > self.bounds.right() {
 7006                size = self.bounds.right() - left_dock_size
 7007            }
 7008        });
 7009        self.right_dock.update(cx, |right_dock, cx| {
 7010            if WorkspaceSettings::get_global(cx)
 7011                .resize_all_panels_in_dock
 7012                .contains(&DockPosition::Right)
 7013            {
 7014                right_dock.resize_all_panels(Some(size), window, cx);
 7015            } else {
 7016                right_dock.resize_active_panel(Some(size), window, cx);
 7017            }
 7018        });
 7019    }
 7020
 7021    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7022        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7023        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7024            if WorkspaceSettings::get_global(cx)
 7025                .resize_all_panels_in_dock
 7026                .contains(&DockPosition::Bottom)
 7027            {
 7028                bottom_dock.resize_all_panels(Some(size), window, cx);
 7029            } else {
 7030                bottom_dock.resize_active_panel(Some(size), window, cx);
 7031            }
 7032        });
 7033    }
 7034
 7035    fn toggle_edit_predictions_all_files(
 7036        &mut self,
 7037        _: &ToggleEditPrediction,
 7038        _window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        let fs = self.project().read(cx).fs().clone();
 7042        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7043        update_settings_file(fs, cx, move |file, _| {
 7044            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7045        });
 7046    }
 7047
 7048    pub fn show_worktree_trust_security_modal(
 7049        &mut self,
 7050        toggle: bool,
 7051        window: &mut Window,
 7052        cx: &mut Context<Self>,
 7053    ) {
 7054        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7055            if toggle {
 7056                security_modal.update(cx, |security_modal, cx| {
 7057                    security_modal.dismiss(cx);
 7058                })
 7059            } else {
 7060                security_modal.update(cx, |security_modal, cx| {
 7061                    security_modal.refresh_restricted_paths(cx);
 7062                });
 7063            }
 7064        } else {
 7065            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7066                .map(|trusted_worktrees| {
 7067                    trusted_worktrees
 7068                        .read(cx)
 7069                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7070                })
 7071                .unwrap_or(false);
 7072            if has_restricted_worktrees {
 7073                let project = self.project().read(cx);
 7074                let remote_host = project
 7075                    .remote_connection_options(cx)
 7076                    .map(RemoteHostLocation::from);
 7077                let worktree_store = project.worktree_store().downgrade();
 7078                self.toggle_modal(window, cx, |_, cx| {
 7079                    SecurityModal::new(worktree_store, remote_host, cx)
 7080                });
 7081            }
 7082        }
 7083    }
 7084}
 7085
 7086pub trait AnyActiveCall {
 7087    fn entity(&self) -> AnyEntity;
 7088    fn is_in_room(&self, _: &App) -> bool;
 7089    fn room_id(&self, _: &App) -> Option<u64>;
 7090    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7091    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7092    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7093    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7094    fn is_sharing_project(&self, _: &App) -> bool;
 7095    fn has_remote_participants(&self, _: &App) -> bool;
 7096    fn local_participant_is_guest(&self, _: &App) -> bool;
 7097    fn client(&self, _: &App) -> Arc<Client>;
 7098    fn share_on_join(&self, _: &App) -> bool;
 7099    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7100    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7101    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7102    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7103    fn join_project(
 7104        &self,
 7105        _: u64,
 7106        _: Arc<LanguageRegistry>,
 7107        _: Arc<dyn Fs>,
 7108        _: &mut App,
 7109    ) -> Task<Result<Entity<Project>>>;
 7110    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7111    fn subscribe(
 7112        &self,
 7113        _: &mut Window,
 7114        _: &mut Context<Workspace>,
 7115        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7116    ) -> Subscription;
 7117    fn create_shared_screen(
 7118        &self,
 7119        _: PeerId,
 7120        _: &Entity<Pane>,
 7121        _: &mut Window,
 7122        _: &mut App,
 7123    ) -> Option<Entity<SharedScreen>>;
 7124}
 7125
 7126#[derive(Clone)]
 7127pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7128impl Global for GlobalAnyActiveCall {}
 7129
 7130impl GlobalAnyActiveCall {
 7131    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7132        cx.try_global()
 7133    }
 7134
 7135    pub(crate) fn global(cx: &App) -> &Self {
 7136        cx.global()
 7137    }
 7138}
 7139/// Workspace-local view of a remote participant's location.
 7140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7141pub enum ParticipantLocation {
 7142    SharedProject { project_id: u64 },
 7143    UnsharedProject,
 7144    External,
 7145}
 7146
 7147impl ParticipantLocation {
 7148    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7149        match location
 7150            .and_then(|l| l.variant)
 7151            .context("participant location was not provided")?
 7152        {
 7153            proto::participant_location::Variant::SharedProject(project) => {
 7154                Ok(Self::SharedProject {
 7155                    project_id: project.id,
 7156                })
 7157            }
 7158            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7159            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7160        }
 7161    }
 7162}
 7163/// Workspace-local view of a remote collaborator's state.
 7164/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7165#[derive(Clone)]
 7166pub struct RemoteCollaborator {
 7167    pub user: Arc<User>,
 7168    pub peer_id: PeerId,
 7169    pub location: ParticipantLocation,
 7170    pub participant_index: ParticipantIndex,
 7171}
 7172
 7173pub enum ActiveCallEvent {
 7174    ParticipantLocationChanged { participant_id: PeerId },
 7175    RemoteVideoTracksChanged { participant_id: PeerId },
 7176}
 7177
 7178fn leader_border_for_pane(
 7179    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7180    pane: &Entity<Pane>,
 7181    _: &Window,
 7182    cx: &App,
 7183) -> Option<Div> {
 7184    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7185        if state.pane() == pane {
 7186            Some((*leader_id, state))
 7187        } else {
 7188            None
 7189        }
 7190    })?;
 7191
 7192    let mut leader_color = match leader_id {
 7193        CollaboratorId::PeerId(leader_peer_id) => {
 7194            let leader = GlobalAnyActiveCall::try_global(cx)?
 7195                .0
 7196                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7197
 7198            cx.theme()
 7199                .players()
 7200                .color_for_participant(leader.participant_index.0)
 7201                .cursor
 7202        }
 7203        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7204    };
 7205    leader_color.fade_out(0.3);
 7206    Some(
 7207        div()
 7208            .absolute()
 7209            .size_full()
 7210            .left_0()
 7211            .top_0()
 7212            .border_2()
 7213            .border_color(leader_color),
 7214    )
 7215}
 7216
 7217fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7218    ZED_WINDOW_POSITION
 7219        .zip(*ZED_WINDOW_SIZE)
 7220        .map(|(position, size)| Bounds {
 7221            origin: position,
 7222            size,
 7223        })
 7224}
 7225
 7226fn open_items(
 7227    serialized_workspace: Option<SerializedWorkspace>,
 7228    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7229    window: &mut Window,
 7230    cx: &mut Context<Workspace>,
 7231) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7232    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7233        Workspace::load_workspace(
 7234            serialized_workspace,
 7235            project_paths_to_open
 7236                .iter()
 7237                .map(|(_, project_path)| project_path)
 7238                .cloned()
 7239                .collect(),
 7240            window,
 7241            cx,
 7242        )
 7243    });
 7244
 7245    cx.spawn_in(window, async move |workspace, cx| {
 7246        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7247
 7248        if let Some(restored_items) = restored_items {
 7249            let restored_items = restored_items.await?;
 7250
 7251            let restored_project_paths = restored_items
 7252                .iter()
 7253                .filter_map(|item| {
 7254                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7255                        .ok()
 7256                        .flatten()
 7257                })
 7258                .collect::<HashSet<_>>();
 7259
 7260            for restored_item in restored_items {
 7261                opened_items.push(restored_item.map(Ok));
 7262            }
 7263
 7264            project_paths_to_open
 7265                .iter_mut()
 7266                .for_each(|(_, project_path)| {
 7267                    if let Some(project_path_to_open) = project_path
 7268                        && restored_project_paths.contains(project_path_to_open)
 7269                    {
 7270                        *project_path = None;
 7271                    }
 7272                });
 7273        } else {
 7274            for _ in 0..project_paths_to_open.len() {
 7275                opened_items.push(None);
 7276            }
 7277        }
 7278        assert!(opened_items.len() == project_paths_to_open.len());
 7279
 7280        let tasks =
 7281            project_paths_to_open
 7282                .into_iter()
 7283                .enumerate()
 7284                .map(|(ix, (abs_path, project_path))| {
 7285                    let workspace = workspace.clone();
 7286                    cx.spawn(async move |cx| {
 7287                        let file_project_path = project_path?;
 7288                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7289                            workspace.project().update(cx, |project, cx| {
 7290                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7291                            })
 7292                        });
 7293
 7294                        // We only want to open file paths here. If one of the items
 7295                        // here is a directory, it was already opened further above
 7296                        // with a `find_or_create_worktree`.
 7297                        if let Ok(task) = abs_path_task
 7298                            && task.await.is_none_or(|p| p.is_file())
 7299                        {
 7300                            return Some((
 7301                                ix,
 7302                                workspace
 7303                                    .update_in(cx, |workspace, window, cx| {
 7304                                        workspace.open_path(
 7305                                            file_project_path,
 7306                                            None,
 7307                                            true,
 7308                                            window,
 7309                                            cx,
 7310                                        )
 7311                                    })
 7312                                    .log_err()?
 7313                                    .await,
 7314                            ));
 7315                        }
 7316                        None
 7317                    })
 7318                });
 7319
 7320        let tasks = tasks.collect::<Vec<_>>();
 7321
 7322        let tasks = futures::future::join_all(tasks);
 7323        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7324            opened_items[ix] = Some(path_open_result);
 7325        }
 7326
 7327        Ok(opened_items)
 7328    })
 7329}
 7330
 7331enum ActivateInDirectionTarget {
 7332    Pane(Entity<Pane>),
 7333    Dock(Entity<Dock>),
 7334}
 7335
 7336fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7337    window
 7338        .update(cx, |multi_workspace, _, cx| {
 7339            let workspace = multi_workspace.workspace().clone();
 7340            workspace.update(cx, |workspace, cx| {
 7341                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7342                    struct DatabaseFailedNotification;
 7343
 7344                    workspace.show_notification(
 7345                        NotificationId::unique::<DatabaseFailedNotification>(),
 7346                        cx,
 7347                        |cx| {
 7348                            cx.new(|cx| {
 7349                                MessageNotification::new("Failed to load the database file.", cx)
 7350                                    .primary_message("File an Issue")
 7351                                    .primary_icon(IconName::Plus)
 7352                                    .primary_on_click(|window, cx| {
 7353                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7354                                    })
 7355                            })
 7356                        },
 7357                    );
 7358                }
 7359            });
 7360        })
 7361        .log_err();
 7362}
 7363
 7364fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7365    if val == 0 {
 7366        ThemeSettings::get_global(cx).ui_font_size(cx)
 7367    } else {
 7368        px(val as f32)
 7369    }
 7370}
 7371
 7372fn adjust_active_dock_size_by_px(
 7373    px: Pixels,
 7374    workspace: &mut Workspace,
 7375    window: &mut Window,
 7376    cx: &mut Context<Workspace>,
 7377) {
 7378    let Some(active_dock) = workspace
 7379        .all_docks()
 7380        .into_iter()
 7381        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7382    else {
 7383        return;
 7384    };
 7385    let dock = active_dock.read(cx);
 7386    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7387        return;
 7388    };
 7389    let dock_pos = dock.position();
 7390    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7391}
 7392
 7393fn adjust_open_docks_size_by_px(
 7394    px: Pixels,
 7395    workspace: &mut Workspace,
 7396    window: &mut Window,
 7397    cx: &mut Context<Workspace>,
 7398) {
 7399    let docks = workspace
 7400        .all_docks()
 7401        .into_iter()
 7402        .filter_map(|dock| {
 7403            if dock.read(cx).is_open() {
 7404                let dock = dock.read(cx);
 7405                let panel_size = dock.active_panel_size(window, cx)?;
 7406                let dock_pos = dock.position();
 7407                Some((panel_size, dock_pos, px))
 7408            } else {
 7409                None
 7410            }
 7411        })
 7412        .collect::<Vec<_>>();
 7413
 7414    docks
 7415        .into_iter()
 7416        .for_each(|(panel_size, dock_pos, offset)| {
 7417            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7418        });
 7419}
 7420
 7421impl Focusable for Workspace {
 7422    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7423        self.active_pane.focus_handle(cx)
 7424    }
 7425}
 7426
 7427#[derive(Clone)]
 7428struct DraggedDock(DockPosition);
 7429
 7430impl Render for DraggedDock {
 7431    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7432        gpui::Empty
 7433    }
 7434}
 7435
 7436impl Render for Workspace {
 7437    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7438        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7439        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7440            log::info!("Rendered first frame");
 7441        }
 7442
 7443        let centered_layout = self.centered_layout
 7444            && self.center.panes().len() == 1
 7445            && self.active_item(cx).is_some();
 7446        let render_padding = |size| {
 7447            (size > 0.0).then(|| {
 7448                div()
 7449                    .h_full()
 7450                    .w(relative(size))
 7451                    .bg(cx.theme().colors().editor_background)
 7452                    .border_color(cx.theme().colors().pane_group_border)
 7453            })
 7454        };
 7455        let paddings = if centered_layout {
 7456            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7457            (
 7458                render_padding(Self::adjust_padding(
 7459                    settings.left_padding.map(|padding| padding.0),
 7460                )),
 7461                render_padding(Self::adjust_padding(
 7462                    settings.right_padding.map(|padding| padding.0),
 7463                )),
 7464            )
 7465        } else {
 7466            (None, None)
 7467        };
 7468        let ui_font = theme::setup_ui_font(window, cx);
 7469
 7470        let theme = cx.theme().clone();
 7471        let colors = theme.colors();
 7472        let notification_entities = self
 7473            .notifications
 7474            .iter()
 7475            .map(|(_, notification)| notification.entity_id())
 7476            .collect::<Vec<_>>();
 7477        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7478
 7479        div()
 7480            .relative()
 7481            .size_full()
 7482            .flex()
 7483            .flex_col()
 7484            .font(ui_font)
 7485            .gap_0()
 7486                .justify_start()
 7487                .items_start()
 7488                .text_color(colors.text)
 7489                .overflow_hidden()
 7490                .children(self.titlebar_item.clone())
 7491                .on_modifiers_changed(move |_, _, cx| {
 7492                    for &id in &notification_entities {
 7493                        cx.notify(id);
 7494                    }
 7495                })
 7496                .child(
 7497                    div()
 7498                        .size_full()
 7499                        .relative()
 7500                        .flex_1()
 7501                        .flex()
 7502                        .flex_col()
 7503                        .child(
 7504                            div()
 7505                                .id("workspace")
 7506                                .bg(colors.background)
 7507                                .relative()
 7508                                .flex_1()
 7509                                .w_full()
 7510                                .flex()
 7511                                .flex_col()
 7512                                .overflow_hidden()
 7513                                .border_t_1()
 7514                                .border_b_1()
 7515                                .border_color(colors.border)
 7516                                .child({
 7517                                    let this = cx.entity();
 7518                                    canvas(
 7519                                        move |bounds, window, cx| {
 7520                                            this.update(cx, |this, cx| {
 7521                                                let bounds_changed = this.bounds != bounds;
 7522                                                this.bounds = bounds;
 7523
 7524                                                if bounds_changed {
 7525                                                    this.left_dock.update(cx, |dock, cx| {
 7526                                                        dock.clamp_panel_size(
 7527                                                            bounds.size.width,
 7528                                                            window,
 7529                                                            cx,
 7530                                                        )
 7531                                                    });
 7532
 7533                                                    this.right_dock.update(cx, |dock, cx| {
 7534                                                        dock.clamp_panel_size(
 7535                                                            bounds.size.width,
 7536                                                            window,
 7537                                                            cx,
 7538                                                        )
 7539                                                    });
 7540
 7541                                                    this.bottom_dock.update(cx, |dock, cx| {
 7542                                                        dock.clamp_panel_size(
 7543                                                            bounds.size.height,
 7544                                                            window,
 7545                                                            cx,
 7546                                                        )
 7547                                                    });
 7548                                                }
 7549                                            })
 7550                                        },
 7551                                        |_, _, _, _| {},
 7552                                    )
 7553                                    .absolute()
 7554                                    .size_full()
 7555                                })
 7556                                .when(self.zoomed.is_none(), |this| {
 7557                                    this.on_drag_move(cx.listener(
 7558                                        move |workspace,
 7559                                              e: &DragMoveEvent<DraggedDock>,
 7560                                              window,
 7561                                              cx| {
 7562                                            if workspace.previous_dock_drag_coordinates
 7563                                                != Some(e.event.position)
 7564                                            {
 7565                                                workspace.previous_dock_drag_coordinates =
 7566                                                    Some(e.event.position);
 7567                                                match e.drag(cx).0 {
 7568                                                    DockPosition::Left => {
 7569                                                        workspace.resize_left_dock(
 7570                                                            e.event.position.x
 7571                                                                - workspace.bounds.left(),
 7572                                                            window,
 7573                                                            cx,
 7574                                                        );
 7575                                                    }
 7576                                                    DockPosition::Right => {
 7577                                                        workspace.resize_right_dock(
 7578                                                            workspace.bounds.right()
 7579                                                                - e.event.position.x,
 7580                                                            window,
 7581                                                            cx,
 7582                                                        );
 7583                                                    }
 7584                                                    DockPosition::Bottom => {
 7585                                                        workspace.resize_bottom_dock(
 7586                                                            workspace.bounds.bottom()
 7587                                                                - e.event.position.y,
 7588                                                            window,
 7589                                                            cx,
 7590                                                        );
 7591                                                    }
 7592                                                };
 7593                                                workspace.serialize_workspace(window, cx);
 7594                                            }
 7595                                        },
 7596                                    ))
 7597
 7598                                })
 7599                                .child({
 7600                                    match bottom_dock_layout {
 7601                                        BottomDockLayout::Full => div()
 7602                                            .flex()
 7603                                            .flex_col()
 7604                                            .h_full()
 7605                                            .child(
 7606                                                div()
 7607                                                    .flex()
 7608                                                    .flex_row()
 7609                                                    .flex_1()
 7610                                                    .overflow_hidden()
 7611                                                    .children(self.render_dock(
 7612                                                        DockPosition::Left,
 7613                                                        &self.left_dock,
 7614                                                        window,
 7615                                                        cx,
 7616                                                    ))
 7617
 7618                                                    .child(
 7619                                                        div()
 7620                                                            .flex()
 7621                                                            .flex_col()
 7622                                                            .flex_1()
 7623                                                            .overflow_hidden()
 7624                                                            .child(
 7625                                                                h_flex()
 7626                                                                    .flex_1()
 7627                                                                    .when_some(
 7628                                                                        paddings.0,
 7629                                                                        |this, p| {
 7630                                                                            this.child(
 7631                                                                                p.border_r_1(),
 7632                                                                            )
 7633                                                                        },
 7634                                                                    )
 7635                                                                    .child(self.center.render(
 7636                                                                        self.zoomed.as_ref(),
 7637                                                                        &PaneRenderContext {
 7638                                                                            follower_states:
 7639                                                                                &self.follower_states,
 7640                                                                            active_call: self.active_call(),
 7641                                                                            active_pane: &self.active_pane,
 7642                                                                            app_state: &self.app_state,
 7643                                                                            project: &self.project,
 7644                                                                            workspace: &self.weak_self,
 7645                                                                        },
 7646                                                                        window,
 7647                                                                        cx,
 7648                                                                    ))
 7649                                                                    .when_some(
 7650                                                                        paddings.1,
 7651                                                                        |this, p| {
 7652                                                                            this.child(
 7653                                                                                p.border_l_1(),
 7654                                                                            )
 7655                                                                        },
 7656                                                                    ),
 7657                                                            ),
 7658                                                    )
 7659
 7660                                                    .children(self.render_dock(
 7661                                                        DockPosition::Right,
 7662                                                        &self.right_dock,
 7663                                                        window,
 7664                                                        cx,
 7665                                                    )),
 7666                                            )
 7667                                            .child(div().w_full().children(self.render_dock(
 7668                                                DockPosition::Bottom,
 7669                                                &self.bottom_dock,
 7670                                                window,
 7671                                                cx
 7672                                            ))),
 7673
 7674                                        BottomDockLayout::LeftAligned => div()
 7675                                            .flex()
 7676                                            .flex_row()
 7677                                            .h_full()
 7678                                            .child(
 7679                                                div()
 7680                                                    .flex()
 7681                                                    .flex_col()
 7682                                                    .flex_1()
 7683                                                    .h_full()
 7684                                                    .child(
 7685                                                        div()
 7686                                                            .flex()
 7687                                                            .flex_row()
 7688                                                            .flex_1()
 7689                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7690
 7691                                                            .child(
 7692                                                                div()
 7693                                                                    .flex()
 7694                                                                    .flex_col()
 7695                                                                    .flex_1()
 7696                                                                    .overflow_hidden()
 7697                                                                    .child(
 7698                                                                        h_flex()
 7699                                                                            .flex_1()
 7700                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7701                                                                            .child(self.center.render(
 7702                                                                                self.zoomed.as_ref(),
 7703                                                                                &PaneRenderContext {
 7704                                                                                    follower_states:
 7705                                                                                        &self.follower_states,
 7706                                                                                    active_call: self.active_call(),
 7707                                                                                    active_pane: &self.active_pane,
 7708                                                                                    app_state: &self.app_state,
 7709                                                                                    project: &self.project,
 7710                                                                                    workspace: &self.weak_self,
 7711                                                                                },
 7712                                                                                window,
 7713                                                                                cx,
 7714                                                                            ))
 7715                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7716                                                                    )
 7717                                                            )
 7718
 7719                                                    )
 7720                                                    .child(
 7721                                                        div()
 7722                                                            .w_full()
 7723                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7724                                                    ),
 7725                                            )
 7726                                            .children(self.render_dock(
 7727                                                DockPosition::Right,
 7728                                                &self.right_dock,
 7729                                                window,
 7730                                                cx,
 7731                                            )),
 7732
 7733                                        BottomDockLayout::RightAligned => div()
 7734                                            .flex()
 7735                                            .flex_row()
 7736                                            .h_full()
 7737                                            .children(self.render_dock(
 7738                                                DockPosition::Left,
 7739                                                &self.left_dock,
 7740                                                window,
 7741                                                cx,
 7742                                            ))
 7743
 7744                                            .child(
 7745                                                div()
 7746                                                    .flex()
 7747                                                    .flex_col()
 7748                                                    .flex_1()
 7749                                                    .h_full()
 7750                                                    .child(
 7751                                                        div()
 7752                                                            .flex()
 7753                                                            .flex_row()
 7754                                                            .flex_1()
 7755                                                            .child(
 7756                                                                div()
 7757                                                                    .flex()
 7758                                                                    .flex_col()
 7759                                                                    .flex_1()
 7760                                                                    .overflow_hidden()
 7761                                                                    .child(
 7762                                                                        h_flex()
 7763                                                                            .flex_1()
 7764                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7765                                                                            .child(self.center.render(
 7766                                                                                self.zoomed.as_ref(),
 7767                                                                                &PaneRenderContext {
 7768                                                                                    follower_states:
 7769                                                                                        &self.follower_states,
 7770                                                                                    active_call: self.active_call(),
 7771                                                                                    active_pane: &self.active_pane,
 7772                                                                                    app_state: &self.app_state,
 7773                                                                                    project: &self.project,
 7774                                                                                    workspace: &self.weak_self,
 7775                                                                                },
 7776                                                                                window,
 7777                                                                                cx,
 7778                                                                            ))
 7779                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7780                                                                    )
 7781                                                            )
 7782
 7783                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7784                                                    )
 7785                                                    .child(
 7786                                                        div()
 7787                                                            .w_full()
 7788                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7789                                                    ),
 7790                                            ),
 7791
 7792                                        BottomDockLayout::Contained => div()
 7793                                            .flex()
 7794                                            .flex_row()
 7795                                            .h_full()
 7796                                            .children(self.render_dock(
 7797                                                DockPosition::Left,
 7798                                                &self.left_dock,
 7799                                                window,
 7800                                                cx,
 7801                                            ))
 7802
 7803                                            .child(
 7804                                                div()
 7805                                                    .flex()
 7806                                                    .flex_col()
 7807                                                    .flex_1()
 7808                                                    .overflow_hidden()
 7809                                                    .child(
 7810                                                        h_flex()
 7811                                                            .flex_1()
 7812                                                            .when_some(paddings.0, |this, p| {
 7813                                                                this.child(p.border_r_1())
 7814                                                            })
 7815                                                            .child(self.center.render(
 7816                                                                self.zoomed.as_ref(),
 7817                                                                &PaneRenderContext {
 7818                                                                    follower_states:
 7819                                                                        &self.follower_states,
 7820                                                                    active_call: self.active_call(),
 7821                                                                    active_pane: &self.active_pane,
 7822                                                                    app_state: &self.app_state,
 7823                                                                    project: &self.project,
 7824                                                                    workspace: &self.weak_self,
 7825                                                                },
 7826                                                                window,
 7827                                                                cx,
 7828                                                            ))
 7829                                                            .when_some(paddings.1, |this, p| {
 7830                                                                this.child(p.border_l_1())
 7831                                                            }),
 7832                                                    )
 7833                                                    .children(self.render_dock(
 7834                                                        DockPosition::Bottom,
 7835                                                        &self.bottom_dock,
 7836                                                        window,
 7837                                                        cx,
 7838                                                    )),
 7839                                            )
 7840
 7841                                            .children(self.render_dock(
 7842                                                DockPosition::Right,
 7843                                                &self.right_dock,
 7844                                                window,
 7845                                                cx,
 7846                                            )),
 7847                                    }
 7848                                })
 7849                                .children(self.zoomed.as_ref().and_then(|view| {
 7850                                    let zoomed_view = view.upgrade()?;
 7851                                    let div = div()
 7852                                        .occlude()
 7853                                        .absolute()
 7854                                        .overflow_hidden()
 7855                                        .border_color(colors.border)
 7856                                        .bg(colors.background)
 7857                                        .child(zoomed_view)
 7858                                        .inset_0()
 7859                                        .shadow_lg();
 7860
 7861                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7862                                       return Some(div);
 7863                                    }
 7864
 7865                                    Some(match self.zoomed_position {
 7866                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7867                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7868                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7869                                        None => {
 7870                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7871                                        }
 7872                                    })
 7873                                }))
 7874                                .children(self.render_notifications(window, cx)),
 7875                        )
 7876                        .when(self.status_bar_visible(cx), |parent| {
 7877                            parent.child(self.status_bar.clone())
 7878                        })
 7879                        .child(self.toast_layer.clone()),
 7880                )
 7881    }
 7882}
 7883
 7884impl WorkspaceStore {
 7885    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7886        Self {
 7887            workspaces: Default::default(),
 7888            _subscriptions: vec![
 7889                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7890                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7891            ],
 7892            client,
 7893        }
 7894    }
 7895
 7896    pub fn update_followers(
 7897        &self,
 7898        project_id: Option<u64>,
 7899        update: proto::update_followers::Variant,
 7900        cx: &App,
 7901    ) -> Option<()> {
 7902        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 7903        let room_id = active_call.0.room_id(cx)?;
 7904        self.client
 7905            .send(proto::UpdateFollowers {
 7906                room_id,
 7907                project_id,
 7908                variant: Some(update),
 7909            })
 7910            .log_err()
 7911    }
 7912
 7913    pub async fn handle_follow(
 7914        this: Entity<Self>,
 7915        envelope: TypedEnvelope<proto::Follow>,
 7916        mut cx: AsyncApp,
 7917    ) -> Result<proto::FollowResponse> {
 7918        this.update(&mut cx, |this, cx| {
 7919            let follower = Follower {
 7920                project_id: envelope.payload.project_id,
 7921                peer_id: envelope.original_sender_id()?,
 7922            };
 7923
 7924            let mut response = proto::FollowResponse::default();
 7925
 7926            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7927                let Some(workspace) = weak_workspace.upgrade() else {
 7928                    return false;
 7929                };
 7930                window_handle
 7931                    .update(cx, |_, window, cx| {
 7932                        workspace.update(cx, |workspace, cx| {
 7933                            let handler_response =
 7934                                workspace.handle_follow(follower.project_id, window, cx);
 7935                            if let Some(active_view) = handler_response.active_view
 7936                                && workspace.project.read(cx).remote_id() == follower.project_id
 7937                            {
 7938                                response.active_view = Some(active_view)
 7939                            }
 7940                        });
 7941                    })
 7942                    .is_ok()
 7943            });
 7944
 7945            Ok(response)
 7946        })
 7947    }
 7948
 7949    async fn handle_update_followers(
 7950        this: Entity<Self>,
 7951        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7952        mut cx: AsyncApp,
 7953    ) -> Result<()> {
 7954        let leader_id = envelope.original_sender_id()?;
 7955        let update = envelope.payload;
 7956
 7957        this.update(&mut cx, |this, cx| {
 7958            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7959                let Some(workspace) = weak_workspace.upgrade() else {
 7960                    return false;
 7961                };
 7962                window_handle
 7963                    .update(cx, |_, window, cx| {
 7964                        workspace.update(cx, |workspace, cx| {
 7965                            let project_id = workspace.project.read(cx).remote_id();
 7966                            if update.project_id != project_id && update.project_id.is_some() {
 7967                                return;
 7968                            }
 7969                            workspace.handle_update_followers(
 7970                                leader_id,
 7971                                update.clone(),
 7972                                window,
 7973                                cx,
 7974                            );
 7975                        });
 7976                    })
 7977                    .is_ok()
 7978            });
 7979            Ok(())
 7980        })
 7981    }
 7982
 7983    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 7984        self.workspaces.iter().map(|(_, weak)| weak)
 7985    }
 7986
 7987    pub fn workspaces_with_windows(
 7988        &self,
 7989    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 7990        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 7991    }
 7992}
 7993
 7994impl ViewId {
 7995    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7996        Ok(Self {
 7997            creator: message
 7998                .creator
 7999                .map(CollaboratorId::PeerId)
 8000                .context("creator is missing")?,
 8001            id: message.id,
 8002        })
 8003    }
 8004
 8005    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8006        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8007            Some(proto::ViewId {
 8008                creator: Some(peer_id),
 8009                id: self.id,
 8010            })
 8011        } else {
 8012            None
 8013        }
 8014    }
 8015}
 8016
 8017impl FollowerState {
 8018    fn pane(&self) -> &Entity<Pane> {
 8019        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8020    }
 8021}
 8022
 8023pub trait WorkspaceHandle {
 8024    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8025}
 8026
 8027impl WorkspaceHandle for Entity<Workspace> {
 8028    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8029        self.read(cx)
 8030            .worktrees(cx)
 8031            .flat_map(|worktree| {
 8032                let worktree_id = worktree.read(cx).id();
 8033                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8034                    worktree_id,
 8035                    path: f.path.clone(),
 8036                })
 8037            })
 8038            .collect::<Vec<_>>()
 8039    }
 8040}
 8041
 8042pub async fn last_opened_workspace_location(
 8043    fs: &dyn fs::Fs,
 8044) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8045    DB.last_workspace(fs)
 8046        .await
 8047        .log_err()
 8048        .flatten()
 8049        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8050}
 8051
 8052pub async fn last_session_workspace_locations(
 8053    last_session_id: &str,
 8054    last_session_window_stack: Option<Vec<WindowId>>,
 8055    fs: &dyn fs::Fs,
 8056) -> Option<Vec<SessionWorkspace>> {
 8057    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8058        .await
 8059        .log_err()
 8060}
 8061
 8062pub struct MultiWorkspaceRestoreResult {
 8063    pub window_handle: WindowHandle<MultiWorkspace>,
 8064    pub errors: Vec<anyhow::Error>,
 8065}
 8066
 8067pub async fn restore_multiworkspace(
 8068    multi_workspace: SerializedMultiWorkspace,
 8069    app_state: Arc<AppState>,
 8070    cx: &mut AsyncApp,
 8071) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8072    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8073    let mut group_iter = workspaces.into_iter();
 8074    let first = group_iter
 8075        .next()
 8076        .context("window group must not be empty")?;
 8077
 8078    let window_handle = if first.paths.is_empty() {
 8079        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8080            .await?
 8081    } else {
 8082        let (window, _items) = cx
 8083            .update(|cx| {
 8084                Workspace::new_local(
 8085                    first.paths.paths().to_vec(),
 8086                    app_state.clone(),
 8087                    None,
 8088                    None,
 8089                    None,
 8090                    cx,
 8091                )
 8092            })
 8093            .await?;
 8094        window
 8095    };
 8096
 8097    let mut errors = Vec::new();
 8098
 8099    for session_workspace in group_iter {
 8100        let error = if session_workspace.paths.is_empty() {
 8101            cx.update(|cx| {
 8102                open_workspace_by_id(
 8103                    session_workspace.workspace_id,
 8104                    app_state.clone(),
 8105                    Some(window_handle),
 8106                    cx,
 8107                )
 8108            })
 8109            .await
 8110            .err()
 8111        } else {
 8112            cx.update(|cx| {
 8113                Workspace::new_local(
 8114                    session_workspace.paths.paths().to_vec(),
 8115                    app_state.clone(),
 8116                    Some(window_handle),
 8117                    None,
 8118                    None,
 8119                    cx,
 8120                )
 8121            })
 8122            .await
 8123            .err()
 8124        };
 8125
 8126        if let Some(error) = error {
 8127            errors.push(error);
 8128        }
 8129    }
 8130
 8131    if let Some(target_id) = state.active_workspace_id {
 8132        window_handle
 8133            .update(cx, |multi_workspace, window, cx| {
 8134                let target_index = multi_workspace
 8135                    .workspaces()
 8136                    .iter()
 8137                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8138                if let Some(index) = target_index {
 8139                    multi_workspace.activate_index(index, window, cx);
 8140                } else if !multi_workspace.workspaces().is_empty() {
 8141                    multi_workspace.activate_index(0, window, cx);
 8142                }
 8143            })
 8144            .ok();
 8145    } else {
 8146        window_handle
 8147            .update(cx, |multi_workspace, window, cx| {
 8148                if !multi_workspace.workspaces().is_empty() {
 8149                    multi_workspace.activate_index(0, window, cx);
 8150                }
 8151            })
 8152            .ok();
 8153    }
 8154
 8155    if state.sidebar_open {
 8156        window_handle
 8157            .update(cx, |multi_workspace, _, cx| {
 8158                multi_workspace.open_sidebar(cx);
 8159            })
 8160            .ok();
 8161    }
 8162
 8163    window_handle
 8164        .update(cx, |_, window, _cx| {
 8165            window.activate_window();
 8166        })
 8167        .ok();
 8168
 8169    Ok(MultiWorkspaceRestoreResult {
 8170        window_handle,
 8171        errors,
 8172    })
 8173}
 8174
 8175actions!(
 8176    collab,
 8177    [
 8178        /// Opens the channel notes for the current call.
 8179        ///
 8180        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8181        /// channel in the collab panel.
 8182        ///
 8183        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8184        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8185        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8186        OpenChannelNotes,
 8187        /// Mutes your microphone.
 8188        Mute,
 8189        /// Deafens yourself (mute both microphone and speakers).
 8190        Deafen,
 8191        /// Leaves the current call.
 8192        LeaveCall,
 8193        /// Shares the current project with collaborators.
 8194        ShareProject,
 8195        /// Shares your screen with collaborators.
 8196        ScreenShare,
 8197        /// Copies the current room name and session id for debugging purposes.
 8198        CopyRoomId,
 8199    ]
 8200);
 8201actions!(
 8202    zed,
 8203    [
 8204        /// Opens the Zed log file.
 8205        OpenLog,
 8206        /// Reveals the Zed log file in the system file manager.
 8207        RevealLogInFileManager
 8208    ]
 8209);
 8210
 8211async fn join_channel_internal(
 8212    channel_id: ChannelId,
 8213    app_state: &Arc<AppState>,
 8214    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8215    requesting_workspace: Option<WeakEntity<Workspace>>,
 8216    active_call: &dyn AnyActiveCall,
 8217    cx: &mut AsyncApp,
 8218) -> Result<bool> {
 8219    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8220        if !active_call.is_in_room(cx) {
 8221            return (false, false);
 8222        }
 8223
 8224        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8225        let should_prompt = active_call.is_sharing_project(cx)
 8226            && active_call.has_remote_participants(cx)
 8227            && !already_in_channel;
 8228        (should_prompt, already_in_channel)
 8229    });
 8230
 8231    if already_in_channel {
 8232        let task = cx.update(|cx| {
 8233            if let Some((project, host)) = active_call.most_active_project(cx) {
 8234                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8235            } else {
 8236                None
 8237            }
 8238        });
 8239        if let Some(task) = task {
 8240            task.await?;
 8241        }
 8242        return anyhow::Ok(true);
 8243    }
 8244
 8245    if should_prompt {
 8246        if let Some(multi_workspace) = requesting_window {
 8247            let answer = multi_workspace
 8248                .update(cx, |_, window, cx| {
 8249                    window.prompt(
 8250                        PromptLevel::Warning,
 8251                        "Do you want to switch channels?",
 8252                        Some("Leaving this call will unshare your current project."),
 8253                        &["Yes, Join Channel", "Cancel"],
 8254                        cx,
 8255                    )
 8256                })?
 8257                .await;
 8258
 8259            if answer == Ok(1) {
 8260                return Ok(false);
 8261            }
 8262        } else {
 8263            return Ok(false);
 8264        }
 8265    }
 8266
 8267    let client = cx.update(|cx| active_call.client(cx));
 8268
 8269    let mut client_status = client.status();
 8270
 8271    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8272    'outer: loop {
 8273        let Some(status) = client_status.recv().await else {
 8274            anyhow::bail!("error connecting");
 8275        };
 8276
 8277        match status {
 8278            Status::Connecting
 8279            | Status::Authenticating
 8280            | Status::Authenticated
 8281            | Status::Reconnecting
 8282            | Status::Reauthenticating
 8283            | Status::Reauthenticated => continue,
 8284            Status::Connected { .. } => break 'outer,
 8285            Status::SignedOut | Status::AuthenticationError => {
 8286                return Err(ErrorCode::SignedOut.into());
 8287            }
 8288            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8289            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8290                return Err(ErrorCode::Disconnected.into());
 8291            }
 8292        }
 8293    }
 8294
 8295    let joined = cx
 8296        .update(|cx| active_call.join_channel(channel_id, cx))
 8297        .await?;
 8298
 8299    if !joined {
 8300        return anyhow::Ok(true);
 8301    }
 8302
 8303    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8304
 8305    let task = cx.update(|cx| {
 8306        if let Some((project, host)) = active_call.most_active_project(cx) {
 8307            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8308        }
 8309
 8310        // If you are the first to join a channel, see if you should share your project.
 8311        if !active_call.has_remote_participants(cx)
 8312            && !active_call.local_participant_is_guest(cx)
 8313            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8314        {
 8315            let project = workspace.update(cx, |workspace, cx| {
 8316                let project = workspace.project.read(cx);
 8317
 8318                if !active_call.share_on_join(cx) {
 8319                    return None;
 8320                }
 8321
 8322                if (project.is_local() || project.is_via_remote_server())
 8323                    && project.visible_worktrees(cx).any(|tree| {
 8324                        tree.read(cx)
 8325                            .root_entry()
 8326                            .is_some_and(|entry| entry.is_dir())
 8327                    })
 8328                {
 8329                    Some(workspace.project.clone())
 8330                } else {
 8331                    None
 8332                }
 8333            });
 8334            if let Some(project) = project {
 8335                let share_task = active_call.share_project(project, cx);
 8336                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8337                    share_task.await?;
 8338                    Ok(())
 8339                }));
 8340            }
 8341        }
 8342
 8343        None
 8344    });
 8345    if let Some(task) = task {
 8346        task.await?;
 8347        return anyhow::Ok(true);
 8348    }
 8349    anyhow::Ok(false)
 8350}
 8351
 8352pub fn join_channel(
 8353    channel_id: ChannelId,
 8354    app_state: Arc<AppState>,
 8355    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8356    requesting_workspace: Option<WeakEntity<Workspace>>,
 8357    cx: &mut App,
 8358) -> Task<Result<()>> {
 8359    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8360    cx.spawn(async move |cx| {
 8361        let result = join_channel_internal(
 8362            channel_id,
 8363            &app_state,
 8364            requesting_window,
 8365            requesting_workspace,
 8366            &*active_call.0,
 8367            cx,
 8368        )
 8369        .await;
 8370
 8371        // join channel succeeded, and opened a window
 8372        if matches!(result, Ok(true)) {
 8373            return anyhow::Ok(());
 8374        }
 8375
 8376        // find an existing workspace to focus and show call controls
 8377        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8378        if active_window.is_none() {
 8379            // no open workspaces, make one to show the error in (blergh)
 8380            let (window_handle, _) = cx
 8381                .update(|cx| {
 8382                    Workspace::new_local(
 8383                        vec![],
 8384                        app_state.clone(),
 8385                        requesting_window,
 8386                        None,
 8387                        None,
 8388                        cx,
 8389                    )
 8390                })
 8391                .await?;
 8392
 8393            window_handle
 8394                .update(cx, |_, window, _cx| {
 8395                    window.activate_window();
 8396                })
 8397                .ok();
 8398
 8399            if result.is_ok() {
 8400                cx.update(|cx| {
 8401                    cx.dispatch_action(&OpenChannelNotes);
 8402                });
 8403            }
 8404
 8405            active_window = Some(window_handle);
 8406        }
 8407
 8408        if let Err(err) = result {
 8409            log::error!("failed to join channel: {}", err);
 8410            if let Some(active_window) = active_window {
 8411                active_window
 8412                    .update(cx, |_, window, cx| {
 8413                        let detail: SharedString = match err.error_code() {
 8414                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8415                            ErrorCode::UpgradeRequired => concat!(
 8416                                "Your are running an unsupported version of Zed. ",
 8417                                "Please update to continue."
 8418                            )
 8419                            .into(),
 8420                            ErrorCode::NoSuchChannel => concat!(
 8421                                "No matching channel was found. ",
 8422                                "Please check the link and try again."
 8423                            )
 8424                            .into(),
 8425                            ErrorCode::Forbidden => concat!(
 8426                                "This channel is private, and you do not have access. ",
 8427                                "Please ask someone to add you and try again."
 8428                            )
 8429                            .into(),
 8430                            ErrorCode::Disconnected => {
 8431                                "Please check your internet connection and try again.".into()
 8432                            }
 8433                            _ => format!("{}\n\nPlease try again.", err).into(),
 8434                        };
 8435                        window.prompt(
 8436                            PromptLevel::Critical,
 8437                            "Failed to join channel",
 8438                            Some(&detail),
 8439                            &["Ok"],
 8440                            cx,
 8441                        )
 8442                    })?
 8443                    .await
 8444                    .ok();
 8445            }
 8446        }
 8447
 8448        // return ok, we showed the error to the user.
 8449        anyhow::Ok(())
 8450    })
 8451}
 8452
 8453pub async fn get_any_active_multi_workspace(
 8454    app_state: Arc<AppState>,
 8455    mut cx: AsyncApp,
 8456) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8457    // find an existing workspace to focus and show call controls
 8458    let active_window = activate_any_workspace_window(&mut cx);
 8459    if active_window.is_none() {
 8460        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
 8461            .await?;
 8462    }
 8463    activate_any_workspace_window(&mut cx).context("could not open zed")
 8464}
 8465
 8466fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8467    cx.update(|cx| {
 8468        if let Some(workspace_window) = cx
 8469            .active_window()
 8470            .and_then(|window| window.downcast::<MultiWorkspace>())
 8471        {
 8472            return Some(workspace_window);
 8473        }
 8474
 8475        for window in cx.windows() {
 8476            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8477                workspace_window
 8478                    .update(cx, |_, window, _| window.activate_window())
 8479                    .ok();
 8480                return Some(workspace_window);
 8481            }
 8482        }
 8483        None
 8484    })
 8485}
 8486
 8487pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8488    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8489}
 8490
 8491pub fn workspace_windows_for_location(
 8492    serialized_location: &SerializedWorkspaceLocation,
 8493    cx: &App,
 8494) -> Vec<WindowHandle<MultiWorkspace>> {
 8495    cx.windows()
 8496        .into_iter()
 8497        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8498        .filter(|multi_workspace| {
 8499            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8500                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8501                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8502                }
 8503                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8504                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8505                    a.distro_name == b.distro_name
 8506                }
 8507                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8508                    a.container_id == b.container_id
 8509                }
 8510                #[cfg(any(test, feature = "test-support"))]
 8511                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8512                    a.id == b.id
 8513                }
 8514                _ => false,
 8515            };
 8516
 8517            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8518                multi_workspace.workspaces().iter().any(|workspace| {
 8519                    match workspace.read(cx).workspace_location(cx) {
 8520                        WorkspaceLocation::Location(location, _) => {
 8521                            match (&location, serialized_location) {
 8522                                (
 8523                                    SerializedWorkspaceLocation::Local,
 8524                                    SerializedWorkspaceLocation::Local,
 8525                                ) => true,
 8526                                (
 8527                                    SerializedWorkspaceLocation::Remote(a),
 8528                                    SerializedWorkspaceLocation::Remote(b),
 8529                                ) => same_host(a, b),
 8530                                _ => false,
 8531                            }
 8532                        }
 8533                        _ => false,
 8534                    }
 8535                })
 8536            })
 8537        })
 8538        .collect()
 8539}
 8540
 8541pub async fn find_existing_workspace(
 8542    abs_paths: &[PathBuf],
 8543    open_options: &OpenOptions,
 8544    location: &SerializedWorkspaceLocation,
 8545    cx: &mut AsyncApp,
 8546) -> (
 8547    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8548    OpenVisible,
 8549) {
 8550    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8551    let mut open_visible = OpenVisible::All;
 8552    let mut best_match = None;
 8553
 8554    if open_options.open_new_workspace != Some(true) {
 8555        cx.update(|cx| {
 8556            for window in workspace_windows_for_location(location, cx) {
 8557                if let Ok(multi_workspace) = window.read(cx) {
 8558                    for workspace in multi_workspace.workspaces() {
 8559                        let project = workspace.read(cx).project.read(cx);
 8560                        let m = project.visibility_for_paths(
 8561                            abs_paths,
 8562                            open_options.open_new_workspace == None,
 8563                            cx,
 8564                        );
 8565                        if m > best_match {
 8566                            existing = Some((window, workspace.clone()));
 8567                            best_match = m;
 8568                        } else if best_match.is_none()
 8569                            && open_options.open_new_workspace == Some(false)
 8570                        {
 8571                            existing = Some((window, workspace.clone()))
 8572                        }
 8573                    }
 8574                }
 8575            }
 8576        });
 8577
 8578        let all_paths_are_files = existing
 8579            .as_ref()
 8580            .and_then(|(_, target_workspace)| {
 8581                cx.update(|cx| {
 8582                    let workspace = target_workspace.read(cx);
 8583                    let project = workspace.project.read(cx);
 8584                    let path_style = workspace.path_style(cx);
 8585                    Some(!abs_paths.iter().any(|path| {
 8586                        let path = util::paths::SanitizedPath::new(path);
 8587                        project.worktrees(cx).any(|worktree| {
 8588                            let worktree = worktree.read(cx);
 8589                            let abs_path = worktree.abs_path();
 8590                            path_style
 8591                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8592                                .and_then(|rel| worktree.entry_for_path(&rel))
 8593                                .is_some_and(|e| e.is_dir())
 8594                        })
 8595                    }))
 8596                })
 8597            })
 8598            .unwrap_or(false);
 8599
 8600        if open_options.open_new_workspace.is_none()
 8601            && existing.is_some()
 8602            && open_options.wait
 8603            && all_paths_are_files
 8604        {
 8605            cx.update(|cx| {
 8606                let windows = workspace_windows_for_location(location, cx);
 8607                let window = cx
 8608                    .active_window()
 8609                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8610                    .filter(|window| windows.contains(window))
 8611                    .or_else(|| windows.into_iter().next());
 8612                if let Some(window) = window {
 8613                    if let Ok(multi_workspace) = window.read(cx) {
 8614                        let active_workspace = multi_workspace.workspace().clone();
 8615                        existing = Some((window, active_workspace));
 8616                        open_visible = OpenVisible::None;
 8617                    }
 8618                }
 8619            });
 8620        }
 8621    }
 8622    (existing, open_visible)
 8623}
 8624
 8625#[derive(Default, Clone)]
 8626pub struct OpenOptions {
 8627    pub visible: Option<OpenVisible>,
 8628    pub focus: Option<bool>,
 8629    pub open_new_workspace: Option<bool>,
 8630    pub wait: bool,
 8631    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8632    pub env: Option<HashMap<String, String>>,
 8633}
 8634
 8635/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8636pub fn open_workspace_by_id(
 8637    workspace_id: WorkspaceId,
 8638    app_state: Arc<AppState>,
 8639    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8640    cx: &mut App,
 8641) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8642    let project_handle = Project::local(
 8643        app_state.client.clone(),
 8644        app_state.node_runtime.clone(),
 8645        app_state.user_store.clone(),
 8646        app_state.languages.clone(),
 8647        app_state.fs.clone(),
 8648        None,
 8649        project::LocalProjectFlags {
 8650            init_worktree_trust: true,
 8651            ..project::LocalProjectFlags::default()
 8652        },
 8653        cx,
 8654    );
 8655
 8656    cx.spawn(async move |cx| {
 8657        let serialized_workspace = persistence::DB
 8658            .workspace_for_id(workspace_id)
 8659            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8660
 8661        let centered_layout = serialized_workspace.centered_layout;
 8662
 8663        let (window, workspace) = if let Some(window) = requesting_window {
 8664            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8665                let workspace = cx.new(|cx| {
 8666                    let mut workspace = Workspace::new(
 8667                        Some(workspace_id),
 8668                        project_handle.clone(),
 8669                        app_state.clone(),
 8670                        window,
 8671                        cx,
 8672                    );
 8673                    workspace.centered_layout = centered_layout;
 8674                    workspace
 8675                });
 8676                multi_workspace.add_workspace(workspace.clone(), cx);
 8677                workspace
 8678            })?;
 8679            (window, workspace)
 8680        } else {
 8681            let window_bounds_override = window_bounds_env_override();
 8682
 8683            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8684                (Some(WindowBounds::Windowed(bounds)), None)
 8685            } else if let Some(display) = serialized_workspace.display
 8686                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8687            {
 8688                (Some(bounds.0), Some(display))
 8689            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8690                (Some(bounds), Some(display))
 8691            } else {
 8692                (None, None)
 8693            };
 8694
 8695            let options = cx.update(|cx| {
 8696                let mut options = (app_state.build_window_options)(display, cx);
 8697                options.window_bounds = window_bounds;
 8698                options
 8699            });
 8700
 8701            let window = cx.open_window(options, {
 8702                let app_state = app_state.clone();
 8703                let project_handle = project_handle.clone();
 8704                move |window, cx| {
 8705                    let workspace = cx.new(|cx| {
 8706                        let mut workspace = Workspace::new(
 8707                            Some(workspace_id),
 8708                            project_handle,
 8709                            app_state,
 8710                            window,
 8711                            cx,
 8712                        );
 8713                        workspace.centered_layout = centered_layout;
 8714                        workspace
 8715                    });
 8716                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8717                }
 8718            })?;
 8719
 8720            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8721                multi_workspace.workspace().clone()
 8722            })?;
 8723
 8724            (window, workspace)
 8725        };
 8726
 8727        notify_if_database_failed(window, cx);
 8728
 8729        // Restore items from the serialized workspace
 8730        window
 8731            .update(cx, |_, window, cx| {
 8732                workspace.update(cx, |_workspace, cx| {
 8733                    open_items(Some(serialized_workspace), vec![], window, cx)
 8734                })
 8735            })?
 8736            .await?;
 8737
 8738        window.update(cx, |_, window, cx| {
 8739            workspace.update(cx, |workspace, cx| {
 8740                workspace.serialize_workspace(window, cx);
 8741            });
 8742        })?;
 8743
 8744        Ok(window)
 8745    })
 8746}
 8747
 8748#[allow(clippy::type_complexity)]
 8749pub fn open_paths(
 8750    abs_paths: &[PathBuf],
 8751    app_state: Arc<AppState>,
 8752    open_options: OpenOptions,
 8753    cx: &mut App,
 8754) -> Task<
 8755    anyhow::Result<(
 8756        WindowHandle<MultiWorkspace>,
 8757        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8758    )>,
 8759> {
 8760    let abs_paths = abs_paths.to_vec();
 8761    #[cfg(target_os = "windows")]
 8762    let wsl_path = abs_paths
 8763        .iter()
 8764        .find_map(|p| util::paths::WslPath::from_path(p));
 8765
 8766    cx.spawn(async move |cx| {
 8767        let (mut existing, mut open_visible) = find_existing_workspace(
 8768            &abs_paths,
 8769            &open_options,
 8770            &SerializedWorkspaceLocation::Local,
 8771            cx,
 8772        )
 8773        .await;
 8774
 8775        // Fallback: if no workspace contains the paths and all paths are files,
 8776        // prefer an existing local workspace window (active window first).
 8777        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8778            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8779            let all_metadatas = futures::future::join_all(all_paths)
 8780                .await
 8781                .into_iter()
 8782                .filter_map(|result| result.ok().flatten())
 8783                .collect::<Vec<_>>();
 8784
 8785            if all_metadatas.iter().all(|file| !file.is_dir) {
 8786                cx.update(|cx| {
 8787                    let windows = workspace_windows_for_location(
 8788                        &SerializedWorkspaceLocation::Local,
 8789                        cx,
 8790                    );
 8791                    let window = cx
 8792                        .active_window()
 8793                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8794                        .filter(|window| windows.contains(window))
 8795                        .or_else(|| windows.into_iter().next());
 8796                    if let Some(window) = window {
 8797                        if let Ok(multi_workspace) = window.read(cx) {
 8798                            let active_workspace = multi_workspace.workspace().clone();
 8799                            existing = Some((window, active_workspace));
 8800                            open_visible = OpenVisible::None;
 8801                        }
 8802                    }
 8803                });
 8804            }
 8805        }
 8806
 8807        let result = if let Some((existing, target_workspace)) = existing {
 8808            let open_task = existing
 8809                .update(cx, |multi_workspace, window, cx| {
 8810                    window.activate_window();
 8811                    multi_workspace.activate(target_workspace.clone(), cx);
 8812                    target_workspace.update(cx, |workspace, cx| {
 8813                        workspace.open_paths(
 8814                            abs_paths,
 8815                            OpenOptions {
 8816                                visible: Some(open_visible),
 8817                                ..Default::default()
 8818                            },
 8819                            None,
 8820                            window,
 8821                            cx,
 8822                        )
 8823                    })
 8824                })?
 8825                .await;
 8826
 8827            _ = existing.update(cx, |multi_workspace, _, cx| {
 8828                let workspace = multi_workspace.workspace().clone();
 8829                workspace.update(cx, |workspace, cx| {
 8830                    for item in open_task.iter().flatten() {
 8831                        if let Err(e) = item {
 8832                            workspace.show_error(&e, cx);
 8833                        }
 8834                    }
 8835                });
 8836            });
 8837
 8838            Ok((existing, open_task))
 8839        } else {
 8840            let result = cx
 8841                .update(move |cx| {
 8842                    Workspace::new_local(
 8843                        abs_paths,
 8844                        app_state.clone(),
 8845                        open_options.replace_window,
 8846                        open_options.env,
 8847                        None,
 8848                        cx,
 8849                    )
 8850                })
 8851                .await;
 8852
 8853            if let Ok((ref window_handle, _)) = result {
 8854                window_handle
 8855                    .update(cx, |_, window, _cx| {
 8856                        window.activate_window();
 8857                    })
 8858                    .log_err();
 8859            }
 8860
 8861            result
 8862        };
 8863
 8864        #[cfg(target_os = "windows")]
 8865        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8866            && let Ok((multi_workspace_window, _)) = &result
 8867        {
 8868            multi_workspace_window
 8869                .update(cx, move |multi_workspace, _window, cx| {
 8870                    struct OpenInWsl;
 8871                    let workspace = multi_workspace.workspace().clone();
 8872                    workspace.update(cx, |workspace, cx| {
 8873                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8874                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8875                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8876                            cx.new(move |cx| {
 8877                                MessageNotification::new(msg, cx)
 8878                                    .primary_message("Open in WSL")
 8879                                    .primary_icon(IconName::FolderOpen)
 8880                                    .primary_on_click(move |window, cx| {
 8881                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 8882                                                distro: remote::WslConnectionOptions {
 8883                                                        distro_name: distro.clone(),
 8884                                                    user: None,
 8885                                                },
 8886                                                paths: vec![path.clone().into()],
 8887                                            }), cx)
 8888                                    })
 8889                            })
 8890                        });
 8891                    });
 8892                })
 8893                .unwrap();
 8894        };
 8895        result
 8896    })
 8897}
 8898
 8899pub fn open_new(
 8900    open_options: OpenOptions,
 8901    app_state: Arc<AppState>,
 8902    cx: &mut App,
 8903    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8904) -> Task<anyhow::Result<()>> {
 8905    let task = Workspace::new_local(
 8906        Vec::new(),
 8907        app_state,
 8908        open_options.replace_window,
 8909        open_options.env,
 8910        Some(Box::new(init)),
 8911        cx,
 8912    );
 8913    cx.spawn(async move |cx| {
 8914        let (window, _opened_paths) = task.await?;
 8915        window
 8916            .update(cx, |_, window, _cx| {
 8917                window.activate_window();
 8918            })
 8919            .ok();
 8920        Ok(())
 8921    })
 8922}
 8923
 8924pub fn create_and_open_local_file(
 8925    path: &'static Path,
 8926    window: &mut Window,
 8927    cx: &mut Context<Workspace>,
 8928    default_content: impl 'static + Send + FnOnce() -> Rope,
 8929) -> Task<Result<Box<dyn ItemHandle>>> {
 8930    cx.spawn_in(window, async move |workspace, cx| {
 8931        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8932        if !fs.is_file(path).await {
 8933            fs.create_file(path, Default::default()).await?;
 8934            fs.save(path, &default_content(), Default::default())
 8935                .await?;
 8936        }
 8937
 8938        workspace
 8939            .update_in(cx, |workspace, window, cx| {
 8940                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 8941                    let path = workspace
 8942                        .project
 8943                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 8944                    cx.spawn_in(window, async move |workspace, cx| {
 8945                        let path = path.await?;
 8946                        let mut items = workspace
 8947                            .update_in(cx, |workspace, window, cx| {
 8948                                workspace.open_paths(
 8949                                    vec![path.to_path_buf()],
 8950                                    OpenOptions {
 8951                                        visible: Some(OpenVisible::None),
 8952                                        ..Default::default()
 8953                                    },
 8954                                    None,
 8955                                    window,
 8956                                    cx,
 8957                                )
 8958                            })?
 8959                            .await;
 8960                        let item = items.pop().flatten();
 8961                        item.with_context(|| format!("path {path:?} is not a file"))?
 8962                    })
 8963                })
 8964            })?
 8965            .await?
 8966            .await
 8967    })
 8968}
 8969
 8970pub fn open_remote_project_with_new_connection(
 8971    window: WindowHandle<MultiWorkspace>,
 8972    remote_connection: Arc<dyn RemoteConnection>,
 8973    cancel_rx: oneshot::Receiver<()>,
 8974    delegate: Arc<dyn RemoteClientDelegate>,
 8975    app_state: Arc<AppState>,
 8976    paths: Vec<PathBuf>,
 8977    cx: &mut App,
 8978) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8979    cx.spawn(async move |cx| {
 8980        let (workspace_id, serialized_workspace) =
 8981            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8982                .await?;
 8983
 8984        let session = match cx
 8985            .update(|cx| {
 8986                remote::RemoteClient::new(
 8987                    ConnectionIdentifier::Workspace(workspace_id.0),
 8988                    remote_connection,
 8989                    cancel_rx,
 8990                    delegate,
 8991                    cx,
 8992                )
 8993            })
 8994            .await?
 8995        {
 8996            Some(result) => result,
 8997            None => return Ok(Vec::new()),
 8998        };
 8999
 9000        let project = cx.update(|cx| {
 9001            project::Project::remote(
 9002                session,
 9003                app_state.client.clone(),
 9004                app_state.node_runtime.clone(),
 9005                app_state.user_store.clone(),
 9006                app_state.languages.clone(),
 9007                app_state.fs.clone(),
 9008                true,
 9009                cx,
 9010            )
 9011        });
 9012
 9013        open_remote_project_inner(
 9014            project,
 9015            paths,
 9016            workspace_id,
 9017            serialized_workspace,
 9018            app_state,
 9019            window,
 9020            cx,
 9021        )
 9022        .await
 9023    })
 9024}
 9025
 9026pub fn open_remote_project_with_existing_connection(
 9027    connection_options: RemoteConnectionOptions,
 9028    project: Entity<Project>,
 9029    paths: Vec<PathBuf>,
 9030    app_state: Arc<AppState>,
 9031    window: WindowHandle<MultiWorkspace>,
 9032    cx: &mut AsyncApp,
 9033) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9034    cx.spawn(async move |cx| {
 9035        let (workspace_id, serialized_workspace) =
 9036            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9037
 9038        open_remote_project_inner(
 9039            project,
 9040            paths,
 9041            workspace_id,
 9042            serialized_workspace,
 9043            app_state,
 9044            window,
 9045            cx,
 9046        )
 9047        .await
 9048    })
 9049}
 9050
 9051async fn open_remote_project_inner(
 9052    project: Entity<Project>,
 9053    paths: Vec<PathBuf>,
 9054    workspace_id: WorkspaceId,
 9055    serialized_workspace: Option<SerializedWorkspace>,
 9056    app_state: Arc<AppState>,
 9057    window: WindowHandle<MultiWorkspace>,
 9058    cx: &mut AsyncApp,
 9059) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9060    let toolchains = DB.toolchains(workspace_id).await?;
 9061    for (toolchain, worktree_path, path) in toolchains {
 9062        project
 9063            .update(cx, |this, cx| {
 9064                let Some(worktree_id) =
 9065                    this.find_worktree(&worktree_path, cx)
 9066                        .and_then(|(worktree, rel_path)| {
 9067                            if rel_path.is_empty() {
 9068                                Some(worktree.read(cx).id())
 9069                            } else {
 9070                                None
 9071                            }
 9072                        })
 9073                else {
 9074                    return Task::ready(None);
 9075                };
 9076
 9077                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9078            })
 9079            .await;
 9080    }
 9081    let mut project_paths_to_open = vec![];
 9082    let mut project_path_errors = vec![];
 9083
 9084    for path in paths {
 9085        let result = cx
 9086            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9087            .await;
 9088        match result {
 9089            Ok((_, project_path)) => {
 9090                project_paths_to_open.push((path.clone(), Some(project_path)));
 9091            }
 9092            Err(error) => {
 9093                project_path_errors.push(error);
 9094            }
 9095        };
 9096    }
 9097
 9098    if project_paths_to_open.is_empty() {
 9099        return Err(project_path_errors.pop().context("no paths given")?);
 9100    }
 9101
 9102    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9103        telemetry::event!("SSH Project Opened");
 9104
 9105        let new_workspace = cx.new(|cx| {
 9106            let mut workspace =
 9107                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9108            workspace.update_history(cx);
 9109
 9110            if let Some(ref serialized) = serialized_workspace {
 9111                workspace.centered_layout = serialized.centered_layout;
 9112            }
 9113
 9114            workspace
 9115        });
 9116
 9117        multi_workspace.activate(new_workspace.clone(), cx);
 9118        new_workspace
 9119    })?;
 9120
 9121    let items = window
 9122        .update(cx, |_, window, cx| {
 9123            window.activate_window();
 9124            workspace.update(cx, |_workspace, cx| {
 9125                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9126            })
 9127        })?
 9128        .await?;
 9129
 9130    workspace.update(cx, |workspace, cx| {
 9131        for error in project_path_errors {
 9132            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9133                if let Some(path) = error.error_tag("path") {
 9134                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9135                }
 9136            } else {
 9137                workspace.show_error(&error, cx)
 9138            }
 9139        }
 9140    });
 9141
 9142    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9143}
 9144
 9145fn deserialize_remote_project(
 9146    connection_options: RemoteConnectionOptions,
 9147    paths: Vec<PathBuf>,
 9148    cx: &AsyncApp,
 9149) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9150    cx.background_spawn(async move {
 9151        let remote_connection_id = persistence::DB
 9152            .get_or_create_remote_connection(connection_options)
 9153            .await?;
 9154
 9155        let serialized_workspace =
 9156            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9157
 9158        let workspace_id = if let Some(workspace_id) =
 9159            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9160        {
 9161            workspace_id
 9162        } else {
 9163            persistence::DB.next_id().await?
 9164        };
 9165
 9166        Ok((workspace_id, serialized_workspace))
 9167    })
 9168}
 9169
 9170pub fn join_in_room_project(
 9171    project_id: u64,
 9172    follow_user_id: u64,
 9173    app_state: Arc<AppState>,
 9174    cx: &mut App,
 9175) -> Task<Result<()>> {
 9176    let windows = cx.windows();
 9177    cx.spawn(async move |cx| {
 9178        let existing_window_and_workspace: Option<(
 9179            WindowHandle<MultiWorkspace>,
 9180            Entity<Workspace>,
 9181        )> = windows.into_iter().find_map(|window_handle| {
 9182            window_handle
 9183                .downcast::<MultiWorkspace>()
 9184                .and_then(|window_handle| {
 9185                    window_handle
 9186                        .update(cx, |multi_workspace, _window, cx| {
 9187                            for workspace in multi_workspace.workspaces() {
 9188                                if workspace.read(cx).project().read(cx).remote_id()
 9189                                    == Some(project_id)
 9190                                {
 9191                                    return Some((window_handle, workspace.clone()));
 9192                                }
 9193                            }
 9194                            None
 9195                        })
 9196                        .unwrap_or(None)
 9197                })
 9198        });
 9199
 9200        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9201            existing_window_and_workspace
 9202        {
 9203            existing_window
 9204                .update(cx, |multi_workspace, _, cx| {
 9205                    multi_workspace.activate(target_workspace, cx);
 9206                })
 9207                .ok();
 9208            existing_window
 9209        } else {
 9210            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9211            let project = cx
 9212                .update(|cx| {
 9213                    active_call.0.join_project(
 9214                        project_id,
 9215                        app_state.languages.clone(),
 9216                        app_state.fs.clone(),
 9217                        cx,
 9218                    )
 9219                })
 9220                .await?;
 9221
 9222            let window_bounds_override = window_bounds_env_override();
 9223            cx.update(|cx| {
 9224                let mut options = (app_state.build_window_options)(None, cx);
 9225                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9226                cx.open_window(options, |window, cx| {
 9227                    let workspace = cx.new(|cx| {
 9228                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9229                    });
 9230                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9231                })
 9232            })?
 9233        };
 9234
 9235        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9236            cx.activate(true);
 9237            window.activate_window();
 9238
 9239            // We set the active workspace above, so this is the correct workspace.
 9240            let workspace = multi_workspace.workspace().clone();
 9241            workspace.update(cx, |workspace, cx| {
 9242                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9243                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9244                    .or_else(|| {
 9245                        // If we couldn't follow the given user, follow the host instead.
 9246                        let collaborator = workspace
 9247                            .project()
 9248                            .read(cx)
 9249                            .collaborators()
 9250                            .values()
 9251                            .find(|collaborator| collaborator.is_host)?;
 9252                        Some(collaborator.peer_id)
 9253                    });
 9254
 9255                if let Some(follow_peer_id) = follow_peer_id {
 9256                    workspace.follow(follow_peer_id, window, cx);
 9257                }
 9258            });
 9259        })?;
 9260
 9261        anyhow::Ok(())
 9262    })
 9263}
 9264
 9265pub fn reload(cx: &mut App) {
 9266    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9267    let mut workspace_windows = cx
 9268        .windows()
 9269        .into_iter()
 9270        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9271        .collect::<Vec<_>>();
 9272
 9273    // If multiple windows have unsaved changes, and need a save prompt,
 9274    // prompt in the active window before switching to a different window.
 9275    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9276
 9277    let mut prompt = None;
 9278    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9279        prompt = window
 9280            .update(cx, |_, window, cx| {
 9281                window.prompt(
 9282                    PromptLevel::Info,
 9283                    "Are you sure you want to restart?",
 9284                    None,
 9285                    &["Restart", "Cancel"],
 9286                    cx,
 9287                )
 9288            })
 9289            .ok();
 9290    }
 9291
 9292    cx.spawn(async move |cx| {
 9293        if let Some(prompt) = prompt {
 9294            let answer = prompt.await?;
 9295            if answer != 0 {
 9296                return anyhow::Ok(());
 9297            }
 9298        }
 9299
 9300        // If the user cancels any save prompt, then keep the app open.
 9301        for window in workspace_windows {
 9302            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9303                let workspace = multi_workspace.workspace().clone();
 9304                workspace.update(cx, |workspace, cx| {
 9305                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9306                })
 9307            }) && !should_close.await?
 9308            {
 9309                return anyhow::Ok(());
 9310            }
 9311        }
 9312        cx.update(|cx| cx.restart());
 9313        anyhow::Ok(())
 9314    })
 9315    .detach_and_log_err(cx);
 9316}
 9317
 9318fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9319    let mut parts = value.split(',');
 9320    let x: usize = parts.next()?.parse().ok()?;
 9321    let y: usize = parts.next()?.parse().ok()?;
 9322    Some(point(px(x as f32), px(y as f32)))
 9323}
 9324
 9325fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9326    let mut parts = value.split(',');
 9327    let width: usize = parts.next()?.parse().ok()?;
 9328    let height: usize = parts.next()?.parse().ok()?;
 9329    Some(size(px(width as f32), px(height as f32)))
 9330}
 9331
 9332/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9333/// appropriate.
 9334///
 9335/// The `border_radius_tiling` parameter allows overriding which corners get
 9336/// rounded, independently of the actual window tiling state. This is used
 9337/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9338/// we want square corners on the left (so the sidebar appears flush with the
 9339/// window edge) but we still need the shadow padding for proper visual
 9340/// appearance. Unlike actual window tiling, this only affects border radius -
 9341/// not padding or shadows.
 9342pub fn client_side_decorations(
 9343    element: impl IntoElement,
 9344    window: &mut Window,
 9345    cx: &mut App,
 9346    border_radius_tiling: Tiling,
 9347) -> Stateful<Div> {
 9348    const BORDER_SIZE: Pixels = px(1.0);
 9349    let decorations = window.window_decorations();
 9350    let tiling = match decorations {
 9351        Decorations::Server => Tiling::default(),
 9352        Decorations::Client { tiling } => tiling,
 9353    };
 9354
 9355    match decorations {
 9356        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9357        Decorations::Server => window.set_client_inset(px(0.0)),
 9358    }
 9359
 9360    struct GlobalResizeEdge(ResizeEdge);
 9361    impl Global for GlobalResizeEdge {}
 9362
 9363    div()
 9364        .id("window-backdrop")
 9365        .bg(transparent_black())
 9366        .map(|div| match decorations {
 9367            Decorations::Server => div,
 9368            Decorations::Client { .. } => div
 9369                .when(
 9370                    !(tiling.top
 9371                        || tiling.right
 9372                        || border_radius_tiling.top
 9373                        || border_radius_tiling.right),
 9374                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9375                )
 9376                .when(
 9377                    !(tiling.top
 9378                        || tiling.left
 9379                        || border_radius_tiling.top
 9380                        || border_radius_tiling.left),
 9381                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9382                )
 9383                .when(
 9384                    !(tiling.bottom
 9385                        || tiling.right
 9386                        || border_radius_tiling.bottom
 9387                        || border_radius_tiling.right),
 9388                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9389                )
 9390                .when(
 9391                    !(tiling.bottom
 9392                        || tiling.left
 9393                        || border_radius_tiling.bottom
 9394                        || border_radius_tiling.left),
 9395                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9396                )
 9397                .when(!tiling.top, |div| {
 9398                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9399                })
 9400                .when(!tiling.bottom, |div| {
 9401                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9402                })
 9403                .when(!tiling.left, |div| {
 9404                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9405                })
 9406                .when(!tiling.right, |div| {
 9407                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9408                })
 9409                .on_mouse_move(move |e, window, cx| {
 9410                    let size = window.window_bounds().get_bounds().size;
 9411                    let pos = e.position;
 9412
 9413                    let new_edge =
 9414                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9415
 9416                    let edge = cx.try_global::<GlobalResizeEdge>();
 9417                    if new_edge != edge.map(|edge| edge.0) {
 9418                        window
 9419                            .window_handle()
 9420                            .update(cx, |workspace, _, cx| {
 9421                                cx.notify(workspace.entity_id());
 9422                            })
 9423                            .ok();
 9424                    }
 9425                })
 9426                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9427                    let size = window.window_bounds().get_bounds().size;
 9428                    let pos = e.position;
 9429
 9430                    let edge = match resize_edge(
 9431                        pos,
 9432                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9433                        size,
 9434                        tiling,
 9435                    ) {
 9436                        Some(value) => value,
 9437                        None => return,
 9438                    };
 9439
 9440                    window.start_window_resize(edge);
 9441                }),
 9442        })
 9443        .size_full()
 9444        .child(
 9445            div()
 9446                .cursor(CursorStyle::Arrow)
 9447                .map(|div| match decorations {
 9448                    Decorations::Server => div,
 9449                    Decorations::Client { .. } => div
 9450                        .border_color(cx.theme().colors().border)
 9451                        .when(
 9452                            !(tiling.top
 9453                                || tiling.right
 9454                                || border_radius_tiling.top
 9455                                || border_radius_tiling.right),
 9456                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9457                        )
 9458                        .when(
 9459                            !(tiling.top
 9460                                || tiling.left
 9461                                || border_radius_tiling.top
 9462                                || border_radius_tiling.left),
 9463                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9464                        )
 9465                        .when(
 9466                            !(tiling.bottom
 9467                                || tiling.right
 9468                                || border_radius_tiling.bottom
 9469                                || border_radius_tiling.right),
 9470                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9471                        )
 9472                        .when(
 9473                            !(tiling.bottom
 9474                                || tiling.left
 9475                                || border_radius_tiling.bottom
 9476                                || border_radius_tiling.left),
 9477                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9478                        )
 9479                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9480                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9481                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9482                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9483                        .when(!tiling.is_tiled(), |div| {
 9484                            div.shadow(vec![gpui::BoxShadow {
 9485                                color: Hsla {
 9486                                    h: 0.,
 9487                                    s: 0.,
 9488                                    l: 0.,
 9489                                    a: 0.4,
 9490                                },
 9491                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9492                                spread_radius: px(0.),
 9493                                offset: point(px(0.0), px(0.0)),
 9494                            }])
 9495                        }),
 9496                })
 9497                .on_mouse_move(|_e, _, cx| {
 9498                    cx.stop_propagation();
 9499                })
 9500                .size_full()
 9501                .child(element),
 9502        )
 9503        .map(|div| match decorations {
 9504            Decorations::Server => div,
 9505            Decorations::Client { tiling, .. } => div.child(
 9506                canvas(
 9507                    |_bounds, window, _| {
 9508                        window.insert_hitbox(
 9509                            Bounds::new(
 9510                                point(px(0.0), px(0.0)),
 9511                                window.window_bounds().get_bounds().size,
 9512                            ),
 9513                            HitboxBehavior::Normal,
 9514                        )
 9515                    },
 9516                    move |_bounds, hitbox, window, cx| {
 9517                        let mouse = window.mouse_position();
 9518                        let size = window.window_bounds().get_bounds().size;
 9519                        let Some(edge) =
 9520                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9521                        else {
 9522                            return;
 9523                        };
 9524                        cx.set_global(GlobalResizeEdge(edge));
 9525                        window.set_cursor_style(
 9526                            match edge {
 9527                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9528                                ResizeEdge::Left | ResizeEdge::Right => {
 9529                                    CursorStyle::ResizeLeftRight
 9530                                }
 9531                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9532                                    CursorStyle::ResizeUpLeftDownRight
 9533                                }
 9534                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9535                                    CursorStyle::ResizeUpRightDownLeft
 9536                                }
 9537                            },
 9538                            &hitbox,
 9539                        );
 9540                    },
 9541                )
 9542                .size_full()
 9543                .absolute(),
 9544            ),
 9545        })
 9546}
 9547
 9548fn resize_edge(
 9549    pos: Point<Pixels>,
 9550    shadow_size: Pixels,
 9551    window_size: Size<Pixels>,
 9552    tiling: Tiling,
 9553) -> Option<ResizeEdge> {
 9554    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9555    if bounds.contains(&pos) {
 9556        return None;
 9557    }
 9558
 9559    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9560    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9561    if !tiling.top && top_left_bounds.contains(&pos) {
 9562        return Some(ResizeEdge::TopLeft);
 9563    }
 9564
 9565    let top_right_bounds = Bounds::new(
 9566        Point::new(window_size.width - corner_size.width, px(0.)),
 9567        corner_size,
 9568    );
 9569    if !tiling.top && top_right_bounds.contains(&pos) {
 9570        return Some(ResizeEdge::TopRight);
 9571    }
 9572
 9573    let bottom_left_bounds = Bounds::new(
 9574        Point::new(px(0.), window_size.height - corner_size.height),
 9575        corner_size,
 9576    );
 9577    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9578        return Some(ResizeEdge::BottomLeft);
 9579    }
 9580
 9581    let bottom_right_bounds = Bounds::new(
 9582        Point::new(
 9583            window_size.width - corner_size.width,
 9584            window_size.height - corner_size.height,
 9585        ),
 9586        corner_size,
 9587    );
 9588    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9589        return Some(ResizeEdge::BottomRight);
 9590    }
 9591
 9592    if !tiling.top && pos.y < shadow_size {
 9593        Some(ResizeEdge::Top)
 9594    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9595        Some(ResizeEdge::Bottom)
 9596    } else if !tiling.left && pos.x < shadow_size {
 9597        Some(ResizeEdge::Left)
 9598    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9599        Some(ResizeEdge::Right)
 9600    } else {
 9601        None
 9602    }
 9603}
 9604
 9605fn join_pane_into_active(
 9606    active_pane: &Entity<Pane>,
 9607    pane: &Entity<Pane>,
 9608    window: &mut Window,
 9609    cx: &mut App,
 9610) {
 9611    if pane == active_pane {
 9612    } else if pane.read(cx).items_len() == 0 {
 9613        pane.update(cx, |_, cx| {
 9614            cx.emit(pane::Event::Remove {
 9615                focus_on_pane: None,
 9616            });
 9617        })
 9618    } else {
 9619        move_all_items(pane, active_pane, window, cx);
 9620    }
 9621}
 9622
 9623fn move_all_items(
 9624    from_pane: &Entity<Pane>,
 9625    to_pane: &Entity<Pane>,
 9626    window: &mut Window,
 9627    cx: &mut App,
 9628) {
 9629    let destination_is_different = from_pane != to_pane;
 9630    let mut moved_items = 0;
 9631    for (item_ix, item_handle) in from_pane
 9632        .read(cx)
 9633        .items()
 9634        .enumerate()
 9635        .map(|(ix, item)| (ix, item.clone()))
 9636        .collect::<Vec<_>>()
 9637    {
 9638        let ix = item_ix - moved_items;
 9639        if destination_is_different {
 9640            // Close item from previous pane
 9641            from_pane.update(cx, |source, cx| {
 9642                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9643            });
 9644            moved_items += 1;
 9645        }
 9646
 9647        // This automatically removes duplicate items in the pane
 9648        to_pane.update(cx, |destination, cx| {
 9649            destination.add_item(item_handle, true, true, None, window, cx);
 9650            window.focus(&destination.focus_handle(cx), cx)
 9651        });
 9652    }
 9653}
 9654
 9655pub fn move_item(
 9656    source: &Entity<Pane>,
 9657    destination: &Entity<Pane>,
 9658    item_id_to_move: EntityId,
 9659    destination_index: usize,
 9660    activate: bool,
 9661    window: &mut Window,
 9662    cx: &mut App,
 9663) {
 9664    let Some((item_ix, item_handle)) = source
 9665        .read(cx)
 9666        .items()
 9667        .enumerate()
 9668        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9669        .map(|(ix, item)| (ix, item.clone()))
 9670    else {
 9671        // Tab was closed during drag
 9672        return;
 9673    };
 9674
 9675    if source != destination {
 9676        // Close item from previous pane
 9677        source.update(cx, |source, cx| {
 9678            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9679        });
 9680    }
 9681
 9682    // This automatically removes duplicate items in the pane
 9683    destination.update(cx, |destination, cx| {
 9684        destination.add_item_inner(
 9685            item_handle,
 9686            activate,
 9687            activate,
 9688            activate,
 9689            Some(destination_index),
 9690            window,
 9691            cx,
 9692        );
 9693        if activate {
 9694            window.focus(&destination.focus_handle(cx), cx)
 9695        }
 9696    });
 9697}
 9698
 9699pub fn move_active_item(
 9700    source: &Entity<Pane>,
 9701    destination: &Entity<Pane>,
 9702    focus_destination: bool,
 9703    close_if_empty: bool,
 9704    window: &mut Window,
 9705    cx: &mut App,
 9706) {
 9707    if source == destination {
 9708        return;
 9709    }
 9710    let Some(active_item) = source.read(cx).active_item() else {
 9711        return;
 9712    };
 9713    source.update(cx, |source_pane, cx| {
 9714        let item_id = active_item.item_id();
 9715        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9716        destination.update(cx, |target_pane, cx| {
 9717            target_pane.add_item(
 9718                active_item,
 9719                focus_destination,
 9720                focus_destination,
 9721                Some(target_pane.items_len()),
 9722                window,
 9723                cx,
 9724            );
 9725        });
 9726    });
 9727}
 9728
 9729pub fn clone_active_item(
 9730    workspace_id: Option<WorkspaceId>,
 9731    source: &Entity<Pane>,
 9732    destination: &Entity<Pane>,
 9733    focus_destination: bool,
 9734    window: &mut Window,
 9735    cx: &mut App,
 9736) {
 9737    if source == destination {
 9738        return;
 9739    }
 9740    let Some(active_item) = source.read(cx).active_item() else {
 9741        return;
 9742    };
 9743    if !active_item.can_split(cx) {
 9744        return;
 9745    }
 9746    let destination = destination.downgrade();
 9747    let task = active_item.clone_on_split(workspace_id, window, cx);
 9748    window
 9749        .spawn(cx, async move |cx| {
 9750            let Some(clone) = task.await else {
 9751                return;
 9752            };
 9753            destination
 9754                .update_in(cx, |target_pane, window, cx| {
 9755                    target_pane.add_item(
 9756                        clone,
 9757                        focus_destination,
 9758                        focus_destination,
 9759                        Some(target_pane.items_len()),
 9760                        window,
 9761                        cx,
 9762                    );
 9763                })
 9764                .log_err();
 9765        })
 9766        .detach();
 9767}
 9768
 9769#[derive(Debug)]
 9770pub struct WorkspacePosition {
 9771    pub window_bounds: Option<WindowBounds>,
 9772    pub display: Option<Uuid>,
 9773    pub centered_layout: bool,
 9774}
 9775
 9776pub fn remote_workspace_position_from_db(
 9777    connection_options: RemoteConnectionOptions,
 9778    paths_to_open: &[PathBuf],
 9779    cx: &App,
 9780) -> Task<Result<WorkspacePosition>> {
 9781    let paths = paths_to_open.to_vec();
 9782
 9783    cx.background_spawn(async move {
 9784        let remote_connection_id = persistence::DB
 9785            .get_or_create_remote_connection(connection_options)
 9786            .await
 9787            .context("fetching serialized ssh project")?;
 9788        let serialized_workspace =
 9789            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9790
 9791        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9792            (Some(WindowBounds::Windowed(bounds)), None)
 9793        } else {
 9794            let restorable_bounds = serialized_workspace
 9795                .as_ref()
 9796                .and_then(|workspace| {
 9797                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9798                })
 9799                .or_else(|| persistence::read_default_window_bounds());
 9800
 9801            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9802                (Some(serialized_bounds), Some(serialized_display))
 9803            } else {
 9804                (None, None)
 9805            }
 9806        };
 9807
 9808        let centered_layout = serialized_workspace
 9809            .as_ref()
 9810            .map(|w| w.centered_layout)
 9811            .unwrap_or(false);
 9812
 9813        Ok(WorkspacePosition {
 9814            window_bounds,
 9815            display,
 9816            centered_layout,
 9817        })
 9818    })
 9819}
 9820
 9821pub fn with_active_or_new_workspace(
 9822    cx: &mut App,
 9823    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9824) {
 9825    match cx
 9826        .active_window()
 9827        .and_then(|w| w.downcast::<MultiWorkspace>())
 9828    {
 9829        Some(multi_workspace) => {
 9830            cx.defer(move |cx| {
 9831                multi_workspace
 9832                    .update(cx, |multi_workspace, window, cx| {
 9833                        let workspace = multi_workspace.workspace().clone();
 9834                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9835                    })
 9836                    .log_err();
 9837            });
 9838        }
 9839        None => {
 9840            let app_state = AppState::global(cx);
 9841            if let Some(app_state) = app_state.upgrade() {
 9842                open_new(
 9843                    OpenOptions::default(),
 9844                    app_state,
 9845                    cx,
 9846                    move |workspace, window, cx| f(workspace, window, cx),
 9847                )
 9848                .detach_and_log_err(cx);
 9849            }
 9850        }
 9851    }
 9852}
 9853
 9854#[cfg(test)]
 9855mod tests {
 9856    use std::{cell::RefCell, rc::Rc};
 9857
 9858    use super::*;
 9859    use crate::{
 9860        dock::{PanelEvent, test::TestPanel},
 9861        item::{
 9862            ItemBufferKind, ItemEvent,
 9863            test::{TestItem, TestProjectItem},
 9864        },
 9865    };
 9866    use fs::FakeFs;
 9867    use gpui::{
 9868        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9869        UpdateGlobal, VisualTestContext, px,
 9870    };
 9871    use project::{Project, ProjectEntryId};
 9872    use serde_json::json;
 9873    use settings::SettingsStore;
 9874    use util::rel_path::rel_path;
 9875
 9876    #[gpui::test]
 9877    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9878        init_test(cx);
 9879
 9880        let fs = FakeFs::new(cx.executor());
 9881        let project = Project::test(fs, [], cx).await;
 9882        let (workspace, cx) =
 9883            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9884
 9885        // Adding an item with no ambiguity renders the tab without detail.
 9886        let item1 = cx.new(|cx| {
 9887            let mut item = TestItem::new(cx);
 9888            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9889            item
 9890        });
 9891        workspace.update_in(cx, |workspace, window, cx| {
 9892            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9893        });
 9894        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9895
 9896        // Adding an item that creates ambiguity increases the level of detail on
 9897        // both tabs.
 9898        let item2 = cx.new_window_entity(|_window, cx| {
 9899            let mut item = TestItem::new(cx);
 9900            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9901            item
 9902        });
 9903        workspace.update_in(cx, |workspace, window, cx| {
 9904            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9905        });
 9906        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9907        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9908
 9909        // Adding an item that creates ambiguity increases the level of detail only
 9910        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9911        // we stop at the highest detail available.
 9912        let item3 = cx.new(|cx| {
 9913            let mut item = TestItem::new(cx);
 9914            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9915            item
 9916        });
 9917        workspace.update_in(cx, |workspace, window, cx| {
 9918            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9919        });
 9920        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9921        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9922        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9923    }
 9924
 9925    #[gpui::test]
 9926    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9927        init_test(cx);
 9928
 9929        let fs = FakeFs::new(cx.executor());
 9930        fs.insert_tree(
 9931            "/root1",
 9932            json!({
 9933                "one.txt": "",
 9934                "two.txt": "",
 9935            }),
 9936        )
 9937        .await;
 9938        fs.insert_tree(
 9939            "/root2",
 9940            json!({
 9941                "three.txt": "",
 9942            }),
 9943        )
 9944        .await;
 9945
 9946        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9947        let (workspace, cx) =
 9948            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9949        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9950        let worktree_id = project.update(cx, |project, cx| {
 9951            project.worktrees(cx).next().unwrap().read(cx).id()
 9952        });
 9953
 9954        let item1 = cx.new(|cx| {
 9955            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9956        });
 9957        let item2 = cx.new(|cx| {
 9958            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9959        });
 9960
 9961        // Add an item to an empty pane
 9962        workspace.update_in(cx, |workspace, window, cx| {
 9963            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9964        });
 9965        project.update(cx, |project, cx| {
 9966            assert_eq!(
 9967                project.active_entry(),
 9968                project
 9969                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9970                    .map(|e| e.id)
 9971            );
 9972        });
 9973        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9974
 9975        // Add a second item to a non-empty pane
 9976        workspace.update_in(cx, |workspace, window, cx| {
 9977            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9978        });
 9979        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9980        project.update(cx, |project, cx| {
 9981            assert_eq!(
 9982                project.active_entry(),
 9983                project
 9984                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9985                    .map(|e| e.id)
 9986            );
 9987        });
 9988
 9989        // Close the active item
 9990        pane.update_in(cx, |pane, window, cx| {
 9991            pane.close_active_item(&Default::default(), window, cx)
 9992        })
 9993        .await
 9994        .unwrap();
 9995        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9996        project.update(cx, |project, cx| {
 9997            assert_eq!(
 9998                project.active_entry(),
 9999                project
10000                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10001                    .map(|e| e.id)
10002            );
10003        });
10004
10005        // Add a project folder
10006        project
10007            .update(cx, |project, cx| {
10008                project.find_or_create_worktree("root2", true, cx)
10009            })
10010            .await
10011            .unwrap();
10012        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10013
10014        // Remove a project folder
10015        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10016        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10017    }
10018
10019    #[gpui::test]
10020    async fn test_close_window(cx: &mut TestAppContext) {
10021        init_test(cx);
10022
10023        let fs = FakeFs::new(cx.executor());
10024        fs.insert_tree("/root", json!({ "one": "" })).await;
10025
10026        let project = Project::test(fs, ["root".as_ref()], cx).await;
10027        let (workspace, cx) =
10028            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10029
10030        // When there are no dirty items, there's nothing to do.
10031        let item1 = cx.new(TestItem::new);
10032        workspace.update_in(cx, |w, window, cx| {
10033            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10034        });
10035        let task = workspace.update_in(cx, |w, window, cx| {
10036            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10037        });
10038        assert!(task.await.unwrap());
10039
10040        // When there are dirty untitled items, prompt to save each one. If the user
10041        // cancels any prompt, then abort.
10042        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10043        let item3 = cx.new(|cx| {
10044            TestItem::new(cx)
10045                .with_dirty(true)
10046                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10047        });
10048        workspace.update_in(cx, |w, window, cx| {
10049            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10050            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10051        });
10052        let task = workspace.update_in(cx, |w, window, cx| {
10053            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10054        });
10055        cx.executor().run_until_parked();
10056        cx.simulate_prompt_answer("Cancel"); // cancel save all
10057        cx.executor().run_until_parked();
10058        assert!(!cx.has_pending_prompt());
10059        assert!(!task.await.unwrap());
10060    }
10061
10062    #[gpui::test]
10063    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10064        init_test(cx);
10065
10066        let fs = FakeFs::new(cx.executor());
10067        fs.insert_tree("/root", json!({ "one": "" })).await;
10068
10069        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10070        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10071        let multi_workspace_handle =
10072            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10073        cx.run_until_parked();
10074
10075        let workspace_a = multi_workspace_handle
10076            .read_with(cx, |mw, _| mw.workspace().clone())
10077            .unwrap();
10078
10079        let workspace_b = multi_workspace_handle
10080            .update(cx, |mw, window, cx| {
10081                mw.test_add_workspace(project_b, window, cx)
10082            })
10083            .unwrap();
10084
10085        // Activate workspace A
10086        multi_workspace_handle
10087            .update(cx, |mw, window, cx| {
10088                mw.activate_index(0, window, cx);
10089            })
10090            .unwrap();
10091
10092        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10093
10094        // Workspace A has a clean item
10095        let item_a = cx.new(TestItem::new);
10096        workspace_a.update_in(cx, |w, window, cx| {
10097            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10098        });
10099
10100        // Workspace B has a dirty item
10101        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10102        workspace_b.update_in(cx, |w, window, cx| {
10103            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10104        });
10105
10106        // Verify workspace A is active
10107        multi_workspace_handle
10108            .read_with(cx, |mw, _| {
10109                assert_eq!(mw.active_workspace_index(), 0);
10110            })
10111            .unwrap();
10112
10113        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10114        multi_workspace_handle
10115            .update(cx, |mw, window, cx| {
10116                mw.close_window(&CloseWindow, window, cx);
10117            })
10118            .unwrap();
10119        cx.run_until_parked();
10120
10121        // Workspace B should now be active since it has dirty items that need attention
10122        multi_workspace_handle
10123            .read_with(cx, |mw, _| {
10124                assert_eq!(
10125                    mw.active_workspace_index(),
10126                    1,
10127                    "workspace B should be activated when it prompts"
10128                );
10129            })
10130            .unwrap();
10131
10132        // User cancels the save prompt from workspace B
10133        cx.simulate_prompt_answer("Cancel");
10134        cx.run_until_parked();
10135
10136        // Window should still exist because workspace B's close was cancelled
10137        assert!(
10138            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10139            "window should still exist after cancelling one workspace's close"
10140        );
10141    }
10142
10143    #[gpui::test]
10144    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10145        init_test(cx);
10146
10147        // Register TestItem as a serializable item
10148        cx.update(|cx| {
10149            register_serializable_item::<TestItem>(cx);
10150        });
10151
10152        let fs = FakeFs::new(cx.executor());
10153        fs.insert_tree("/root", json!({ "one": "" })).await;
10154
10155        let project = Project::test(fs, ["root".as_ref()], cx).await;
10156        let (workspace, cx) =
10157            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10158
10159        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10160        let item1 = cx.new(|cx| {
10161            TestItem::new(cx)
10162                .with_dirty(true)
10163                .with_serialize(|| Some(Task::ready(Ok(()))))
10164        });
10165        let item2 = cx.new(|cx| {
10166            TestItem::new(cx)
10167                .with_dirty(true)
10168                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10169                .with_serialize(|| Some(Task::ready(Ok(()))))
10170        });
10171        workspace.update_in(cx, |w, window, cx| {
10172            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10173            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10174        });
10175        let task = workspace.update_in(cx, |w, window, cx| {
10176            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10177        });
10178        assert!(task.await.unwrap());
10179    }
10180
10181    #[gpui::test]
10182    async fn test_close_pane_items(cx: &mut TestAppContext) {
10183        init_test(cx);
10184
10185        let fs = FakeFs::new(cx.executor());
10186
10187        let project = Project::test(fs, None, cx).await;
10188        let (workspace, cx) =
10189            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10190
10191        let item1 = cx.new(|cx| {
10192            TestItem::new(cx)
10193                .with_dirty(true)
10194                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10195        });
10196        let item2 = cx.new(|cx| {
10197            TestItem::new(cx)
10198                .with_dirty(true)
10199                .with_conflict(true)
10200                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10201        });
10202        let item3 = cx.new(|cx| {
10203            TestItem::new(cx)
10204                .with_dirty(true)
10205                .with_conflict(true)
10206                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10207        });
10208        let item4 = cx.new(|cx| {
10209            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10210                let project_item = TestProjectItem::new_untitled(cx);
10211                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10212                project_item
10213            }])
10214        });
10215        let pane = workspace.update_in(cx, |workspace, window, cx| {
10216            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10217            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10218            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10219            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10220            workspace.active_pane().clone()
10221        });
10222
10223        let close_items = pane.update_in(cx, |pane, window, cx| {
10224            pane.activate_item(1, true, true, window, cx);
10225            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10226            let item1_id = item1.item_id();
10227            let item3_id = item3.item_id();
10228            let item4_id = item4.item_id();
10229            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10230                [item1_id, item3_id, item4_id].contains(&id)
10231            })
10232        });
10233        cx.executor().run_until_parked();
10234
10235        assert!(cx.has_pending_prompt());
10236        cx.simulate_prompt_answer("Save all");
10237
10238        cx.executor().run_until_parked();
10239
10240        // Item 1 is saved. There's a prompt to save item 3.
10241        pane.update(cx, |pane, cx| {
10242            assert_eq!(item1.read(cx).save_count, 1);
10243            assert_eq!(item1.read(cx).save_as_count, 0);
10244            assert_eq!(item1.read(cx).reload_count, 0);
10245            assert_eq!(pane.items_len(), 3);
10246            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10247        });
10248        assert!(cx.has_pending_prompt());
10249
10250        // Cancel saving item 3.
10251        cx.simulate_prompt_answer("Discard");
10252        cx.executor().run_until_parked();
10253
10254        // Item 3 is reloaded. There's a prompt to save item 4.
10255        pane.update(cx, |pane, cx| {
10256            assert_eq!(item3.read(cx).save_count, 0);
10257            assert_eq!(item3.read(cx).save_as_count, 0);
10258            assert_eq!(item3.read(cx).reload_count, 1);
10259            assert_eq!(pane.items_len(), 2);
10260            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10261        });
10262
10263        // There's a prompt for a path for item 4.
10264        cx.simulate_new_path_selection(|_| Some(Default::default()));
10265        close_items.await.unwrap();
10266
10267        // The requested items are closed.
10268        pane.update(cx, |pane, cx| {
10269            assert_eq!(item4.read(cx).save_count, 0);
10270            assert_eq!(item4.read(cx).save_as_count, 1);
10271            assert_eq!(item4.read(cx).reload_count, 0);
10272            assert_eq!(pane.items_len(), 1);
10273            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10274        });
10275    }
10276
10277    #[gpui::test]
10278    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10279        init_test(cx);
10280
10281        let fs = FakeFs::new(cx.executor());
10282        let project = Project::test(fs, [], cx).await;
10283        let (workspace, cx) =
10284            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10285
10286        // Create several workspace items with single project entries, and two
10287        // workspace items with multiple project entries.
10288        let single_entry_items = (0..=4)
10289            .map(|project_entry_id| {
10290                cx.new(|cx| {
10291                    TestItem::new(cx)
10292                        .with_dirty(true)
10293                        .with_project_items(&[dirty_project_item(
10294                            project_entry_id,
10295                            &format!("{project_entry_id}.txt"),
10296                            cx,
10297                        )])
10298                })
10299            })
10300            .collect::<Vec<_>>();
10301        let item_2_3 = cx.new(|cx| {
10302            TestItem::new(cx)
10303                .with_dirty(true)
10304                .with_buffer_kind(ItemBufferKind::Multibuffer)
10305                .with_project_items(&[
10306                    single_entry_items[2].read(cx).project_items[0].clone(),
10307                    single_entry_items[3].read(cx).project_items[0].clone(),
10308                ])
10309        });
10310        let item_3_4 = cx.new(|cx| {
10311            TestItem::new(cx)
10312                .with_dirty(true)
10313                .with_buffer_kind(ItemBufferKind::Multibuffer)
10314                .with_project_items(&[
10315                    single_entry_items[3].read(cx).project_items[0].clone(),
10316                    single_entry_items[4].read(cx).project_items[0].clone(),
10317                ])
10318        });
10319
10320        // Create two panes that contain the following project entries:
10321        //   left pane:
10322        //     multi-entry items:   (2, 3)
10323        //     single-entry items:  0, 2, 3, 4
10324        //   right pane:
10325        //     single-entry items:  4, 1
10326        //     multi-entry items:   (3, 4)
10327        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10328            let left_pane = workspace.active_pane().clone();
10329            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10330            workspace.add_item_to_active_pane(
10331                single_entry_items[0].boxed_clone(),
10332                None,
10333                true,
10334                window,
10335                cx,
10336            );
10337            workspace.add_item_to_active_pane(
10338                single_entry_items[2].boxed_clone(),
10339                None,
10340                true,
10341                window,
10342                cx,
10343            );
10344            workspace.add_item_to_active_pane(
10345                single_entry_items[3].boxed_clone(),
10346                None,
10347                true,
10348                window,
10349                cx,
10350            );
10351            workspace.add_item_to_active_pane(
10352                single_entry_items[4].boxed_clone(),
10353                None,
10354                true,
10355                window,
10356                cx,
10357            );
10358
10359            let right_pane =
10360                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10361
10362            let boxed_clone = single_entry_items[1].boxed_clone();
10363            let right_pane = window.spawn(cx, async move |cx| {
10364                right_pane.await.inspect(|right_pane| {
10365                    right_pane
10366                        .update_in(cx, |pane, window, cx| {
10367                            pane.add_item(boxed_clone, true, true, None, window, cx);
10368                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10369                        })
10370                        .unwrap();
10371                })
10372            });
10373
10374            (left_pane, right_pane)
10375        });
10376        let right_pane = right_pane.await.unwrap();
10377        cx.focus(&right_pane);
10378
10379        let close = right_pane.update_in(cx, |pane, window, cx| {
10380            pane.close_all_items(&CloseAllItems::default(), window, cx)
10381                .unwrap()
10382        });
10383        cx.executor().run_until_parked();
10384
10385        let msg = cx.pending_prompt().unwrap().0;
10386        assert!(msg.contains("1.txt"));
10387        assert!(!msg.contains("2.txt"));
10388        assert!(!msg.contains("3.txt"));
10389        assert!(!msg.contains("4.txt"));
10390
10391        // With best-effort close, cancelling item 1 keeps it open but items 4
10392        // and (3,4) still close since their entries exist in left pane.
10393        cx.simulate_prompt_answer("Cancel");
10394        close.await;
10395
10396        right_pane.read_with(cx, |pane, _| {
10397            assert_eq!(pane.items_len(), 1);
10398        });
10399
10400        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10401        left_pane
10402            .update_in(cx, |left_pane, window, cx| {
10403                left_pane.close_item_by_id(
10404                    single_entry_items[3].entity_id(),
10405                    SaveIntent::Skip,
10406                    window,
10407                    cx,
10408                )
10409            })
10410            .await
10411            .unwrap();
10412
10413        let close = left_pane.update_in(cx, |pane, window, cx| {
10414            pane.close_all_items(&CloseAllItems::default(), window, cx)
10415                .unwrap()
10416        });
10417        cx.executor().run_until_parked();
10418
10419        let details = cx.pending_prompt().unwrap().1;
10420        assert!(details.contains("0.txt"));
10421        assert!(details.contains("3.txt"));
10422        assert!(details.contains("4.txt"));
10423        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10424        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10425        // assert!(!details.contains("2.txt"));
10426
10427        cx.simulate_prompt_answer("Save all");
10428        cx.executor().run_until_parked();
10429        close.await;
10430
10431        left_pane.read_with(cx, |pane, _| {
10432            assert_eq!(pane.items_len(), 0);
10433        });
10434    }
10435
10436    #[gpui::test]
10437    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10438        init_test(cx);
10439
10440        let fs = FakeFs::new(cx.executor());
10441        let project = Project::test(fs, [], cx).await;
10442        let (workspace, cx) =
10443            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10444        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10445
10446        let item = cx.new(|cx| {
10447            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10448        });
10449        let item_id = item.entity_id();
10450        workspace.update_in(cx, |workspace, window, cx| {
10451            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10452        });
10453
10454        // Autosave on window change.
10455        item.update(cx, |item, cx| {
10456            SettingsStore::update_global(cx, |settings, cx| {
10457                settings.update_user_settings(cx, |settings| {
10458                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10459                })
10460            });
10461            item.is_dirty = true;
10462        });
10463
10464        // Deactivating the window saves the file.
10465        cx.deactivate_window();
10466        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10467
10468        // Re-activating the window doesn't save the file.
10469        cx.update(|window, _| window.activate_window());
10470        cx.executor().run_until_parked();
10471        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10472
10473        // Autosave on focus change.
10474        item.update_in(cx, |item, window, cx| {
10475            cx.focus_self(window);
10476            SettingsStore::update_global(cx, |settings, cx| {
10477                settings.update_user_settings(cx, |settings| {
10478                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10479                })
10480            });
10481            item.is_dirty = true;
10482        });
10483        // Blurring the item saves the file.
10484        item.update_in(cx, |_, window, _| window.blur());
10485        cx.executor().run_until_parked();
10486        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10487
10488        // Deactivating the window still saves the file.
10489        item.update_in(cx, |item, window, cx| {
10490            cx.focus_self(window);
10491            item.is_dirty = true;
10492        });
10493        cx.deactivate_window();
10494        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10495
10496        // Autosave after delay.
10497        item.update(cx, |item, cx| {
10498            SettingsStore::update_global(cx, |settings, cx| {
10499                settings.update_user_settings(cx, |settings| {
10500                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10501                        milliseconds: 500.into(),
10502                    });
10503                })
10504            });
10505            item.is_dirty = true;
10506            cx.emit(ItemEvent::Edit);
10507        });
10508
10509        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10510        cx.executor().advance_clock(Duration::from_millis(250));
10511        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10512
10513        // After delay expires, the file is saved.
10514        cx.executor().advance_clock(Duration::from_millis(250));
10515        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10516
10517        // Autosave after delay, should save earlier than delay if tab is closed
10518        item.update(cx, |item, cx| {
10519            item.is_dirty = true;
10520            cx.emit(ItemEvent::Edit);
10521        });
10522        cx.executor().advance_clock(Duration::from_millis(250));
10523        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10524
10525        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10526        pane.update_in(cx, |pane, window, cx| {
10527            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10528        })
10529        .await
10530        .unwrap();
10531        assert!(!cx.has_pending_prompt());
10532        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10533
10534        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10535        workspace.update_in(cx, |workspace, window, cx| {
10536            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10537        });
10538        item.update_in(cx, |item, _window, cx| {
10539            item.is_dirty = true;
10540            for project_item in &mut item.project_items {
10541                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10542            }
10543        });
10544        cx.run_until_parked();
10545        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10546
10547        // Autosave on focus change, ensuring closing the tab counts as such.
10548        item.update(cx, |item, cx| {
10549            SettingsStore::update_global(cx, |settings, cx| {
10550                settings.update_user_settings(cx, |settings| {
10551                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10552                })
10553            });
10554            item.is_dirty = true;
10555            for project_item in &mut item.project_items {
10556                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10557            }
10558        });
10559
10560        pane.update_in(cx, |pane, window, cx| {
10561            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10562        })
10563        .await
10564        .unwrap();
10565        assert!(!cx.has_pending_prompt());
10566        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10567
10568        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10569        workspace.update_in(cx, |workspace, window, cx| {
10570            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10571        });
10572        item.update_in(cx, |item, window, cx| {
10573            item.project_items[0].update(cx, |item, _| {
10574                item.entry_id = None;
10575            });
10576            item.is_dirty = true;
10577            window.blur();
10578        });
10579        cx.run_until_parked();
10580        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10581
10582        // Ensure autosave is prevented for deleted files also when closing the buffer.
10583        let _close_items = pane.update_in(cx, |pane, window, cx| {
10584            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10585        });
10586        cx.run_until_parked();
10587        assert!(cx.has_pending_prompt());
10588        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10589    }
10590
10591    #[gpui::test]
10592    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10593        init_test(cx);
10594
10595        let fs = FakeFs::new(cx.executor());
10596
10597        let project = Project::test(fs, [], cx).await;
10598        let (workspace, cx) =
10599            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10600
10601        let item = cx.new(|cx| {
10602            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10603        });
10604        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10605        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10606        let toolbar_notify_count = Rc::new(RefCell::new(0));
10607
10608        workspace.update_in(cx, |workspace, window, cx| {
10609            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10610            let toolbar_notification_count = toolbar_notify_count.clone();
10611            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10612                *toolbar_notification_count.borrow_mut() += 1
10613            })
10614            .detach();
10615        });
10616
10617        pane.read_with(cx, |pane, _| {
10618            assert!(!pane.can_navigate_backward());
10619            assert!(!pane.can_navigate_forward());
10620        });
10621
10622        item.update_in(cx, |item, _, cx| {
10623            item.set_state("one".to_string(), cx);
10624        });
10625
10626        // Toolbar must be notified to re-render the navigation buttons
10627        assert_eq!(*toolbar_notify_count.borrow(), 1);
10628
10629        pane.read_with(cx, |pane, _| {
10630            assert!(pane.can_navigate_backward());
10631            assert!(!pane.can_navigate_forward());
10632        });
10633
10634        workspace
10635            .update_in(cx, |workspace, window, cx| {
10636                workspace.go_back(pane.downgrade(), window, cx)
10637            })
10638            .await
10639            .unwrap();
10640
10641        assert_eq!(*toolbar_notify_count.borrow(), 2);
10642        pane.read_with(cx, |pane, _| {
10643            assert!(!pane.can_navigate_backward());
10644            assert!(pane.can_navigate_forward());
10645        });
10646    }
10647
10648    #[gpui::test]
10649    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10650        init_test(cx);
10651        let fs = FakeFs::new(cx.executor());
10652        let project = Project::test(fs, [], cx).await;
10653        let (multi_workspace, cx) =
10654            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10655        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10656
10657        workspace.update_in(cx, |workspace, window, cx| {
10658            let first_item = cx.new(|cx| {
10659                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10660            });
10661            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10662            workspace.split_pane(
10663                workspace.active_pane().clone(),
10664                SplitDirection::Right,
10665                window,
10666                cx,
10667            );
10668            workspace.split_pane(
10669                workspace.active_pane().clone(),
10670                SplitDirection::Right,
10671                window,
10672                cx,
10673            );
10674        });
10675
10676        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10677            let panes = workspace.center.panes();
10678            assert!(panes.len() >= 2);
10679            (
10680                panes.first().expect("at least one pane").entity_id(),
10681                panes.last().expect("at least one pane").entity_id(),
10682            )
10683        });
10684
10685        workspace.update_in(cx, |workspace, window, cx| {
10686            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10687        });
10688        workspace.update(cx, |workspace, _| {
10689            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10690            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10691        });
10692
10693        cx.dispatch_action(ActivateLastPane);
10694
10695        workspace.update(cx, |workspace, _| {
10696            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10697        });
10698    }
10699
10700    #[gpui::test]
10701    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10702        init_test(cx);
10703        let fs = FakeFs::new(cx.executor());
10704
10705        let project = Project::test(fs, [], cx).await;
10706        let (workspace, cx) =
10707            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10708
10709        let panel = workspace.update_in(cx, |workspace, window, cx| {
10710            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10711            workspace.add_panel(panel.clone(), window, cx);
10712
10713            workspace
10714                .right_dock()
10715                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10716
10717            panel
10718        });
10719
10720        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10721        pane.update_in(cx, |pane, window, cx| {
10722            let item = cx.new(TestItem::new);
10723            pane.add_item(Box::new(item), true, true, None, window, cx);
10724        });
10725
10726        // Transfer focus from center to panel
10727        workspace.update_in(cx, |workspace, window, cx| {
10728            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10729        });
10730
10731        workspace.update_in(cx, |workspace, window, cx| {
10732            assert!(workspace.right_dock().read(cx).is_open());
10733            assert!(!panel.is_zoomed(window, cx));
10734            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10735        });
10736
10737        // Transfer focus from panel to center
10738        workspace.update_in(cx, |workspace, window, cx| {
10739            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10740        });
10741
10742        workspace.update_in(cx, |workspace, window, cx| {
10743            assert!(workspace.right_dock().read(cx).is_open());
10744            assert!(!panel.is_zoomed(window, cx));
10745            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10746        });
10747
10748        // Close the dock
10749        workspace.update_in(cx, |workspace, window, cx| {
10750            workspace.toggle_dock(DockPosition::Right, window, cx);
10751        });
10752
10753        workspace.update_in(cx, |workspace, window, cx| {
10754            assert!(!workspace.right_dock().read(cx).is_open());
10755            assert!(!panel.is_zoomed(window, cx));
10756            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10757        });
10758
10759        // Open the dock
10760        workspace.update_in(cx, |workspace, window, cx| {
10761            workspace.toggle_dock(DockPosition::Right, window, cx);
10762        });
10763
10764        workspace.update_in(cx, |workspace, window, cx| {
10765            assert!(workspace.right_dock().read(cx).is_open());
10766            assert!(!panel.is_zoomed(window, cx));
10767            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10768        });
10769
10770        // Focus and zoom panel
10771        panel.update_in(cx, |panel, window, cx| {
10772            cx.focus_self(window);
10773            panel.set_zoomed(true, window, cx)
10774        });
10775
10776        workspace.update_in(cx, |workspace, window, cx| {
10777            assert!(workspace.right_dock().read(cx).is_open());
10778            assert!(panel.is_zoomed(window, cx));
10779            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10780        });
10781
10782        // Transfer focus to the center closes the dock
10783        workspace.update_in(cx, |workspace, window, cx| {
10784            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10785        });
10786
10787        workspace.update_in(cx, |workspace, window, cx| {
10788            assert!(!workspace.right_dock().read(cx).is_open());
10789            assert!(panel.is_zoomed(window, cx));
10790            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10791        });
10792
10793        // Transferring focus back to the panel keeps it zoomed
10794        workspace.update_in(cx, |workspace, window, cx| {
10795            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10796        });
10797
10798        workspace.update_in(cx, |workspace, window, cx| {
10799            assert!(workspace.right_dock().read(cx).is_open());
10800            assert!(panel.is_zoomed(window, cx));
10801            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10802        });
10803
10804        // Close the dock while it is zoomed
10805        workspace.update_in(cx, |workspace, window, cx| {
10806            workspace.toggle_dock(DockPosition::Right, window, cx)
10807        });
10808
10809        workspace.update_in(cx, |workspace, window, cx| {
10810            assert!(!workspace.right_dock().read(cx).is_open());
10811            assert!(panel.is_zoomed(window, cx));
10812            assert!(workspace.zoomed.is_none());
10813            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10814        });
10815
10816        // Opening the dock, when it's zoomed, retains focus
10817        workspace.update_in(cx, |workspace, window, cx| {
10818            workspace.toggle_dock(DockPosition::Right, window, cx)
10819        });
10820
10821        workspace.update_in(cx, |workspace, window, cx| {
10822            assert!(workspace.right_dock().read(cx).is_open());
10823            assert!(panel.is_zoomed(window, cx));
10824            assert!(workspace.zoomed.is_some());
10825            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10826        });
10827
10828        // Unzoom and close the panel, zoom the active pane.
10829        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10830        workspace.update_in(cx, |workspace, window, cx| {
10831            workspace.toggle_dock(DockPosition::Right, window, cx)
10832        });
10833        pane.update_in(cx, |pane, window, cx| {
10834            pane.toggle_zoom(&Default::default(), window, cx)
10835        });
10836
10837        // Opening a dock unzooms the pane.
10838        workspace.update_in(cx, |workspace, window, cx| {
10839            workspace.toggle_dock(DockPosition::Right, window, cx)
10840        });
10841        workspace.update_in(cx, |workspace, window, cx| {
10842            let pane = pane.read(cx);
10843            assert!(!pane.is_zoomed());
10844            assert!(!pane.focus_handle(cx).is_focused(window));
10845            assert!(workspace.right_dock().read(cx).is_open());
10846            assert!(workspace.zoomed.is_none());
10847        });
10848    }
10849
10850    #[gpui::test]
10851    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10852        init_test(cx);
10853        let fs = FakeFs::new(cx.executor());
10854
10855        let project = Project::test(fs, [], cx).await;
10856        let (workspace, cx) =
10857            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10858
10859        let panel = workspace.update_in(cx, |workspace, window, cx| {
10860            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10861            workspace.add_panel(panel.clone(), window, cx);
10862            panel
10863        });
10864
10865        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10866        pane.update_in(cx, |pane, window, cx| {
10867            let item = cx.new(TestItem::new);
10868            pane.add_item(Box::new(item), true, true, None, window, cx);
10869        });
10870
10871        // Enable close_panel_on_toggle
10872        cx.update_global(|store: &mut SettingsStore, cx| {
10873            store.update_user_settings(cx, |settings| {
10874                settings.workspace.close_panel_on_toggle = Some(true);
10875            });
10876        });
10877
10878        // Panel starts closed. Toggling should open and focus it.
10879        workspace.update_in(cx, |workspace, window, cx| {
10880            assert!(!workspace.right_dock().read(cx).is_open());
10881            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10882        });
10883
10884        workspace.update_in(cx, |workspace, window, cx| {
10885            assert!(
10886                workspace.right_dock().read(cx).is_open(),
10887                "Dock should be open after toggling from center"
10888            );
10889            assert!(
10890                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10891                "Panel should be focused after toggling from center"
10892            );
10893        });
10894
10895        // Panel is open and focused. Toggling should close the panel and
10896        // return focus to the center.
10897        workspace.update_in(cx, |workspace, window, cx| {
10898            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10899        });
10900
10901        workspace.update_in(cx, |workspace, window, cx| {
10902            assert!(
10903                !workspace.right_dock().read(cx).is_open(),
10904                "Dock should be closed after toggling from focused panel"
10905            );
10906            assert!(
10907                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10908                "Panel should not be focused after toggling from focused panel"
10909            );
10910        });
10911
10912        // Open the dock and focus something else so the panel is open but not
10913        // focused. Toggling should focus the panel (not close it).
10914        workspace.update_in(cx, |workspace, window, cx| {
10915            workspace
10916                .right_dock()
10917                .update(cx, |dock, cx| dock.set_open(true, window, cx));
10918            window.focus(&pane.read(cx).focus_handle(cx), cx);
10919        });
10920
10921        workspace.update_in(cx, |workspace, window, cx| {
10922            assert!(workspace.right_dock().read(cx).is_open());
10923            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10924            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10925        });
10926
10927        workspace.update_in(cx, |workspace, window, cx| {
10928            assert!(
10929                workspace.right_dock().read(cx).is_open(),
10930                "Dock should remain open when toggling focuses an open-but-unfocused panel"
10931            );
10932            assert!(
10933                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10934                "Panel should be focused after toggling an open-but-unfocused panel"
10935            );
10936        });
10937
10938        // Now disable the setting and verify the original behavior: toggling
10939        // from a focused panel moves focus to center but leaves the dock open.
10940        cx.update_global(|store: &mut SettingsStore, cx| {
10941            store.update_user_settings(cx, |settings| {
10942                settings.workspace.close_panel_on_toggle = Some(false);
10943            });
10944        });
10945
10946        workspace.update_in(cx, |workspace, window, cx| {
10947            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10948        });
10949
10950        workspace.update_in(cx, |workspace, window, cx| {
10951            assert!(
10952                workspace.right_dock().read(cx).is_open(),
10953                "Dock should remain open when setting is disabled"
10954            );
10955            assert!(
10956                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10957                "Panel should not be focused after toggling with setting disabled"
10958            );
10959        });
10960    }
10961
10962    #[gpui::test]
10963    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10964        init_test(cx);
10965        let fs = FakeFs::new(cx.executor());
10966
10967        let project = Project::test(fs, [], cx).await;
10968        let (workspace, cx) =
10969            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10970
10971        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10972            workspace.active_pane().clone()
10973        });
10974
10975        // Add an item to the pane so it can be zoomed
10976        workspace.update_in(cx, |workspace, window, cx| {
10977            let item = cx.new(TestItem::new);
10978            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10979        });
10980
10981        // Initially not zoomed
10982        workspace.update_in(cx, |workspace, _window, cx| {
10983            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10984            assert!(
10985                workspace.zoomed.is_none(),
10986                "Workspace should track no zoomed pane"
10987            );
10988            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10989        });
10990
10991        // Zoom In
10992        pane.update_in(cx, |pane, window, cx| {
10993            pane.zoom_in(&crate::ZoomIn, window, cx);
10994        });
10995
10996        workspace.update_in(cx, |workspace, window, cx| {
10997            assert!(
10998                pane.read(cx).is_zoomed(),
10999                "Pane should be zoomed after ZoomIn"
11000            );
11001            assert!(
11002                workspace.zoomed.is_some(),
11003                "Workspace should track the zoomed pane"
11004            );
11005            assert!(
11006                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11007                "ZoomIn should focus the pane"
11008            );
11009        });
11010
11011        // Zoom In again is a no-op
11012        pane.update_in(cx, |pane, window, cx| {
11013            pane.zoom_in(&crate::ZoomIn, window, cx);
11014        });
11015
11016        workspace.update_in(cx, |workspace, window, cx| {
11017            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11018            assert!(
11019                workspace.zoomed.is_some(),
11020                "Workspace still tracks zoomed pane"
11021            );
11022            assert!(
11023                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11024                "Pane remains focused after repeated ZoomIn"
11025            );
11026        });
11027
11028        // Zoom Out
11029        pane.update_in(cx, |pane, window, cx| {
11030            pane.zoom_out(&crate::ZoomOut, window, cx);
11031        });
11032
11033        workspace.update_in(cx, |workspace, _window, cx| {
11034            assert!(
11035                !pane.read(cx).is_zoomed(),
11036                "Pane should unzoom after ZoomOut"
11037            );
11038            assert!(
11039                workspace.zoomed.is_none(),
11040                "Workspace clears zoom tracking after ZoomOut"
11041            );
11042        });
11043
11044        // Zoom Out again is a no-op
11045        pane.update_in(cx, |pane, window, cx| {
11046            pane.zoom_out(&crate::ZoomOut, window, cx);
11047        });
11048
11049        workspace.update_in(cx, |workspace, _window, cx| {
11050            assert!(
11051                !pane.read(cx).is_zoomed(),
11052                "Second ZoomOut keeps pane unzoomed"
11053            );
11054            assert!(
11055                workspace.zoomed.is_none(),
11056                "Workspace remains without zoomed pane"
11057            );
11058        });
11059    }
11060
11061    #[gpui::test]
11062    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11063        init_test(cx);
11064        let fs = FakeFs::new(cx.executor());
11065
11066        let project = Project::test(fs, [], cx).await;
11067        let (workspace, cx) =
11068            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11069        workspace.update_in(cx, |workspace, window, cx| {
11070            // Open two docks
11071            let left_dock = workspace.dock_at_position(DockPosition::Left);
11072            let right_dock = workspace.dock_at_position(DockPosition::Right);
11073
11074            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11075            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11076
11077            assert!(left_dock.read(cx).is_open());
11078            assert!(right_dock.read(cx).is_open());
11079        });
11080
11081        workspace.update_in(cx, |workspace, window, cx| {
11082            // Toggle all docks - should close both
11083            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11084
11085            let left_dock = workspace.dock_at_position(DockPosition::Left);
11086            let right_dock = workspace.dock_at_position(DockPosition::Right);
11087            assert!(!left_dock.read(cx).is_open());
11088            assert!(!right_dock.read(cx).is_open());
11089        });
11090
11091        workspace.update_in(cx, |workspace, window, cx| {
11092            // Toggle again - should reopen both
11093            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11094
11095            let left_dock = workspace.dock_at_position(DockPosition::Left);
11096            let right_dock = workspace.dock_at_position(DockPosition::Right);
11097            assert!(left_dock.read(cx).is_open());
11098            assert!(right_dock.read(cx).is_open());
11099        });
11100    }
11101
11102    #[gpui::test]
11103    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11104        init_test(cx);
11105        let fs = FakeFs::new(cx.executor());
11106
11107        let project = Project::test(fs, [], cx).await;
11108        let (workspace, cx) =
11109            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11110        workspace.update_in(cx, |workspace, window, cx| {
11111            // Open two docks
11112            let left_dock = workspace.dock_at_position(DockPosition::Left);
11113            let right_dock = workspace.dock_at_position(DockPosition::Right);
11114
11115            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11116            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11117
11118            assert!(left_dock.read(cx).is_open());
11119            assert!(right_dock.read(cx).is_open());
11120        });
11121
11122        workspace.update_in(cx, |workspace, window, cx| {
11123            // Close them manually
11124            workspace.toggle_dock(DockPosition::Left, window, cx);
11125            workspace.toggle_dock(DockPosition::Right, window, cx);
11126
11127            let left_dock = workspace.dock_at_position(DockPosition::Left);
11128            let right_dock = workspace.dock_at_position(DockPosition::Right);
11129            assert!(!left_dock.read(cx).is_open());
11130            assert!(!right_dock.read(cx).is_open());
11131        });
11132
11133        workspace.update_in(cx, |workspace, window, cx| {
11134            // Toggle all docks - only last closed (right dock) should reopen
11135            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11136
11137            let left_dock = workspace.dock_at_position(DockPosition::Left);
11138            let right_dock = workspace.dock_at_position(DockPosition::Right);
11139            assert!(!left_dock.read(cx).is_open());
11140            assert!(right_dock.read(cx).is_open());
11141        });
11142    }
11143
11144    #[gpui::test]
11145    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11146        init_test(cx);
11147        let fs = FakeFs::new(cx.executor());
11148        let project = Project::test(fs, [], cx).await;
11149        let (multi_workspace, cx) =
11150            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11151        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11152
11153        // Open two docks (left and right) with one panel each
11154        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11155            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11156            workspace.add_panel(left_panel.clone(), window, cx);
11157
11158            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11159            workspace.add_panel(right_panel.clone(), window, cx);
11160
11161            workspace.toggle_dock(DockPosition::Left, window, cx);
11162            workspace.toggle_dock(DockPosition::Right, window, cx);
11163
11164            // Verify initial state
11165            assert!(
11166                workspace.left_dock().read(cx).is_open(),
11167                "Left dock should be open"
11168            );
11169            assert_eq!(
11170                workspace
11171                    .left_dock()
11172                    .read(cx)
11173                    .visible_panel()
11174                    .unwrap()
11175                    .panel_id(),
11176                left_panel.panel_id(),
11177                "Left panel should be visible in left dock"
11178            );
11179            assert!(
11180                workspace.right_dock().read(cx).is_open(),
11181                "Right dock should be open"
11182            );
11183            assert_eq!(
11184                workspace
11185                    .right_dock()
11186                    .read(cx)
11187                    .visible_panel()
11188                    .unwrap()
11189                    .panel_id(),
11190                right_panel.panel_id(),
11191                "Right panel should be visible in right dock"
11192            );
11193            assert!(
11194                !workspace.bottom_dock().read(cx).is_open(),
11195                "Bottom dock should be closed"
11196            );
11197
11198            (left_panel, right_panel)
11199        });
11200
11201        // Focus the left panel and move it to the next position (bottom dock)
11202        workspace.update_in(cx, |workspace, window, cx| {
11203            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11204            assert!(
11205                left_panel.read(cx).focus_handle(cx).is_focused(window),
11206                "Left panel should be focused"
11207            );
11208        });
11209
11210        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11211
11212        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11213        workspace.update(cx, |workspace, cx| {
11214            assert!(
11215                !workspace.left_dock().read(cx).is_open(),
11216                "Left dock should be closed"
11217            );
11218            assert!(
11219                workspace.bottom_dock().read(cx).is_open(),
11220                "Bottom dock should now be open"
11221            );
11222            assert_eq!(
11223                left_panel.read(cx).position,
11224                DockPosition::Bottom,
11225                "Left panel should now be in the bottom dock"
11226            );
11227            assert_eq!(
11228                workspace
11229                    .bottom_dock()
11230                    .read(cx)
11231                    .visible_panel()
11232                    .unwrap()
11233                    .panel_id(),
11234                left_panel.panel_id(),
11235                "Left panel should be the visible panel in the bottom dock"
11236            );
11237        });
11238
11239        // Toggle all docks off
11240        workspace.update_in(cx, |workspace, window, cx| {
11241            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11242            assert!(
11243                !workspace.left_dock().read(cx).is_open(),
11244                "Left dock should be closed"
11245            );
11246            assert!(
11247                !workspace.right_dock().read(cx).is_open(),
11248                "Right dock should be closed"
11249            );
11250            assert!(
11251                !workspace.bottom_dock().read(cx).is_open(),
11252                "Bottom dock should be closed"
11253            );
11254        });
11255
11256        // Toggle all docks back on and verify positions are restored
11257        workspace.update_in(cx, |workspace, window, cx| {
11258            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11259            assert!(
11260                !workspace.left_dock().read(cx).is_open(),
11261                "Left dock should remain closed"
11262            );
11263            assert!(
11264                workspace.right_dock().read(cx).is_open(),
11265                "Right dock should remain open"
11266            );
11267            assert!(
11268                workspace.bottom_dock().read(cx).is_open(),
11269                "Bottom dock should remain open"
11270            );
11271            assert_eq!(
11272                left_panel.read(cx).position,
11273                DockPosition::Bottom,
11274                "Left panel should remain in the bottom dock"
11275            );
11276            assert_eq!(
11277                right_panel.read(cx).position,
11278                DockPosition::Right,
11279                "Right panel should remain in the right dock"
11280            );
11281            assert_eq!(
11282                workspace
11283                    .bottom_dock()
11284                    .read(cx)
11285                    .visible_panel()
11286                    .unwrap()
11287                    .panel_id(),
11288                left_panel.panel_id(),
11289                "Left panel should be the visible panel in the right dock"
11290            );
11291        });
11292    }
11293
11294    #[gpui::test]
11295    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11296        init_test(cx);
11297
11298        let fs = FakeFs::new(cx.executor());
11299
11300        let project = Project::test(fs, None, cx).await;
11301        let (workspace, cx) =
11302            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11303
11304        // Let's arrange the panes like this:
11305        //
11306        // +-----------------------+
11307        // |         top           |
11308        // +------+--------+-------+
11309        // | left | center | right |
11310        // +------+--------+-------+
11311        // |        bottom         |
11312        // +-----------------------+
11313
11314        let top_item = cx.new(|cx| {
11315            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11316        });
11317        let bottom_item = cx.new(|cx| {
11318            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11319        });
11320        let left_item = cx.new(|cx| {
11321            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11322        });
11323        let right_item = cx.new(|cx| {
11324            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11325        });
11326        let center_item = cx.new(|cx| {
11327            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11328        });
11329
11330        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11331            let top_pane_id = workspace.active_pane().entity_id();
11332            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11333            workspace.split_pane(
11334                workspace.active_pane().clone(),
11335                SplitDirection::Down,
11336                window,
11337                cx,
11338            );
11339            top_pane_id
11340        });
11341        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11342            let bottom_pane_id = workspace.active_pane().entity_id();
11343            workspace.add_item_to_active_pane(
11344                Box::new(bottom_item.clone()),
11345                None,
11346                false,
11347                window,
11348                cx,
11349            );
11350            workspace.split_pane(
11351                workspace.active_pane().clone(),
11352                SplitDirection::Up,
11353                window,
11354                cx,
11355            );
11356            bottom_pane_id
11357        });
11358        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11359            let left_pane_id = workspace.active_pane().entity_id();
11360            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11361            workspace.split_pane(
11362                workspace.active_pane().clone(),
11363                SplitDirection::Right,
11364                window,
11365                cx,
11366            );
11367            left_pane_id
11368        });
11369        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11370            let right_pane_id = workspace.active_pane().entity_id();
11371            workspace.add_item_to_active_pane(
11372                Box::new(right_item.clone()),
11373                None,
11374                false,
11375                window,
11376                cx,
11377            );
11378            workspace.split_pane(
11379                workspace.active_pane().clone(),
11380                SplitDirection::Left,
11381                window,
11382                cx,
11383            );
11384            right_pane_id
11385        });
11386        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11387            let center_pane_id = workspace.active_pane().entity_id();
11388            workspace.add_item_to_active_pane(
11389                Box::new(center_item.clone()),
11390                None,
11391                false,
11392                window,
11393                cx,
11394            );
11395            center_pane_id
11396        });
11397        cx.executor().run_until_parked();
11398
11399        workspace.update_in(cx, |workspace, window, cx| {
11400            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11401
11402            // Join into next from center pane into right
11403            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11404        });
11405
11406        workspace.update_in(cx, |workspace, window, cx| {
11407            let active_pane = workspace.active_pane();
11408            assert_eq!(right_pane_id, active_pane.entity_id());
11409            assert_eq!(2, active_pane.read(cx).items_len());
11410            let item_ids_in_pane =
11411                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11412            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11413            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11414
11415            // Join into next from right pane into bottom
11416            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11417        });
11418
11419        workspace.update_in(cx, |workspace, window, cx| {
11420            let active_pane = workspace.active_pane();
11421            assert_eq!(bottom_pane_id, active_pane.entity_id());
11422            assert_eq!(3, active_pane.read(cx).items_len());
11423            let item_ids_in_pane =
11424                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11425            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11426            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11427            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11428
11429            // Join into next from bottom pane into left
11430            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11431        });
11432
11433        workspace.update_in(cx, |workspace, window, cx| {
11434            let active_pane = workspace.active_pane();
11435            assert_eq!(left_pane_id, active_pane.entity_id());
11436            assert_eq!(4, active_pane.read(cx).items_len());
11437            let item_ids_in_pane =
11438                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11439            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11440            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11441            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11442            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11443
11444            // Join into next from left pane into top
11445            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11446        });
11447
11448        workspace.update_in(cx, |workspace, window, cx| {
11449            let active_pane = workspace.active_pane();
11450            assert_eq!(top_pane_id, active_pane.entity_id());
11451            assert_eq!(5, active_pane.read(cx).items_len());
11452            let item_ids_in_pane =
11453                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11454            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11455            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11456            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11457            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11458            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11459
11460            // Single pane left: no-op
11461            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11462        });
11463
11464        workspace.update(cx, |workspace, _cx| {
11465            let active_pane = workspace.active_pane();
11466            assert_eq!(top_pane_id, active_pane.entity_id());
11467        });
11468    }
11469
11470    fn add_an_item_to_active_pane(
11471        cx: &mut VisualTestContext,
11472        workspace: &Entity<Workspace>,
11473        item_id: u64,
11474    ) -> Entity<TestItem> {
11475        let item = cx.new(|cx| {
11476            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11477                item_id,
11478                "item{item_id}.txt",
11479                cx,
11480            )])
11481        });
11482        workspace.update_in(cx, |workspace, window, cx| {
11483            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11484        });
11485        item
11486    }
11487
11488    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11489        workspace.update_in(cx, |workspace, window, cx| {
11490            workspace.split_pane(
11491                workspace.active_pane().clone(),
11492                SplitDirection::Right,
11493                window,
11494                cx,
11495            )
11496        })
11497    }
11498
11499    #[gpui::test]
11500    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11501        init_test(cx);
11502        let fs = FakeFs::new(cx.executor());
11503        let project = Project::test(fs, None, cx).await;
11504        let (workspace, cx) =
11505            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11506
11507        add_an_item_to_active_pane(cx, &workspace, 1);
11508        split_pane(cx, &workspace);
11509        add_an_item_to_active_pane(cx, &workspace, 2);
11510        split_pane(cx, &workspace); // empty pane
11511        split_pane(cx, &workspace);
11512        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11513
11514        cx.executor().run_until_parked();
11515
11516        workspace.update(cx, |workspace, cx| {
11517            let num_panes = workspace.panes().len();
11518            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11519            let active_item = workspace
11520                .active_pane()
11521                .read(cx)
11522                .active_item()
11523                .expect("item is in focus");
11524
11525            assert_eq!(num_panes, 4);
11526            assert_eq!(num_items_in_current_pane, 1);
11527            assert_eq!(active_item.item_id(), last_item.item_id());
11528        });
11529
11530        workspace.update_in(cx, |workspace, window, cx| {
11531            workspace.join_all_panes(window, cx);
11532        });
11533
11534        workspace.update(cx, |workspace, cx| {
11535            let num_panes = workspace.panes().len();
11536            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11537            let active_item = workspace
11538                .active_pane()
11539                .read(cx)
11540                .active_item()
11541                .expect("item is in focus");
11542
11543            assert_eq!(num_panes, 1);
11544            assert_eq!(num_items_in_current_pane, 3);
11545            assert_eq!(active_item.item_id(), last_item.item_id());
11546        });
11547    }
11548    struct TestModal(FocusHandle);
11549
11550    impl TestModal {
11551        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11552            Self(cx.focus_handle())
11553        }
11554    }
11555
11556    impl EventEmitter<DismissEvent> for TestModal {}
11557
11558    impl Focusable for TestModal {
11559        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11560            self.0.clone()
11561        }
11562    }
11563
11564    impl ModalView for TestModal {}
11565
11566    impl Render for TestModal {
11567        fn render(
11568            &mut self,
11569            _window: &mut Window,
11570            _cx: &mut Context<TestModal>,
11571        ) -> impl IntoElement {
11572            div().track_focus(&self.0)
11573        }
11574    }
11575
11576    #[gpui::test]
11577    async fn test_panels(cx: &mut gpui::TestAppContext) {
11578        init_test(cx);
11579        let fs = FakeFs::new(cx.executor());
11580
11581        let project = Project::test(fs, [], cx).await;
11582        let (multi_workspace, cx) =
11583            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11584        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11585
11586        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11587            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11588            workspace.add_panel(panel_1.clone(), window, cx);
11589            workspace.toggle_dock(DockPosition::Left, window, cx);
11590            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11591            workspace.add_panel(panel_2.clone(), window, cx);
11592            workspace.toggle_dock(DockPosition::Right, window, cx);
11593
11594            let left_dock = workspace.left_dock();
11595            assert_eq!(
11596                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11597                panel_1.panel_id()
11598            );
11599            assert_eq!(
11600                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11601                panel_1.size(window, cx)
11602            );
11603
11604            left_dock.update(cx, |left_dock, cx| {
11605                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11606            });
11607            assert_eq!(
11608                workspace
11609                    .right_dock()
11610                    .read(cx)
11611                    .visible_panel()
11612                    .unwrap()
11613                    .panel_id(),
11614                panel_2.panel_id(),
11615            );
11616
11617            (panel_1, panel_2)
11618        });
11619
11620        // Move panel_1 to the right
11621        panel_1.update_in(cx, |panel_1, window, cx| {
11622            panel_1.set_position(DockPosition::Right, window, cx)
11623        });
11624
11625        workspace.update_in(cx, |workspace, window, cx| {
11626            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11627            // Since it was the only panel on the left, the left dock should now be closed.
11628            assert!(!workspace.left_dock().read(cx).is_open());
11629            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11630            let right_dock = workspace.right_dock();
11631            assert_eq!(
11632                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11633                panel_1.panel_id()
11634            );
11635            assert_eq!(
11636                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11637                px(1337.)
11638            );
11639
11640            // Now we move panel_2 to the left
11641            panel_2.set_position(DockPosition::Left, window, cx);
11642        });
11643
11644        workspace.update(cx, |workspace, cx| {
11645            // Since panel_2 was not visible on the right, we don't open the left dock.
11646            assert!(!workspace.left_dock().read(cx).is_open());
11647            // And the right dock is unaffected in its displaying of panel_1
11648            assert!(workspace.right_dock().read(cx).is_open());
11649            assert_eq!(
11650                workspace
11651                    .right_dock()
11652                    .read(cx)
11653                    .visible_panel()
11654                    .unwrap()
11655                    .panel_id(),
11656                panel_1.panel_id(),
11657            );
11658        });
11659
11660        // Move panel_1 back to the left
11661        panel_1.update_in(cx, |panel_1, window, cx| {
11662            panel_1.set_position(DockPosition::Left, window, cx)
11663        });
11664
11665        workspace.update_in(cx, |workspace, window, cx| {
11666            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11667            let left_dock = workspace.left_dock();
11668            assert!(left_dock.read(cx).is_open());
11669            assert_eq!(
11670                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11671                panel_1.panel_id()
11672            );
11673            assert_eq!(
11674                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11675                px(1337.)
11676            );
11677            // And the right dock should be closed as it no longer has any panels.
11678            assert!(!workspace.right_dock().read(cx).is_open());
11679
11680            // Now we move panel_1 to the bottom
11681            panel_1.set_position(DockPosition::Bottom, window, cx);
11682        });
11683
11684        workspace.update_in(cx, |workspace, window, cx| {
11685            // Since panel_1 was visible on the left, we close the left dock.
11686            assert!(!workspace.left_dock().read(cx).is_open());
11687            // The bottom dock is sized based on the panel's default size,
11688            // since the panel orientation changed from vertical to horizontal.
11689            let bottom_dock = workspace.bottom_dock();
11690            assert_eq!(
11691                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11692                panel_1.size(window, cx),
11693            );
11694            // Close bottom dock and move panel_1 back to the left.
11695            bottom_dock.update(cx, |bottom_dock, cx| {
11696                bottom_dock.set_open(false, window, cx)
11697            });
11698            panel_1.set_position(DockPosition::Left, window, cx);
11699        });
11700
11701        // Emit activated event on panel 1
11702        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11703
11704        // Now the left dock is open and panel_1 is active and focused.
11705        workspace.update_in(cx, |workspace, window, cx| {
11706            let left_dock = workspace.left_dock();
11707            assert!(left_dock.read(cx).is_open());
11708            assert_eq!(
11709                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11710                panel_1.panel_id(),
11711            );
11712            assert!(panel_1.focus_handle(cx).is_focused(window));
11713        });
11714
11715        // Emit closed event on panel 2, which is not active
11716        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11717
11718        // Wo don't close the left dock, because panel_2 wasn't the active panel
11719        workspace.update(cx, |workspace, cx| {
11720            let left_dock = workspace.left_dock();
11721            assert!(left_dock.read(cx).is_open());
11722            assert_eq!(
11723                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11724                panel_1.panel_id(),
11725            );
11726        });
11727
11728        // Emitting a ZoomIn event shows the panel as zoomed.
11729        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11730        workspace.read_with(cx, |workspace, _| {
11731            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11732            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11733        });
11734
11735        // Move panel to another dock while it is zoomed
11736        panel_1.update_in(cx, |panel, window, cx| {
11737            panel.set_position(DockPosition::Right, window, cx)
11738        });
11739        workspace.read_with(cx, |workspace, _| {
11740            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11741
11742            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11743        });
11744
11745        // This is a helper for getting a:
11746        // - valid focus on an element,
11747        // - that isn't a part of the panes and panels system of the Workspace,
11748        // - and doesn't trigger the 'on_focus_lost' API.
11749        let focus_other_view = {
11750            let workspace = workspace.clone();
11751            move |cx: &mut VisualTestContext| {
11752                workspace.update_in(cx, |workspace, window, cx| {
11753                    if workspace.active_modal::<TestModal>(cx).is_some() {
11754                        workspace.toggle_modal(window, cx, TestModal::new);
11755                        workspace.toggle_modal(window, cx, TestModal::new);
11756                    } else {
11757                        workspace.toggle_modal(window, cx, TestModal::new);
11758                    }
11759                })
11760            }
11761        };
11762
11763        // If focus is transferred to another view that's not a panel or another pane, we still show
11764        // the panel as zoomed.
11765        focus_other_view(cx);
11766        workspace.read_with(cx, |workspace, _| {
11767            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11768            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11769        });
11770
11771        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11772        workspace.update_in(cx, |_workspace, window, cx| {
11773            cx.focus_self(window);
11774        });
11775        workspace.read_with(cx, |workspace, _| {
11776            assert_eq!(workspace.zoomed, None);
11777            assert_eq!(workspace.zoomed_position, None);
11778        });
11779
11780        // If focus is transferred again to another view that's not a panel or a pane, we won't
11781        // show the panel as zoomed because it wasn't zoomed before.
11782        focus_other_view(cx);
11783        workspace.read_with(cx, |workspace, _| {
11784            assert_eq!(workspace.zoomed, None);
11785            assert_eq!(workspace.zoomed_position, None);
11786        });
11787
11788        // When the panel is activated, it is zoomed again.
11789        cx.dispatch_action(ToggleRightDock);
11790        workspace.read_with(cx, |workspace, _| {
11791            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11792            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11793        });
11794
11795        // Emitting a ZoomOut event unzooms the panel.
11796        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11797        workspace.read_with(cx, |workspace, _| {
11798            assert_eq!(workspace.zoomed, None);
11799            assert_eq!(workspace.zoomed_position, None);
11800        });
11801
11802        // Emit closed event on panel 1, which is active
11803        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11804
11805        // Now the left dock is closed, because panel_1 was the active panel
11806        workspace.update(cx, |workspace, cx| {
11807            let right_dock = workspace.right_dock();
11808            assert!(!right_dock.read(cx).is_open());
11809        });
11810    }
11811
11812    #[gpui::test]
11813    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11814        init_test(cx);
11815
11816        let fs = FakeFs::new(cx.background_executor.clone());
11817        let project = Project::test(fs, [], cx).await;
11818        let (workspace, cx) =
11819            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11820        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11821
11822        let dirty_regular_buffer = cx.new(|cx| {
11823            TestItem::new(cx)
11824                .with_dirty(true)
11825                .with_label("1.txt")
11826                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11827        });
11828        let dirty_regular_buffer_2 = cx.new(|cx| {
11829            TestItem::new(cx)
11830                .with_dirty(true)
11831                .with_label("2.txt")
11832                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11833        });
11834        let dirty_multi_buffer_with_both = cx.new(|cx| {
11835            TestItem::new(cx)
11836                .with_dirty(true)
11837                .with_buffer_kind(ItemBufferKind::Multibuffer)
11838                .with_label("Fake Project Search")
11839                .with_project_items(&[
11840                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11841                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11842                ])
11843        });
11844        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11845        workspace.update_in(cx, |workspace, window, cx| {
11846            workspace.add_item(
11847                pane.clone(),
11848                Box::new(dirty_regular_buffer.clone()),
11849                None,
11850                false,
11851                false,
11852                window,
11853                cx,
11854            );
11855            workspace.add_item(
11856                pane.clone(),
11857                Box::new(dirty_regular_buffer_2.clone()),
11858                None,
11859                false,
11860                false,
11861                window,
11862                cx,
11863            );
11864            workspace.add_item(
11865                pane.clone(),
11866                Box::new(dirty_multi_buffer_with_both.clone()),
11867                None,
11868                false,
11869                false,
11870                window,
11871                cx,
11872            );
11873        });
11874
11875        pane.update_in(cx, |pane, window, cx| {
11876            pane.activate_item(2, true, true, window, cx);
11877            assert_eq!(
11878                pane.active_item().unwrap().item_id(),
11879                multi_buffer_with_both_files_id,
11880                "Should select the multi buffer in the pane"
11881            );
11882        });
11883        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11884            pane.close_other_items(
11885                &CloseOtherItems {
11886                    save_intent: Some(SaveIntent::Save),
11887                    close_pinned: true,
11888                },
11889                None,
11890                window,
11891                cx,
11892            )
11893        });
11894        cx.background_executor.run_until_parked();
11895        assert!(!cx.has_pending_prompt());
11896        close_all_but_multi_buffer_task
11897            .await
11898            .expect("Closing all buffers but the multi buffer failed");
11899        pane.update(cx, |pane, cx| {
11900            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11901            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11902            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11903            assert_eq!(pane.items_len(), 1);
11904            assert_eq!(
11905                pane.active_item().unwrap().item_id(),
11906                multi_buffer_with_both_files_id,
11907                "Should have only the multi buffer left in the pane"
11908            );
11909            assert!(
11910                dirty_multi_buffer_with_both.read(cx).is_dirty,
11911                "The multi buffer containing the unsaved buffer should still be dirty"
11912            );
11913        });
11914
11915        dirty_regular_buffer.update(cx, |buffer, cx| {
11916            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11917        });
11918
11919        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11920            pane.close_active_item(
11921                &CloseActiveItem {
11922                    save_intent: Some(SaveIntent::Close),
11923                    close_pinned: false,
11924                },
11925                window,
11926                cx,
11927            )
11928        });
11929        cx.background_executor.run_until_parked();
11930        assert!(
11931            cx.has_pending_prompt(),
11932            "Dirty multi buffer should prompt a save dialog"
11933        );
11934        cx.simulate_prompt_answer("Save");
11935        cx.background_executor.run_until_parked();
11936        close_multi_buffer_task
11937            .await
11938            .expect("Closing the multi buffer failed");
11939        pane.update(cx, |pane, cx| {
11940            assert_eq!(
11941                dirty_multi_buffer_with_both.read(cx).save_count,
11942                1,
11943                "Multi buffer item should get be saved"
11944            );
11945            // Test impl does not save inner items, so we do not assert them
11946            assert_eq!(
11947                pane.items_len(),
11948                0,
11949                "No more items should be left in the pane"
11950            );
11951            assert!(pane.active_item().is_none());
11952        });
11953    }
11954
11955    #[gpui::test]
11956    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11957        cx: &mut TestAppContext,
11958    ) {
11959        init_test(cx);
11960
11961        let fs = FakeFs::new(cx.background_executor.clone());
11962        let project = Project::test(fs, [], cx).await;
11963        let (workspace, cx) =
11964            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11965        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11966
11967        let dirty_regular_buffer = cx.new(|cx| {
11968            TestItem::new(cx)
11969                .with_dirty(true)
11970                .with_label("1.txt")
11971                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11972        });
11973        let dirty_regular_buffer_2 = cx.new(|cx| {
11974            TestItem::new(cx)
11975                .with_dirty(true)
11976                .with_label("2.txt")
11977                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11978        });
11979        let clear_regular_buffer = cx.new(|cx| {
11980            TestItem::new(cx)
11981                .with_label("3.txt")
11982                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11983        });
11984
11985        let dirty_multi_buffer_with_both = cx.new(|cx| {
11986            TestItem::new(cx)
11987                .with_dirty(true)
11988                .with_buffer_kind(ItemBufferKind::Multibuffer)
11989                .with_label("Fake Project Search")
11990                .with_project_items(&[
11991                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11992                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11993                    clear_regular_buffer.read(cx).project_items[0].clone(),
11994                ])
11995        });
11996        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11997        workspace.update_in(cx, |workspace, window, cx| {
11998            workspace.add_item(
11999                pane.clone(),
12000                Box::new(dirty_regular_buffer.clone()),
12001                None,
12002                false,
12003                false,
12004                window,
12005                cx,
12006            );
12007            workspace.add_item(
12008                pane.clone(),
12009                Box::new(dirty_multi_buffer_with_both.clone()),
12010                None,
12011                false,
12012                false,
12013                window,
12014                cx,
12015            );
12016        });
12017
12018        pane.update_in(cx, |pane, window, cx| {
12019            pane.activate_item(1, true, true, window, cx);
12020            assert_eq!(
12021                pane.active_item().unwrap().item_id(),
12022                multi_buffer_with_both_files_id,
12023                "Should select the multi buffer in the pane"
12024            );
12025        });
12026        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12027            pane.close_active_item(
12028                &CloseActiveItem {
12029                    save_intent: None,
12030                    close_pinned: false,
12031                },
12032                window,
12033                cx,
12034            )
12035        });
12036        cx.background_executor.run_until_parked();
12037        assert!(
12038            cx.has_pending_prompt(),
12039            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12040        );
12041    }
12042
12043    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12044    /// closed when they are deleted from disk.
12045    #[gpui::test]
12046    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12047        init_test(cx);
12048
12049        // Enable the close_on_disk_deletion setting
12050        cx.update_global(|store: &mut SettingsStore, cx| {
12051            store.update_user_settings(cx, |settings| {
12052                settings.workspace.close_on_file_delete = Some(true);
12053            });
12054        });
12055
12056        let fs = FakeFs::new(cx.background_executor.clone());
12057        let project = Project::test(fs, [], cx).await;
12058        let (workspace, cx) =
12059            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12060        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12061
12062        // Create a test item that simulates a file
12063        let item = cx.new(|cx| {
12064            TestItem::new(cx)
12065                .with_label("test.txt")
12066                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12067        });
12068
12069        // Add item to workspace
12070        workspace.update_in(cx, |workspace, window, cx| {
12071            workspace.add_item(
12072                pane.clone(),
12073                Box::new(item.clone()),
12074                None,
12075                false,
12076                false,
12077                window,
12078                cx,
12079            );
12080        });
12081
12082        // Verify the item is in the pane
12083        pane.read_with(cx, |pane, _| {
12084            assert_eq!(pane.items().count(), 1);
12085        });
12086
12087        // Simulate file deletion by setting the item's deleted state
12088        item.update(cx, |item, _| {
12089            item.set_has_deleted_file(true);
12090        });
12091
12092        // Emit UpdateTab event to trigger the close behavior
12093        cx.run_until_parked();
12094        item.update(cx, |_, cx| {
12095            cx.emit(ItemEvent::UpdateTab);
12096        });
12097
12098        // Allow the close operation to complete
12099        cx.run_until_parked();
12100
12101        // Verify the item was automatically closed
12102        pane.read_with(cx, |pane, _| {
12103            assert_eq!(
12104                pane.items().count(),
12105                0,
12106                "Item should be automatically closed when file is deleted"
12107            );
12108        });
12109    }
12110
12111    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12112    /// open with a strikethrough when they are deleted from disk.
12113    #[gpui::test]
12114    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12115        init_test(cx);
12116
12117        // Ensure close_on_disk_deletion is disabled (default)
12118        cx.update_global(|store: &mut SettingsStore, cx| {
12119            store.update_user_settings(cx, |settings| {
12120                settings.workspace.close_on_file_delete = Some(false);
12121            });
12122        });
12123
12124        let fs = FakeFs::new(cx.background_executor.clone());
12125        let project = Project::test(fs, [], cx).await;
12126        let (workspace, cx) =
12127            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12128        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12129
12130        // Create a test item that simulates a file
12131        let item = cx.new(|cx| {
12132            TestItem::new(cx)
12133                .with_label("test.txt")
12134                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12135        });
12136
12137        // Add item to workspace
12138        workspace.update_in(cx, |workspace, window, cx| {
12139            workspace.add_item(
12140                pane.clone(),
12141                Box::new(item.clone()),
12142                None,
12143                false,
12144                false,
12145                window,
12146                cx,
12147            );
12148        });
12149
12150        // Verify the item is in the pane
12151        pane.read_with(cx, |pane, _| {
12152            assert_eq!(pane.items().count(), 1);
12153        });
12154
12155        // Simulate file deletion
12156        item.update(cx, |item, _| {
12157            item.set_has_deleted_file(true);
12158        });
12159
12160        // Emit UpdateTab event
12161        cx.run_until_parked();
12162        item.update(cx, |_, cx| {
12163            cx.emit(ItemEvent::UpdateTab);
12164        });
12165
12166        // Allow any potential close operation to complete
12167        cx.run_until_parked();
12168
12169        // Verify the item remains open (with strikethrough)
12170        pane.read_with(cx, |pane, _| {
12171            assert_eq!(
12172                pane.items().count(),
12173                1,
12174                "Item should remain open when close_on_disk_deletion is disabled"
12175            );
12176        });
12177
12178        // Verify the item shows as deleted
12179        item.read_with(cx, |item, _| {
12180            assert!(
12181                item.has_deleted_file,
12182                "Item should be marked as having deleted file"
12183            );
12184        });
12185    }
12186
12187    /// Tests that dirty files are not automatically closed when deleted from disk,
12188    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12189    /// unsaved changes without being prompted.
12190    #[gpui::test]
12191    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12192        init_test(cx);
12193
12194        // Enable the close_on_file_delete setting
12195        cx.update_global(|store: &mut SettingsStore, cx| {
12196            store.update_user_settings(cx, |settings| {
12197                settings.workspace.close_on_file_delete = Some(true);
12198            });
12199        });
12200
12201        let fs = FakeFs::new(cx.background_executor.clone());
12202        let project = Project::test(fs, [], cx).await;
12203        let (workspace, cx) =
12204            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12205        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12206
12207        // Create a dirty test item
12208        let item = cx.new(|cx| {
12209            TestItem::new(cx)
12210                .with_dirty(true)
12211                .with_label("test.txt")
12212                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12213        });
12214
12215        // Add item to workspace
12216        workspace.update_in(cx, |workspace, window, cx| {
12217            workspace.add_item(
12218                pane.clone(),
12219                Box::new(item.clone()),
12220                None,
12221                false,
12222                false,
12223                window,
12224                cx,
12225            );
12226        });
12227
12228        // Simulate file deletion
12229        item.update(cx, |item, _| {
12230            item.set_has_deleted_file(true);
12231        });
12232
12233        // Emit UpdateTab event to trigger the close behavior
12234        cx.run_until_parked();
12235        item.update(cx, |_, cx| {
12236            cx.emit(ItemEvent::UpdateTab);
12237        });
12238
12239        // Allow any potential close operation to complete
12240        cx.run_until_parked();
12241
12242        // Verify the item remains open (dirty files are not auto-closed)
12243        pane.read_with(cx, |pane, _| {
12244            assert_eq!(
12245                pane.items().count(),
12246                1,
12247                "Dirty items should not be automatically closed even when file is deleted"
12248            );
12249        });
12250
12251        // Verify the item is marked as deleted and still dirty
12252        item.read_with(cx, |item, _| {
12253            assert!(
12254                item.has_deleted_file,
12255                "Item should be marked as having deleted file"
12256            );
12257            assert!(item.is_dirty, "Item should still be dirty");
12258        });
12259    }
12260
12261    /// Tests that navigation history is cleaned up when files are auto-closed
12262    /// due to deletion from disk.
12263    #[gpui::test]
12264    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12265        init_test(cx);
12266
12267        // Enable the close_on_file_delete setting
12268        cx.update_global(|store: &mut SettingsStore, cx| {
12269            store.update_user_settings(cx, |settings| {
12270                settings.workspace.close_on_file_delete = Some(true);
12271            });
12272        });
12273
12274        let fs = FakeFs::new(cx.background_executor.clone());
12275        let project = Project::test(fs, [], cx).await;
12276        let (workspace, cx) =
12277            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12278        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12279
12280        // Create test items
12281        let item1 = cx.new(|cx| {
12282            TestItem::new(cx)
12283                .with_label("test1.txt")
12284                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12285        });
12286        let item1_id = item1.item_id();
12287
12288        let item2 = cx.new(|cx| {
12289            TestItem::new(cx)
12290                .with_label("test2.txt")
12291                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12292        });
12293
12294        // Add items to workspace
12295        workspace.update_in(cx, |workspace, window, cx| {
12296            workspace.add_item(
12297                pane.clone(),
12298                Box::new(item1.clone()),
12299                None,
12300                false,
12301                false,
12302                window,
12303                cx,
12304            );
12305            workspace.add_item(
12306                pane.clone(),
12307                Box::new(item2.clone()),
12308                None,
12309                false,
12310                false,
12311                window,
12312                cx,
12313            );
12314        });
12315
12316        // Activate item1 to ensure it gets navigation entries
12317        pane.update_in(cx, |pane, window, cx| {
12318            pane.activate_item(0, true, true, window, cx);
12319        });
12320
12321        // Switch to item2 and back to create navigation history
12322        pane.update_in(cx, |pane, window, cx| {
12323            pane.activate_item(1, true, true, window, cx);
12324        });
12325        cx.run_until_parked();
12326
12327        pane.update_in(cx, |pane, window, cx| {
12328            pane.activate_item(0, true, true, window, cx);
12329        });
12330        cx.run_until_parked();
12331
12332        // Simulate file deletion for item1
12333        item1.update(cx, |item, _| {
12334            item.set_has_deleted_file(true);
12335        });
12336
12337        // Emit UpdateTab event to trigger the close behavior
12338        item1.update(cx, |_, cx| {
12339            cx.emit(ItemEvent::UpdateTab);
12340        });
12341        cx.run_until_parked();
12342
12343        // Verify item1 was closed
12344        pane.read_with(cx, |pane, _| {
12345            assert_eq!(
12346                pane.items().count(),
12347                1,
12348                "Should have 1 item remaining after auto-close"
12349            );
12350        });
12351
12352        // Check navigation history after close
12353        let has_item = pane.read_with(cx, |pane, cx| {
12354            let mut has_item = false;
12355            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12356                if entry.item.id() == item1_id {
12357                    has_item = true;
12358                }
12359            });
12360            has_item
12361        });
12362
12363        assert!(
12364            !has_item,
12365            "Navigation history should not contain closed item entries"
12366        );
12367    }
12368
12369    #[gpui::test]
12370    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12371        cx: &mut TestAppContext,
12372    ) {
12373        init_test(cx);
12374
12375        let fs = FakeFs::new(cx.background_executor.clone());
12376        let project = Project::test(fs, [], cx).await;
12377        let (workspace, cx) =
12378            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12379        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12380
12381        let dirty_regular_buffer = cx.new(|cx| {
12382            TestItem::new(cx)
12383                .with_dirty(true)
12384                .with_label("1.txt")
12385                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12386        });
12387        let dirty_regular_buffer_2 = cx.new(|cx| {
12388            TestItem::new(cx)
12389                .with_dirty(true)
12390                .with_label("2.txt")
12391                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12392        });
12393        let clear_regular_buffer = cx.new(|cx| {
12394            TestItem::new(cx)
12395                .with_label("3.txt")
12396                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12397        });
12398
12399        let dirty_multi_buffer = cx.new(|cx| {
12400            TestItem::new(cx)
12401                .with_dirty(true)
12402                .with_buffer_kind(ItemBufferKind::Multibuffer)
12403                .with_label("Fake Project Search")
12404                .with_project_items(&[
12405                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12406                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12407                    clear_regular_buffer.read(cx).project_items[0].clone(),
12408                ])
12409        });
12410        workspace.update_in(cx, |workspace, window, cx| {
12411            workspace.add_item(
12412                pane.clone(),
12413                Box::new(dirty_regular_buffer.clone()),
12414                None,
12415                false,
12416                false,
12417                window,
12418                cx,
12419            );
12420            workspace.add_item(
12421                pane.clone(),
12422                Box::new(dirty_regular_buffer_2.clone()),
12423                None,
12424                false,
12425                false,
12426                window,
12427                cx,
12428            );
12429            workspace.add_item(
12430                pane.clone(),
12431                Box::new(dirty_multi_buffer.clone()),
12432                None,
12433                false,
12434                false,
12435                window,
12436                cx,
12437            );
12438        });
12439
12440        pane.update_in(cx, |pane, window, cx| {
12441            pane.activate_item(2, true, true, window, cx);
12442            assert_eq!(
12443                pane.active_item().unwrap().item_id(),
12444                dirty_multi_buffer.item_id(),
12445                "Should select the multi buffer in the pane"
12446            );
12447        });
12448        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12449            pane.close_active_item(
12450                &CloseActiveItem {
12451                    save_intent: None,
12452                    close_pinned: false,
12453                },
12454                window,
12455                cx,
12456            )
12457        });
12458        cx.background_executor.run_until_parked();
12459        assert!(
12460            !cx.has_pending_prompt(),
12461            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12462        );
12463        close_multi_buffer_task
12464            .await
12465            .expect("Closing multi buffer failed");
12466        pane.update(cx, |pane, cx| {
12467            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12468            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12469            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12470            assert_eq!(
12471                pane.items()
12472                    .map(|item| item.item_id())
12473                    .sorted()
12474                    .collect::<Vec<_>>(),
12475                vec![
12476                    dirty_regular_buffer.item_id(),
12477                    dirty_regular_buffer_2.item_id(),
12478                ],
12479                "Should have no multi buffer left in the pane"
12480            );
12481            assert!(dirty_regular_buffer.read(cx).is_dirty);
12482            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12483        });
12484    }
12485
12486    #[gpui::test]
12487    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12488        init_test(cx);
12489        let fs = FakeFs::new(cx.executor());
12490        let project = Project::test(fs, [], cx).await;
12491        let (multi_workspace, cx) =
12492            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12493        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12494
12495        // Add a new panel to the right dock, opening the dock and setting the
12496        // focus to the new panel.
12497        let panel = workspace.update_in(cx, |workspace, window, cx| {
12498            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12499            workspace.add_panel(panel.clone(), window, cx);
12500
12501            workspace
12502                .right_dock()
12503                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12504
12505            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12506
12507            panel
12508        });
12509
12510        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12511        // panel to the next valid position which, in this case, is the left
12512        // dock.
12513        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12514        workspace.update(cx, |workspace, cx| {
12515            assert!(workspace.left_dock().read(cx).is_open());
12516            assert_eq!(panel.read(cx).position, DockPosition::Left);
12517        });
12518
12519        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12520        // panel to the next valid position which, in this case, is the bottom
12521        // dock.
12522        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12523        workspace.update(cx, |workspace, cx| {
12524            assert!(workspace.bottom_dock().read(cx).is_open());
12525            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12526        });
12527
12528        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12529        // around moving the panel to its initial position, the right dock.
12530        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12531        workspace.update(cx, |workspace, cx| {
12532            assert!(workspace.right_dock().read(cx).is_open());
12533            assert_eq!(panel.read(cx).position, DockPosition::Right);
12534        });
12535
12536        // Remove focus from the panel, ensuring that, if the panel is not
12537        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12538        // the panel's position, so the panel is still in the right dock.
12539        workspace.update_in(cx, |workspace, window, cx| {
12540            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12541        });
12542
12543        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12544        workspace.update(cx, |workspace, cx| {
12545            assert!(workspace.right_dock().read(cx).is_open());
12546            assert_eq!(panel.read(cx).position, DockPosition::Right);
12547        });
12548    }
12549
12550    #[gpui::test]
12551    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12552        init_test(cx);
12553
12554        let fs = FakeFs::new(cx.executor());
12555        let project = Project::test(fs, [], cx).await;
12556        let (workspace, cx) =
12557            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12558
12559        let item_1 = cx.new(|cx| {
12560            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12561        });
12562        workspace.update_in(cx, |workspace, window, cx| {
12563            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12564            workspace.move_item_to_pane_in_direction(
12565                &MoveItemToPaneInDirection {
12566                    direction: SplitDirection::Right,
12567                    focus: true,
12568                    clone: false,
12569                },
12570                window,
12571                cx,
12572            );
12573            workspace.move_item_to_pane_at_index(
12574                &MoveItemToPane {
12575                    destination: 3,
12576                    focus: true,
12577                    clone: false,
12578                },
12579                window,
12580                cx,
12581            );
12582
12583            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12584            assert_eq!(
12585                pane_items_paths(&workspace.active_pane, cx),
12586                vec!["first.txt".to_string()],
12587                "Single item was not moved anywhere"
12588            );
12589        });
12590
12591        let item_2 = cx.new(|cx| {
12592            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12593        });
12594        workspace.update_in(cx, |workspace, window, cx| {
12595            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12596            assert_eq!(
12597                pane_items_paths(&workspace.panes[0], cx),
12598                vec!["first.txt".to_string(), "second.txt".to_string()],
12599            );
12600            workspace.move_item_to_pane_in_direction(
12601                &MoveItemToPaneInDirection {
12602                    direction: SplitDirection::Right,
12603                    focus: true,
12604                    clone: false,
12605                },
12606                window,
12607                cx,
12608            );
12609
12610            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12611            assert_eq!(
12612                pane_items_paths(&workspace.panes[0], cx),
12613                vec!["first.txt".to_string()],
12614                "After moving, one item should be left in the original pane"
12615            );
12616            assert_eq!(
12617                pane_items_paths(&workspace.panes[1], cx),
12618                vec!["second.txt".to_string()],
12619                "New item should have been moved to the new pane"
12620            );
12621        });
12622
12623        let item_3 = cx.new(|cx| {
12624            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12625        });
12626        workspace.update_in(cx, |workspace, window, cx| {
12627            let original_pane = workspace.panes[0].clone();
12628            workspace.set_active_pane(&original_pane, window, cx);
12629            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12630            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12631            assert_eq!(
12632                pane_items_paths(&workspace.active_pane, cx),
12633                vec!["first.txt".to_string(), "third.txt".to_string()],
12634                "New pane should be ready to move one item out"
12635            );
12636
12637            workspace.move_item_to_pane_at_index(
12638                &MoveItemToPane {
12639                    destination: 3,
12640                    focus: true,
12641                    clone: false,
12642                },
12643                window,
12644                cx,
12645            );
12646            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12647            assert_eq!(
12648                pane_items_paths(&workspace.active_pane, cx),
12649                vec!["first.txt".to_string()],
12650                "After moving, one item should be left in the original pane"
12651            );
12652            assert_eq!(
12653                pane_items_paths(&workspace.panes[1], cx),
12654                vec!["second.txt".to_string()],
12655                "Previously created pane should be unchanged"
12656            );
12657            assert_eq!(
12658                pane_items_paths(&workspace.panes[2], cx),
12659                vec!["third.txt".to_string()],
12660                "New item should have been moved to the new pane"
12661            );
12662        });
12663    }
12664
12665    #[gpui::test]
12666    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12667        init_test(cx);
12668
12669        let fs = FakeFs::new(cx.executor());
12670        let project = Project::test(fs, [], cx).await;
12671        let (workspace, cx) =
12672            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12673
12674        let item_1 = cx.new(|cx| {
12675            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12676        });
12677        workspace.update_in(cx, |workspace, window, cx| {
12678            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12679            workspace.move_item_to_pane_in_direction(
12680                &MoveItemToPaneInDirection {
12681                    direction: SplitDirection::Right,
12682                    focus: true,
12683                    clone: true,
12684                },
12685                window,
12686                cx,
12687            );
12688        });
12689        cx.run_until_parked();
12690        workspace.update_in(cx, |workspace, window, cx| {
12691            workspace.move_item_to_pane_at_index(
12692                &MoveItemToPane {
12693                    destination: 3,
12694                    focus: true,
12695                    clone: true,
12696                },
12697                window,
12698                cx,
12699            );
12700        });
12701        cx.run_until_parked();
12702
12703        workspace.update(cx, |workspace, cx| {
12704            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12705            for pane in workspace.panes() {
12706                assert_eq!(
12707                    pane_items_paths(pane, cx),
12708                    vec!["first.txt".to_string()],
12709                    "Single item exists in all panes"
12710                );
12711            }
12712        });
12713
12714        // verify that the active pane has been updated after waiting for the
12715        // pane focus event to fire and resolve
12716        workspace.read_with(cx, |workspace, _app| {
12717            assert_eq!(
12718                workspace.active_pane(),
12719                &workspace.panes[2],
12720                "The third pane should be the active one: {:?}",
12721                workspace.panes
12722            );
12723        })
12724    }
12725
12726    #[gpui::test]
12727    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12728        init_test(cx);
12729
12730        let fs = FakeFs::new(cx.executor());
12731        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12732
12733        let project = Project::test(fs, ["root".as_ref()], cx).await;
12734        let (workspace, cx) =
12735            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12736
12737        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12738        // Add item to pane A with project path
12739        let item_a = cx.new(|cx| {
12740            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12741        });
12742        workspace.update_in(cx, |workspace, window, cx| {
12743            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12744        });
12745
12746        // Split to create pane B
12747        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12748            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12749        });
12750
12751        // Add item with SAME project path to pane B, and pin it
12752        let item_b = cx.new(|cx| {
12753            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12754        });
12755        pane_b.update_in(cx, |pane, window, cx| {
12756            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12757            pane.set_pinned_count(1);
12758        });
12759
12760        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12761        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12762
12763        // close_pinned: false should only close the unpinned copy
12764        workspace.update_in(cx, |workspace, window, cx| {
12765            workspace.close_item_in_all_panes(
12766                &CloseItemInAllPanes {
12767                    save_intent: Some(SaveIntent::Close),
12768                    close_pinned: false,
12769                },
12770                window,
12771                cx,
12772            )
12773        });
12774        cx.executor().run_until_parked();
12775
12776        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12777        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12778        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12779        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12780
12781        // Split again, seeing as closing the previous item also closed its
12782        // pane, so only pane remains, which does not allow us to properly test
12783        // that both items close when `close_pinned: true`.
12784        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12785            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12786        });
12787
12788        // Add an item with the same project path to pane C so that
12789        // close_item_in_all_panes can determine what to close across all panes
12790        // (it reads the active item from the active pane, and split_pane
12791        // creates an empty pane).
12792        let item_c = cx.new(|cx| {
12793            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12794        });
12795        pane_c.update_in(cx, |pane, window, cx| {
12796            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12797        });
12798
12799        // close_pinned: true should close the pinned copy too
12800        workspace.update_in(cx, |workspace, window, cx| {
12801            let panes_count = workspace.panes().len();
12802            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12803
12804            workspace.close_item_in_all_panes(
12805                &CloseItemInAllPanes {
12806                    save_intent: Some(SaveIntent::Close),
12807                    close_pinned: true,
12808                },
12809                window,
12810                cx,
12811            )
12812        });
12813        cx.executor().run_until_parked();
12814
12815        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12816        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12817        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12818        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12819    }
12820
12821    mod register_project_item_tests {
12822
12823        use super::*;
12824
12825        // View
12826        struct TestPngItemView {
12827            focus_handle: FocusHandle,
12828        }
12829        // Model
12830        struct TestPngItem {}
12831
12832        impl project::ProjectItem for TestPngItem {
12833            fn try_open(
12834                _project: &Entity<Project>,
12835                path: &ProjectPath,
12836                cx: &mut App,
12837            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12838                if path.path.extension().unwrap() == "png" {
12839                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12840                } else {
12841                    None
12842                }
12843            }
12844
12845            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12846                None
12847            }
12848
12849            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12850                None
12851            }
12852
12853            fn is_dirty(&self) -> bool {
12854                false
12855            }
12856        }
12857
12858        impl Item for TestPngItemView {
12859            type Event = ();
12860            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12861                "".into()
12862            }
12863        }
12864        impl EventEmitter<()> for TestPngItemView {}
12865        impl Focusable for TestPngItemView {
12866            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12867                self.focus_handle.clone()
12868            }
12869        }
12870
12871        impl Render for TestPngItemView {
12872            fn render(
12873                &mut self,
12874                _window: &mut Window,
12875                _cx: &mut Context<Self>,
12876            ) -> impl IntoElement {
12877                Empty
12878            }
12879        }
12880
12881        impl ProjectItem for TestPngItemView {
12882            type Item = TestPngItem;
12883
12884            fn for_project_item(
12885                _project: Entity<Project>,
12886                _pane: Option<&Pane>,
12887                _item: Entity<Self::Item>,
12888                _: &mut Window,
12889                cx: &mut Context<Self>,
12890            ) -> Self
12891            where
12892                Self: Sized,
12893            {
12894                Self {
12895                    focus_handle: cx.focus_handle(),
12896                }
12897            }
12898        }
12899
12900        // View
12901        struct TestIpynbItemView {
12902            focus_handle: FocusHandle,
12903        }
12904        // Model
12905        struct TestIpynbItem {}
12906
12907        impl project::ProjectItem for TestIpynbItem {
12908            fn try_open(
12909                _project: &Entity<Project>,
12910                path: &ProjectPath,
12911                cx: &mut App,
12912            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12913                if path.path.extension().unwrap() == "ipynb" {
12914                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12915                } else {
12916                    None
12917                }
12918            }
12919
12920            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12921                None
12922            }
12923
12924            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12925                None
12926            }
12927
12928            fn is_dirty(&self) -> bool {
12929                false
12930            }
12931        }
12932
12933        impl Item for TestIpynbItemView {
12934            type Event = ();
12935            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12936                "".into()
12937            }
12938        }
12939        impl EventEmitter<()> for TestIpynbItemView {}
12940        impl Focusable for TestIpynbItemView {
12941            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12942                self.focus_handle.clone()
12943            }
12944        }
12945
12946        impl Render for TestIpynbItemView {
12947            fn render(
12948                &mut self,
12949                _window: &mut Window,
12950                _cx: &mut Context<Self>,
12951            ) -> impl IntoElement {
12952                Empty
12953            }
12954        }
12955
12956        impl ProjectItem for TestIpynbItemView {
12957            type Item = TestIpynbItem;
12958
12959            fn for_project_item(
12960                _project: Entity<Project>,
12961                _pane: Option<&Pane>,
12962                _item: Entity<Self::Item>,
12963                _: &mut Window,
12964                cx: &mut Context<Self>,
12965            ) -> Self
12966            where
12967                Self: Sized,
12968            {
12969                Self {
12970                    focus_handle: cx.focus_handle(),
12971                }
12972            }
12973        }
12974
12975        struct TestAlternatePngItemView {
12976            focus_handle: FocusHandle,
12977        }
12978
12979        impl Item for TestAlternatePngItemView {
12980            type Event = ();
12981            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12982                "".into()
12983            }
12984        }
12985
12986        impl EventEmitter<()> for TestAlternatePngItemView {}
12987        impl Focusable for TestAlternatePngItemView {
12988            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12989                self.focus_handle.clone()
12990            }
12991        }
12992
12993        impl Render for TestAlternatePngItemView {
12994            fn render(
12995                &mut self,
12996                _window: &mut Window,
12997                _cx: &mut Context<Self>,
12998            ) -> impl IntoElement {
12999                Empty
13000            }
13001        }
13002
13003        impl ProjectItem for TestAlternatePngItemView {
13004            type Item = TestPngItem;
13005
13006            fn for_project_item(
13007                _project: Entity<Project>,
13008                _pane: Option<&Pane>,
13009                _item: Entity<Self::Item>,
13010                _: &mut Window,
13011                cx: &mut Context<Self>,
13012            ) -> Self
13013            where
13014                Self: Sized,
13015            {
13016                Self {
13017                    focus_handle: cx.focus_handle(),
13018                }
13019            }
13020        }
13021
13022        #[gpui::test]
13023        async fn test_register_project_item(cx: &mut TestAppContext) {
13024            init_test(cx);
13025
13026            cx.update(|cx| {
13027                register_project_item::<TestPngItemView>(cx);
13028                register_project_item::<TestIpynbItemView>(cx);
13029            });
13030
13031            let fs = FakeFs::new(cx.executor());
13032            fs.insert_tree(
13033                "/root1",
13034                json!({
13035                    "one.png": "BINARYDATAHERE",
13036                    "two.ipynb": "{ totally a notebook }",
13037                    "three.txt": "editing text, sure why not?"
13038                }),
13039            )
13040            .await;
13041
13042            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13043            let (workspace, cx) =
13044                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13045
13046            let worktree_id = project.update(cx, |project, cx| {
13047                project.worktrees(cx).next().unwrap().read(cx).id()
13048            });
13049
13050            let handle = workspace
13051                .update_in(cx, |workspace, window, cx| {
13052                    let project_path = (worktree_id, rel_path("one.png"));
13053                    workspace.open_path(project_path, None, true, window, cx)
13054                })
13055                .await
13056                .unwrap();
13057
13058            // Now we can check if the handle we got back errored or not
13059            assert_eq!(
13060                handle.to_any_view().entity_type(),
13061                TypeId::of::<TestPngItemView>()
13062            );
13063
13064            let handle = workspace
13065                .update_in(cx, |workspace, window, cx| {
13066                    let project_path = (worktree_id, rel_path("two.ipynb"));
13067                    workspace.open_path(project_path, None, true, window, cx)
13068                })
13069                .await
13070                .unwrap();
13071
13072            assert_eq!(
13073                handle.to_any_view().entity_type(),
13074                TypeId::of::<TestIpynbItemView>()
13075            );
13076
13077            let handle = workspace
13078                .update_in(cx, |workspace, window, cx| {
13079                    let project_path = (worktree_id, rel_path("three.txt"));
13080                    workspace.open_path(project_path, None, true, window, cx)
13081                })
13082                .await;
13083            assert!(handle.is_err());
13084        }
13085
13086        #[gpui::test]
13087        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13088            init_test(cx);
13089
13090            cx.update(|cx| {
13091                register_project_item::<TestPngItemView>(cx);
13092                register_project_item::<TestAlternatePngItemView>(cx);
13093            });
13094
13095            let fs = FakeFs::new(cx.executor());
13096            fs.insert_tree(
13097                "/root1",
13098                json!({
13099                    "one.png": "BINARYDATAHERE",
13100                    "two.ipynb": "{ totally a notebook }",
13101                    "three.txt": "editing text, sure why not?"
13102                }),
13103            )
13104            .await;
13105            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13106            let (workspace, cx) =
13107                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13108            let worktree_id = project.update(cx, |project, cx| {
13109                project.worktrees(cx).next().unwrap().read(cx).id()
13110            });
13111
13112            let handle = workspace
13113                .update_in(cx, |workspace, window, cx| {
13114                    let project_path = (worktree_id, rel_path("one.png"));
13115                    workspace.open_path(project_path, None, true, window, cx)
13116                })
13117                .await
13118                .unwrap();
13119
13120            // This _must_ be the second item registered
13121            assert_eq!(
13122                handle.to_any_view().entity_type(),
13123                TypeId::of::<TestAlternatePngItemView>()
13124            );
13125
13126            let handle = workspace
13127                .update_in(cx, |workspace, window, cx| {
13128                    let project_path = (worktree_id, rel_path("three.txt"));
13129                    workspace.open_path(project_path, None, true, window, cx)
13130                })
13131                .await;
13132            assert!(handle.is_err());
13133        }
13134    }
13135
13136    #[gpui::test]
13137    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13138        init_test(cx);
13139
13140        let fs = FakeFs::new(cx.executor());
13141        let project = Project::test(fs, [], cx).await;
13142        let (workspace, _cx) =
13143            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13144
13145        // Test with status bar shown (default)
13146        workspace.read_with(cx, |workspace, cx| {
13147            let visible = workspace.status_bar_visible(cx);
13148            assert!(visible, "Status bar should be visible by default");
13149        });
13150
13151        // Test with status bar hidden
13152        cx.update_global(|store: &mut SettingsStore, cx| {
13153            store.update_user_settings(cx, |settings| {
13154                settings.status_bar.get_or_insert_default().show = Some(false);
13155            });
13156        });
13157
13158        workspace.read_with(cx, |workspace, cx| {
13159            let visible = workspace.status_bar_visible(cx);
13160            assert!(!visible, "Status bar should be hidden when show is false");
13161        });
13162
13163        // Test with status bar shown explicitly
13164        cx.update_global(|store: &mut SettingsStore, cx| {
13165            store.update_user_settings(cx, |settings| {
13166                settings.status_bar.get_or_insert_default().show = Some(true);
13167            });
13168        });
13169
13170        workspace.read_with(cx, |workspace, cx| {
13171            let visible = workspace.status_bar_visible(cx);
13172            assert!(visible, "Status bar should be visible when show is true");
13173        });
13174    }
13175
13176    #[gpui::test]
13177    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13178        init_test(cx);
13179
13180        let fs = FakeFs::new(cx.executor());
13181        let project = Project::test(fs, [], cx).await;
13182        let (multi_workspace, cx) =
13183            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13184        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13185        let panel = workspace.update_in(cx, |workspace, window, cx| {
13186            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13187            workspace.add_panel(panel.clone(), window, cx);
13188
13189            workspace
13190                .right_dock()
13191                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13192
13193            panel
13194        });
13195
13196        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13197        let item_a = cx.new(TestItem::new);
13198        let item_b = cx.new(TestItem::new);
13199        let item_a_id = item_a.entity_id();
13200        let item_b_id = item_b.entity_id();
13201
13202        pane.update_in(cx, |pane, window, cx| {
13203            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13204            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13205        });
13206
13207        pane.read_with(cx, |pane, _| {
13208            assert_eq!(pane.items_len(), 2);
13209            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13210        });
13211
13212        workspace.update_in(cx, |workspace, window, cx| {
13213            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13214        });
13215
13216        workspace.update_in(cx, |_, window, cx| {
13217            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13218        });
13219
13220        // Assert that the `pane::CloseActiveItem` action is handled at the
13221        // workspace level when one of the dock panels is focused and, in that
13222        // case, the center pane's active item is closed but the focus is not
13223        // moved.
13224        cx.dispatch_action(pane::CloseActiveItem::default());
13225        cx.run_until_parked();
13226
13227        pane.read_with(cx, |pane, _| {
13228            assert_eq!(pane.items_len(), 1);
13229            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13230        });
13231
13232        workspace.update_in(cx, |workspace, window, cx| {
13233            assert!(workspace.right_dock().read(cx).is_open());
13234            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13235        });
13236    }
13237
13238    #[gpui::test]
13239    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13240        init_test(cx);
13241        let fs = FakeFs::new(cx.executor());
13242
13243        let project_a = Project::test(fs.clone(), [], cx).await;
13244        let project_b = Project::test(fs, [], cx).await;
13245
13246        let multi_workspace_handle =
13247            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13248        cx.run_until_parked();
13249
13250        let workspace_a = multi_workspace_handle
13251            .read_with(cx, |mw, _| mw.workspace().clone())
13252            .unwrap();
13253
13254        let _workspace_b = multi_workspace_handle
13255            .update(cx, |mw, window, cx| {
13256                mw.test_add_workspace(project_b, window, cx)
13257            })
13258            .unwrap();
13259
13260        // Switch to workspace A
13261        multi_workspace_handle
13262            .update(cx, |mw, window, cx| {
13263                mw.activate_index(0, window, cx);
13264            })
13265            .unwrap();
13266
13267        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13268
13269        // Add a panel to workspace A's right dock and open the dock
13270        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13271            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13272            workspace.add_panel(panel.clone(), window, cx);
13273            workspace
13274                .right_dock()
13275                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13276            panel
13277        });
13278
13279        // Focus the panel through the workspace (matching existing test pattern)
13280        workspace_a.update_in(cx, |workspace, window, cx| {
13281            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13282        });
13283
13284        // Zoom the panel
13285        panel.update_in(cx, |panel, window, cx| {
13286            panel.set_zoomed(true, window, cx);
13287        });
13288
13289        // Verify the panel is zoomed and the dock is open
13290        workspace_a.update_in(cx, |workspace, window, cx| {
13291            assert!(
13292                workspace.right_dock().read(cx).is_open(),
13293                "dock should be open before switch"
13294            );
13295            assert!(
13296                panel.is_zoomed(window, cx),
13297                "panel should be zoomed before switch"
13298            );
13299            assert!(
13300                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13301                "panel should be focused before switch"
13302            );
13303        });
13304
13305        // Switch to workspace B
13306        multi_workspace_handle
13307            .update(cx, |mw, window, cx| {
13308                mw.activate_index(1, window, cx);
13309            })
13310            .unwrap();
13311        cx.run_until_parked();
13312
13313        // Switch back to workspace A
13314        multi_workspace_handle
13315            .update(cx, |mw, window, cx| {
13316                mw.activate_index(0, window, cx);
13317            })
13318            .unwrap();
13319        cx.run_until_parked();
13320
13321        // Verify the panel is still zoomed and the dock is still open
13322        workspace_a.update_in(cx, |workspace, window, cx| {
13323            assert!(
13324                workspace.right_dock().read(cx).is_open(),
13325                "dock should still be open after switching back"
13326            );
13327            assert!(
13328                panel.is_zoomed(window, cx),
13329                "panel should still be zoomed after switching back"
13330            );
13331        });
13332    }
13333
13334    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13335        pane.read(cx)
13336            .items()
13337            .flat_map(|item| {
13338                item.project_paths(cx)
13339                    .into_iter()
13340                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13341            })
13342            .collect()
13343    }
13344
13345    pub fn init_test(cx: &mut TestAppContext) {
13346        cx.update(|cx| {
13347            let settings_store = SettingsStore::test(cx);
13348            cx.set_global(settings_store);
13349            theme::init(theme::LoadThemes::JustBase, cx);
13350        });
13351    }
13352
13353    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13354        let item = TestProjectItem::new(id, path, cx);
13355        item.update(cx, |item, _| {
13356            item.is_dirty = true;
13357        });
13358        item
13359    }
13360
13361    #[gpui::test]
13362    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13363        cx: &mut gpui::TestAppContext,
13364    ) {
13365        init_test(cx);
13366        let fs = FakeFs::new(cx.executor());
13367
13368        let project = Project::test(fs, [], cx).await;
13369        let (workspace, cx) =
13370            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13371
13372        let panel = workspace.update_in(cx, |workspace, window, cx| {
13373            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13374            workspace.add_panel(panel.clone(), window, cx);
13375            workspace
13376                .right_dock()
13377                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13378            panel
13379        });
13380
13381        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13382        pane.update_in(cx, |pane, window, cx| {
13383            let item = cx.new(TestItem::new);
13384            pane.add_item(Box::new(item), true, true, None, window, cx);
13385        });
13386
13387        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13388        // mirrors the real-world flow and avoids side effects from directly
13389        // focusing the panel while the center pane is active.
13390        workspace.update_in(cx, |workspace, window, cx| {
13391            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13392        });
13393
13394        panel.update_in(cx, |panel, window, cx| {
13395            panel.set_zoomed(true, window, cx);
13396        });
13397
13398        workspace.update_in(cx, |workspace, window, cx| {
13399            assert!(workspace.right_dock().read(cx).is_open());
13400            assert!(panel.is_zoomed(window, cx));
13401            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13402        });
13403
13404        // Simulate a spurious pane::Event::Focus on the center pane while the
13405        // panel still has focus. This mirrors what happens during macOS window
13406        // activation: the center pane fires a focus event even though actual
13407        // focus remains on the dock panel.
13408        pane.update_in(cx, |_, _, cx| {
13409            cx.emit(pane::Event::Focus);
13410        });
13411
13412        // The dock must remain open because the panel had focus at the time the
13413        // event was processed. Before the fix, dock_to_preserve was None for
13414        // panels that don't implement pane(), causing the dock to close.
13415        workspace.update_in(cx, |workspace, window, cx| {
13416            assert!(
13417                workspace.right_dock().read(cx).is_open(),
13418                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13419            );
13420            assert!(panel.is_zoomed(window, cx));
13421        });
13422    }
13423}