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, MultiWorkspaceEvent,
   31    NewWorkspaceInWindow, NextWorkspaceInWindow, PreviousWorkspaceInWindow,
   32    SIDEBAR_RESIZE_HANDLE_SIZE, ToggleWorkspaceSidebar, multi_workspace_enabled,
   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, deferred, 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::{
   83        DockStructure, ItemId, MultiWorkspaceId, SerializedMultiWorkspace,
   84        SerializedWorkspaceLocation, SessionWorkspace,
   85    },
   86    read_serialized_multi_workspaces,
   87};
   88use postage::stream::Stream;
   89use project::{
   90    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   91    WorktreeSettings,
   92    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   93    project_settings::ProjectSettings,
   94    toolchain_store::ToolchainStoreEvent,
   95    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   96};
   97use remote::{
   98    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   99    remote_client::ConnectionIdentifier,
  100};
  101use schemars::JsonSchema;
  102use serde::Deserialize;
  103use session::AppSession;
  104use settings::{
  105    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  106};
  107
  108use sqlez::{
  109    bindable::{Bind, Column, StaticColumnCount},
  110    statement::Statement,
  111};
  112use status_bar::StatusBar;
  113pub use status_bar::StatusItemView;
  114use std::{
  115    any::TypeId,
  116    borrow::Cow,
  117    cell::RefCell,
  118    cmp,
  119    collections::VecDeque,
  120    env,
  121    hash::Hash,
  122    path::{Path, PathBuf},
  123    process::ExitStatus,
  124    rc::Rc,
  125    sync::{
  126        Arc, LazyLock, Weak,
  127        atomic::{AtomicBool, AtomicUsize},
  128    },
  129    time::Duration,
  130};
  131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  133pub use toolbar::{
  134    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  135};
  136pub use ui;
  137use ui::{Window, prelude::*};
  138use util::{
  139    ResultExt, TryFutureExt,
  140    paths::{PathStyle, SanitizedPath},
  141    rel_path::RelPath,
  142    serde::default_true,
  143};
  144use uuid::Uuid;
  145pub use workspace_settings::{
  146    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  147    WorkspaceSettings,
  148};
  149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  150
  151use crate::{item::ItemBufferKind, notifications::NotificationId};
  152use crate::{
  153    persistence::{
  154        SerializedAxis,
  155        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  156    },
  157    security_modal::SecurityModal,
  158};
  159
  160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  161
  162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  163    env::var("ZED_WINDOW_SIZE")
  164        .ok()
  165        .as_deref()
  166        .and_then(parse_pixel_size_env_var)
  167});
  168
  169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  170    env::var("ZED_WINDOW_POSITION")
  171        .ok()
  172        .as_deref()
  173        .and_then(parse_pixel_position_env_var)
  174});
  175
  176pub trait TerminalProvider {
  177    fn spawn(
  178        &self,
  179        task: SpawnInTerminal,
  180        window: &mut Window,
  181        cx: &mut App,
  182    ) -> Task<Option<Result<ExitStatus>>>;
  183}
  184
  185pub trait DebuggerProvider {
  186    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  187    fn start_session(
  188        &self,
  189        definition: DebugScenario,
  190        task_context: SharedTaskContext,
  191        active_buffer: Option<Entity<Buffer>>,
  192        worktree_id: Option<WorktreeId>,
  193        window: &mut Window,
  194        cx: &mut App,
  195    );
  196
  197    fn spawn_task_or_modal(
  198        &self,
  199        workspace: &mut Workspace,
  200        action: &Spawn,
  201        window: &mut Window,
  202        cx: &mut Context<Workspace>,
  203    );
  204
  205    fn task_scheduled(&self, cx: &mut App);
  206    fn debug_scenario_scheduled(&self, cx: &mut App);
  207    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  208
  209    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  210}
  211
  212/// Opens a file or directory.
  213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  214#[action(namespace = workspace)]
  215pub struct Open {
  216    /// When true, opens in a new window. When false, adds to the current
  217    /// window as a new workspace (multi-workspace).
  218    #[serde(default = "Open::default_create_new_window")]
  219    pub create_new_window: bool,
  220}
  221
  222impl Open {
  223    pub const DEFAULT: Self = Self {
  224        create_new_window: true,
  225    };
  226
  227    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  228    /// the serde default and `Open::DEFAULT` stay in sync.
  229    fn default_create_new_window() -> bool {
  230        Self::DEFAULT.create_new_window
  231    }
  232}
  233
  234impl Default for Open {
  235    fn default() -> Self {
  236        Self::DEFAULT
  237    }
  238}
  239
  240actions!(
  241    workspace,
  242    [
  243        /// Activates the next pane in the workspace.
  244        ActivateNextPane,
  245        /// Activates the previous pane in the workspace.
  246        ActivatePreviousPane,
  247        /// Activates the last pane in the workspace.
  248        ActivateLastPane,
  249        /// Switches to the next window.
  250        ActivateNextWindow,
  251        /// Switches to the previous window.
  252        ActivatePreviousWindow,
  253        /// Adds a folder to the current project.
  254        AddFolderToProject,
  255        /// Clears all notifications.
  256        ClearAllNotifications,
  257        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  258        ClearNavigationHistory,
  259        /// Closes the active dock.
  260        CloseActiveDock,
  261        /// Closes all docks.
  262        CloseAllDocks,
  263        /// Toggles all docks.
  264        ToggleAllDocks,
  265        /// Closes the current window.
  266        CloseWindow,
  267        /// Closes the current project.
  268        CloseProject,
  269        /// Opens the feedback dialog.
  270        Feedback,
  271        /// Follows the next collaborator in the session.
  272        FollowNextCollaborator,
  273        /// Moves the focused panel to the next position.
  274        MoveFocusedPanelToNextPosition,
  275        /// Creates a new file.
  276        NewFile,
  277        /// Creates a new file in a vertical split.
  278        NewFileSplitVertical,
  279        /// Creates a new file in a horizontal split.
  280        NewFileSplitHorizontal,
  281        /// Opens a new search.
  282        NewSearch,
  283        /// Opens a new window.
  284        NewWindow,
  285        /// Opens multiple files.
  286        OpenFiles,
  287        /// Opens the current location in terminal.
  288        OpenInTerminal,
  289        /// Opens the component preview.
  290        OpenComponentPreview,
  291        /// Reloads the active item.
  292        ReloadActiveItem,
  293        /// Resets the active dock to its default size.
  294        ResetActiveDockSize,
  295        /// Resets all open docks to their default sizes.
  296        ResetOpenDocksSize,
  297        /// Reloads the application
  298        Reload,
  299        /// Saves the current file with a new name.
  300        SaveAs,
  301        /// Saves without formatting.
  302        SaveWithoutFormat,
  303        /// Shuts down all debug adapters.
  304        ShutdownDebugAdapters,
  305        /// Suppresses the current notification.
  306        SuppressNotification,
  307        /// Toggles the bottom dock.
  308        ToggleBottomDock,
  309        /// Toggles centered layout mode.
  310        ToggleCenteredLayout,
  311        /// Toggles edit prediction feature globally for all files.
  312        ToggleEditPrediction,
  313        /// Toggles the left dock.
  314        ToggleLeftDock,
  315        /// Toggles the right dock.
  316        ToggleRightDock,
  317        /// Toggles zoom on the active pane.
  318        ToggleZoom,
  319        /// Toggles read-only mode for the active item (if supported by that item).
  320        ToggleReadOnlyFile,
  321        /// Zooms in on the active pane.
  322        ZoomIn,
  323        /// Zooms out of the active pane.
  324        ZoomOut,
  325        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  326        /// If the modal is shown already, closes it without trusting any worktree.
  327        ToggleWorktreeSecurity,
  328        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  329        /// Requires restart to take effect on already opened projects.
  330        ClearTrustedWorktrees,
  331        /// Stops following a collaborator.
  332        Unfollow,
  333        /// Restores the banner.
  334        RestoreBanner,
  335        /// Toggles expansion of the selected item.
  336        ToggleExpandItem,
  337    ]
  338);
  339
  340/// Activates a specific pane by its index.
  341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  342#[action(namespace = workspace)]
  343pub struct ActivatePane(pub usize);
  344
  345/// Moves an item to a specific pane by index.
  346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348#[serde(deny_unknown_fields)]
  349pub struct MoveItemToPane {
  350    #[serde(default = "default_1")]
  351    pub destination: usize,
  352    #[serde(default = "default_true")]
  353    pub focus: bool,
  354    #[serde(default)]
  355    pub clone: bool,
  356}
  357
  358fn default_1() -> usize {
  359    1
  360}
  361
  362/// Moves an item to a pane in the specified direction.
  363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  364#[action(namespace = workspace)]
  365#[serde(deny_unknown_fields)]
  366pub struct MoveItemToPaneInDirection {
  367    #[serde(default = "default_right")]
  368    pub direction: SplitDirection,
  369    #[serde(default = "default_true")]
  370    pub focus: bool,
  371    #[serde(default)]
  372    pub clone: bool,
  373}
  374
  375/// Creates a new file in a split of the desired direction.
  376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  377#[action(namespace = workspace)]
  378#[serde(deny_unknown_fields)]
  379pub struct NewFileSplit(pub SplitDirection);
  380
  381fn default_right() -> SplitDirection {
  382    SplitDirection::Right
  383}
  384
  385/// Saves all open files in the workspace.
  386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  387#[action(namespace = workspace)]
  388#[serde(deny_unknown_fields)]
  389pub struct SaveAll {
  390    #[serde(default)]
  391    pub save_intent: Option<SaveIntent>,
  392}
  393
  394/// Saves the current file with the specified options.
  395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  396#[action(namespace = workspace)]
  397#[serde(deny_unknown_fields)]
  398pub struct Save {
  399    #[serde(default)]
  400    pub save_intent: Option<SaveIntent>,
  401}
  402
  403/// Closes all items and panes in the workspace.
  404#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  405#[action(namespace = workspace)]
  406#[serde(deny_unknown_fields)]
  407pub struct CloseAllItemsAndPanes {
  408    #[serde(default)]
  409    pub save_intent: Option<SaveIntent>,
  410}
  411
  412/// Closes all inactive tabs and panes in the workspace.
  413#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  414#[action(namespace = workspace)]
  415#[serde(deny_unknown_fields)]
  416pub struct CloseInactiveTabsAndPanes {
  417    #[serde(default)]
  418    pub save_intent: Option<SaveIntent>,
  419}
  420
  421/// Closes the active item across all panes.
  422#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  423#[action(namespace = workspace)]
  424#[serde(deny_unknown_fields)]
  425pub struct CloseItemInAllPanes {
  426    #[serde(default)]
  427    pub save_intent: Option<SaveIntent>,
  428    #[serde(default)]
  429    pub close_pinned: bool,
  430}
  431
  432/// Sends a sequence of keystrokes to the active element.
  433#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  434#[action(namespace = workspace)]
  435pub struct SendKeystrokes(pub String);
  436
  437actions!(
  438    project_symbols,
  439    [
  440        /// Toggles the project symbols search.
  441        #[action(name = "Toggle")]
  442        ToggleProjectSymbols
  443    ]
  444);
  445
  446/// Toggles the file finder interface.
  447#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  448#[action(namespace = file_finder, name = "Toggle")]
  449#[serde(deny_unknown_fields)]
  450pub struct ToggleFileFinder {
  451    #[serde(default)]
  452    pub separate_history: bool,
  453}
  454
  455/// Opens a new terminal in the center.
  456#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  457#[action(namespace = workspace)]
  458#[serde(deny_unknown_fields)]
  459pub struct NewCenterTerminal {
  460    /// If true, creates a local terminal even in remote projects.
  461    #[serde(default)]
  462    pub local: bool,
  463}
  464
  465/// Opens a new terminal.
  466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  467#[action(namespace = workspace)]
  468#[serde(deny_unknown_fields)]
  469pub struct NewTerminal {
  470    /// If true, creates a local terminal even in remote projects.
  471    #[serde(default)]
  472    pub local: bool,
  473}
  474
  475/// Increases size of a currently focused dock by a given amount of pixels.
  476#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  477#[action(namespace = workspace)]
  478#[serde(deny_unknown_fields)]
  479pub struct IncreaseActiveDockSize {
  480    /// For 0px parameter, uses UI font size value.
  481    #[serde(default)]
  482    pub px: u32,
  483}
  484
  485/// Decreases size of a currently focused dock by a given amount of pixels.
  486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  487#[action(namespace = workspace)]
  488#[serde(deny_unknown_fields)]
  489pub struct DecreaseActiveDockSize {
  490    /// For 0px parameter, uses UI font size value.
  491    #[serde(default)]
  492    pub px: u32,
  493}
  494
  495/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  497#[action(namespace = workspace)]
  498#[serde(deny_unknown_fields)]
  499pub struct IncreaseOpenDocksSize {
  500    /// For 0px parameter, uses UI font size value.
  501    #[serde(default)]
  502    pub px: u32,
  503}
  504
  505/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  507#[action(namespace = workspace)]
  508#[serde(deny_unknown_fields)]
  509pub struct DecreaseOpenDocksSize {
  510    /// For 0px parameter, uses UI font size value.
  511    #[serde(default)]
  512    pub px: u32,
  513}
  514
  515actions!(
  516    workspace,
  517    [
  518        /// Activates the pane to the left.
  519        ActivatePaneLeft,
  520        /// Activates the pane to the right.
  521        ActivatePaneRight,
  522        /// Activates the pane above.
  523        ActivatePaneUp,
  524        /// Activates the pane below.
  525        ActivatePaneDown,
  526        /// Swaps the current pane with the one to the left.
  527        SwapPaneLeft,
  528        /// Swaps the current pane with the one to the right.
  529        SwapPaneRight,
  530        /// Swaps the current pane with the one above.
  531        SwapPaneUp,
  532        /// Swaps the current pane with the one below.
  533        SwapPaneDown,
  534        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  535        SwapPaneAdjacent,
  536        /// Move the current pane to be at the far left.
  537        MovePaneLeft,
  538        /// Move the current pane to be at the far right.
  539        MovePaneRight,
  540        /// Move the current pane to be at the very top.
  541        MovePaneUp,
  542        /// Move the current pane to be at the very bottom.
  543        MovePaneDown,
  544    ]
  545);
  546
  547#[derive(PartialEq, Eq, Debug)]
  548pub enum CloseIntent {
  549    /// Quit the program entirely.
  550    Quit,
  551    /// Close a window.
  552    CloseWindow,
  553    /// Replace the workspace in an existing window.
  554    ReplaceWindow,
  555}
  556
  557#[derive(Clone)]
  558pub struct Toast {
  559    id: NotificationId,
  560    msg: Cow<'static, str>,
  561    autohide: bool,
  562    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  563}
  564
  565impl Toast {
  566    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  567        Toast {
  568            id,
  569            msg: msg.into(),
  570            on_click: None,
  571            autohide: false,
  572        }
  573    }
  574
  575    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  576    where
  577        M: Into<Cow<'static, str>>,
  578        F: Fn(&mut Window, &mut App) + 'static,
  579    {
  580        self.on_click = Some((message.into(), Arc::new(on_click)));
  581        self
  582    }
  583
  584    pub fn autohide(mut self) -> Self {
  585        self.autohide = true;
  586        self
  587    }
  588}
  589
  590impl PartialEq for Toast {
  591    fn eq(&self, other: &Self) -> bool {
  592        self.id == other.id
  593            && self.msg == other.msg
  594            && self.on_click.is_some() == other.on_click.is_some()
  595    }
  596}
  597
  598/// Opens a new terminal with the specified working directory.
  599#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  600#[action(namespace = workspace)]
  601#[serde(deny_unknown_fields)]
  602pub struct OpenTerminal {
  603    pub working_directory: PathBuf,
  604    /// If true, creates a local terminal even in remote projects.
  605    #[serde(default)]
  606    pub local: bool,
  607}
  608
  609#[derive(
  610    Clone,
  611    Copy,
  612    Debug,
  613    Default,
  614    Hash,
  615    PartialEq,
  616    Eq,
  617    PartialOrd,
  618    Ord,
  619    serde::Serialize,
  620    serde::Deserialize,
  621)]
  622pub struct WorkspaceId(i64);
  623
  624impl WorkspaceId {
  625    pub fn from_i64(value: i64) -> Self {
  626        Self(value)
  627    }
  628}
  629
  630impl StaticColumnCount for WorkspaceId {}
  631impl Bind for WorkspaceId {
  632    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  633        self.0.bind(statement, start_index)
  634    }
  635}
  636impl Column for WorkspaceId {
  637    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  638        i64::column(statement, start_index)
  639            .map(|(i, next_index)| (Self(i), next_index))
  640            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  641    }
  642}
  643impl From<WorkspaceId> for i64 {
  644    fn from(val: WorkspaceId) -> Self {
  645        val.0
  646    }
  647}
  648
  649fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  650    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  651        workspace_window
  652            .update(cx, |multi_workspace, window, cx| {
  653                let workspace = multi_workspace.workspace().clone();
  654                workspace.update(cx, |workspace, cx| {
  655                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  656                });
  657            })
  658            .ok();
  659    } else {
  660        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  661        cx.spawn(async move |cx| {
  662            let OpenResult { window, .. } = task.await?;
  663            window.update(cx, |multi_workspace, window, cx| {
  664                window.activate_window();
  665                let workspace = multi_workspace.workspace().clone();
  666                workspace.update(cx, |workspace, cx| {
  667                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  668                });
  669            })?;
  670            anyhow::Ok(())
  671        })
  672        .detach_and_log_err(cx);
  673    }
  674}
  675
  676pub fn prompt_for_open_path_and_open(
  677    workspace: &mut Workspace,
  678    app_state: Arc<AppState>,
  679    options: PathPromptOptions,
  680    create_new_window: bool,
  681    window: &mut Window,
  682    cx: &mut Context<Workspace>,
  683) {
  684    let paths = workspace.prompt_for_open_path(
  685        options,
  686        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  687        window,
  688        cx,
  689    );
  690    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  691    cx.spawn_in(window, async move |this, cx| {
  692        let Some(paths) = paths.await.log_err().flatten() else {
  693            return;
  694        };
  695        if !create_new_window {
  696            if let Some(handle) = multi_workspace_handle {
  697                if let Some(task) = handle
  698                    .update(cx, |multi_workspace, window, cx| {
  699                        multi_workspace.open_project(paths, window, cx)
  700                    })
  701                    .log_err()
  702                {
  703                    task.await.log_err();
  704                }
  705                return;
  706            }
  707        }
  708        if let Some(task) = this
  709            .update_in(cx, |this, window, cx| {
  710                this.open_workspace_for_paths(false, paths, window, cx)
  711            })
  712            .log_err()
  713        {
  714            task.await.log_err();
  715        }
  716    })
  717    .detach();
  718}
  719
  720pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  721    component::init();
  722    theme_preview::init(cx);
  723    toast_layer::init(cx);
  724    history_manager::init(app_state.fs.clone(), cx);
  725
  726    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  727        .on_action(|_: &Reload, cx| reload(cx))
  728        .on_action({
  729            let app_state = Arc::downgrade(&app_state);
  730            move |_: &Open, cx: &mut App| {
  731                if let Some(app_state) = app_state.upgrade() {
  732                    prompt_and_open_paths(
  733                        app_state,
  734                        PathPromptOptions {
  735                            files: true,
  736                            directories: true,
  737                            multiple: true,
  738                            prompt: None,
  739                        },
  740                        cx,
  741                    );
  742                }
  743            }
  744        })
  745        .on_action({
  746            let app_state = Arc::downgrade(&app_state);
  747            move |_: &OpenFiles, cx: &mut App| {
  748                let directories = cx.can_select_mixed_files_and_dirs();
  749                if let Some(app_state) = app_state.upgrade() {
  750                    prompt_and_open_paths(
  751                        app_state,
  752                        PathPromptOptions {
  753                            files: true,
  754                            directories,
  755                            multiple: true,
  756                            prompt: None,
  757                        },
  758                        cx,
  759                    );
  760                }
  761            }
  762        });
  763}
  764
  765type BuildProjectItemFn =
  766    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  767
  768type BuildProjectItemForPathFn =
  769    fn(
  770        &Entity<Project>,
  771        &ProjectPath,
  772        &mut Window,
  773        &mut App,
  774    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  775
  776#[derive(Clone, Default)]
  777struct ProjectItemRegistry {
  778    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  779    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  780}
  781
  782impl ProjectItemRegistry {
  783    fn register<T: ProjectItem>(&mut self) {
  784        self.build_project_item_fns_by_type.insert(
  785            TypeId::of::<T::Item>(),
  786            |item, project, pane, window, cx| {
  787                let item = item.downcast().unwrap();
  788                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  789                    as Box<dyn ItemHandle>
  790            },
  791        );
  792        self.build_project_item_for_path_fns
  793            .push(|project, project_path, window, cx| {
  794                let project_path = project_path.clone();
  795                let is_file = project
  796                    .read(cx)
  797                    .entry_for_path(&project_path, cx)
  798                    .is_some_and(|entry| entry.is_file());
  799                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  800                let is_local = project.read(cx).is_local();
  801                let project_item =
  802                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  803                let project = project.clone();
  804                Some(window.spawn(cx, async move |cx| {
  805                    match project_item.await.with_context(|| {
  806                        format!(
  807                            "opening project path {:?}",
  808                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  809                        )
  810                    }) {
  811                        Ok(project_item) => {
  812                            let project_item = project_item;
  813                            let project_entry_id: Option<ProjectEntryId> =
  814                                project_item.read_with(cx, project::ProjectItem::entry_id);
  815                            let build_workspace_item = Box::new(
  816                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  817                                    Box::new(cx.new(|cx| {
  818                                        T::for_project_item(
  819                                            project,
  820                                            Some(pane),
  821                                            project_item,
  822                                            window,
  823                                            cx,
  824                                        )
  825                                    })) as Box<dyn ItemHandle>
  826                                },
  827                            ) as Box<_>;
  828                            Ok((project_entry_id, build_workspace_item))
  829                        }
  830                        Err(e) => {
  831                            log::warn!("Failed to open a project item: {e:#}");
  832                            if e.error_code() == ErrorCode::Internal {
  833                                if let Some(abs_path) =
  834                                    entry_abs_path.as_deref().filter(|_| is_file)
  835                                {
  836                                    if let Some(broken_project_item_view) =
  837                                        cx.update(|window, cx| {
  838                                            T::for_broken_project_item(
  839                                                abs_path, is_local, &e, window, cx,
  840                                            )
  841                                        })?
  842                                    {
  843                                        let build_workspace_item = Box::new(
  844                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  845                                                cx.new(|_| broken_project_item_view).boxed_clone()
  846                                            },
  847                                        )
  848                                        as Box<_>;
  849                                        return Ok((None, build_workspace_item));
  850                                    }
  851                                }
  852                            }
  853                            Err(e)
  854                        }
  855                    }
  856                }))
  857            });
  858    }
  859
  860    fn open_path(
  861        &self,
  862        project: &Entity<Project>,
  863        path: &ProjectPath,
  864        window: &mut Window,
  865        cx: &mut App,
  866    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  867        let Some(open_project_item) = self
  868            .build_project_item_for_path_fns
  869            .iter()
  870            .rev()
  871            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  872        else {
  873            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  874        };
  875        open_project_item
  876    }
  877
  878    fn build_item<T: project::ProjectItem>(
  879        &self,
  880        item: Entity<T>,
  881        project: Entity<Project>,
  882        pane: Option<&Pane>,
  883        window: &mut Window,
  884        cx: &mut App,
  885    ) -> Option<Box<dyn ItemHandle>> {
  886        let build = self
  887            .build_project_item_fns_by_type
  888            .get(&TypeId::of::<T>())?;
  889        Some(build(item.into_any(), project, pane, window, cx))
  890    }
  891}
  892
  893type WorkspaceItemBuilder =
  894    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  895
  896impl Global for ProjectItemRegistry {}
  897
  898/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  899/// items will get a chance to open the file, starting from the project item that
  900/// was added last.
  901pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  902    cx.default_global::<ProjectItemRegistry>().register::<I>();
  903}
  904
  905#[derive(Default)]
  906pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  907
  908struct FollowableViewDescriptor {
  909    from_state_proto: fn(
  910        Entity<Workspace>,
  911        ViewId,
  912        &mut Option<proto::view::Variant>,
  913        &mut Window,
  914        &mut App,
  915    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  916    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  917}
  918
  919impl Global for FollowableViewRegistry {}
  920
  921impl FollowableViewRegistry {
  922    pub fn register<I: FollowableItem>(cx: &mut App) {
  923        cx.default_global::<Self>().0.insert(
  924            TypeId::of::<I>(),
  925            FollowableViewDescriptor {
  926                from_state_proto: |workspace, id, state, window, cx| {
  927                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  928                        cx.foreground_executor()
  929                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  930                    })
  931                },
  932                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  933            },
  934        );
  935    }
  936
  937    pub fn from_state_proto(
  938        workspace: Entity<Workspace>,
  939        view_id: ViewId,
  940        mut state: Option<proto::view::Variant>,
  941        window: &mut Window,
  942        cx: &mut App,
  943    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  944        cx.update_default_global(|this: &mut Self, cx| {
  945            this.0.values().find_map(|descriptor| {
  946                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  947            })
  948        })
  949    }
  950
  951    pub fn to_followable_view(
  952        view: impl Into<AnyView>,
  953        cx: &App,
  954    ) -> Option<Box<dyn FollowableItemHandle>> {
  955        let this = cx.try_global::<Self>()?;
  956        let view = view.into();
  957        let descriptor = this.0.get(&view.entity_type())?;
  958        Some((descriptor.to_followable_view)(&view))
  959    }
  960}
  961
  962#[derive(Copy, Clone)]
  963struct SerializableItemDescriptor {
  964    deserialize: fn(
  965        Entity<Project>,
  966        WeakEntity<Workspace>,
  967        WorkspaceId,
  968        ItemId,
  969        &mut Window,
  970        &mut Context<Pane>,
  971    ) -> Task<Result<Box<dyn ItemHandle>>>,
  972    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  973    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  974}
  975
  976#[derive(Default)]
  977struct SerializableItemRegistry {
  978    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  979    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  980}
  981
  982impl Global for SerializableItemRegistry {}
  983
  984impl SerializableItemRegistry {
  985    fn deserialize(
  986        item_kind: &str,
  987        project: Entity<Project>,
  988        workspace: WeakEntity<Workspace>,
  989        workspace_id: WorkspaceId,
  990        item_item: ItemId,
  991        window: &mut Window,
  992        cx: &mut Context<Pane>,
  993    ) -> Task<Result<Box<dyn ItemHandle>>> {
  994        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  995            return Task::ready(Err(anyhow!(
  996                "cannot deserialize {}, descriptor not found",
  997                item_kind
  998            )));
  999        };
 1000
 1001        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1002    }
 1003
 1004    fn cleanup(
 1005        item_kind: &str,
 1006        workspace_id: WorkspaceId,
 1007        loaded_items: Vec<ItemId>,
 1008        window: &mut Window,
 1009        cx: &mut App,
 1010    ) -> Task<Result<()>> {
 1011        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1012            return Task::ready(Err(anyhow!(
 1013                "cannot cleanup {}, descriptor not found",
 1014                item_kind
 1015            )));
 1016        };
 1017
 1018        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1019    }
 1020
 1021    fn view_to_serializable_item_handle(
 1022        view: AnyView,
 1023        cx: &App,
 1024    ) -> Option<Box<dyn SerializableItemHandle>> {
 1025        let this = cx.try_global::<Self>()?;
 1026        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1027        Some((descriptor.view_to_serializable_item)(view))
 1028    }
 1029
 1030    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1031        let this = cx.try_global::<Self>()?;
 1032        this.descriptors_by_kind.get(item_kind).copied()
 1033    }
 1034}
 1035
 1036pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1037    let serialized_item_kind = I::serialized_item_kind();
 1038
 1039    let registry = cx.default_global::<SerializableItemRegistry>();
 1040    let descriptor = SerializableItemDescriptor {
 1041        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1042            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1043            cx.foreground_executor()
 1044                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1045        },
 1046        cleanup: |workspace_id, loaded_items, window, cx| {
 1047            I::cleanup(workspace_id, loaded_items, window, cx)
 1048        },
 1049        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1050    };
 1051    registry
 1052        .descriptors_by_kind
 1053        .insert(Arc::from(serialized_item_kind), descriptor);
 1054    registry
 1055        .descriptors_by_type
 1056        .insert(TypeId::of::<I>(), descriptor);
 1057}
 1058
 1059pub struct AppState {
 1060    pub languages: Arc<LanguageRegistry>,
 1061    pub client: Arc<Client>,
 1062    pub user_store: Entity<UserStore>,
 1063    pub workspace_store: Entity<WorkspaceStore>,
 1064    pub fs: Arc<dyn fs::Fs>,
 1065    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1066    pub node_runtime: NodeRuntime,
 1067    pub session: Entity<AppSession>,
 1068}
 1069
 1070struct GlobalAppState(Weak<AppState>);
 1071
 1072impl Global for GlobalAppState {}
 1073
 1074pub struct WorkspaceStore {
 1075    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1076    client: Arc<Client>,
 1077    _subscriptions: Vec<client::Subscription>,
 1078}
 1079
 1080#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1081pub enum CollaboratorId {
 1082    PeerId(PeerId),
 1083    Agent,
 1084}
 1085
 1086impl From<PeerId> for CollaboratorId {
 1087    fn from(peer_id: PeerId) -> Self {
 1088        CollaboratorId::PeerId(peer_id)
 1089    }
 1090}
 1091
 1092impl From<&PeerId> for CollaboratorId {
 1093    fn from(peer_id: &PeerId) -> Self {
 1094        CollaboratorId::PeerId(*peer_id)
 1095    }
 1096}
 1097
 1098#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1099struct Follower {
 1100    project_id: Option<u64>,
 1101    peer_id: PeerId,
 1102}
 1103
 1104impl AppState {
 1105    #[track_caller]
 1106    pub fn global(cx: &App) -> Weak<Self> {
 1107        cx.global::<GlobalAppState>().0.clone()
 1108    }
 1109    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1110        cx.try_global::<GlobalAppState>()
 1111            .map(|state| state.0.clone())
 1112    }
 1113    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1114        cx.set_global(GlobalAppState(state));
 1115    }
 1116
 1117    #[cfg(any(test, feature = "test-support"))]
 1118    pub fn test(cx: &mut App) -> Arc<Self> {
 1119        use fs::Fs;
 1120        use node_runtime::NodeRuntime;
 1121        use session::Session;
 1122        use settings::SettingsStore;
 1123
 1124        if !cx.has_global::<SettingsStore>() {
 1125            let settings_store = SettingsStore::test(cx);
 1126            cx.set_global(settings_store);
 1127        }
 1128
 1129        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1130        <dyn Fs>::set_global(fs.clone(), cx);
 1131        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1132        let clock = Arc::new(clock::FakeSystemClock::new());
 1133        let http_client = http_client::FakeHttpClient::with_404_response();
 1134        let client = Client::new(clock, http_client, cx);
 1135        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1136        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1137        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1138
 1139        theme::init(theme::LoadThemes::JustBase, cx);
 1140        client::init(&client, cx);
 1141
 1142        Arc::new(Self {
 1143            client,
 1144            fs,
 1145            languages,
 1146            user_store,
 1147            workspace_store,
 1148            node_runtime: NodeRuntime::unavailable(),
 1149            build_window_options: |_, _| Default::default(),
 1150            session,
 1151        })
 1152    }
 1153}
 1154
 1155struct DelayedDebouncedEditAction {
 1156    task: Option<Task<()>>,
 1157    cancel_channel: Option<oneshot::Sender<()>>,
 1158}
 1159
 1160impl DelayedDebouncedEditAction {
 1161    fn new() -> DelayedDebouncedEditAction {
 1162        DelayedDebouncedEditAction {
 1163            task: None,
 1164            cancel_channel: None,
 1165        }
 1166    }
 1167
 1168    fn fire_new<F>(
 1169        &mut self,
 1170        delay: Duration,
 1171        window: &mut Window,
 1172        cx: &mut Context<Workspace>,
 1173        func: F,
 1174    ) where
 1175        F: 'static
 1176            + Send
 1177            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1178    {
 1179        if let Some(channel) = self.cancel_channel.take() {
 1180            _ = channel.send(());
 1181        }
 1182
 1183        let (sender, mut receiver) = oneshot::channel::<()>();
 1184        self.cancel_channel = Some(sender);
 1185
 1186        let previous_task = self.task.take();
 1187        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1188            let mut timer = cx.background_executor().timer(delay).fuse();
 1189            if let Some(previous_task) = previous_task {
 1190                previous_task.await;
 1191            }
 1192
 1193            futures::select_biased! {
 1194                _ = receiver => return,
 1195                    _ = timer => {}
 1196            }
 1197
 1198            if let Some(result) = workspace
 1199                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1200                .log_err()
 1201            {
 1202                result.await.log_err();
 1203            }
 1204        }));
 1205    }
 1206}
 1207
 1208pub enum Event {
 1209    PaneAdded(Entity<Pane>),
 1210    PaneRemoved,
 1211    ItemAdded {
 1212        item: Box<dyn ItemHandle>,
 1213    },
 1214    ActiveItemChanged,
 1215    ItemRemoved {
 1216        item_id: EntityId,
 1217    },
 1218    UserSavedItem {
 1219        pane: WeakEntity<Pane>,
 1220        item: Box<dyn WeakItemHandle>,
 1221        save_intent: SaveIntent,
 1222    },
 1223    ContactRequestedJoin(u64),
 1224    WorkspaceCreated(WeakEntity<Workspace>),
 1225    OpenBundledFile {
 1226        text: Cow<'static, str>,
 1227        title: &'static str,
 1228        language: &'static str,
 1229    },
 1230    ZoomChanged,
 1231    ModalOpened,
 1232    Activate,
 1233    PanelAdded(AnyView),
 1234}
 1235
 1236#[derive(Debug, Clone)]
 1237pub enum OpenVisible {
 1238    All,
 1239    None,
 1240    OnlyFiles,
 1241    OnlyDirectories,
 1242}
 1243
 1244enum WorkspaceLocation {
 1245    // Valid local paths or SSH project to serialize
 1246    Location(SerializedWorkspaceLocation, PathList),
 1247    // No valid location found hence clear session id
 1248    DetachFromSession,
 1249    // No valid location found to serialize
 1250    None,
 1251}
 1252
 1253type PromptForNewPath = Box<
 1254    dyn Fn(
 1255        &mut Workspace,
 1256        DirectoryLister,
 1257        Option<String>,
 1258        &mut Window,
 1259        &mut Context<Workspace>,
 1260    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1261>;
 1262
 1263type PromptForOpenPath = Box<
 1264    dyn Fn(
 1265        &mut Workspace,
 1266        DirectoryLister,
 1267        &mut Window,
 1268        &mut Context<Workspace>,
 1269    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1270>;
 1271
 1272#[derive(Default)]
 1273struct DispatchingKeystrokes {
 1274    dispatched: HashSet<Vec<Keystroke>>,
 1275    queue: VecDeque<Keystroke>,
 1276    task: Option<Shared<Task<()>>>,
 1277}
 1278
 1279/// Collects everything project-related for a certain window opened.
 1280/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1281///
 1282/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1283/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1284/// that can be used to register a global action to be triggered from any place in the window.
 1285pub struct Workspace {
 1286    weak_self: WeakEntity<Self>,
 1287    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1288    zoomed: Option<AnyWeakView>,
 1289    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1290    zoomed_position: Option<DockPosition>,
 1291    center: PaneGroup,
 1292    left_dock: Entity<Dock>,
 1293    bottom_dock: Entity<Dock>,
 1294    right_dock: Entity<Dock>,
 1295    left_drawer: Option<Drawer>,
 1296    right_drawer: Option<Drawer>,
 1297    panes: Vec<Entity<Pane>>,
 1298    active_worktree_override: Option<WorktreeId>,
 1299    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1300    active_pane: Entity<Pane>,
 1301    last_active_center_pane: Option<WeakEntity<Pane>>,
 1302    last_active_view_id: Option<proto::ViewId>,
 1303    status_bar: Entity<StatusBar>,
 1304    pub(crate) modal_layer: Entity<ModalLayer>,
 1305    toast_layer: Entity<ToastLayer>,
 1306    titlebar_item: Option<AnyView>,
 1307    notifications: Notifications,
 1308    suppressed_notifications: HashSet<NotificationId>,
 1309    project: Entity<Project>,
 1310    follower_states: HashMap<CollaboratorId, FollowerState>,
 1311    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1312    window_edited: bool,
 1313    last_window_title: Option<String>,
 1314    dirty_items: HashMap<EntityId, Subscription>,
 1315    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1316    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1317    database_id: Option<WorkspaceId>,
 1318    app_state: Arc<AppState>,
 1319    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1320    _subscriptions: Vec<Subscription>,
 1321    _apply_leader_updates: Task<Result<()>>,
 1322    _observe_current_user: Task<Result<()>>,
 1323    _schedule_serialize_workspace: Option<Task<()>>,
 1324    _serialize_workspace_task: Option<Task<()>>,
 1325    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1326    pane_history_timestamp: Arc<AtomicUsize>,
 1327    bounds: Bounds<Pixels>,
 1328    pub centered_layout: bool,
 1329    bounds_save_task_queued: Option<Task<()>>,
 1330    on_prompt_for_new_path: Option<PromptForNewPath>,
 1331    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1332    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1333    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1334    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1335    _items_serializer: Task<Result<()>>,
 1336    session_id: Option<String>,
 1337    scheduled_tasks: Vec<Task<()>>,
 1338    last_open_dock_positions: Vec<DockPosition>,
 1339    removing: bool,
 1340    _panels_task: Option<Task<Result<()>>>,
 1341}
 1342
 1343impl EventEmitter<Event> for Workspace {}
 1344
 1345#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1346pub struct ViewId {
 1347    pub creator: CollaboratorId,
 1348    pub id: u64,
 1349}
 1350
 1351pub struct FollowerState {
 1352    center_pane: Entity<Pane>,
 1353    dock_pane: Option<Entity<Pane>>,
 1354    active_view_id: Option<ViewId>,
 1355    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1356}
 1357
 1358struct FollowerView {
 1359    view: Box<dyn FollowableItemHandle>,
 1360    location: Option<proto::PanelId>,
 1361}
 1362
 1363impl Workspace {
 1364    pub fn new(
 1365        workspace_id: Option<WorkspaceId>,
 1366        project: Entity<Project>,
 1367        app_state: Arc<AppState>,
 1368        window: &mut Window,
 1369        cx: &mut Context<Self>,
 1370    ) -> Self {
 1371        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1372            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1373                if let TrustedWorktreesEvent::Trusted(..) = e {
 1374                    // Do not persist auto trusted worktrees
 1375                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1376                        worktrees_store.update(cx, |worktrees_store, cx| {
 1377                            worktrees_store.schedule_serialization(
 1378                                cx,
 1379                                |new_trusted_worktrees, cx| {
 1380                                    let timeout =
 1381                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1382                                    cx.background_spawn(async move {
 1383                                        timeout.await;
 1384                                        persistence::DB
 1385                                            .save_trusted_worktrees(new_trusted_worktrees)
 1386                                            .await
 1387                                            .log_err();
 1388                                    })
 1389                                },
 1390                            )
 1391                        });
 1392                    }
 1393                }
 1394            })
 1395            .detach();
 1396        }
 1397
 1398        cx.observe_global_in::<SettingsStore>(window, |this, window, cx| {
 1399            if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1400                if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1401                    trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1402                        trusted_worktrees.auto_trust_all(cx);
 1403                    })
 1404                }
 1405            }
 1406            this.reposition_panels(window, cx);
 1407        })
 1408        .detach();
 1409
 1410        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1411            match event {
 1412                project::Event::RemoteIdChanged(_) => {
 1413                    this.update_window_title(window, cx);
 1414                }
 1415
 1416                project::Event::CollaboratorLeft(peer_id) => {
 1417                    this.collaborator_left(*peer_id, window, cx);
 1418                }
 1419
 1420                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1421                    this.update_window_title(window, cx);
 1422                    if this
 1423                        .project()
 1424                        .read(cx)
 1425                        .worktree_for_id(id, cx)
 1426                        .is_some_and(|wt| wt.read(cx).is_visible())
 1427                    {
 1428                        this.serialize_workspace(window, cx);
 1429                        this.update_history(cx);
 1430                    }
 1431                }
 1432                project::Event::WorktreeUpdatedEntries(..) => {
 1433                    this.update_window_title(window, cx);
 1434                    this.serialize_workspace(window, cx);
 1435                }
 1436
 1437                project::Event::DisconnectedFromHost => {
 1438                    this.update_window_edited(window, cx);
 1439                    let leaders_to_unfollow =
 1440                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1441                    for leader_id in leaders_to_unfollow {
 1442                        this.unfollow(leader_id, window, cx);
 1443                    }
 1444                }
 1445
 1446                project::Event::DisconnectedFromRemote {
 1447                    server_not_running: _,
 1448                } => {
 1449                    this.update_window_edited(window, cx);
 1450                }
 1451
 1452                project::Event::Closed => {
 1453                    window.remove_window();
 1454                }
 1455
 1456                project::Event::DeletedEntry(_, entry_id) => {
 1457                    for pane in this.panes.iter() {
 1458                        pane.update(cx, |pane, cx| {
 1459                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1460                        });
 1461                    }
 1462                }
 1463
 1464                project::Event::Toast {
 1465                    notification_id,
 1466                    message,
 1467                    link,
 1468                } => this.show_notification(
 1469                    NotificationId::named(notification_id.clone()),
 1470                    cx,
 1471                    |cx| {
 1472                        let mut notification = MessageNotification::new(message.clone(), cx);
 1473                        if let Some(link) = link {
 1474                            notification = notification
 1475                                .more_info_message(link.label)
 1476                                .more_info_url(link.url);
 1477                        }
 1478
 1479                        cx.new(|_| notification)
 1480                    },
 1481                ),
 1482
 1483                project::Event::HideToast { notification_id } => {
 1484                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1485                }
 1486
 1487                project::Event::LanguageServerPrompt(request) => {
 1488                    struct LanguageServerPrompt;
 1489
 1490                    this.show_notification(
 1491                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1492                        cx,
 1493                        |cx| {
 1494                            cx.new(|cx| {
 1495                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1496                            })
 1497                        },
 1498                    );
 1499                }
 1500
 1501                project::Event::AgentLocationChanged => {
 1502                    this.handle_agent_location_changed(window, cx)
 1503                }
 1504
 1505                _ => {}
 1506            }
 1507            cx.notify()
 1508        })
 1509        .detach();
 1510
 1511        cx.subscribe_in(
 1512            &project.read(cx).breakpoint_store(),
 1513            window,
 1514            |workspace, _, event, window, cx| match event {
 1515                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1516                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1517                    workspace.serialize_workspace(window, cx);
 1518                }
 1519                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1520            },
 1521        )
 1522        .detach();
 1523        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1524            cx.subscribe_in(
 1525                &toolchain_store,
 1526                window,
 1527                |workspace, _, event, window, cx| match event {
 1528                    ToolchainStoreEvent::CustomToolchainsModified => {
 1529                        workspace.serialize_workspace(window, cx);
 1530                    }
 1531                    _ => {}
 1532                },
 1533            )
 1534            .detach();
 1535        }
 1536
 1537        cx.on_focus_lost(window, |this, window, cx| {
 1538            let focus_handle = this.focus_handle(cx);
 1539            window.focus(&focus_handle, cx);
 1540        })
 1541        .detach();
 1542
 1543        let weak_handle = cx.entity().downgrade();
 1544        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1545
 1546        let center_pane = cx.new(|cx| {
 1547            let mut center_pane = Pane::new(
 1548                weak_handle.clone(),
 1549                project.clone(),
 1550                pane_history_timestamp.clone(),
 1551                None,
 1552                NewFile.boxed_clone(),
 1553                true,
 1554                window,
 1555                cx,
 1556            );
 1557            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1558            center_pane.set_should_display_welcome_page(true);
 1559            center_pane
 1560        });
 1561        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1562            .detach();
 1563
 1564        window.focus(&center_pane.focus_handle(cx), cx);
 1565
 1566        cx.emit(Event::PaneAdded(center_pane.clone()));
 1567
 1568        let any_window_handle = window.window_handle();
 1569        app_state.workspace_store.update(cx, |store, _| {
 1570            store
 1571                .workspaces
 1572                .insert((any_window_handle, weak_handle.clone()));
 1573        });
 1574
 1575        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1576        let mut connection_status = app_state.client.status();
 1577        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1578            current_user.next().await;
 1579            connection_status.next().await;
 1580            let mut stream =
 1581                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1582
 1583            while stream.recv().await.is_some() {
 1584                this.update(cx, |_, cx| cx.notify())?;
 1585            }
 1586            anyhow::Ok(())
 1587        });
 1588
 1589        // All leader updates are enqueued and then processed in a single task, so
 1590        // that each asynchronous operation can be run in order.
 1591        let (leader_updates_tx, mut leader_updates_rx) =
 1592            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1593        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1594            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1595                Self::process_leader_update(&this, leader_id, update, cx)
 1596                    .await
 1597                    .log_err();
 1598            }
 1599
 1600            Ok(())
 1601        });
 1602
 1603        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1604        let modal_layer = cx.new(|_| ModalLayer::new());
 1605        let toast_layer = cx.new(|_| ToastLayer::new());
 1606        cx.subscribe(
 1607            &modal_layer,
 1608            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1609                cx.emit(Event::ModalOpened);
 1610            },
 1611        )
 1612        .detach();
 1613
 1614        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1615        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1616        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1617        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1618        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1619        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1620        let status_bar = cx.new(|cx| {
 1621            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1622            status_bar.add_left_item(left_dock_buttons, window, cx);
 1623            status_bar.add_right_item(right_dock_buttons, window, cx);
 1624            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1625            status_bar
 1626        });
 1627
 1628        let session_id = app_state.session.read(cx).id().to_owned();
 1629
 1630        let mut active_call = None;
 1631        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1632            let subscriptions =
 1633                vec![
 1634                    call.0
 1635                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1636                ];
 1637            active_call = Some((call, subscriptions));
 1638        }
 1639
 1640        let (serializable_items_tx, serializable_items_rx) =
 1641            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1642        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1643            Self::serialize_items(&this, serializable_items_rx, cx).await
 1644        });
 1645
 1646        let subscriptions = vec![
 1647            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1648            cx.observe_window_bounds(window, move |this, window, cx| {
 1649                if this.bounds_save_task_queued.is_some() {
 1650                    return;
 1651                }
 1652                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1653                    cx.background_executor()
 1654                        .timer(Duration::from_millis(100))
 1655                        .await;
 1656                    this.update_in(cx, |this, window, cx| {
 1657                        this.save_window_bounds(window, cx).detach();
 1658                        this.bounds_save_task_queued.take();
 1659                    })
 1660                    .ok();
 1661                }));
 1662                cx.notify();
 1663            }),
 1664            cx.observe_window_appearance(window, |_, window, cx| {
 1665                let window_appearance = window.appearance();
 1666
 1667                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1668
 1669                GlobalTheme::reload_theme(cx);
 1670                GlobalTheme::reload_icon_theme(cx);
 1671            }),
 1672            cx.on_release({
 1673                let weak_handle = weak_handle.clone();
 1674                move |this, cx| {
 1675                    this.app_state.workspace_store.update(cx, move |store, _| {
 1676                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1677                    })
 1678                }
 1679            }),
 1680        ];
 1681
 1682        cx.defer_in(window, move |this, window, cx| {
 1683            this.update_window_title(window, cx);
 1684            this.show_initial_notifications(cx);
 1685        });
 1686
 1687        let mut center = PaneGroup::new(center_pane.clone());
 1688        center.set_is_center(true);
 1689        center.mark_positions(cx);
 1690
 1691        Workspace {
 1692            weak_self: weak_handle.clone(),
 1693            zoomed: None,
 1694            zoomed_position: None,
 1695            previous_dock_drag_coordinates: None,
 1696            center,
 1697            panes: vec![center_pane.clone()],
 1698            panes_by_item: Default::default(),
 1699            active_pane: center_pane.clone(),
 1700            last_active_center_pane: Some(center_pane.downgrade()),
 1701            last_active_view_id: None,
 1702            status_bar,
 1703            modal_layer,
 1704            toast_layer,
 1705            titlebar_item: None,
 1706            active_worktree_override: None,
 1707            notifications: Notifications::default(),
 1708            suppressed_notifications: HashSet::default(),
 1709            left_dock,
 1710            bottom_dock,
 1711            right_dock,
 1712            left_drawer: None,
 1713            right_drawer: None,
 1714            _panels_task: None,
 1715            project: project.clone(),
 1716            follower_states: Default::default(),
 1717            last_leaders_by_pane: Default::default(),
 1718            dispatching_keystrokes: Default::default(),
 1719            window_edited: false,
 1720            last_window_title: None,
 1721            dirty_items: Default::default(),
 1722            active_call,
 1723            database_id: workspace_id,
 1724            app_state,
 1725            _observe_current_user,
 1726            _apply_leader_updates,
 1727            _schedule_serialize_workspace: None,
 1728            _serialize_workspace_task: None,
 1729            _schedule_serialize_ssh_paths: None,
 1730            leader_updates_tx,
 1731            _subscriptions: subscriptions,
 1732            pane_history_timestamp,
 1733            workspace_actions: Default::default(),
 1734            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1735            bounds: Default::default(),
 1736            centered_layout: false,
 1737            bounds_save_task_queued: None,
 1738            on_prompt_for_new_path: None,
 1739            on_prompt_for_open_path: None,
 1740            terminal_provider: None,
 1741            debugger_provider: None,
 1742            serializable_items_tx,
 1743            _items_serializer,
 1744            session_id: Some(session_id),
 1745
 1746            scheduled_tasks: Vec::new(),
 1747            last_open_dock_positions: Vec::new(),
 1748            removing: false,
 1749        }
 1750    }
 1751
 1752    pub fn new_local(
 1753        abs_paths: Vec<PathBuf>,
 1754        app_state: Arc<AppState>,
 1755        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1756        env: Option<HashMap<String, String>>,
 1757        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1758        activate: bool,
 1759        cx: &mut App,
 1760    ) -> Task<anyhow::Result<OpenResult>> {
 1761        let project_handle = Project::local(
 1762            app_state.client.clone(),
 1763            app_state.node_runtime.clone(),
 1764            app_state.user_store.clone(),
 1765            app_state.languages.clone(),
 1766            app_state.fs.clone(),
 1767            env,
 1768            Default::default(),
 1769            cx,
 1770        );
 1771
 1772        cx.spawn(async move |cx| {
 1773            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1774            for path in abs_paths.into_iter() {
 1775                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1776                    paths_to_open.push(canonical)
 1777                } else {
 1778                    paths_to_open.push(path)
 1779                }
 1780            }
 1781
 1782            let serialized_workspace =
 1783                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1784
 1785            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1786                paths_to_open = paths.ordered_paths().cloned().collect();
 1787                if !paths.is_lexicographically_ordered() {
 1788                    project_handle.update(cx, |project, cx| {
 1789                        project.set_worktrees_reordered(true, cx);
 1790                    });
 1791                }
 1792            }
 1793
 1794            // Get project paths for all of the abs_paths
 1795            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1796                Vec::with_capacity(paths_to_open.len());
 1797
 1798            for path in paths_to_open.into_iter() {
 1799                if let Some((_, project_entry)) = cx
 1800                    .update(|cx| {
 1801                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1802                    })
 1803                    .await
 1804                    .log_err()
 1805                {
 1806                    project_paths.push((path, Some(project_entry)));
 1807                } else {
 1808                    project_paths.push((path, None));
 1809                }
 1810            }
 1811
 1812            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1813                serialized_workspace.id
 1814            } else {
 1815                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1816            };
 1817
 1818            let toolchains = DB.toolchains(workspace_id).await?;
 1819
 1820            for (toolchain, worktree_path, path) in toolchains {
 1821                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1822                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1823                    this.find_worktree(&worktree_path, cx)
 1824                        .and_then(|(worktree, rel_path)| {
 1825                            if rel_path.is_empty() {
 1826                                Some(worktree.read(cx).id())
 1827                            } else {
 1828                                None
 1829                            }
 1830                        })
 1831                }) else {
 1832                    // We did not find a worktree with a given path, but that's whatever.
 1833                    continue;
 1834                };
 1835                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1836                    continue;
 1837                }
 1838
 1839                project_handle
 1840                    .update(cx, |this, cx| {
 1841                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1842                    })
 1843                    .await;
 1844            }
 1845            if let Some(workspace) = serialized_workspace.as_ref() {
 1846                project_handle.update(cx, |this, cx| {
 1847                    for (scope, toolchains) in &workspace.user_toolchains {
 1848                        for toolchain in toolchains {
 1849                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1850                        }
 1851                    }
 1852                });
 1853            }
 1854
 1855            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1856                if let Some(window) = requesting_window {
 1857                    let centered_layout = serialized_workspace
 1858                        .as_ref()
 1859                        .map(|w| w.centered_layout)
 1860                        .unwrap_or(false);
 1861
 1862                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1863                        let workspace = cx.new(|cx| {
 1864                            let mut workspace = Workspace::new(
 1865                                Some(workspace_id),
 1866                                project_handle.clone(),
 1867                                app_state.clone(),
 1868                                window,
 1869                                cx,
 1870                            );
 1871
 1872                            workspace.centered_layout = centered_layout;
 1873
 1874                            // Call init callback to add items before window renders
 1875                            if let Some(init) = init {
 1876                                init(&mut workspace, window, cx);
 1877                            }
 1878
 1879                            workspace
 1880                        });
 1881                        if activate {
 1882                            multi_workspace.activate(workspace.clone(), cx);
 1883                        } else {
 1884                            multi_workspace.add_workspace(workspace.clone(), cx);
 1885                        }
 1886                        workspace
 1887                    })?;
 1888                    (window, workspace)
 1889                } else {
 1890                    let window_bounds_override = window_bounds_env_override();
 1891
 1892                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1893                        (Some(WindowBounds::Windowed(bounds)), None)
 1894                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1895                        && let Some(display) = workspace.display
 1896                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1897                    {
 1898                        // Reopening an existing workspace - restore its saved bounds
 1899                        (Some(bounds.0), Some(display))
 1900                    } else if let Some((display, bounds)) =
 1901                        persistence::read_default_window_bounds()
 1902                    {
 1903                        // New or empty workspace - use the last known window bounds
 1904                        (Some(bounds), Some(display))
 1905                    } else {
 1906                        // New window - let GPUI's default_bounds() handle cascading
 1907                        (None, None)
 1908                    };
 1909
 1910                    // Use the serialized workspace to construct the new window
 1911                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1912                    options.window_bounds = window_bounds;
 1913                    let centered_layout = serialized_workspace
 1914                        .as_ref()
 1915                        .map(|w| w.centered_layout)
 1916                        .unwrap_or(false);
 1917                    let window = cx.open_window(options, {
 1918                        let app_state = app_state.clone();
 1919                        let project_handle = project_handle.clone();
 1920                        move |window, cx| {
 1921                            let workspace = cx.new(|cx| {
 1922                                let mut workspace = Workspace::new(
 1923                                    Some(workspace_id),
 1924                                    project_handle,
 1925                                    app_state,
 1926                                    window,
 1927                                    cx,
 1928                                );
 1929                                workspace.centered_layout = centered_layout;
 1930
 1931                                // Call init callback to add items before window renders
 1932                                if let Some(init) = init {
 1933                                    init(&mut workspace, window, cx);
 1934                                }
 1935
 1936                                workspace
 1937                            });
 1938                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1939                        }
 1940                    })?;
 1941                    let workspace =
 1942                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1943                            multi_workspace.workspace().clone()
 1944                        })?;
 1945                    (window, workspace)
 1946                };
 1947
 1948            notify_if_database_failed(window, cx);
 1949            // Check if this is an empty workspace (no paths to open)
 1950            // An empty workspace is one where project_paths is empty
 1951            let is_empty_workspace = project_paths.is_empty();
 1952            // Check if serialized workspace has paths before it's moved
 1953            let serialized_workspace_has_paths = serialized_workspace
 1954                .as_ref()
 1955                .map(|ws| !ws.paths.is_empty())
 1956                .unwrap_or(false);
 1957
 1958            let opened_items = window
 1959                .update(cx, |_, window, cx| {
 1960                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1961                        open_items(serialized_workspace, project_paths, window, cx)
 1962                    })
 1963                })?
 1964                .await
 1965                .unwrap_or_default();
 1966
 1967            // Restore default dock state for empty workspaces
 1968            // Only restore if:
 1969            // 1. This is an empty workspace (no paths), AND
 1970            // 2. The serialized workspace either doesn't exist or has no paths
 1971            if is_empty_workspace && !serialized_workspace_has_paths {
 1972                if let Some(default_docks) = persistence::read_default_dock_state() {
 1973                    window
 1974                        .update(cx, |_, window, cx| {
 1975                            workspace.update(cx, |workspace, cx| {
 1976                                for (dock, serialized_dock) in [
 1977                                    (&workspace.right_dock, &default_docks.right),
 1978                                    (&workspace.left_dock, &default_docks.left),
 1979                                    (&workspace.bottom_dock, &default_docks.bottom),
 1980                                ] {
 1981                                    dock.update(cx, |dock, cx| {
 1982                                        dock.serialized_dock = Some(serialized_dock.clone());
 1983                                        dock.restore_state(window, cx);
 1984                                    });
 1985                                }
 1986                                cx.notify();
 1987                            });
 1988                        })
 1989                        .log_err();
 1990                }
 1991            }
 1992
 1993            window
 1994                .update(cx, |_, _window, cx| {
 1995                    workspace.update(cx, |this: &mut Workspace, cx| {
 1996                        this.update_history(cx);
 1997                    });
 1998                })
 1999                .log_err();
 2000            Ok(OpenResult {
 2001                window,
 2002                workspace,
 2003                opened_items,
 2004            })
 2005        })
 2006    }
 2007
 2008    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2009        self.weak_self.clone()
 2010    }
 2011
 2012    pub fn left_dock(&self) -> &Entity<Dock> {
 2013        &self.left_dock
 2014    }
 2015
 2016    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2017        &self.bottom_dock
 2018    }
 2019
 2020    pub fn set_bottom_dock_layout(
 2021        &mut self,
 2022        layout: BottomDockLayout,
 2023        window: &mut Window,
 2024        cx: &mut Context<Self>,
 2025    ) {
 2026        let fs = self.project().read(cx).fs();
 2027        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2028            content.workspace.bottom_dock_layout = Some(layout);
 2029        });
 2030
 2031        cx.notify();
 2032        self.serialize_workspace(window, cx);
 2033    }
 2034
 2035    pub fn right_dock(&self) -> &Entity<Dock> {
 2036        &self.right_dock
 2037    }
 2038
 2039    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2040        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2041    }
 2042
 2043    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2044        let left_dock = self.left_dock.read(cx);
 2045        let left_visible = left_dock.is_open();
 2046        let left_active_panel = left_dock
 2047            .active_panel()
 2048            .map(|panel| panel.persistent_name().to_string());
 2049        // `zoomed_position` is kept in sync with individual panel zoom state
 2050        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2051        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2052
 2053        let right_dock = self.right_dock.read(cx);
 2054        let right_visible = right_dock.is_open();
 2055        let right_active_panel = right_dock
 2056            .active_panel()
 2057            .map(|panel| panel.persistent_name().to_string());
 2058        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2059
 2060        let bottom_dock = self.bottom_dock.read(cx);
 2061        let bottom_visible = bottom_dock.is_open();
 2062        let bottom_active_panel = bottom_dock
 2063            .active_panel()
 2064            .map(|panel| panel.persistent_name().to_string());
 2065        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2066
 2067        DockStructure {
 2068            left: DockData {
 2069                visible: left_visible,
 2070                active_panel: left_active_panel,
 2071                zoom: left_dock_zoom,
 2072            },
 2073            right: DockData {
 2074                visible: right_visible,
 2075                active_panel: right_active_panel,
 2076                zoom: right_dock_zoom,
 2077            },
 2078            bottom: DockData {
 2079                visible: bottom_visible,
 2080                active_panel: bottom_active_panel,
 2081                zoom: bottom_dock_zoom,
 2082            },
 2083        }
 2084    }
 2085
 2086    pub fn set_dock_structure(
 2087        &self,
 2088        docks: DockStructure,
 2089        window: &mut Window,
 2090        cx: &mut Context<Self>,
 2091    ) {
 2092        for (dock, data) in [
 2093            (&self.left_dock, docks.left),
 2094            (&self.bottom_dock, docks.bottom),
 2095            (&self.right_dock, docks.right),
 2096        ] {
 2097            dock.update(cx, |dock, cx| {
 2098                dock.serialized_dock = Some(data);
 2099                dock.restore_state(window, cx);
 2100            });
 2101        }
 2102    }
 2103
 2104    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2105        self.items(cx)
 2106            .filter_map(|item| {
 2107                let project_path = item.project_path(cx)?;
 2108                self.project.read(cx).absolute_path(&project_path, cx)
 2109            })
 2110            .collect()
 2111    }
 2112
 2113    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2114        match position {
 2115            DockPosition::Left => &self.left_dock,
 2116            DockPosition::Bottom => &self.bottom_dock,
 2117            DockPosition::Right => &self.right_dock,
 2118        }
 2119    }
 2120
 2121    pub fn is_edited(&self) -> bool {
 2122        self.window_edited
 2123    }
 2124
 2125    pub fn add_panel<T: Panel>(
 2126        &mut self,
 2127        panel: Entity<T>,
 2128        window: &mut Window,
 2129        cx: &mut Context<Self>,
 2130    ) {
 2131        let focus_handle = panel.panel_focus_handle(cx);
 2132        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2133            .detach();
 2134
 2135        let dock_position = panel.position(window, cx);
 2136        let dock = self.dock_at_position(dock_position);
 2137        let any_panel = panel.to_any();
 2138
 2139        dock.update(cx, |dock, cx| {
 2140            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2141        });
 2142
 2143        cx.emit(Event::PanelAdded(any_panel));
 2144    }
 2145
 2146    pub fn remove_panel<T: Panel>(
 2147        &mut self,
 2148        panel: &Entity<T>,
 2149        window: &mut Window,
 2150        cx: &mut Context<Self>,
 2151    ) {
 2152        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2153            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2154        }
 2155    }
 2156
 2157    fn reposition_panels(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2158        let mut panels_to_move = Vec::new();
 2159        for dock_entity in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2160            let dock = dock_entity.read(cx);
 2161            let old_position = dock.position();
 2162            let visible_panel_id = dock.visible_panel().map(|panel| panel.panel_id());
 2163            for panel in dock.panels() {
 2164                let new_position = panel.position(window, cx);
 2165                if new_position != old_position {
 2166                    let was_visible = Some(panel.panel_id()) == visible_panel_id;
 2167                    panels_to_move.push((dock_entity, panel.clone(), new_position, was_visible));
 2168                }
 2169            }
 2170        }
 2171
 2172        for (old_dock, panel, new_position, was_visible) in panels_to_move {
 2173            if panel.is_zoomed(window, cx) {
 2174                self.zoomed_position = Some(new_position);
 2175            }
 2176
 2177            panel.remove_from_dock(old_dock, window, cx);
 2178            let new_dock = self.dock_at_position(new_position).clone();
 2179            let index = panel.add_to_dock(&new_dock, self.weak_self.clone(), window, cx);
 2180            if was_visible {
 2181                new_dock.update(cx, |new_dock, cx| {
 2182                    new_dock.set_open(true, window, cx);
 2183                    new_dock.activate_panel(index, window, cx);
 2184                });
 2185            }
 2186        }
 2187
 2188        self.serialize_workspace(window, cx);
 2189    }
 2190
 2191    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2192        &self.status_bar
 2193    }
 2194
 2195    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2196        StatusBarSettings::get_global(cx).show
 2197    }
 2198
 2199    pub fn app_state(&self) -> &Arc<AppState> {
 2200        &self.app_state
 2201    }
 2202
 2203    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2204        self._panels_task = Some(task);
 2205    }
 2206
 2207    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2208        self._panels_task.take()
 2209    }
 2210
 2211    pub fn user_store(&self) -> &Entity<UserStore> {
 2212        &self.app_state.user_store
 2213    }
 2214
 2215    pub fn project(&self) -> &Entity<Project> {
 2216        &self.project
 2217    }
 2218
 2219    pub fn path_style(&self, cx: &App) -> PathStyle {
 2220        self.project.read(cx).path_style(cx)
 2221    }
 2222
 2223    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2224        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2225
 2226        for pane_handle in &self.panes {
 2227            let pane = pane_handle.read(cx);
 2228
 2229            for entry in pane.activation_history() {
 2230                history.insert(
 2231                    entry.entity_id,
 2232                    history
 2233                        .get(&entry.entity_id)
 2234                        .cloned()
 2235                        .unwrap_or(0)
 2236                        .max(entry.timestamp),
 2237                );
 2238            }
 2239        }
 2240
 2241        history
 2242    }
 2243
 2244    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2245        let mut recent_item: Option<Entity<T>> = None;
 2246        let mut recent_timestamp = 0;
 2247        for pane_handle in &self.panes {
 2248            let pane = pane_handle.read(cx);
 2249            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2250                pane.items().map(|item| (item.item_id(), item)).collect();
 2251            for entry in pane.activation_history() {
 2252                if entry.timestamp > recent_timestamp
 2253                    && let Some(&item) = item_map.get(&entry.entity_id)
 2254                    && let Some(typed_item) = item.act_as::<T>(cx)
 2255                {
 2256                    recent_timestamp = entry.timestamp;
 2257                    recent_item = Some(typed_item);
 2258                }
 2259            }
 2260        }
 2261        recent_item
 2262    }
 2263
 2264    pub fn recent_navigation_history_iter(
 2265        &self,
 2266        cx: &App,
 2267    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2268        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2269        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2270
 2271        for pane in &self.panes {
 2272            let pane = pane.read(cx);
 2273
 2274            pane.nav_history()
 2275                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2276                    if let Some(fs_path) = &fs_path {
 2277                        abs_paths_opened
 2278                            .entry(fs_path.clone())
 2279                            .or_default()
 2280                            .insert(project_path.clone());
 2281                    }
 2282                    let timestamp = entry.timestamp;
 2283                    match history.entry(project_path) {
 2284                        hash_map::Entry::Occupied(mut entry) => {
 2285                            let (_, old_timestamp) = entry.get();
 2286                            if &timestamp > old_timestamp {
 2287                                entry.insert((fs_path, timestamp));
 2288                            }
 2289                        }
 2290                        hash_map::Entry::Vacant(entry) => {
 2291                            entry.insert((fs_path, timestamp));
 2292                        }
 2293                    }
 2294                });
 2295
 2296            if let Some(item) = pane.active_item()
 2297                && let Some(project_path) = item.project_path(cx)
 2298            {
 2299                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2300
 2301                if let Some(fs_path) = &fs_path {
 2302                    abs_paths_opened
 2303                        .entry(fs_path.clone())
 2304                        .or_default()
 2305                        .insert(project_path.clone());
 2306                }
 2307
 2308                history.insert(project_path, (fs_path, std::usize::MAX));
 2309            }
 2310        }
 2311
 2312        history
 2313            .into_iter()
 2314            .sorted_by_key(|(_, (_, order))| *order)
 2315            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2316            .rev()
 2317            .filter(move |(history_path, abs_path)| {
 2318                let latest_project_path_opened = abs_path
 2319                    .as_ref()
 2320                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2321                    .and_then(|project_paths| {
 2322                        project_paths
 2323                            .iter()
 2324                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2325                    });
 2326
 2327                latest_project_path_opened.is_none_or(|path| path == history_path)
 2328            })
 2329    }
 2330
 2331    pub fn recent_navigation_history(
 2332        &self,
 2333        limit: Option<usize>,
 2334        cx: &App,
 2335    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2336        self.recent_navigation_history_iter(cx)
 2337            .take(limit.unwrap_or(usize::MAX))
 2338            .collect()
 2339    }
 2340
 2341    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2342        for pane in &self.panes {
 2343            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2344        }
 2345    }
 2346
 2347    fn navigate_history(
 2348        &mut self,
 2349        pane: WeakEntity<Pane>,
 2350        mode: NavigationMode,
 2351        window: &mut Window,
 2352        cx: &mut Context<Workspace>,
 2353    ) -> Task<Result<()>> {
 2354        self.navigate_history_impl(
 2355            pane,
 2356            mode,
 2357            window,
 2358            &mut |history, cx| history.pop(mode, cx),
 2359            cx,
 2360        )
 2361    }
 2362
 2363    fn navigate_tag_history(
 2364        &mut self,
 2365        pane: WeakEntity<Pane>,
 2366        mode: TagNavigationMode,
 2367        window: &mut Window,
 2368        cx: &mut Context<Workspace>,
 2369    ) -> Task<Result<()>> {
 2370        self.navigate_history_impl(
 2371            pane,
 2372            NavigationMode::Normal,
 2373            window,
 2374            &mut |history, _cx| history.pop_tag(mode),
 2375            cx,
 2376        )
 2377    }
 2378
 2379    fn navigate_history_impl(
 2380        &mut self,
 2381        pane: WeakEntity<Pane>,
 2382        mode: NavigationMode,
 2383        window: &mut Window,
 2384        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2385        cx: &mut Context<Workspace>,
 2386    ) -> Task<Result<()>> {
 2387        let to_load = if let Some(pane) = pane.upgrade() {
 2388            pane.update(cx, |pane, cx| {
 2389                window.focus(&pane.focus_handle(cx), cx);
 2390                loop {
 2391                    // Retrieve the weak item handle from the history.
 2392                    let entry = cb(pane.nav_history_mut(), cx)?;
 2393
 2394                    // If the item is still present in this pane, then activate it.
 2395                    if let Some(index) = entry
 2396                        .item
 2397                        .upgrade()
 2398                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2399                    {
 2400                        let prev_active_item_index = pane.active_item_index();
 2401                        pane.nav_history_mut().set_mode(mode);
 2402                        pane.activate_item(index, true, true, window, cx);
 2403                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2404
 2405                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2406                        if let Some(data) = entry.data {
 2407                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2408                        }
 2409
 2410                        if navigated {
 2411                            break None;
 2412                        }
 2413                    } else {
 2414                        // If the item is no longer present in this pane, then retrieve its
 2415                        // path info in order to reopen it.
 2416                        break pane
 2417                            .nav_history()
 2418                            .path_for_item(entry.item.id())
 2419                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2420                    }
 2421                }
 2422            })
 2423        } else {
 2424            None
 2425        };
 2426
 2427        if let Some((project_path, abs_path, entry)) = to_load {
 2428            // If the item was no longer present, then load it again from its previous path, first try the local path
 2429            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2430
 2431            cx.spawn_in(window, async move  |workspace, cx| {
 2432                let open_by_project_path = open_by_project_path.await;
 2433                let mut navigated = false;
 2434                match open_by_project_path
 2435                    .with_context(|| format!("Navigating to {project_path:?}"))
 2436                {
 2437                    Ok((project_entry_id, build_item)) => {
 2438                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2439                            pane.nav_history_mut().set_mode(mode);
 2440                            pane.active_item().map(|p| p.item_id())
 2441                        })?;
 2442
 2443                        pane.update_in(cx, |pane, window, cx| {
 2444                            let item = pane.open_item(
 2445                                project_entry_id,
 2446                                project_path,
 2447                                true,
 2448                                entry.is_preview,
 2449                                true,
 2450                                None,
 2451                                window, cx,
 2452                                build_item,
 2453                            );
 2454                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2455                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2456                            if let Some(data) = entry.data {
 2457                                navigated |= item.navigate(data, window, cx);
 2458                            }
 2459                        })?;
 2460                    }
 2461                    Err(open_by_project_path_e) => {
 2462                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2463                        // and its worktree is now dropped
 2464                        if let Some(abs_path) = abs_path {
 2465                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2466                                pane.nav_history_mut().set_mode(mode);
 2467                                pane.active_item().map(|p| p.item_id())
 2468                            })?;
 2469                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2470                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2471                            })?;
 2472                            match open_by_abs_path
 2473                                .await
 2474                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2475                            {
 2476                                Ok(item) => {
 2477                                    pane.update_in(cx, |pane, window, cx| {
 2478                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2479                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2480                                        if let Some(data) = entry.data {
 2481                                            navigated |= item.navigate(data, window, cx);
 2482                                        }
 2483                                    })?;
 2484                                }
 2485                                Err(open_by_abs_path_e) => {
 2486                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2487                                }
 2488                            }
 2489                        }
 2490                    }
 2491                }
 2492
 2493                if !navigated {
 2494                    workspace
 2495                        .update_in(cx, |workspace, window, cx| {
 2496                            Self::navigate_history(workspace, pane, mode, window, cx)
 2497                        })?
 2498                        .await?;
 2499                }
 2500
 2501                Ok(())
 2502            })
 2503        } else {
 2504            Task::ready(Ok(()))
 2505        }
 2506    }
 2507
 2508    pub fn go_back(
 2509        &mut self,
 2510        pane: WeakEntity<Pane>,
 2511        window: &mut Window,
 2512        cx: &mut Context<Workspace>,
 2513    ) -> Task<Result<()>> {
 2514        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2515    }
 2516
 2517    pub fn go_forward(
 2518        &mut self,
 2519        pane: WeakEntity<Pane>,
 2520        window: &mut Window,
 2521        cx: &mut Context<Workspace>,
 2522    ) -> Task<Result<()>> {
 2523        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2524    }
 2525
 2526    pub fn reopen_closed_item(
 2527        &mut self,
 2528        window: &mut Window,
 2529        cx: &mut Context<Workspace>,
 2530    ) -> Task<Result<()>> {
 2531        self.navigate_history(
 2532            self.active_pane().downgrade(),
 2533            NavigationMode::ReopeningClosedItem,
 2534            window,
 2535            cx,
 2536        )
 2537    }
 2538
 2539    pub fn client(&self) -> &Arc<Client> {
 2540        &self.app_state.client
 2541    }
 2542
 2543    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2544        self.titlebar_item = Some(item);
 2545        cx.notify();
 2546    }
 2547
 2548    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2549        self.on_prompt_for_new_path = Some(prompt)
 2550    }
 2551
 2552    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2553        self.on_prompt_for_open_path = Some(prompt)
 2554    }
 2555
 2556    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2557        self.terminal_provider = Some(Box::new(provider));
 2558    }
 2559
 2560    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2561        self.debugger_provider = Some(Arc::new(provider));
 2562    }
 2563
 2564    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2565        self.debugger_provider.clone()
 2566    }
 2567
 2568    pub fn prompt_for_open_path(
 2569        &mut self,
 2570        path_prompt_options: PathPromptOptions,
 2571        lister: DirectoryLister,
 2572        window: &mut Window,
 2573        cx: &mut Context<Self>,
 2574    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2575        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2576            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2577            let rx = prompt(self, lister, window, cx);
 2578            self.on_prompt_for_open_path = Some(prompt);
 2579            rx
 2580        } else {
 2581            let (tx, rx) = oneshot::channel();
 2582            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2583
 2584            cx.spawn_in(window, async move |workspace, cx| {
 2585                let Ok(result) = abs_path.await else {
 2586                    return Ok(());
 2587                };
 2588
 2589                match result {
 2590                    Ok(result) => {
 2591                        tx.send(result).ok();
 2592                    }
 2593                    Err(err) => {
 2594                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2595                            workspace.show_portal_error(err.to_string(), cx);
 2596                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2597                            let rx = prompt(workspace, lister, window, cx);
 2598                            workspace.on_prompt_for_open_path = Some(prompt);
 2599                            rx
 2600                        })?;
 2601                        if let Ok(path) = rx.await {
 2602                            tx.send(path).ok();
 2603                        }
 2604                    }
 2605                };
 2606                anyhow::Ok(())
 2607            })
 2608            .detach();
 2609
 2610            rx
 2611        }
 2612    }
 2613
 2614    pub fn prompt_for_new_path(
 2615        &mut self,
 2616        lister: DirectoryLister,
 2617        suggested_name: Option<String>,
 2618        window: &mut Window,
 2619        cx: &mut Context<Self>,
 2620    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2621        if self.project.read(cx).is_via_collab()
 2622            || self.project.read(cx).is_via_remote_server()
 2623            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2624        {
 2625            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2626            let rx = prompt(self, lister, suggested_name, window, cx);
 2627            self.on_prompt_for_new_path = Some(prompt);
 2628            return rx;
 2629        }
 2630
 2631        let (tx, rx) = oneshot::channel();
 2632        cx.spawn_in(window, async move |workspace, cx| {
 2633            let abs_path = workspace.update(cx, |workspace, cx| {
 2634                let relative_to = workspace
 2635                    .most_recent_active_path(cx)
 2636                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2637                    .or_else(|| {
 2638                        let project = workspace.project.read(cx);
 2639                        project.visible_worktrees(cx).find_map(|worktree| {
 2640                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2641                        })
 2642                    })
 2643                    .or_else(std::env::home_dir)
 2644                    .unwrap_or_else(|| PathBuf::from(""));
 2645                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2646            })?;
 2647            let abs_path = match abs_path.await? {
 2648                Ok(path) => path,
 2649                Err(err) => {
 2650                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2651                        workspace.show_portal_error(err.to_string(), cx);
 2652
 2653                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2654                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2655                        workspace.on_prompt_for_new_path = Some(prompt);
 2656                        rx
 2657                    })?;
 2658                    if let Ok(path) = rx.await {
 2659                        tx.send(path).ok();
 2660                    }
 2661                    return anyhow::Ok(());
 2662                }
 2663            };
 2664
 2665            tx.send(abs_path.map(|path| vec![path])).ok();
 2666            anyhow::Ok(())
 2667        })
 2668        .detach();
 2669
 2670        rx
 2671    }
 2672
 2673    pub fn titlebar_item(&self) -> Option<AnyView> {
 2674        self.titlebar_item.clone()
 2675    }
 2676
 2677    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2678    /// When set, git-related operations should use this worktree instead of deriving
 2679    /// the active worktree from the focused file.
 2680    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2681        self.active_worktree_override
 2682    }
 2683
 2684    pub fn set_active_worktree_override(
 2685        &mut self,
 2686        worktree_id: Option<WorktreeId>,
 2687        cx: &mut Context<Self>,
 2688    ) {
 2689        self.active_worktree_override = worktree_id;
 2690        cx.notify();
 2691    }
 2692
 2693    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2694        self.active_worktree_override = None;
 2695        cx.notify();
 2696    }
 2697
 2698    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2699    ///
 2700    /// If the given workspace has a local project, then it will be passed
 2701    /// to the callback. Otherwise, a new empty window will be created.
 2702    pub fn with_local_workspace<T, F>(
 2703        &mut self,
 2704        window: &mut Window,
 2705        cx: &mut Context<Self>,
 2706        callback: F,
 2707    ) -> Task<Result<T>>
 2708    where
 2709        T: 'static,
 2710        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2711    {
 2712        if self.project.read(cx).is_local() {
 2713            Task::ready(Ok(callback(self, window, cx)))
 2714        } else {
 2715            let env = self.project.read(cx).cli_environment(cx);
 2716            let task = Self::new_local(
 2717                Vec::new(),
 2718                self.app_state.clone(),
 2719                None,
 2720                env,
 2721                None,
 2722                true,
 2723                cx,
 2724            );
 2725            cx.spawn_in(window, async move |_vh, cx| {
 2726                let OpenResult {
 2727                    window: multi_workspace_window,
 2728                    ..
 2729                } = task.await?;
 2730                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2731                    let workspace = multi_workspace.workspace().clone();
 2732                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2733                })
 2734            })
 2735        }
 2736    }
 2737
 2738    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2739    ///
 2740    /// If the given workspace has a local project, then it will be passed
 2741    /// to the callback. Otherwise, a new empty window will be created.
 2742    pub fn with_local_or_wsl_workspace<T, F>(
 2743        &mut self,
 2744        window: &mut Window,
 2745        cx: &mut Context<Self>,
 2746        callback: F,
 2747    ) -> Task<Result<T>>
 2748    where
 2749        T: 'static,
 2750        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2751    {
 2752        let project = self.project.read(cx);
 2753        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2754            Task::ready(Ok(callback(self, window, cx)))
 2755        } else {
 2756            let env = self.project.read(cx).cli_environment(cx);
 2757            let task = Self::new_local(
 2758                Vec::new(),
 2759                self.app_state.clone(),
 2760                None,
 2761                env,
 2762                None,
 2763                true,
 2764                cx,
 2765            );
 2766            cx.spawn_in(window, async move |_vh, cx| {
 2767                let OpenResult {
 2768                    window: multi_workspace_window,
 2769                    ..
 2770                } = task.await?;
 2771                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2772                    let workspace = multi_workspace.workspace().clone();
 2773                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2774                })
 2775            })
 2776        }
 2777    }
 2778
 2779    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2780        self.project.read(cx).worktrees(cx)
 2781    }
 2782
 2783    pub fn visible_worktrees<'a>(
 2784        &self,
 2785        cx: &'a App,
 2786    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2787        self.project.read(cx).visible_worktrees(cx)
 2788    }
 2789
 2790    #[cfg(any(test, feature = "test-support"))]
 2791    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2792        let futures = self
 2793            .worktrees(cx)
 2794            .filter_map(|worktree| worktree.read(cx).as_local())
 2795            .map(|worktree| worktree.scan_complete())
 2796            .collect::<Vec<_>>();
 2797        async move {
 2798            for future in futures {
 2799                future.await;
 2800            }
 2801        }
 2802    }
 2803
 2804    pub fn close_global(cx: &mut App) {
 2805        cx.defer(|cx| {
 2806            cx.windows().iter().find(|window| {
 2807                window
 2808                    .update(cx, |_, window, _| {
 2809                        if window.is_window_active() {
 2810                            //This can only get called when the window's project connection has been lost
 2811                            //so we don't need to prompt the user for anything and instead just close the window
 2812                            window.remove_window();
 2813                            true
 2814                        } else {
 2815                            false
 2816                        }
 2817                    })
 2818                    .unwrap_or(false)
 2819            });
 2820        });
 2821    }
 2822
 2823    pub fn move_focused_panel_to_next_position(
 2824        &mut self,
 2825        _: &MoveFocusedPanelToNextPosition,
 2826        window: &mut Window,
 2827        cx: &mut Context<Self>,
 2828    ) {
 2829        let docks = self.all_docks();
 2830        let active_dock = docks
 2831            .into_iter()
 2832            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2833
 2834        if let Some(dock) = active_dock {
 2835            dock.update(cx, |dock, cx| {
 2836                let active_panel = dock
 2837                    .active_panel()
 2838                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2839
 2840                if let Some(panel) = active_panel {
 2841                    panel.move_to_next_position(window, cx);
 2842                }
 2843            })
 2844        }
 2845    }
 2846
 2847    pub fn prepare_to_close(
 2848        &mut self,
 2849        close_intent: CloseIntent,
 2850        window: &mut Window,
 2851        cx: &mut Context<Self>,
 2852    ) -> Task<Result<bool>> {
 2853        let active_call = self.active_global_call();
 2854
 2855        cx.spawn_in(window, async move |this, cx| {
 2856            this.update(cx, |this, _| {
 2857                if close_intent == CloseIntent::CloseWindow {
 2858                    this.removing = true;
 2859                }
 2860            })?;
 2861
 2862            let workspace_count = cx.update(|_window, cx| {
 2863                cx.windows()
 2864                    .iter()
 2865                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2866                    .count()
 2867            })?;
 2868
 2869            #[cfg(target_os = "macos")]
 2870            let save_last_workspace = false;
 2871
 2872            // On Linux and Windows, closing the last window should restore the last workspace.
 2873            #[cfg(not(target_os = "macos"))]
 2874            let save_last_workspace = {
 2875                let remaining_workspaces = cx.update(|_window, cx| {
 2876                    cx.windows()
 2877                        .iter()
 2878                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2879                        .filter_map(|multi_workspace| {
 2880                            multi_workspace
 2881                                .update(cx, |multi_workspace, _, cx| {
 2882                                    multi_workspace.workspace().read(cx).removing
 2883                                })
 2884                                .ok()
 2885                        })
 2886                        .filter(|removing| !removing)
 2887                        .count()
 2888                })?;
 2889
 2890                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2891            };
 2892
 2893            if let Some(active_call) = active_call
 2894                && workspace_count == 1
 2895                && cx
 2896                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2897                    .unwrap_or(false)
 2898            {
 2899                if close_intent == CloseIntent::CloseWindow {
 2900                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2901                    let answer = cx.update(|window, cx| {
 2902                        window.prompt(
 2903                            PromptLevel::Warning,
 2904                            "Do you want to leave the current call?",
 2905                            None,
 2906                            &["Close window and hang up", "Cancel"],
 2907                            cx,
 2908                        )
 2909                    })?;
 2910
 2911                    if answer.await.log_err() == Some(1) {
 2912                        return anyhow::Ok(false);
 2913                    } else {
 2914                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2915                            task.await.log_err();
 2916                        }
 2917                    }
 2918                }
 2919                if close_intent == CloseIntent::ReplaceWindow {
 2920                    _ = cx.update(|_window, cx| {
 2921                        let multi_workspace = cx
 2922                            .windows()
 2923                            .iter()
 2924                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2925                            .next()
 2926                            .unwrap();
 2927                        let project = multi_workspace
 2928                            .read(cx)?
 2929                            .workspace()
 2930                            .read(cx)
 2931                            .project
 2932                            .clone();
 2933                        if project.read(cx).is_shared() {
 2934                            active_call.0.unshare_project(project, cx)?;
 2935                        }
 2936                        Ok::<_, anyhow::Error>(())
 2937                    });
 2938                }
 2939            }
 2940
 2941            let save_result = this
 2942                .update_in(cx, |this, window, cx| {
 2943                    this.save_all_internal(SaveIntent::Close, window, cx)
 2944                })?
 2945                .await;
 2946
 2947            // If we're not quitting, but closing, we remove the workspace from
 2948            // the current session.
 2949            if close_intent != CloseIntent::Quit
 2950                && !save_last_workspace
 2951                && save_result.as_ref().is_ok_and(|&res| res)
 2952            {
 2953                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2954                    .await;
 2955            }
 2956
 2957            save_result
 2958        })
 2959    }
 2960
 2961    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2962        self.save_all_internal(
 2963            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2964            window,
 2965            cx,
 2966        )
 2967        .detach_and_log_err(cx);
 2968    }
 2969
 2970    fn send_keystrokes(
 2971        &mut self,
 2972        action: &SendKeystrokes,
 2973        window: &mut Window,
 2974        cx: &mut Context<Self>,
 2975    ) {
 2976        let keystrokes: Vec<Keystroke> = action
 2977            .0
 2978            .split(' ')
 2979            .flat_map(|k| Keystroke::parse(k).log_err())
 2980            .map(|k| {
 2981                cx.keyboard_mapper()
 2982                    .map_key_equivalent(k, false)
 2983                    .inner()
 2984                    .clone()
 2985            })
 2986            .collect();
 2987        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2988    }
 2989
 2990    pub fn send_keystrokes_impl(
 2991        &mut self,
 2992        keystrokes: Vec<Keystroke>,
 2993        window: &mut Window,
 2994        cx: &mut Context<Self>,
 2995    ) -> Shared<Task<()>> {
 2996        let mut state = self.dispatching_keystrokes.borrow_mut();
 2997        if !state.dispatched.insert(keystrokes.clone()) {
 2998            cx.propagate();
 2999            return state.task.clone().unwrap();
 3000        }
 3001
 3002        state.queue.extend(keystrokes);
 3003
 3004        let keystrokes = self.dispatching_keystrokes.clone();
 3005        if state.task.is_none() {
 3006            state.task = Some(
 3007                window
 3008                    .spawn(cx, async move |cx| {
 3009                        // limit to 100 keystrokes to avoid infinite recursion.
 3010                        for _ in 0..100 {
 3011                            let keystroke = {
 3012                                let mut state = keystrokes.borrow_mut();
 3013                                let Some(keystroke) = state.queue.pop_front() else {
 3014                                    state.dispatched.clear();
 3015                                    state.task.take();
 3016                                    return;
 3017                                };
 3018                                keystroke
 3019                            };
 3020                            cx.update(|window, cx| {
 3021                                let focused = window.focused(cx);
 3022                                window.dispatch_keystroke(keystroke.clone(), cx);
 3023                                if window.focused(cx) != focused {
 3024                                    // dispatch_keystroke may cause the focus to change.
 3025                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3026                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3027                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3028                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3029                                    // )
 3030                                    window.draw(cx).clear();
 3031                                }
 3032                            })
 3033                            .ok();
 3034
 3035                            // Yield between synthetic keystrokes so deferred focus and
 3036                            // other effects can settle before dispatching the next key.
 3037                            yield_now().await;
 3038                        }
 3039
 3040                        *keystrokes.borrow_mut() = Default::default();
 3041                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3042                    })
 3043                    .shared(),
 3044            );
 3045        }
 3046        state.task.clone().unwrap()
 3047    }
 3048
 3049    fn save_all_internal(
 3050        &mut self,
 3051        mut save_intent: SaveIntent,
 3052        window: &mut Window,
 3053        cx: &mut Context<Self>,
 3054    ) -> Task<Result<bool>> {
 3055        if self.project.read(cx).is_disconnected(cx) {
 3056            return Task::ready(Ok(true));
 3057        }
 3058        let dirty_items = self
 3059            .panes
 3060            .iter()
 3061            .flat_map(|pane| {
 3062                pane.read(cx).items().filter_map(|item| {
 3063                    if item.is_dirty(cx) {
 3064                        item.tab_content_text(0, cx);
 3065                        Some((pane.downgrade(), item.boxed_clone()))
 3066                    } else {
 3067                        None
 3068                    }
 3069                })
 3070            })
 3071            .collect::<Vec<_>>();
 3072
 3073        let project = self.project.clone();
 3074        cx.spawn_in(window, async move |workspace, cx| {
 3075            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3076                let (serialize_tasks, remaining_dirty_items) =
 3077                    workspace.update_in(cx, |workspace, window, cx| {
 3078                        let mut remaining_dirty_items = Vec::new();
 3079                        let mut serialize_tasks = Vec::new();
 3080                        for (pane, item) in dirty_items {
 3081                            if let Some(task) = item
 3082                                .to_serializable_item_handle(cx)
 3083                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3084                            {
 3085                                serialize_tasks.push(task);
 3086                            } else {
 3087                                remaining_dirty_items.push((pane, item));
 3088                            }
 3089                        }
 3090                        (serialize_tasks, remaining_dirty_items)
 3091                    })?;
 3092
 3093                futures::future::try_join_all(serialize_tasks).await?;
 3094
 3095                if !remaining_dirty_items.is_empty() {
 3096                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3097                }
 3098
 3099                if remaining_dirty_items.len() > 1 {
 3100                    let answer = workspace.update_in(cx, |_, window, cx| {
 3101                        let detail = Pane::file_names_for_prompt(
 3102                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3103                            cx,
 3104                        );
 3105                        window.prompt(
 3106                            PromptLevel::Warning,
 3107                            "Do you want to save all changes in the following files?",
 3108                            Some(&detail),
 3109                            &["Save all", "Discard all", "Cancel"],
 3110                            cx,
 3111                        )
 3112                    })?;
 3113                    match answer.await.log_err() {
 3114                        Some(0) => save_intent = SaveIntent::SaveAll,
 3115                        Some(1) => save_intent = SaveIntent::Skip,
 3116                        Some(2) => return Ok(false),
 3117                        _ => {}
 3118                    }
 3119                }
 3120
 3121                remaining_dirty_items
 3122            } else {
 3123                dirty_items
 3124            };
 3125
 3126            for (pane, item) in dirty_items {
 3127                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3128                    (
 3129                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3130                        item.project_entry_ids(cx),
 3131                    )
 3132                })?;
 3133                if (singleton || !project_entry_ids.is_empty())
 3134                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3135                {
 3136                    return Ok(false);
 3137                }
 3138            }
 3139            Ok(true)
 3140        })
 3141    }
 3142
 3143    pub fn open_workspace_for_paths(
 3144        &mut self,
 3145        replace_current_window: bool,
 3146        paths: Vec<PathBuf>,
 3147        window: &mut Window,
 3148        cx: &mut Context<Self>,
 3149    ) -> Task<Result<Entity<Workspace>>> {
 3150        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3151        let is_remote = self.project.read(cx).is_via_collab();
 3152        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3153        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3154
 3155        let window_to_replace = if replace_current_window {
 3156            window_handle
 3157        } else if is_remote || has_worktree || has_dirty_items {
 3158            None
 3159        } else {
 3160            window_handle
 3161        };
 3162        let app_state = self.app_state.clone();
 3163
 3164        cx.spawn(async move |_, cx| {
 3165            let OpenResult { workspace, .. } = cx
 3166                .update(|cx| {
 3167                    open_paths(
 3168                        &paths,
 3169                        app_state,
 3170                        OpenOptions {
 3171                            replace_window: window_to_replace,
 3172                            ..Default::default()
 3173                        },
 3174                        cx,
 3175                    )
 3176                })
 3177                .await?;
 3178            Ok(workspace)
 3179        })
 3180    }
 3181
 3182    #[allow(clippy::type_complexity)]
 3183    pub fn open_paths(
 3184        &mut self,
 3185        mut abs_paths: Vec<PathBuf>,
 3186        options: OpenOptions,
 3187        pane: Option<WeakEntity<Pane>>,
 3188        window: &mut Window,
 3189        cx: &mut Context<Self>,
 3190    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3191        let fs = self.app_state.fs.clone();
 3192
 3193        let caller_ordered_abs_paths = abs_paths.clone();
 3194
 3195        // Sort the paths to ensure we add worktrees for parents before their children.
 3196        abs_paths.sort_unstable();
 3197        cx.spawn_in(window, async move |this, cx| {
 3198            let mut tasks = Vec::with_capacity(abs_paths.len());
 3199
 3200            for abs_path in &abs_paths {
 3201                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3202                    OpenVisible::All => Some(true),
 3203                    OpenVisible::None => Some(false),
 3204                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3205                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3206                        Some(None) => Some(true),
 3207                        None => None,
 3208                    },
 3209                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3210                        Some(Some(metadata)) => Some(metadata.is_dir),
 3211                        Some(None) => Some(false),
 3212                        None => None,
 3213                    },
 3214                };
 3215                let project_path = match visible {
 3216                    Some(visible) => match this
 3217                        .update(cx, |this, cx| {
 3218                            Workspace::project_path_for_path(
 3219                                this.project.clone(),
 3220                                abs_path,
 3221                                visible,
 3222                                cx,
 3223                            )
 3224                        })
 3225                        .log_err()
 3226                    {
 3227                        Some(project_path) => project_path.await.log_err(),
 3228                        None => None,
 3229                    },
 3230                    None => None,
 3231                };
 3232
 3233                let this = this.clone();
 3234                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3235                let fs = fs.clone();
 3236                let pane = pane.clone();
 3237                let task = cx.spawn(async move |cx| {
 3238                    let (_worktree, project_path) = project_path?;
 3239                    if fs.is_dir(&abs_path).await {
 3240                        // Opening a directory should not race to update the active entry.
 3241                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3242                        None
 3243                    } else {
 3244                        Some(
 3245                            this.update_in(cx, |this, window, cx| {
 3246                                this.open_path(
 3247                                    project_path,
 3248                                    pane,
 3249                                    options.focus.unwrap_or(true),
 3250                                    window,
 3251                                    cx,
 3252                                )
 3253                            })
 3254                            .ok()?
 3255                            .await,
 3256                        )
 3257                    }
 3258                });
 3259                tasks.push(task);
 3260            }
 3261
 3262            let results = futures::future::join_all(tasks).await;
 3263
 3264            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3265            let mut winner: Option<(PathBuf, bool)> = None;
 3266            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3267                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3268                    if !metadata.is_dir {
 3269                        winner = Some((abs_path, false));
 3270                        break;
 3271                    }
 3272                    if winner.is_none() {
 3273                        winner = Some((abs_path, true));
 3274                    }
 3275                } else if winner.is_none() {
 3276                    winner = Some((abs_path, false));
 3277                }
 3278            }
 3279
 3280            // Compute the winner entry id on the foreground thread and emit once, after all
 3281            // paths finish opening. This avoids races between concurrently-opening paths
 3282            // (directories in particular) and makes the resulting project panel selection
 3283            // deterministic.
 3284            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3285                'emit_winner: {
 3286                    let winner_abs_path: Arc<Path> =
 3287                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3288
 3289                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3290                        OpenVisible::All => true,
 3291                        OpenVisible::None => false,
 3292                        OpenVisible::OnlyFiles => !winner_is_dir,
 3293                        OpenVisible::OnlyDirectories => winner_is_dir,
 3294                    };
 3295
 3296                    let Some(worktree_task) = this
 3297                        .update(cx, |workspace, cx| {
 3298                            workspace.project.update(cx, |project, cx| {
 3299                                project.find_or_create_worktree(
 3300                                    winner_abs_path.as_ref(),
 3301                                    visible,
 3302                                    cx,
 3303                                )
 3304                            })
 3305                        })
 3306                        .ok()
 3307                    else {
 3308                        break 'emit_winner;
 3309                    };
 3310
 3311                    let Ok((worktree, _)) = worktree_task.await else {
 3312                        break 'emit_winner;
 3313                    };
 3314
 3315                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3316                        let worktree = worktree.read(cx);
 3317                        let worktree_abs_path = worktree.abs_path();
 3318                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3319                            worktree.root_entry()
 3320                        } else {
 3321                            winner_abs_path
 3322                                .strip_prefix(worktree_abs_path.as_ref())
 3323                                .ok()
 3324                                .and_then(|relative_path| {
 3325                                    let relative_path =
 3326                                        RelPath::new(relative_path, PathStyle::local())
 3327                                            .log_err()?;
 3328                                    worktree.entry_for_path(&relative_path)
 3329                                })
 3330                        }?;
 3331                        Some(entry.id)
 3332                    }) else {
 3333                        break 'emit_winner;
 3334                    };
 3335
 3336                    this.update(cx, |workspace, cx| {
 3337                        workspace.project.update(cx, |_, cx| {
 3338                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3339                        });
 3340                    })
 3341                    .ok();
 3342                }
 3343            }
 3344
 3345            results
 3346        })
 3347    }
 3348
 3349    pub fn open_resolved_path(
 3350        &mut self,
 3351        path: ResolvedPath,
 3352        window: &mut Window,
 3353        cx: &mut Context<Self>,
 3354    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3355        match path {
 3356            ResolvedPath::ProjectPath { project_path, .. } => {
 3357                self.open_path(project_path, None, true, window, cx)
 3358            }
 3359            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3360                PathBuf::from(path),
 3361                OpenOptions {
 3362                    visible: Some(OpenVisible::None),
 3363                    ..Default::default()
 3364                },
 3365                window,
 3366                cx,
 3367            ),
 3368        }
 3369    }
 3370
 3371    pub fn absolute_path_of_worktree(
 3372        &self,
 3373        worktree_id: WorktreeId,
 3374        cx: &mut Context<Self>,
 3375    ) -> Option<PathBuf> {
 3376        self.project
 3377            .read(cx)
 3378            .worktree_for_id(worktree_id, cx)
 3379            // TODO: use `abs_path` or `root_dir`
 3380            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3381    }
 3382
 3383    fn add_folder_to_project(
 3384        &mut self,
 3385        _: &AddFolderToProject,
 3386        window: &mut Window,
 3387        cx: &mut Context<Self>,
 3388    ) {
 3389        let project = self.project.read(cx);
 3390        if project.is_via_collab() {
 3391            self.show_error(
 3392                &anyhow!("You cannot add folders to someone else's project"),
 3393                cx,
 3394            );
 3395            return;
 3396        }
 3397        let paths = self.prompt_for_open_path(
 3398            PathPromptOptions {
 3399                files: false,
 3400                directories: true,
 3401                multiple: true,
 3402                prompt: None,
 3403            },
 3404            DirectoryLister::Project(self.project.clone()),
 3405            window,
 3406            cx,
 3407        );
 3408        cx.spawn_in(window, async move |this, cx| {
 3409            if let Some(paths) = paths.await.log_err().flatten() {
 3410                let results = this
 3411                    .update_in(cx, |this, window, cx| {
 3412                        this.open_paths(
 3413                            paths,
 3414                            OpenOptions {
 3415                                visible: Some(OpenVisible::All),
 3416                                ..Default::default()
 3417                            },
 3418                            None,
 3419                            window,
 3420                            cx,
 3421                        )
 3422                    })?
 3423                    .await;
 3424                for result in results.into_iter().flatten() {
 3425                    result.log_err();
 3426                }
 3427            }
 3428            anyhow::Ok(())
 3429        })
 3430        .detach_and_log_err(cx);
 3431    }
 3432
 3433    pub fn project_path_for_path(
 3434        project: Entity<Project>,
 3435        abs_path: &Path,
 3436        visible: bool,
 3437        cx: &mut App,
 3438    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3439        let entry = project.update(cx, |project, cx| {
 3440            project.find_or_create_worktree(abs_path, visible, cx)
 3441        });
 3442        cx.spawn(async move |cx| {
 3443            let (worktree, path) = entry.await?;
 3444            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3445            Ok((worktree, ProjectPath { worktree_id, path }))
 3446        })
 3447    }
 3448
 3449    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3450        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3451    }
 3452
 3453    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3454        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3455    }
 3456
 3457    pub fn items_of_type<'a, T: Item>(
 3458        &'a self,
 3459        cx: &'a App,
 3460    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3461        self.panes
 3462            .iter()
 3463            .flat_map(|pane| pane.read(cx).items_of_type())
 3464    }
 3465
 3466    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3467        self.active_pane().read(cx).active_item()
 3468    }
 3469
 3470    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3471        let item = self.active_item(cx)?;
 3472        item.to_any_view().downcast::<I>().ok()
 3473    }
 3474
 3475    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3476        self.active_item(cx).and_then(|item| item.project_path(cx))
 3477    }
 3478
 3479    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3480        self.recent_navigation_history_iter(cx)
 3481            .filter_map(|(path, abs_path)| {
 3482                let worktree = self
 3483                    .project
 3484                    .read(cx)
 3485                    .worktree_for_id(path.worktree_id, cx)?;
 3486                if worktree.read(cx).is_visible() {
 3487                    abs_path
 3488                } else {
 3489                    None
 3490                }
 3491            })
 3492            .next()
 3493    }
 3494
 3495    pub fn save_active_item(
 3496        &mut self,
 3497        save_intent: SaveIntent,
 3498        window: &mut Window,
 3499        cx: &mut App,
 3500    ) -> Task<Result<()>> {
 3501        let project = self.project.clone();
 3502        let pane = self.active_pane();
 3503        let item = pane.read(cx).active_item();
 3504        let pane = pane.downgrade();
 3505
 3506        window.spawn(cx, async move |cx| {
 3507            if let Some(item) = item {
 3508                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3509                    .await
 3510                    .map(|_| ())
 3511            } else {
 3512                Ok(())
 3513            }
 3514        })
 3515    }
 3516
 3517    pub fn close_inactive_items_and_panes(
 3518        &mut self,
 3519        action: &CloseInactiveTabsAndPanes,
 3520        window: &mut Window,
 3521        cx: &mut Context<Self>,
 3522    ) {
 3523        if let Some(task) = self.close_all_internal(
 3524            true,
 3525            action.save_intent.unwrap_or(SaveIntent::Close),
 3526            window,
 3527            cx,
 3528        ) {
 3529            task.detach_and_log_err(cx)
 3530        }
 3531    }
 3532
 3533    pub fn close_all_items_and_panes(
 3534        &mut self,
 3535        action: &CloseAllItemsAndPanes,
 3536        window: &mut Window,
 3537        cx: &mut Context<Self>,
 3538    ) {
 3539        if let Some(task) = self.close_all_internal(
 3540            false,
 3541            action.save_intent.unwrap_or(SaveIntent::Close),
 3542            window,
 3543            cx,
 3544        ) {
 3545            task.detach_and_log_err(cx)
 3546        }
 3547    }
 3548
 3549    /// Closes the active item across all panes.
 3550    pub fn close_item_in_all_panes(
 3551        &mut self,
 3552        action: &CloseItemInAllPanes,
 3553        window: &mut Window,
 3554        cx: &mut Context<Self>,
 3555    ) {
 3556        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3557            return;
 3558        };
 3559
 3560        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3561        let close_pinned = action.close_pinned;
 3562
 3563        if let Some(project_path) = active_item.project_path(cx) {
 3564            self.close_items_with_project_path(
 3565                &project_path,
 3566                save_intent,
 3567                close_pinned,
 3568                window,
 3569                cx,
 3570            );
 3571        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3572            let item_id = active_item.item_id();
 3573            self.active_pane().update(cx, |pane, cx| {
 3574                pane.close_item_by_id(item_id, save_intent, window, cx)
 3575                    .detach_and_log_err(cx);
 3576            });
 3577        }
 3578    }
 3579
 3580    /// Closes all items with the given project path across all panes.
 3581    pub fn close_items_with_project_path(
 3582        &mut self,
 3583        project_path: &ProjectPath,
 3584        save_intent: SaveIntent,
 3585        close_pinned: bool,
 3586        window: &mut Window,
 3587        cx: &mut Context<Self>,
 3588    ) {
 3589        let panes = self.panes().to_vec();
 3590        for pane in panes {
 3591            pane.update(cx, |pane, cx| {
 3592                pane.close_items_for_project_path(
 3593                    project_path,
 3594                    save_intent,
 3595                    close_pinned,
 3596                    window,
 3597                    cx,
 3598                )
 3599                .detach_and_log_err(cx);
 3600            });
 3601        }
 3602    }
 3603
 3604    fn close_all_internal(
 3605        &mut self,
 3606        retain_active_pane: bool,
 3607        save_intent: SaveIntent,
 3608        window: &mut Window,
 3609        cx: &mut Context<Self>,
 3610    ) -> Option<Task<Result<()>>> {
 3611        let current_pane = self.active_pane();
 3612
 3613        let mut tasks = Vec::new();
 3614
 3615        if retain_active_pane {
 3616            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3617                pane.close_other_items(
 3618                    &CloseOtherItems {
 3619                        save_intent: None,
 3620                        close_pinned: false,
 3621                    },
 3622                    None,
 3623                    window,
 3624                    cx,
 3625                )
 3626            });
 3627
 3628            tasks.push(current_pane_close);
 3629        }
 3630
 3631        for pane in self.panes() {
 3632            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3633                continue;
 3634            }
 3635
 3636            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3637                pane.close_all_items(
 3638                    &CloseAllItems {
 3639                        save_intent: Some(save_intent),
 3640                        close_pinned: false,
 3641                    },
 3642                    window,
 3643                    cx,
 3644                )
 3645            });
 3646
 3647            tasks.push(close_pane_items)
 3648        }
 3649
 3650        if tasks.is_empty() {
 3651            None
 3652        } else {
 3653            Some(cx.spawn_in(window, async move |_, _| {
 3654                for task in tasks {
 3655                    task.await?
 3656                }
 3657                Ok(())
 3658            }))
 3659        }
 3660    }
 3661
 3662    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3663        self.dock_at_position(position).read(cx).is_open()
 3664    }
 3665
 3666    pub fn toggle_dock(
 3667        &mut self,
 3668        dock_side: DockPosition,
 3669        window: &mut Window,
 3670        cx: &mut Context<Self>,
 3671    ) {
 3672        let mut focus_center = false;
 3673        let mut reveal_dock = false;
 3674
 3675        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3676        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3677
 3678        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3679            telemetry::event!(
 3680                "Panel Button Clicked",
 3681                name = panel.persistent_name(),
 3682                toggle_state = !was_visible
 3683            );
 3684        }
 3685        if was_visible {
 3686            self.save_open_dock_positions(cx);
 3687        }
 3688
 3689        let dock = self.dock_at_position(dock_side);
 3690        dock.update(cx, |dock, cx| {
 3691            dock.set_open(!was_visible, window, cx);
 3692
 3693            if dock.active_panel().is_none() {
 3694                let Some(panel_ix) = dock
 3695                    .first_enabled_panel_idx(cx)
 3696                    .log_with_level(log::Level::Info)
 3697                else {
 3698                    return;
 3699                };
 3700                dock.activate_panel(panel_ix, window, cx);
 3701            }
 3702
 3703            if let Some(active_panel) = dock.active_panel() {
 3704                if was_visible {
 3705                    if active_panel
 3706                        .panel_focus_handle(cx)
 3707                        .contains_focused(window, cx)
 3708                    {
 3709                        focus_center = true;
 3710                    }
 3711                } else {
 3712                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3713                    window.focus(focus_handle, cx);
 3714                    reveal_dock = true;
 3715                }
 3716            }
 3717        });
 3718
 3719        if reveal_dock {
 3720            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3721        }
 3722
 3723        if focus_center {
 3724            self.active_pane
 3725                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3726        }
 3727
 3728        cx.notify();
 3729        self.serialize_workspace(window, cx);
 3730    }
 3731
 3732    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3733        self.all_docks().into_iter().find(|&dock| {
 3734            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3735        })
 3736    }
 3737
 3738    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3739        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3740            self.save_open_dock_positions(cx);
 3741            dock.update(cx, |dock, cx| {
 3742                dock.set_open(false, window, cx);
 3743            });
 3744            return true;
 3745        }
 3746        false
 3747    }
 3748
 3749    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3750        self.save_open_dock_positions(cx);
 3751        for dock in self.all_docks() {
 3752            dock.update(cx, |dock, cx| {
 3753                dock.set_open(false, window, cx);
 3754            });
 3755        }
 3756
 3757        cx.focus_self(window);
 3758        cx.notify();
 3759        self.serialize_workspace(window, cx);
 3760    }
 3761
 3762    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3763        self.all_docks()
 3764            .into_iter()
 3765            .filter_map(|dock| {
 3766                let dock_ref = dock.read(cx);
 3767                if dock_ref.is_open() {
 3768                    Some(dock_ref.position())
 3769                } else {
 3770                    None
 3771                }
 3772            })
 3773            .collect()
 3774    }
 3775
 3776    /// Saves the positions of currently open docks.
 3777    ///
 3778    /// Updates `last_open_dock_positions` with positions of all currently open
 3779    /// docks, to later be restored by the 'Toggle All Docks' action.
 3780    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3781        let open_dock_positions = self.get_open_dock_positions(cx);
 3782        if !open_dock_positions.is_empty() {
 3783            self.last_open_dock_positions = open_dock_positions;
 3784        }
 3785    }
 3786
 3787    /// Toggles all docks between open and closed states.
 3788    ///
 3789    /// If any docks are open, closes all and remembers their positions. If all
 3790    /// docks are closed, restores the last remembered dock configuration.
 3791    fn toggle_all_docks(
 3792        &mut self,
 3793        _: &ToggleAllDocks,
 3794        window: &mut Window,
 3795        cx: &mut Context<Self>,
 3796    ) {
 3797        let open_dock_positions = self.get_open_dock_positions(cx);
 3798
 3799        if !open_dock_positions.is_empty() {
 3800            self.close_all_docks(window, cx);
 3801        } else if !self.last_open_dock_positions.is_empty() {
 3802            self.restore_last_open_docks(window, cx);
 3803        }
 3804    }
 3805
 3806    /// Reopens docks from the most recently remembered configuration.
 3807    ///
 3808    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3809    /// and clears the stored positions.
 3810    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3811        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3812
 3813        for position in positions_to_open {
 3814            let dock = self.dock_at_position(position);
 3815            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3816        }
 3817
 3818        cx.focus_self(window);
 3819        cx.notify();
 3820        self.serialize_workspace(window, cx);
 3821    }
 3822
 3823    /// Transfer focus to the panel of the given type.
 3824    pub fn focus_panel<T: Panel>(
 3825        &mut self,
 3826        window: &mut Window,
 3827        cx: &mut Context<Self>,
 3828    ) -> Option<Entity<T>> {
 3829        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3830        panel.to_any().downcast().ok()
 3831    }
 3832
 3833    /// Focus the panel of the given type if it isn't already focused. If it is
 3834    /// already focused, then transfer focus back to the workspace center.
 3835    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3836    /// panel when transferring focus back to the center.
 3837    pub fn toggle_panel_focus<T: Panel>(
 3838        &mut self,
 3839        window: &mut Window,
 3840        cx: &mut Context<Self>,
 3841    ) -> bool {
 3842        let mut did_focus_panel = false;
 3843        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3844            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3845            did_focus_panel
 3846        });
 3847
 3848        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3849            self.close_panel::<T>(window, cx);
 3850        }
 3851
 3852        telemetry::event!(
 3853            "Panel Button Clicked",
 3854            name = T::persistent_name(),
 3855            toggle_state = did_focus_panel
 3856        );
 3857
 3858        did_focus_panel
 3859    }
 3860
 3861    pub fn activate_panel_for_proto_id(
 3862        &mut self,
 3863        panel_id: PanelId,
 3864        window: &mut Window,
 3865        cx: &mut Context<Self>,
 3866    ) -> Option<Arc<dyn PanelHandle>> {
 3867        let mut panel = None;
 3868        for dock in self.all_docks() {
 3869            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3870                panel = dock.update(cx, |dock, cx| {
 3871                    dock.activate_panel(panel_index, window, cx);
 3872                    dock.set_open(true, window, cx);
 3873                    dock.active_panel().cloned()
 3874                });
 3875                break;
 3876            }
 3877        }
 3878
 3879        if panel.is_some() {
 3880            cx.notify();
 3881            self.serialize_workspace(window, cx);
 3882        }
 3883
 3884        panel
 3885    }
 3886
 3887    /// Focus or unfocus the given panel type, depending on the given callback.
 3888    fn focus_or_unfocus_panel<T: Panel>(
 3889        &mut self,
 3890        window: &mut Window,
 3891        cx: &mut Context<Self>,
 3892        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3893    ) -> Option<Arc<dyn PanelHandle>> {
 3894        let mut result_panel = None;
 3895        let mut serialize = false;
 3896        for dock in self.all_docks() {
 3897            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3898                let mut focus_center = false;
 3899                let panel = dock.update(cx, |dock, cx| {
 3900                    dock.activate_panel(panel_index, window, cx);
 3901
 3902                    let panel = dock.active_panel().cloned();
 3903                    if let Some(panel) = panel.as_ref() {
 3904                        if should_focus(&**panel, window, cx) {
 3905                            dock.set_open(true, window, cx);
 3906                            panel.panel_focus_handle(cx).focus(window, cx);
 3907                        } else {
 3908                            focus_center = true;
 3909                        }
 3910                    }
 3911                    panel
 3912                });
 3913
 3914                if focus_center {
 3915                    self.active_pane
 3916                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3917                }
 3918
 3919                result_panel = panel;
 3920                serialize = true;
 3921                break;
 3922            }
 3923        }
 3924
 3925        if serialize {
 3926            self.serialize_workspace(window, cx);
 3927        }
 3928
 3929        cx.notify();
 3930        result_panel
 3931    }
 3932
 3933    /// Open the panel of the given type
 3934    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3935        for dock in self.all_docks() {
 3936            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3937                dock.update(cx, |dock, cx| {
 3938                    dock.activate_panel(panel_index, window, cx);
 3939                    dock.set_open(true, window, cx);
 3940                });
 3941            }
 3942        }
 3943    }
 3944
 3945    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3946        for dock in self.all_docks().iter() {
 3947            dock.update(cx, |dock, cx| {
 3948                if dock.panel::<T>().is_some() {
 3949                    dock.set_open(false, window, cx)
 3950                }
 3951            })
 3952        }
 3953    }
 3954
 3955    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3956        self.all_docks()
 3957            .iter()
 3958            .find_map(|dock| dock.read(cx).panel::<T>())
 3959    }
 3960
 3961    fn dismiss_zoomed_items_to_reveal(
 3962        &mut self,
 3963        dock_to_reveal: Option<DockPosition>,
 3964        window: &mut Window,
 3965        cx: &mut Context<Self>,
 3966    ) {
 3967        // If a center pane is zoomed, unzoom it.
 3968        for pane in &self.panes {
 3969            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3970                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3971            }
 3972        }
 3973
 3974        // If another dock is zoomed, hide it.
 3975        let mut focus_center = false;
 3976        for dock in self.all_docks() {
 3977            dock.update(cx, |dock, cx| {
 3978                if Some(dock.position()) != dock_to_reveal
 3979                    && let Some(panel) = dock.active_panel()
 3980                    && panel.is_zoomed(window, cx)
 3981                {
 3982                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3983                    dock.set_open(false, window, cx);
 3984                }
 3985            });
 3986        }
 3987
 3988        if focus_center {
 3989            self.active_pane
 3990                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3991        }
 3992
 3993        if self.zoomed_position != dock_to_reveal {
 3994            self.zoomed = None;
 3995            self.zoomed_position = None;
 3996            cx.emit(Event::ZoomChanged);
 3997        }
 3998
 3999        cx.notify();
 4000    }
 4001
 4002    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4003        let pane = cx.new(|cx| {
 4004            let mut pane = Pane::new(
 4005                self.weak_handle(),
 4006                self.project.clone(),
 4007                self.pane_history_timestamp.clone(),
 4008                None,
 4009                NewFile.boxed_clone(),
 4010                true,
 4011                window,
 4012                cx,
 4013            );
 4014            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4015            pane
 4016        });
 4017        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4018            .detach();
 4019        self.panes.push(pane.clone());
 4020
 4021        window.focus(&pane.focus_handle(cx), cx);
 4022
 4023        cx.emit(Event::PaneAdded(pane.clone()));
 4024        pane
 4025    }
 4026
 4027    pub fn add_item_to_center(
 4028        &mut self,
 4029        item: Box<dyn ItemHandle>,
 4030        window: &mut Window,
 4031        cx: &mut Context<Self>,
 4032    ) -> bool {
 4033        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4034            if let Some(center_pane) = center_pane.upgrade() {
 4035                center_pane.update(cx, |pane, cx| {
 4036                    pane.add_item(item, true, true, None, window, cx)
 4037                });
 4038                true
 4039            } else {
 4040                false
 4041            }
 4042        } else {
 4043            false
 4044        }
 4045    }
 4046
 4047    pub fn add_item_to_active_pane(
 4048        &mut self,
 4049        item: Box<dyn ItemHandle>,
 4050        destination_index: Option<usize>,
 4051        focus_item: bool,
 4052        window: &mut Window,
 4053        cx: &mut App,
 4054    ) {
 4055        self.add_item(
 4056            self.active_pane.clone(),
 4057            item,
 4058            destination_index,
 4059            false,
 4060            focus_item,
 4061            window,
 4062            cx,
 4063        )
 4064    }
 4065
 4066    pub fn add_item(
 4067        &mut self,
 4068        pane: Entity<Pane>,
 4069        item: Box<dyn ItemHandle>,
 4070        destination_index: Option<usize>,
 4071        activate_pane: bool,
 4072        focus_item: bool,
 4073        window: &mut Window,
 4074        cx: &mut App,
 4075    ) {
 4076        pane.update(cx, |pane, cx| {
 4077            pane.add_item(
 4078                item,
 4079                activate_pane,
 4080                focus_item,
 4081                destination_index,
 4082                window,
 4083                cx,
 4084            )
 4085        });
 4086    }
 4087
 4088    pub fn split_item(
 4089        &mut self,
 4090        split_direction: SplitDirection,
 4091        item: Box<dyn ItemHandle>,
 4092        window: &mut Window,
 4093        cx: &mut Context<Self>,
 4094    ) {
 4095        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4096        self.add_item(new_pane, item, None, true, true, window, cx);
 4097    }
 4098
 4099    pub fn open_abs_path(
 4100        &mut self,
 4101        abs_path: PathBuf,
 4102        options: OpenOptions,
 4103        window: &mut Window,
 4104        cx: &mut Context<Self>,
 4105    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4106        cx.spawn_in(window, async move |workspace, cx| {
 4107            let open_paths_task_result = workspace
 4108                .update_in(cx, |workspace, window, cx| {
 4109                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4110                })
 4111                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4112                .await;
 4113            anyhow::ensure!(
 4114                open_paths_task_result.len() == 1,
 4115                "open abs path {abs_path:?} task returned incorrect number of results"
 4116            );
 4117            match open_paths_task_result
 4118                .into_iter()
 4119                .next()
 4120                .expect("ensured single task result")
 4121            {
 4122                Some(open_result) => {
 4123                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4124                }
 4125                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4126            }
 4127        })
 4128    }
 4129
 4130    pub fn split_abs_path(
 4131        &mut self,
 4132        abs_path: PathBuf,
 4133        visible: bool,
 4134        window: &mut Window,
 4135        cx: &mut Context<Self>,
 4136    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4137        let project_path_task =
 4138            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4139        cx.spawn_in(window, async move |this, cx| {
 4140            let (_, path) = project_path_task.await?;
 4141            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4142                .await
 4143        })
 4144    }
 4145
 4146    pub fn open_path(
 4147        &mut self,
 4148        path: impl Into<ProjectPath>,
 4149        pane: Option<WeakEntity<Pane>>,
 4150        focus_item: bool,
 4151        window: &mut Window,
 4152        cx: &mut App,
 4153    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4154        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4155    }
 4156
 4157    pub fn open_path_preview(
 4158        &mut self,
 4159        path: impl Into<ProjectPath>,
 4160        pane: Option<WeakEntity<Pane>>,
 4161        focus_item: bool,
 4162        allow_preview: bool,
 4163        activate: bool,
 4164        window: &mut Window,
 4165        cx: &mut App,
 4166    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4167        let pane = pane.unwrap_or_else(|| {
 4168            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4169                self.panes
 4170                    .first()
 4171                    .expect("There must be an active pane")
 4172                    .downgrade()
 4173            })
 4174        });
 4175
 4176        let project_path = path.into();
 4177        let task = self.load_path(project_path.clone(), window, cx);
 4178        window.spawn(cx, async move |cx| {
 4179            let (project_entry_id, build_item) = task.await?;
 4180
 4181            pane.update_in(cx, |pane, window, cx| {
 4182                pane.open_item(
 4183                    project_entry_id,
 4184                    project_path,
 4185                    focus_item,
 4186                    allow_preview,
 4187                    activate,
 4188                    None,
 4189                    window,
 4190                    cx,
 4191                    build_item,
 4192                )
 4193            })
 4194        })
 4195    }
 4196
 4197    pub fn split_path(
 4198        &mut self,
 4199        path: impl Into<ProjectPath>,
 4200        window: &mut Window,
 4201        cx: &mut Context<Self>,
 4202    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4203        self.split_path_preview(path, false, None, window, cx)
 4204    }
 4205
 4206    pub fn split_path_preview(
 4207        &mut self,
 4208        path: impl Into<ProjectPath>,
 4209        allow_preview: bool,
 4210        split_direction: Option<SplitDirection>,
 4211        window: &mut Window,
 4212        cx: &mut Context<Self>,
 4213    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4214        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4215            self.panes
 4216                .first()
 4217                .expect("There must be an active pane")
 4218                .downgrade()
 4219        });
 4220
 4221        if let Member::Pane(center_pane) = &self.center.root
 4222            && center_pane.read(cx).items_len() == 0
 4223        {
 4224            return self.open_path(path, Some(pane), true, window, cx);
 4225        }
 4226
 4227        let project_path = path.into();
 4228        let task = self.load_path(project_path.clone(), window, cx);
 4229        cx.spawn_in(window, async move |this, cx| {
 4230            let (project_entry_id, build_item) = task.await?;
 4231            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4232                let pane = pane.upgrade()?;
 4233                let new_pane = this.split_pane(
 4234                    pane,
 4235                    split_direction.unwrap_or(SplitDirection::Right),
 4236                    window,
 4237                    cx,
 4238                );
 4239                new_pane.update(cx, |new_pane, cx| {
 4240                    Some(new_pane.open_item(
 4241                        project_entry_id,
 4242                        project_path,
 4243                        true,
 4244                        allow_preview,
 4245                        true,
 4246                        None,
 4247                        window,
 4248                        cx,
 4249                        build_item,
 4250                    ))
 4251                })
 4252            })
 4253            .map(|option| option.context("pane was dropped"))?
 4254        })
 4255    }
 4256
 4257    fn load_path(
 4258        &mut self,
 4259        path: ProjectPath,
 4260        window: &mut Window,
 4261        cx: &mut App,
 4262    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4263        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4264        registry.open_path(self.project(), &path, window, cx)
 4265    }
 4266
 4267    pub fn find_project_item<T>(
 4268        &self,
 4269        pane: &Entity<Pane>,
 4270        project_item: &Entity<T::Item>,
 4271        cx: &App,
 4272    ) -> Option<Entity<T>>
 4273    where
 4274        T: ProjectItem,
 4275    {
 4276        use project::ProjectItem as _;
 4277        let project_item = project_item.read(cx);
 4278        let entry_id = project_item.entry_id(cx);
 4279        let project_path = project_item.project_path(cx);
 4280
 4281        let mut item = None;
 4282        if let Some(entry_id) = entry_id {
 4283            item = pane.read(cx).item_for_entry(entry_id, cx);
 4284        }
 4285        if item.is_none()
 4286            && let Some(project_path) = project_path
 4287        {
 4288            item = pane.read(cx).item_for_path(project_path, cx);
 4289        }
 4290
 4291        item.and_then(|item| item.downcast::<T>())
 4292    }
 4293
 4294    pub fn is_project_item_open<T>(
 4295        &self,
 4296        pane: &Entity<Pane>,
 4297        project_item: &Entity<T::Item>,
 4298        cx: &App,
 4299    ) -> bool
 4300    where
 4301        T: ProjectItem,
 4302    {
 4303        self.find_project_item::<T>(pane, project_item, cx)
 4304            .is_some()
 4305    }
 4306
 4307    pub fn open_project_item<T>(
 4308        &mut self,
 4309        pane: Entity<Pane>,
 4310        project_item: Entity<T::Item>,
 4311        activate_pane: bool,
 4312        focus_item: bool,
 4313        keep_old_preview: bool,
 4314        allow_new_preview: bool,
 4315        window: &mut Window,
 4316        cx: &mut Context<Self>,
 4317    ) -> Entity<T>
 4318    where
 4319        T: ProjectItem,
 4320    {
 4321        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4322
 4323        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4324            if !keep_old_preview
 4325                && let Some(old_id) = old_item_id
 4326                && old_id != item.item_id()
 4327            {
 4328                // switching to a different item, so unpreview old active item
 4329                pane.update(cx, |pane, _| {
 4330                    pane.unpreview_item_if_preview(old_id);
 4331                });
 4332            }
 4333
 4334            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4335            if !allow_new_preview {
 4336                pane.update(cx, |pane, _| {
 4337                    pane.unpreview_item_if_preview(item.item_id());
 4338                });
 4339            }
 4340            return item;
 4341        }
 4342
 4343        let item = pane.update(cx, |pane, cx| {
 4344            cx.new(|cx| {
 4345                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4346            })
 4347        });
 4348        let mut destination_index = None;
 4349        pane.update(cx, |pane, cx| {
 4350            if !keep_old_preview && let Some(old_id) = old_item_id {
 4351                pane.unpreview_item_if_preview(old_id);
 4352            }
 4353            if allow_new_preview {
 4354                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4355            }
 4356        });
 4357
 4358        self.add_item(
 4359            pane,
 4360            Box::new(item.clone()),
 4361            destination_index,
 4362            activate_pane,
 4363            focus_item,
 4364            window,
 4365            cx,
 4366        );
 4367        item
 4368    }
 4369
 4370    pub fn open_shared_screen(
 4371        &mut self,
 4372        peer_id: PeerId,
 4373        window: &mut Window,
 4374        cx: &mut Context<Self>,
 4375    ) {
 4376        if let Some(shared_screen) =
 4377            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4378        {
 4379            self.active_pane.update(cx, |pane, cx| {
 4380                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4381            });
 4382        }
 4383    }
 4384
 4385    pub fn activate_item(
 4386        &mut self,
 4387        item: &dyn ItemHandle,
 4388        activate_pane: bool,
 4389        focus_item: bool,
 4390        window: &mut Window,
 4391        cx: &mut App,
 4392    ) -> bool {
 4393        let result = self.panes.iter().find_map(|pane| {
 4394            pane.read(cx)
 4395                .index_for_item(item)
 4396                .map(|ix| (pane.clone(), ix))
 4397        });
 4398        if let Some((pane, ix)) = result {
 4399            pane.update(cx, |pane, cx| {
 4400                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4401            });
 4402            true
 4403        } else {
 4404            false
 4405        }
 4406    }
 4407
 4408    fn activate_pane_at_index(
 4409        &mut self,
 4410        action: &ActivatePane,
 4411        window: &mut Window,
 4412        cx: &mut Context<Self>,
 4413    ) {
 4414        let panes = self.center.panes();
 4415        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4416            window.focus(&pane.focus_handle(cx), cx);
 4417        } else {
 4418            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4419                .detach();
 4420        }
 4421    }
 4422
 4423    fn move_item_to_pane_at_index(
 4424        &mut self,
 4425        action: &MoveItemToPane,
 4426        window: &mut Window,
 4427        cx: &mut Context<Self>,
 4428    ) {
 4429        let panes = self.center.panes();
 4430        let destination = match panes.get(action.destination) {
 4431            Some(&destination) => destination.clone(),
 4432            None => {
 4433                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4434                    return;
 4435                }
 4436                let direction = SplitDirection::Right;
 4437                let split_off_pane = self
 4438                    .find_pane_in_direction(direction, cx)
 4439                    .unwrap_or_else(|| self.active_pane.clone());
 4440                let new_pane = self.add_pane(window, cx);
 4441                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4442                new_pane
 4443            }
 4444        };
 4445
 4446        if action.clone {
 4447            if self
 4448                .active_pane
 4449                .read(cx)
 4450                .active_item()
 4451                .is_some_and(|item| item.can_split(cx))
 4452            {
 4453                clone_active_item(
 4454                    self.database_id(),
 4455                    &self.active_pane,
 4456                    &destination,
 4457                    action.focus,
 4458                    window,
 4459                    cx,
 4460                );
 4461                return;
 4462            }
 4463        }
 4464        move_active_item(
 4465            &self.active_pane,
 4466            &destination,
 4467            action.focus,
 4468            true,
 4469            window,
 4470            cx,
 4471        )
 4472    }
 4473
 4474    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4475        let panes = self.center.panes();
 4476        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4477            let next_ix = (ix + 1) % panes.len();
 4478            let next_pane = panes[next_ix].clone();
 4479            window.focus(&next_pane.focus_handle(cx), cx);
 4480        }
 4481    }
 4482
 4483    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4484        let panes = self.center.panes();
 4485        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4486            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4487            let prev_pane = panes[prev_ix].clone();
 4488            window.focus(&prev_pane.focus_handle(cx), cx);
 4489        }
 4490    }
 4491
 4492    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4493        let last_pane = self.center.last_pane();
 4494        window.focus(&last_pane.focus_handle(cx), cx);
 4495    }
 4496
 4497    pub fn activate_pane_in_direction(
 4498        &mut self,
 4499        direction: SplitDirection,
 4500        window: &mut Window,
 4501        cx: &mut App,
 4502    ) {
 4503        use ActivateInDirectionTarget as Target;
 4504        enum Origin {
 4505            LeftDock,
 4506            RightDock,
 4507            BottomDock,
 4508            Center,
 4509        }
 4510
 4511        let origin: Origin = [
 4512            (&self.left_dock, Origin::LeftDock),
 4513            (&self.right_dock, Origin::RightDock),
 4514            (&self.bottom_dock, Origin::BottomDock),
 4515        ]
 4516        .into_iter()
 4517        .find_map(|(dock, origin)| {
 4518            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4519                Some(origin)
 4520            } else {
 4521                None
 4522            }
 4523        })
 4524        .unwrap_or(Origin::Center);
 4525
 4526        let get_last_active_pane = || {
 4527            let pane = self
 4528                .last_active_center_pane
 4529                .clone()
 4530                .unwrap_or_else(|| {
 4531                    self.panes
 4532                        .first()
 4533                        .expect("There must be an active pane")
 4534                        .downgrade()
 4535                })
 4536                .upgrade()?;
 4537            (pane.read(cx).items_len() != 0).then_some(pane)
 4538        };
 4539
 4540        let try_dock =
 4541            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4542
 4543        let target = match (origin, direction) {
 4544            // We're in the center, so we first try to go to a different pane,
 4545            // otherwise try to go to a dock.
 4546            (Origin::Center, direction) => {
 4547                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4548                    Some(Target::Pane(pane))
 4549                } else {
 4550                    match direction {
 4551                        SplitDirection::Up => None,
 4552                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4553                        SplitDirection::Left => try_dock(&self.left_dock),
 4554                        SplitDirection::Right => try_dock(&self.right_dock),
 4555                    }
 4556                }
 4557            }
 4558
 4559            (Origin::LeftDock, SplitDirection::Right) => {
 4560                if let Some(last_active_pane) = get_last_active_pane() {
 4561                    Some(Target::Pane(last_active_pane))
 4562                } else {
 4563                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4564                }
 4565            }
 4566
 4567            (Origin::LeftDock, SplitDirection::Down)
 4568            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4569
 4570            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4571            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4572            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4573
 4574            (Origin::RightDock, SplitDirection::Left) => {
 4575                if let Some(last_active_pane) = get_last_active_pane() {
 4576                    Some(Target::Pane(last_active_pane))
 4577                } else {
 4578                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4579                }
 4580            }
 4581
 4582            _ => None,
 4583        };
 4584
 4585        match target {
 4586            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4587                let pane = pane.read(cx);
 4588                if let Some(item) = pane.active_item() {
 4589                    item.item_focus_handle(cx).focus(window, cx);
 4590                } else {
 4591                    log::error!(
 4592                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4593                    );
 4594                }
 4595            }
 4596            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4597                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4598                window.defer(cx, move |window, cx| {
 4599                    let dock = dock.read(cx);
 4600                    if let Some(panel) = dock.active_panel() {
 4601                        panel.panel_focus_handle(cx).focus(window, cx);
 4602                    } else {
 4603                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4604                    }
 4605                })
 4606            }
 4607            None => {}
 4608        }
 4609    }
 4610
 4611    pub fn move_item_to_pane_in_direction(
 4612        &mut self,
 4613        action: &MoveItemToPaneInDirection,
 4614        window: &mut Window,
 4615        cx: &mut Context<Self>,
 4616    ) {
 4617        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4618            Some(destination) => destination,
 4619            None => {
 4620                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4621                    return;
 4622                }
 4623                let new_pane = self.add_pane(window, cx);
 4624                self.center
 4625                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4626                new_pane
 4627            }
 4628        };
 4629
 4630        if action.clone {
 4631            if self
 4632                .active_pane
 4633                .read(cx)
 4634                .active_item()
 4635                .is_some_and(|item| item.can_split(cx))
 4636            {
 4637                clone_active_item(
 4638                    self.database_id(),
 4639                    &self.active_pane,
 4640                    &destination,
 4641                    action.focus,
 4642                    window,
 4643                    cx,
 4644                );
 4645                return;
 4646            }
 4647        }
 4648        move_active_item(
 4649            &self.active_pane,
 4650            &destination,
 4651            action.focus,
 4652            true,
 4653            window,
 4654            cx,
 4655        );
 4656    }
 4657
 4658    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4659        self.center.bounding_box_for_pane(pane)
 4660    }
 4661
 4662    pub fn find_pane_in_direction(
 4663        &mut self,
 4664        direction: SplitDirection,
 4665        cx: &App,
 4666    ) -> Option<Entity<Pane>> {
 4667        self.center
 4668            .find_pane_in_direction(&self.active_pane, direction, cx)
 4669            .cloned()
 4670    }
 4671
 4672    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4673        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4674            self.center.swap(&self.active_pane, &to, cx);
 4675            cx.notify();
 4676        }
 4677    }
 4678
 4679    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4680        if self
 4681            .center
 4682            .move_to_border(&self.active_pane, direction, cx)
 4683            .unwrap()
 4684        {
 4685            cx.notify();
 4686        }
 4687    }
 4688
 4689    pub fn resize_pane(
 4690        &mut self,
 4691        axis: gpui::Axis,
 4692        amount: Pixels,
 4693        window: &mut Window,
 4694        cx: &mut Context<Self>,
 4695    ) {
 4696        let docks = self.all_docks();
 4697        let active_dock = docks
 4698            .into_iter()
 4699            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4700
 4701        if let Some(dock) = active_dock {
 4702            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4703                return;
 4704            };
 4705            match dock.read(cx).position() {
 4706                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4707                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4708                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4709            }
 4710        } else {
 4711            self.center
 4712                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4713        }
 4714        cx.notify();
 4715    }
 4716
 4717    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4718        self.center.reset_pane_sizes(cx);
 4719        cx.notify();
 4720    }
 4721
 4722    fn handle_pane_focused(
 4723        &mut self,
 4724        pane: Entity<Pane>,
 4725        window: &mut Window,
 4726        cx: &mut Context<Self>,
 4727    ) {
 4728        // This is explicitly hoisted out of the following check for pane identity as
 4729        // terminal panel panes are not registered as a center panes.
 4730        self.status_bar.update(cx, |status_bar, cx| {
 4731            status_bar.set_active_pane(&pane, window, cx);
 4732        });
 4733        if self.active_pane != pane {
 4734            self.set_active_pane(&pane, window, cx);
 4735        }
 4736
 4737        if self.last_active_center_pane.is_none() {
 4738            self.last_active_center_pane = Some(pane.downgrade());
 4739        }
 4740
 4741        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4742        // This prevents the dock from closing when focus events fire during window activation.
 4743        // We also preserve any dock whose active panel itself has focus — this covers
 4744        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4745        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4746            let dock_read = dock.read(cx);
 4747            if let Some(panel) = dock_read.active_panel() {
 4748                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4749                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4750                {
 4751                    return Some(dock_read.position());
 4752                }
 4753            }
 4754            None
 4755        });
 4756
 4757        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4758        if pane.read(cx).is_zoomed() {
 4759            self.zoomed = Some(pane.downgrade().into());
 4760        } else {
 4761            self.zoomed = None;
 4762        }
 4763        self.zoomed_position = None;
 4764        cx.emit(Event::ZoomChanged);
 4765        self.update_active_view_for_followers(window, cx);
 4766        pane.update(cx, |pane, _| {
 4767            pane.track_alternate_file_items();
 4768        });
 4769
 4770        cx.notify();
 4771    }
 4772
 4773    fn set_active_pane(
 4774        &mut self,
 4775        pane: &Entity<Pane>,
 4776        window: &mut Window,
 4777        cx: &mut Context<Self>,
 4778    ) {
 4779        self.active_pane = pane.clone();
 4780        self.active_item_path_changed(true, window, cx);
 4781        self.last_active_center_pane = Some(pane.downgrade());
 4782    }
 4783
 4784    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4785        self.update_active_view_for_followers(window, cx);
 4786    }
 4787
 4788    fn handle_pane_event(
 4789        &mut self,
 4790        pane: &Entity<Pane>,
 4791        event: &pane::Event,
 4792        window: &mut Window,
 4793        cx: &mut Context<Self>,
 4794    ) {
 4795        let mut serialize_workspace = true;
 4796        match event {
 4797            pane::Event::AddItem { item } => {
 4798                item.added_to_pane(self, pane.clone(), window, cx);
 4799                cx.emit(Event::ItemAdded {
 4800                    item: item.boxed_clone(),
 4801                });
 4802            }
 4803            pane::Event::Split { direction, mode } => {
 4804                match mode {
 4805                    SplitMode::ClonePane => {
 4806                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4807                            .detach();
 4808                    }
 4809                    SplitMode::EmptyPane => {
 4810                        self.split_pane(pane.clone(), *direction, window, cx);
 4811                    }
 4812                    SplitMode::MovePane => {
 4813                        self.split_and_move(pane.clone(), *direction, window, cx);
 4814                    }
 4815                };
 4816            }
 4817            pane::Event::JoinIntoNext => {
 4818                self.join_pane_into_next(pane.clone(), window, cx);
 4819            }
 4820            pane::Event::JoinAll => {
 4821                self.join_all_panes(window, cx);
 4822            }
 4823            pane::Event::Remove { focus_on_pane } => {
 4824                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4825            }
 4826            pane::Event::ActivateItem {
 4827                local,
 4828                focus_changed,
 4829            } => {
 4830                window.invalidate_character_coordinates();
 4831
 4832                pane.update(cx, |pane, _| {
 4833                    pane.track_alternate_file_items();
 4834                });
 4835                if *local {
 4836                    self.unfollow_in_pane(pane, window, cx);
 4837                }
 4838                serialize_workspace = *focus_changed || pane != self.active_pane();
 4839                if pane == self.active_pane() {
 4840                    self.active_item_path_changed(*focus_changed, window, cx);
 4841                    self.update_active_view_for_followers(window, cx);
 4842                } else if *local {
 4843                    self.set_active_pane(pane, window, cx);
 4844                }
 4845            }
 4846            pane::Event::UserSavedItem { item, save_intent } => {
 4847                cx.emit(Event::UserSavedItem {
 4848                    pane: pane.downgrade(),
 4849                    item: item.boxed_clone(),
 4850                    save_intent: *save_intent,
 4851                });
 4852                serialize_workspace = false;
 4853            }
 4854            pane::Event::ChangeItemTitle => {
 4855                if *pane == self.active_pane {
 4856                    self.active_item_path_changed(false, window, cx);
 4857                }
 4858                serialize_workspace = false;
 4859            }
 4860            pane::Event::RemovedItem { item } => {
 4861                cx.emit(Event::ActiveItemChanged);
 4862                self.update_window_edited(window, cx);
 4863                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4864                    && entry.get().entity_id() == pane.entity_id()
 4865                {
 4866                    entry.remove();
 4867                }
 4868                cx.emit(Event::ItemRemoved {
 4869                    item_id: item.item_id(),
 4870                });
 4871            }
 4872            pane::Event::Focus => {
 4873                window.invalidate_character_coordinates();
 4874                self.handle_pane_focused(pane.clone(), window, cx);
 4875            }
 4876            pane::Event::ZoomIn => {
 4877                if *pane == self.active_pane {
 4878                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4879                    if pane.read(cx).has_focus(window, cx) {
 4880                        self.zoomed = Some(pane.downgrade().into());
 4881                        self.zoomed_position = None;
 4882                        cx.emit(Event::ZoomChanged);
 4883                    }
 4884                    cx.notify();
 4885                }
 4886            }
 4887            pane::Event::ZoomOut => {
 4888                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4889                if self.zoomed_position.is_none() {
 4890                    self.zoomed = None;
 4891                    cx.emit(Event::ZoomChanged);
 4892                }
 4893                cx.notify();
 4894            }
 4895            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4896        }
 4897
 4898        if serialize_workspace {
 4899            self.serialize_workspace(window, cx);
 4900        }
 4901    }
 4902
 4903    pub fn unfollow_in_pane(
 4904        &mut self,
 4905        pane: &Entity<Pane>,
 4906        window: &mut Window,
 4907        cx: &mut Context<Workspace>,
 4908    ) -> Option<CollaboratorId> {
 4909        let leader_id = self.leader_for_pane(pane)?;
 4910        self.unfollow(leader_id, window, cx);
 4911        Some(leader_id)
 4912    }
 4913
 4914    pub fn split_pane(
 4915        &mut self,
 4916        pane_to_split: Entity<Pane>,
 4917        split_direction: SplitDirection,
 4918        window: &mut Window,
 4919        cx: &mut Context<Self>,
 4920    ) -> Entity<Pane> {
 4921        let new_pane = self.add_pane(window, cx);
 4922        self.center
 4923            .split(&pane_to_split, &new_pane, split_direction, cx);
 4924        cx.notify();
 4925        new_pane
 4926    }
 4927
 4928    pub fn split_and_move(
 4929        &mut self,
 4930        pane: Entity<Pane>,
 4931        direction: SplitDirection,
 4932        window: &mut Window,
 4933        cx: &mut Context<Self>,
 4934    ) {
 4935        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4936            return;
 4937        };
 4938        let new_pane = self.add_pane(window, cx);
 4939        new_pane.update(cx, |pane, cx| {
 4940            pane.add_item(item, true, true, None, window, cx)
 4941        });
 4942        self.center.split(&pane, &new_pane, direction, cx);
 4943        cx.notify();
 4944    }
 4945
 4946    pub fn split_and_clone(
 4947        &mut self,
 4948        pane: Entity<Pane>,
 4949        direction: SplitDirection,
 4950        window: &mut Window,
 4951        cx: &mut Context<Self>,
 4952    ) -> Task<Option<Entity<Pane>>> {
 4953        let Some(item) = pane.read(cx).active_item() else {
 4954            return Task::ready(None);
 4955        };
 4956        if !item.can_split(cx) {
 4957            return Task::ready(None);
 4958        }
 4959        let task = item.clone_on_split(self.database_id(), window, cx);
 4960        cx.spawn_in(window, async move |this, cx| {
 4961            if let Some(clone) = task.await {
 4962                this.update_in(cx, |this, window, cx| {
 4963                    let new_pane = this.add_pane(window, cx);
 4964                    let nav_history = pane.read(cx).fork_nav_history();
 4965                    new_pane.update(cx, |pane, cx| {
 4966                        pane.set_nav_history(nav_history, cx);
 4967                        pane.add_item(clone, true, true, None, window, cx)
 4968                    });
 4969                    this.center.split(&pane, &new_pane, direction, cx);
 4970                    cx.notify();
 4971                    new_pane
 4972                })
 4973                .ok()
 4974            } else {
 4975                None
 4976            }
 4977        })
 4978    }
 4979
 4980    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4981        let active_item = self.active_pane.read(cx).active_item();
 4982        for pane in &self.panes {
 4983            join_pane_into_active(&self.active_pane, pane, window, cx);
 4984        }
 4985        if let Some(active_item) = active_item {
 4986            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4987        }
 4988        cx.notify();
 4989    }
 4990
 4991    pub fn join_pane_into_next(
 4992        &mut self,
 4993        pane: Entity<Pane>,
 4994        window: &mut Window,
 4995        cx: &mut Context<Self>,
 4996    ) {
 4997        let next_pane = self
 4998            .find_pane_in_direction(SplitDirection::Right, cx)
 4999            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5000            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5001            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5002        let Some(next_pane) = next_pane else {
 5003            return;
 5004        };
 5005        move_all_items(&pane, &next_pane, window, cx);
 5006        cx.notify();
 5007    }
 5008
 5009    fn remove_pane(
 5010        &mut self,
 5011        pane: Entity<Pane>,
 5012        focus_on: Option<Entity<Pane>>,
 5013        window: &mut Window,
 5014        cx: &mut Context<Self>,
 5015    ) {
 5016        if self.center.remove(&pane, cx).unwrap() {
 5017            self.force_remove_pane(&pane, &focus_on, window, cx);
 5018            self.unfollow_in_pane(&pane, window, cx);
 5019            self.last_leaders_by_pane.remove(&pane.downgrade());
 5020            for removed_item in pane.read(cx).items() {
 5021                self.panes_by_item.remove(&removed_item.item_id());
 5022            }
 5023
 5024            cx.notify();
 5025        } else {
 5026            self.active_item_path_changed(true, window, cx);
 5027        }
 5028        cx.emit(Event::PaneRemoved);
 5029    }
 5030
 5031    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5032        &mut self.panes
 5033    }
 5034
 5035    pub fn panes(&self) -> &[Entity<Pane>] {
 5036        &self.panes
 5037    }
 5038
 5039    pub fn active_pane(&self) -> &Entity<Pane> {
 5040        &self.active_pane
 5041    }
 5042
 5043    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5044        for dock in self.all_docks() {
 5045            if dock.focus_handle(cx).contains_focused(window, cx)
 5046                && let Some(pane) = dock
 5047                    .read(cx)
 5048                    .active_panel()
 5049                    .and_then(|panel| panel.pane(cx))
 5050            {
 5051                return pane;
 5052            }
 5053        }
 5054        self.active_pane().clone()
 5055    }
 5056
 5057    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5058        self.find_pane_in_direction(SplitDirection::Right, cx)
 5059            .unwrap_or_else(|| {
 5060                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5061            })
 5062    }
 5063
 5064    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5065        self.pane_for_item_id(handle.item_id())
 5066    }
 5067
 5068    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5069        let weak_pane = self.panes_by_item.get(&item_id)?;
 5070        weak_pane.upgrade()
 5071    }
 5072
 5073    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5074        self.panes
 5075            .iter()
 5076            .find(|pane| pane.entity_id() == entity_id)
 5077            .cloned()
 5078    }
 5079
 5080    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5081        self.follower_states.retain(|leader_id, state| {
 5082            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5083                for item in state.items_by_leader_view_id.values() {
 5084                    item.view.set_leader_id(None, window, cx);
 5085                }
 5086                false
 5087            } else {
 5088                true
 5089            }
 5090        });
 5091        cx.notify();
 5092    }
 5093
 5094    pub fn start_following(
 5095        &mut self,
 5096        leader_id: impl Into<CollaboratorId>,
 5097        window: &mut Window,
 5098        cx: &mut Context<Self>,
 5099    ) -> Option<Task<Result<()>>> {
 5100        let leader_id = leader_id.into();
 5101        let pane = self.active_pane().clone();
 5102
 5103        self.last_leaders_by_pane
 5104            .insert(pane.downgrade(), leader_id);
 5105        self.unfollow(leader_id, window, cx);
 5106        self.unfollow_in_pane(&pane, window, cx);
 5107        self.follower_states.insert(
 5108            leader_id,
 5109            FollowerState {
 5110                center_pane: pane.clone(),
 5111                dock_pane: None,
 5112                active_view_id: None,
 5113                items_by_leader_view_id: Default::default(),
 5114            },
 5115        );
 5116        cx.notify();
 5117
 5118        match leader_id {
 5119            CollaboratorId::PeerId(leader_peer_id) => {
 5120                let room_id = self.active_call()?.room_id(cx)?;
 5121                let project_id = self.project.read(cx).remote_id();
 5122                let request = self.app_state.client.request(proto::Follow {
 5123                    room_id,
 5124                    project_id,
 5125                    leader_id: Some(leader_peer_id),
 5126                });
 5127
 5128                Some(cx.spawn_in(window, async move |this, cx| {
 5129                    let response = request.await?;
 5130                    this.update(cx, |this, _| {
 5131                        let state = this
 5132                            .follower_states
 5133                            .get_mut(&leader_id)
 5134                            .context("following interrupted")?;
 5135                        state.active_view_id = response
 5136                            .active_view
 5137                            .as_ref()
 5138                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5139                        anyhow::Ok(())
 5140                    })??;
 5141                    if let Some(view) = response.active_view {
 5142                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5143                    }
 5144                    this.update_in(cx, |this, window, cx| {
 5145                        this.leader_updated(leader_id, window, cx)
 5146                    })?;
 5147                    Ok(())
 5148                }))
 5149            }
 5150            CollaboratorId::Agent => {
 5151                self.leader_updated(leader_id, window, cx)?;
 5152                Some(Task::ready(Ok(())))
 5153            }
 5154        }
 5155    }
 5156
 5157    pub fn follow_next_collaborator(
 5158        &mut self,
 5159        _: &FollowNextCollaborator,
 5160        window: &mut Window,
 5161        cx: &mut Context<Self>,
 5162    ) {
 5163        let collaborators = self.project.read(cx).collaborators();
 5164        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5165            let mut collaborators = collaborators.keys().copied();
 5166            for peer_id in collaborators.by_ref() {
 5167                if CollaboratorId::PeerId(peer_id) == leader_id {
 5168                    break;
 5169                }
 5170            }
 5171            collaborators.next().map(CollaboratorId::PeerId)
 5172        } else if let Some(last_leader_id) =
 5173            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5174        {
 5175            match last_leader_id {
 5176                CollaboratorId::PeerId(peer_id) => {
 5177                    if collaborators.contains_key(peer_id) {
 5178                        Some(*last_leader_id)
 5179                    } else {
 5180                        None
 5181                    }
 5182                }
 5183                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5184            }
 5185        } else {
 5186            None
 5187        };
 5188
 5189        let pane = self.active_pane.clone();
 5190        let Some(leader_id) = next_leader_id.or_else(|| {
 5191            Some(CollaboratorId::PeerId(
 5192                collaborators.keys().copied().next()?,
 5193            ))
 5194        }) else {
 5195            return;
 5196        };
 5197        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5198            return;
 5199        }
 5200        if let Some(task) = self.start_following(leader_id, window, cx) {
 5201            task.detach_and_log_err(cx)
 5202        }
 5203    }
 5204
 5205    pub fn follow(
 5206        &mut self,
 5207        leader_id: impl Into<CollaboratorId>,
 5208        window: &mut Window,
 5209        cx: &mut Context<Self>,
 5210    ) {
 5211        let leader_id = leader_id.into();
 5212
 5213        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5214            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5215                return;
 5216            };
 5217            let Some(remote_participant) =
 5218                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5219            else {
 5220                return;
 5221            };
 5222
 5223            let project = self.project.read(cx);
 5224
 5225            let other_project_id = match remote_participant.location {
 5226                ParticipantLocation::External => None,
 5227                ParticipantLocation::UnsharedProject => None,
 5228                ParticipantLocation::SharedProject { project_id } => {
 5229                    if Some(project_id) == project.remote_id() {
 5230                        None
 5231                    } else {
 5232                        Some(project_id)
 5233                    }
 5234                }
 5235            };
 5236
 5237            // if they are active in another project, follow there.
 5238            if let Some(project_id) = other_project_id {
 5239                let app_state = self.app_state.clone();
 5240                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5241                    .detach_and_log_err(cx);
 5242            }
 5243        }
 5244
 5245        // if you're already following, find the right pane and focus it.
 5246        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5247            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5248
 5249            return;
 5250        }
 5251
 5252        // Otherwise, follow.
 5253        if let Some(task) = self.start_following(leader_id, window, cx) {
 5254            task.detach_and_log_err(cx)
 5255        }
 5256    }
 5257
 5258    pub fn unfollow(
 5259        &mut self,
 5260        leader_id: impl Into<CollaboratorId>,
 5261        window: &mut Window,
 5262        cx: &mut Context<Self>,
 5263    ) -> Option<()> {
 5264        cx.notify();
 5265
 5266        let leader_id = leader_id.into();
 5267        let state = self.follower_states.remove(&leader_id)?;
 5268        for (_, item) in state.items_by_leader_view_id {
 5269            item.view.set_leader_id(None, window, cx);
 5270        }
 5271
 5272        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5273            let project_id = self.project.read(cx).remote_id();
 5274            let room_id = self.active_call()?.room_id(cx)?;
 5275            self.app_state
 5276                .client
 5277                .send(proto::Unfollow {
 5278                    room_id,
 5279                    project_id,
 5280                    leader_id: Some(leader_peer_id),
 5281                })
 5282                .log_err();
 5283        }
 5284
 5285        Some(())
 5286    }
 5287
 5288    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5289        self.follower_states.contains_key(&id.into())
 5290    }
 5291
 5292    fn active_item_path_changed(
 5293        &mut self,
 5294        focus_changed: bool,
 5295        window: &mut Window,
 5296        cx: &mut Context<Self>,
 5297    ) {
 5298        cx.emit(Event::ActiveItemChanged);
 5299        let active_entry = self.active_project_path(cx);
 5300        self.project.update(cx, |project, cx| {
 5301            project.set_active_path(active_entry.clone(), cx)
 5302        });
 5303
 5304        if focus_changed && let Some(project_path) = &active_entry {
 5305            let git_store_entity = self.project.read(cx).git_store().clone();
 5306            git_store_entity.update(cx, |git_store, cx| {
 5307                git_store.set_active_repo_for_path(project_path, cx);
 5308            });
 5309        }
 5310
 5311        self.update_window_title(window, cx);
 5312    }
 5313
 5314    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5315        let project = self.project().read(cx);
 5316        let mut title = String::new();
 5317
 5318        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5319            let name = {
 5320                let settings_location = SettingsLocation {
 5321                    worktree_id: worktree.read(cx).id(),
 5322                    path: RelPath::empty(),
 5323                };
 5324
 5325                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5326                match &settings.project_name {
 5327                    Some(name) => name.as_str(),
 5328                    None => worktree.read(cx).root_name_str(),
 5329                }
 5330            };
 5331            if i > 0 {
 5332                title.push_str(", ");
 5333            }
 5334            title.push_str(name);
 5335        }
 5336
 5337        if title.is_empty() {
 5338            title = "empty project".to_string();
 5339        }
 5340
 5341        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5342            let filename = path.path.file_name().or_else(|| {
 5343                Some(
 5344                    project
 5345                        .worktree_for_id(path.worktree_id, cx)?
 5346                        .read(cx)
 5347                        .root_name_str(),
 5348                )
 5349            });
 5350
 5351            if let Some(filename) = filename {
 5352                title.push_str("");
 5353                title.push_str(filename.as_ref());
 5354            }
 5355        }
 5356
 5357        if project.is_via_collab() {
 5358            title.push_str("");
 5359        } else if project.is_shared() {
 5360            title.push_str("");
 5361        }
 5362
 5363        if let Some(last_title) = self.last_window_title.as_ref()
 5364            && &title == last_title
 5365        {
 5366            return;
 5367        }
 5368        window.set_window_title(&title);
 5369        SystemWindowTabController::update_tab_title(
 5370            cx,
 5371            window.window_handle().window_id(),
 5372            SharedString::from(&title),
 5373        );
 5374        self.last_window_title = Some(title);
 5375    }
 5376
 5377    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5378        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5379        if is_edited != self.window_edited {
 5380            self.window_edited = is_edited;
 5381            window.set_window_edited(self.window_edited)
 5382        }
 5383    }
 5384
 5385    fn update_item_dirty_state(
 5386        &mut self,
 5387        item: &dyn ItemHandle,
 5388        window: &mut Window,
 5389        cx: &mut App,
 5390    ) {
 5391        let is_dirty = item.is_dirty(cx);
 5392        let item_id = item.item_id();
 5393        let was_dirty = self.dirty_items.contains_key(&item_id);
 5394        if is_dirty == was_dirty {
 5395            return;
 5396        }
 5397        if was_dirty {
 5398            self.dirty_items.remove(&item_id);
 5399            self.update_window_edited(window, cx);
 5400            return;
 5401        }
 5402
 5403        let workspace = self.weak_handle();
 5404        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5405            return;
 5406        };
 5407        let on_release_callback = Box::new(move |cx: &mut App| {
 5408            window_handle
 5409                .update(cx, |_, window, cx| {
 5410                    workspace
 5411                        .update(cx, |workspace, cx| {
 5412                            workspace.dirty_items.remove(&item_id);
 5413                            workspace.update_window_edited(window, cx)
 5414                        })
 5415                        .ok();
 5416                })
 5417                .ok();
 5418        });
 5419
 5420        let s = item.on_release(cx, on_release_callback);
 5421        self.dirty_items.insert(item_id, s);
 5422        self.update_window_edited(window, cx);
 5423    }
 5424
 5425    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5426        if self.notifications.is_empty() {
 5427            None
 5428        } else {
 5429            Some(
 5430                div()
 5431                    .absolute()
 5432                    .right_3()
 5433                    .bottom_3()
 5434                    .w_112()
 5435                    .h_full()
 5436                    .flex()
 5437                    .flex_col()
 5438                    .justify_end()
 5439                    .gap_2()
 5440                    .children(
 5441                        self.notifications
 5442                            .iter()
 5443                            .map(|(_, notification)| notification.clone().into_any()),
 5444                    ),
 5445            )
 5446        }
 5447    }
 5448
 5449    // RPC handlers
 5450
 5451    fn active_view_for_follower(
 5452        &self,
 5453        follower_project_id: Option<u64>,
 5454        window: &mut Window,
 5455        cx: &mut Context<Self>,
 5456    ) -> Option<proto::View> {
 5457        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5458        let item = item?;
 5459        let leader_id = self
 5460            .pane_for(&*item)
 5461            .and_then(|pane| self.leader_for_pane(&pane));
 5462        let leader_peer_id = match leader_id {
 5463            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5464            Some(CollaboratorId::Agent) | None => None,
 5465        };
 5466
 5467        let item_handle = item.to_followable_item_handle(cx)?;
 5468        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5469        let variant = item_handle.to_state_proto(window, cx)?;
 5470
 5471        if item_handle.is_project_item(window, cx)
 5472            && (follower_project_id.is_none()
 5473                || follower_project_id != self.project.read(cx).remote_id())
 5474        {
 5475            return None;
 5476        }
 5477
 5478        Some(proto::View {
 5479            id: id.to_proto(),
 5480            leader_id: leader_peer_id,
 5481            variant: Some(variant),
 5482            panel_id: panel_id.map(|id| id as i32),
 5483        })
 5484    }
 5485
 5486    fn handle_follow(
 5487        &mut self,
 5488        follower_project_id: Option<u64>,
 5489        window: &mut Window,
 5490        cx: &mut Context<Self>,
 5491    ) -> proto::FollowResponse {
 5492        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5493
 5494        cx.notify();
 5495        proto::FollowResponse {
 5496            views: active_view.iter().cloned().collect(),
 5497            active_view,
 5498        }
 5499    }
 5500
 5501    fn handle_update_followers(
 5502        &mut self,
 5503        leader_id: PeerId,
 5504        message: proto::UpdateFollowers,
 5505        _window: &mut Window,
 5506        _cx: &mut Context<Self>,
 5507    ) {
 5508        self.leader_updates_tx
 5509            .unbounded_send((leader_id, message))
 5510            .ok();
 5511    }
 5512
 5513    async fn process_leader_update(
 5514        this: &WeakEntity<Self>,
 5515        leader_id: PeerId,
 5516        update: proto::UpdateFollowers,
 5517        cx: &mut AsyncWindowContext,
 5518    ) -> Result<()> {
 5519        match update.variant.context("invalid update")? {
 5520            proto::update_followers::Variant::CreateView(view) => {
 5521                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5522                let should_add_view = this.update(cx, |this, _| {
 5523                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5524                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5525                    } else {
 5526                        anyhow::Ok(false)
 5527                    }
 5528                })??;
 5529
 5530                if should_add_view {
 5531                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5532                }
 5533            }
 5534            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5535                let should_add_view = this.update(cx, |this, _| {
 5536                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5537                        state.active_view_id = update_active_view
 5538                            .view
 5539                            .as_ref()
 5540                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5541
 5542                        if state.active_view_id.is_some_and(|view_id| {
 5543                            !state.items_by_leader_view_id.contains_key(&view_id)
 5544                        }) {
 5545                            anyhow::Ok(true)
 5546                        } else {
 5547                            anyhow::Ok(false)
 5548                        }
 5549                    } else {
 5550                        anyhow::Ok(false)
 5551                    }
 5552                })??;
 5553
 5554                if should_add_view && let Some(view) = update_active_view.view {
 5555                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5556                }
 5557            }
 5558            proto::update_followers::Variant::UpdateView(update_view) => {
 5559                let variant = update_view.variant.context("missing update view variant")?;
 5560                let id = update_view.id.context("missing update view id")?;
 5561                let mut tasks = Vec::new();
 5562                this.update_in(cx, |this, window, cx| {
 5563                    let project = this.project.clone();
 5564                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5565                        let view_id = ViewId::from_proto(id.clone())?;
 5566                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5567                            tasks.push(item.view.apply_update_proto(
 5568                                &project,
 5569                                variant.clone(),
 5570                                window,
 5571                                cx,
 5572                            ));
 5573                        }
 5574                    }
 5575                    anyhow::Ok(())
 5576                })??;
 5577                try_join_all(tasks).await.log_err();
 5578            }
 5579        }
 5580        this.update_in(cx, |this, window, cx| {
 5581            this.leader_updated(leader_id, window, cx)
 5582        })?;
 5583        Ok(())
 5584    }
 5585
 5586    async fn add_view_from_leader(
 5587        this: WeakEntity<Self>,
 5588        leader_id: PeerId,
 5589        view: &proto::View,
 5590        cx: &mut AsyncWindowContext,
 5591    ) -> Result<()> {
 5592        let this = this.upgrade().context("workspace dropped")?;
 5593
 5594        let Some(id) = view.id.clone() else {
 5595            anyhow::bail!("no id for view");
 5596        };
 5597        let id = ViewId::from_proto(id)?;
 5598        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5599
 5600        let pane = this.update(cx, |this, _cx| {
 5601            let state = this
 5602                .follower_states
 5603                .get(&leader_id.into())
 5604                .context("stopped following")?;
 5605            anyhow::Ok(state.pane().clone())
 5606        })?;
 5607        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5608            let client = this.read(cx).client().clone();
 5609            pane.items().find_map(|item| {
 5610                let item = item.to_followable_item_handle(cx)?;
 5611                if item.remote_id(&client, window, cx) == Some(id) {
 5612                    Some(item)
 5613                } else {
 5614                    None
 5615                }
 5616            })
 5617        })?;
 5618        let item = if let Some(existing_item) = existing_item {
 5619            existing_item
 5620        } else {
 5621            let variant = view.variant.clone();
 5622            anyhow::ensure!(variant.is_some(), "missing view variant");
 5623
 5624            let task = cx.update(|window, cx| {
 5625                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5626            })?;
 5627
 5628            let Some(task) = task else {
 5629                anyhow::bail!(
 5630                    "failed to construct view from leader (maybe from a different version of zed?)"
 5631                );
 5632            };
 5633
 5634            let mut new_item = task.await?;
 5635            pane.update_in(cx, |pane, window, cx| {
 5636                let mut item_to_remove = None;
 5637                for (ix, item) in pane.items().enumerate() {
 5638                    if let Some(item) = item.to_followable_item_handle(cx) {
 5639                        match new_item.dedup(item.as_ref(), window, cx) {
 5640                            Some(item::Dedup::KeepExisting) => {
 5641                                new_item =
 5642                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5643                                break;
 5644                            }
 5645                            Some(item::Dedup::ReplaceExisting) => {
 5646                                item_to_remove = Some((ix, item.item_id()));
 5647                                break;
 5648                            }
 5649                            None => {}
 5650                        }
 5651                    }
 5652                }
 5653
 5654                if let Some((ix, id)) = item_to_remove {
 5655                    pane.remove_item(id, false, false, window, cx);
 5656                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5657                }
 5658            })?;
 5659
 5660            new_item
 5661        };
 5662
 5663        this.update_in(cx, |this, window, cx| {
 5664            let state = this.follower_states.get_mut(&leader_id.into())?;
 5665            item.set_leader_id(Some(leader_id.into()), window, cx);
 5666            state.items_by_leader_view_id.insert(
 5667                id,
 5668                FollowerView {
 5669                    view: item,
 5670                    location: panel_id,
 5671                },
 5672            );
 5673
 5674            Some(())
 5675        })
 5676        .context("no follower state")?;
 5677
 5678        Ok(())
 5679    }
 5680
 5681    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5682        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5683            return;
 5684        };
 5685
 5686        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5687            let buffer_entity_id = agent_location.buffer.entity_id();
 5688            let view_id = ViewId {
 5689                creator: CollaboratorId::Agent,
 5690                id: buffer_entity_id.as_u64(),
 5691            };
 5692            follower_state.active_view_id = Some(view_id);
 5693
 5694            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5695                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5696                hash_map::Entry::Vacant(entry) => {
 5697                    let existing_view =
 5698                        follower_state
 5699                            .center_pane
 5700                            .read(cx)
 5701                            .items()
 5702                            .find_map(|item| {
 5703                                let item = item.to_followable_item_handle(cx)?;
 5704                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5705                                    && item.project_item_model_ids(cx).as_slice()
 5706                                        == [buffer_entity_id]
 5707                                {
 5708                                    Some(item)
 5709                                } else {
 5710                                    None
 5711                                }
 5712                            });
 5713                    let view = existing_view.or_else(|| {
 5714                        agent_location.buffer.upgrade().and_then(|buffer| {
 5715                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5716                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5717                            })?
 5718                            .to_followable_item_handle(cx)
 5719                        })
 5720                    });
 5721
 5722                    view.map(|view| {
 5723                        entry.insert(FollowerView {
 5724                            view,
 5725                            location: None,
 5726                        })
 5727                    })
 5728                }
 5729            };
 5730
 5731            if let Some(item) = item {
 5732                item.view
 5733                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5734                item.view
 5735                    .update_agent_location(agent_location.position, window, cx);
 5736            }
 5737        } else {
 5738            follower_state.active_view_id = None;
 5739        }
 5740
 5741        self.leader_updated(CollaboratorId::Agent, window, cx);
 5742    }
 5743
 5744    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5745        let mut is_project_item = true;
 5746        let mut update = proto::UpdateActiveView::default();
 5747        if window.is_window_active() {
 5748            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5749
 5750            if let Some(item) = active_item
 5751                && item.item_focus_handle(cx).contains_focused(window, cx)
 5752            {
 5753                let leader_id = self
 5754                    .pane_for(&*item)
 5755                    .and_then(|pane| self.leader_for_pane(&pane));
 5756                let leader_peer_id = match leader_id {
 5757                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5758                    Some(CollaboratorId::Agent) | None => None,
 5759                };
 5760
 5761                if let Some(item) = item.to_followable_item_handle(cx) {
 5762                    let id = item
 5763                        .remote_id(&self.app_state.client, window, cx)
 5764                        .map(|id| id.to_proto());
 5765
 5766                    if let Some(id) = id
 5767                        && let Some(variant) = item.to_state_proto(window, cx)
 5768                    {
 5769                        let view = Some(proto::View {
 5770                            id,
 5771                            leader_id: leader_peer_id,
 5772                            variant: Some(variant),
 5773                            panel_id: panel_id.map(|id| id as i32),
 5774                        });
 5775
 5776                        is_project_item = item.is_project_item(window, cx);
 5777                        update = proto::UpdateActiveView { view };
 5778                    };
 5779                }
 5780            }
 5781        }
 5782
 5783        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5784        if active_view_id != self.last_active_view_id.as_ref() {
 5785            self.last_active_view_id = active_view_id.cloned();
 5786            self.update_followers(
 5787                is_project_item,
 5788                proto::update_followers::Variant::UpdateActiveView(update),
 5789                window,
 5790                cx,
 5791            );
 5792        }
 5793    }
 5794
 5795    fn active_item_for_followers(
 5796        &self,
 5797        window: &mut Window,
 5798        cx: &mut App,
 5799    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5800        let mut active_item = None;
 5801        let mut panel_id = None;
 5802        for dock in self.all_docks() {
 5803            if dock.focus_handle(cx).contains_focused(window, cx)
 5804                && let Some(panel) = dock.read(cx).active_panel()
 5805                && let Some(pane) = panel.pane(cx)
 5806                && let Some(item) = pane.read(cx).active_item()
 5807            {
 5808                active_item = Some(item);
 5809                panel_id = panel.remote_id();
 5810                break;
 5811            }
 5812        }
 5813
 5814        if active_item.is_none() {
 5815            active_item = self.active_pane().read(cx).active_item();
 5816        }
 5817        (active_item, panel_id)
 5818    }
 5819
 5820    fn update_followers(
 5821        &self,
 5822        project_only: bool,
 5823        update: proto::update_followers::Variant,
 5824        _: &mut Window,
 5825        cx: &mut App,
 5826    ) -> Option<()> {
 5827        // If this update only applies to for followers in the current project,
 5828        // then skip it unless this project is shared. If it applies to all
 5829        // followers, regardless of project, then set `project_id` to none,
 5830        // indicating that it goes to all followers.
 5831        let project_id = if project_only {
 5832            Some(self.project.read(cx).remote_id()?)
 5833        } else {
 5834            None
 5835        };
 5836        self.app_state().workspace_store.update(cx, |store, cx| {
 5837            store.update_followers(project_id, update, cx)
 5838        })
 5839    }
 5840
 5841    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5842        self.follower_states.iter().find_map(|(leader_id, state)| {
 5843            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5844                Some(*leader_id)
 5845            } else {
 5846                None
 5847            }
 5848        })
 5849    }
 5850
 5851    fn leader_updated(
 5852        &mut self,
 5853        leader_id: impl Into<CollaboratorId>,
 5854        window: &mut Window,
 5855        cx: &mut Context<Self>,
 5856    ) -> Option<Box<dyn ItemHandle>> {
 5857        cx.notify();
 5858
 5859        let leader_id = leader_id.into();
 5860        let (panel_id, item) = match leader_id {
 5861            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5862            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5863        };
 5864
 5865        let state = self.follower_states.get(&leader_id)?;
 5866        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5867        let pane;
 5868        if let Some(panel_id) = panel_id {
 5869            pane = self
 5870                .activate_panel_for_proto_id(panel_id, window, cx)?
 5871                .pane(cx)?;
 5872            let state = self.follower_states.get_mut(&leader_id)?;
 5873            state.dock_pane = Some(pane.clone());
 5874        } else {
 5875            pane = state.center_pane.clone();
 5876            let state = self.follower_states.get_mut(&leader_id)?;
 5877            if let Some(dock_pane) = state.dock_pane.take() {
 5878                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5879            }
 5880        }
 5881
 5882        pane.update(cx, |pane, cx| {
 5883            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5884            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5885                pane.activate_item(index, false, false, window, cx);
 5886            } else {
 5887                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5888            }
 5889
 5890            if focus_active_item {
 5891                pane.focus_active_item(window, cx)
 5892            }
 5893        });
 5894
 5895        Some(item)
 5896    }
 5897
 5898    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5899        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5900        let active_view_id = state.active_view_id?;
 5901        Some(
 5902            state
 5903                .items_by_leader_view_id
 5904                .get(&active_view_id)?
 5905                .view
 5906                .boxed_clone(),
 5907        )
 5908    }
 5909
 5910    fn active_item_for_peer(
 5911        &self,
 5912        peer_id: PeerId,
 5913        window: &mut Window,
 5914        cx: &mut Context<Self>,
 5915    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5916        let call = self.active_call()?;
 5917        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5918        let leader_in_this_app;
 5919        let leader_in_this_project;
 5920        match participant.location {
 5921            ParticipantLocation::SharedProject { project_id } => {
 5922                leader_in_this_app = true;
 5923                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5924            }
 5925            ParticipantLocation::UnsharedProject => {
 5926                leader_in_this_app = true;
 5927                leader_in_this_project = false;
 5928            }
 5929            ParticipantLocation::External => {
 5930                leader_in_this_app = false;
 5931                leader_in_this_project = false;
 5932            }
 5933        };
 5934        let state = self.follower_states.get(&peer_id.into())?;
 5935        let mut item_to_activate = None;
 5936        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5937            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5938                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5939            {
 5940                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5941            }
 5942        } else if let Some(shared_screen) =
 5943            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5944        {
 5945            item_to_activate = Some((None, Box::new(shared_screen)));
 5946        }
 5947        item_to_activate
 5948    }
 5949
 5950    fn shared_screen_for_peer(
 5951        &self,
 5952        peer_id: PeerId,
 5953        pane: &Entity<Pane>,
 5954        window: &mut Window,
 5955        cx: &mut App,
 5956    ) -> Option<Entity<SharedScreen>> {
 5957        self.active_call()?
 5958            .create_shared_screen(peer_id, pane, window, cx)
 5959    }
 5960
 5961    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5962        if window.is_window_active() {
 5963            self.update_active_view_for_followers(window, cx);
 5964
 5965            if let Some(database_id) = self.database_id {
 5966                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5967                    .detach();
 5968            }
 5969        } else {
 5970            for pane in &self.panes {
 5971                pane.update(cx, |pane, cx| {
 5972                    if let Some(item) = pane.active_item() {
 5973                        item.workspace_deactivated(window, cx);
 5974                    }
 5975                    for item in pane.items() {
 5976                        if matches!(
 5977                            item.workspace_settings(cx).autosave,
 5978                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5979                        ) {
 5980                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5981                                .detach_and_log_err(cx);
 5982                        }
 5983                    }
 5984                });
 5985            }
 5986        }
 5987    }
 5988
 5989    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5990        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5991    }
 5992
 5993    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5994        self.active_call.as_ref().map(|(call, _)| call.clone())
 5995    }
 5996
 5997    fn on_active_call_event(
 5998        &mut self,
 5999        event: &ActiveCallEvent,
 6000        window: &mut Window,
 6001        cx: &mut Context<Self>,
 6002    ) {
 6003        match event {
 6004            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6005            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6006                self.leader_updated(participant_id, window, cx);
 6007            }
 6008        }
 6009    }
 6010
 6011    pub fn database_id(&self) -> Option<WorkspaceId> {
 6012        self.database_id
 6013    }
 6014
 6015    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6016        self.database_id = Some(id);
 6017    }
 6018
 6019    pub fn session_id(&self) -> Option<String> {
 6020        self.session_id.clone()
 6021    }
 6022
 6023    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6024        let Some(display) = window.display(cx) else {
 6025            return Task::ready(());
 6026        };
 6027        let Ok(display_uuid) = display.uuid() else {
 6028            return Task::ready(());
 6029        };
 6030
 6031        let window_bounds = window.inner_window_bounds();
 6032        let database_id = self.database_id;
 6033        let has_paths = !self.root_paths(cx).is_empty();
 6034
 6035        cx.background_executor().spawn(async move {
 6036            if !has_paths {
 6037                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6038                    .await
 6039                    .log_err();
 6040            }
 6041            if let Some(database_id) = database_id {
 6042                DB.set_window_open_status(
 6043                    database_id,
 6044                    SerializedWindowBounds(window_bounds),
 6045                    display_uuid,
 6046                )
 6047                .await
 6048                .log_err();
 6049            } else {
 6050                persistence::write_default_window_bounds(window_bounds, display_uuid)
 6051                    .await
 6052                    .log_err();
 6053            }
 6054        })
 6055    }
 6056
 6057    /// Bypass the 200ms serialization throttle and write workspace state to
 6058    /// the DB immediately. Returns a task the caller can await to ensure the
 6059    /// write completes. Used by the quit handler so the most recent state
 6060    /// isn't lost to a pending throttle timer when the process exits.
 6061    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6062        self._schedule_serialize_workspace.take();
 6063        self._serialize_workspace_task.take();
 6064        self.bounds_save_task_queued.take();
 6065
 6066        let bounds_task = self.save_window_bounds(window, cx);
 6067        let serialize_task = self.serialize_workspace_internal(window, cx);
 6068        cx.spawn(async move |_| {
 6069            bounds_task.await;
 6070            serialize_task.await;
 6071        })
 6072    }
 6073
 6074    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6075        let project = self.project().read(cx);
 6076        project
 6077            .visible_worktrees(cx)
 6078            .map(|worktree| worktree.read(cx).abs_path())
 6079            .collect::<Vec<_>>()
 6080    }
 6081
 6082    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6083        match member {
 6084            Member::Axis(PaneAxis { members, .. }) => {
 6085                for child in members.iter() {
 6086                    self.remove_panes(child.clone(), window, cx)
 6087                }
 6088            }
 6089            Member::Pane(pane) => {
 6090                self.force_remove_pane(&pane, &None, window, cx);
 6091            }
 6092        }
 6093    }
 6094
 6095    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6096        self.session_id.take();
 6097        self.serialize_workspace_internal(window, cx)
 6098    }
 6099
 6100    fn force_remove_pane(
 6101        &mut self,
 6102        pane: &Entity<Pane>,
 6103        focus_on: &Option<Entity<Pane>>,
 6104        window: &mut Window,
 6105        cx: &mut Context<Workspace>,
 6106    ) {
 6107        self.panes.retain(|p| p != pane);
 6108        if let Some(focus_on) = focus_on {
 6109            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6110        } else if self.active_pane() == pane {
 6111            self.panes
 6112                .last()
 6113                .unwrap()
 6114                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6115        }
 6116        if self.last_active_center_pane == Some(pane.downgrade()) {
 6117            self.last_active_center_pane = None;
 6118        }
 6119        cx.notify();
 6120    }
 6121
 6122    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6123        if self._schedule_serialize_workspace.is_none() {
 6124            self._schedule_serialize_workspace =
 6125                Some(cx.spawn_in(window, async move |this, cx| {
 6126                    cx.background_executor()
 6127                        .timer(SERIALIZATION_THROTTLE_TIME)
 6128                        .await;
 6129                    this.update_in(cx, |this, window, cx| {
 6130                        this._serialize_workspace_task =
 6131                            Some(this.serialize_workspace_internal(window, cx));
 6132                        this._schedule_serialize_workspace.take();
 6133                    })
 6134                    .log_err();
 6135                }));
 6136        }
 6137    }
 6138
 6139    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6140        let Some(database_id) = self.database_id() else {
 6141            return Task::ready(());
 6142        };
 6143
 6144        fn serialize_pane_handle(
 6145            pane_handle: &Entity<Pane>,
 6146            window: &mut Window,
 6147            cx: &mut App,
 6148        ) -> SerializedPane {
 6149            let (items, active, pinned_count) = {
 6150                let pane = pane_handle.read(cx);
 6151                let active_item_id = pane.active_item().map(|item| item.item_id());
 6152                (
 6153                    pane.items()
 6154                        .filter_map(|handle| {
 6155                            let handle = handle.to_serializable_item_handle(cx)?;
 6156
 6157                            Some(SerializedItem {
 6158                                kind: Arc::from(handle.serialized_item_kind()),
 6159                                item_id: handle.item_id().as_u64(),
 6160                                active: Some(handle.item_id()) == active_item_id,
 6161                                preview: pane.is_active_preview_item(handle.item_id()),
 6162                            })
 6163                        })
 6164                        .collect::<Vec<_>>(),
 6165                    pane.has_focus(window, cx),
 6166                    pane.pinned_count(),
 6167                )
 6168            };
 6169
 6170            SerializedPane::new(items, active, pinned_count)
 6171        }
 6172
 6173        fn build_serialized_pane_group(
 6174            pane_group: &Member,
 6175            window: &mut Window,
 6176            cx: &mut App,
 6177        ) -> SerializedPaneGroup {
 6178            match pane_group {
 6179                Member::Axis(PaneAxis {
 6180                    axis,
 6181                    members,
 6182                    flexes,
 6183                    bounding_boxes: _,
 6184                }) => SerializedPaneGroup::Group {
 6185                    axis: SerializedAxis(*axis),
 6186                    children: members
 6187                        .iter()
 6188                        .map(|member| build_serialized_pane_group(member, window, cx))
 6189                        .collect::<Vec<_>>(),
 6190                    flexes: Some(flexes.lock().clone()),
 6191                },
 6192                Member::Pane(pane_handle) => {
 6193                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6194                }
 6195            }
 6196        }
 6197
 6198        fn build_serialized_docks(
 6199            this: &Workspace,
 6200            window: &mut Window,
 6201            cx: &mut App,
 6202        ) -> DockStructure {
 6203            this.capture_dock_state(window, cx)
 6204        }
 6205
 6206        match self.workspace_location(cx) {
 6207            WorkspaceLocation::Location(location, paths) => {
 6208                let breakpoints = self.project.update(cx, |project, cx| {
 6209                    project
 6210                        .breakpoint_store()
 6211                        .read(cx)
 6212                        .all_source_breakpoints(cx)
 6213                });
 6214                let user_toolchains = self
 6215                    .project
 6216                    .read(cx)
 6217                    .user_toolchains(cx)
 6218                    .unwrap_or_default();
 6219
 6220                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6221                let docks = build_serialized_docks(self, window, cx);
 6222                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6223
 6224                let serialized_workspace = SerializedWorkspace {
 6225                    id: database_id,
 6226                    location,
 6227                    paths,
 6228                    center_group,
 6229                    window_bounds,
 6230                    display: Default::default(),
 6231                    docks,
 6232                    centered_layout: self.centered_layout,
 6233                    session_id: self.session_id.clone(),
 6234                    breakpoints,
 6235                    window_id: Some(window.window_handle().window_id().as_u64()),
 6236                    user_toolchains,
 6237                };
 6238
 6239                window.spawn(cx, async move |_| {
 6240                    persistence::DB.save_workspace(serialized_workspace).await;
 6241                })
 6242            }
 6243            WorkspaceLocation::DetachFromSession => {
 6244                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6245                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6246                // Save dock state for empty local workspaces
 6247                let docks = build_serialized_docks(self, window, cx);
 6248                window.spawn(cx, async move |_| {
 6249                    persistence::DB
 6250                        .set_window_open_status(
 6251                            database_id,
 6252                            window_bounds,
 6253                            display.unwrap_or_default(),
 6254                        )
 6255                        .await
 6256                        .log_err();
 6257                    persistence::DB
 6258                        .set_session_id(database_id, None)
 6259                        .await
 6260                        .log_err();
 6261                    persistence::write_default_dock_state(docks).await.log_err();
 6262                })
 6263            }
 6264            WorkspaceLocation::None => {
 6265                // Save dock state for empty non-local workspaces
 6266                let docks = build_serialized_docks(self, window, cx);
 6267                window.spawn(cx, async move |_| {
 6268                    persistence::write_default_dock_state(docks).await.log_err();
 6269                })
 6270            }
 6271        }
 6272    }
 6273
 6274    fn has_any_items_open(&self, cx: &App) -> bool {
 6275        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6276    }
 6277
 6278    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6279        let paths = PathList::new(&self.root_paths(cx));
 6280        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6281            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6282        } else if self.project.read(cx).is_local() {
 6283            if !paths.is_empty() || self.has_any_items_open(cx) {
 6284                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6285            } else {
 6286                WorkspaceLocation::DetachFromSession
 6287            }
 6288        } else {
 6289            WorkspaceLocation::None
 6290        }
 6291    }
 6292
 6293    fn update_history(&self, cx: &mut App) {
 6294        let Some(id) = self.database_id() else {
 6295            return;
 6296        };
 6297        if !self.project.read(cx).is_local() {
 6298            return;
 6299        }
 6300        if let Some(manager) = HistoryManager::global(cx) {
 6301            let paths = PathList::new(&self.root_paths(cx));
 6302            manager.update(cx, |this, cx| {
 6303                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6304            });
 6305        }
 6306    }
 6307
 6308    async fn serialize_items(
 6309        this: &WeakEntity<Self>,
 6310        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6311        cx: &mut AsyncWindowContext,
 6312    ) -> Result<()> {
 6313        const CHUNK_SIZE: usize = 200;
 6314
 6315        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6316
 6317        while let Some(items_received) = serializable_items.next().await {
 6318            let unique_items =
 6319                items_received
 6320                    .into_iter()
 6321                    .fold(HashMap::default(), |mut acc, item| {
 6322                        acc.entry(item.item_id()).or_insert(item);
 6323                        acc
 6324                    });
 6325
 6326            // We use into_iter() here so that the references to the items are moved into
 6327            // the tasks and not kept alive while we're sleeping.
 6328            for (_, item) in unique_items.into_iter() {
 6329                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6330                    item.serialize(workspace, false, window, cx)
 6331                }) {
 6332                    cx.background_spawn(async move { task.await.log_err() })
 6333                        .detach();
 6334                }
 6335            }
 6336
 6337            cx.background_executor()
 6338                .timer(SERIALIZATION_THROTTLE_TIME)
 6339                .await;
 6340        }
 6341
 6342        Ok(())
 6343    }
 6344
 6345    pub(crate) fn enqueue_item_serialization(
 6346        &mut self,
 6347        item: Box<dyn SerializableItemHandle>,
 6348    ) -> Result<()> {
 6349        self.serializable_items_tx
 6350            .unbounded_send(item)
 6351            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6352    }
 6353
 6354    pub(crate) fn load_workspace(
 6355        serialized_workspace: SerializedWorkspace,
 6356        paths_to_open: Vec<Option<ProjectPath>>,
 6357        window: &mut Window,
 6358        cx: &mut Context<Workspace>,
 6359    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6360        cx.spawn_in(window, async move |workspace, cx| {
 6361            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6362
 6363            let mut center_group = None;
 6364            let mut center_items = None;
 6365
 6366            // Traverse the splits tree and add to things
 6367            if let Some((group, active_pane, items)) = serialized_workspace
 6368                .center_group
 6369                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6370                .await
 6371            {
 6372                center_items = Some(items);
 6373                center_group = Some((group, active_pane))
 6374            }
 6375
 6376            let mut items_by_project_path = HashMap::default();
 6377            let mut item_ids_by_kind = HashMap::default();
 6378            let mut all_deserialized_items = Vec::default();
 6379            cx.update(|_, cx| {
 6380                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6381                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6382                        item_ids_by_kind
 6383                            .entry(serializable_item_handle.serialized_item_kind())
 6384                            .or_insert(Vec::new())
 6385                            .push(item.item_id().as_u64() as ItemId);
 6386                    }
 6387
 6388                    if let Some(project_path) = item.project_path(cx) {
 6389                        items_by_project_path.insert(project_path, item.clone());
 6390                    }
 6391                    all_deserialized_items.push(item);
 6392                }
 6393            })?;
 6394
 6395            let opened_items = paths_to_open
 6396                .into_iter()
 6397                .map(|path_to_open| {
 6398                    path_to_open
 6399                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6400                })
 6401                .collect::<Vec<_>>();
 6402
 6403            // Remove old panes from workspace panes list
 6404            workspace.update_in(cx, |workspace, window, cx| {
 6405                if let Some((center_group, active_pane)) = center_group {
 6406                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6407
 6408                    // Swap workspace center group
 6409                    workspace.center = PaneGroup::with_root(center_group);
 6410                    workspace.center.set_is_center(true);
 6411                    workspace.center.mark_positions(cx);
 6412
 6413                    if let Some(active_pane) = active_pane {
 6414                        workspace.set_active_pane(&active_pane, window, cx);
 6415                        cx.focus_self(window);
 6416                    } else {
 6417                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6418                    }
 6419                }
 6420
 6421                let docks = serialized_workspace.docks;
 6422
 6423                for (dock, serialized_dock) in [
 6424                    (&mut workspace.right_dock, docks.right),
 6425                    (&mut workspace.left_dock, docks.left),
 6426                    (&mut workspace.bottom_dock, docks.bottom),
 6427                ]
 6428                .iter_mut()
 6429                {
 6430                    dock.update(cx, |dock, cx| {
 6431                        dock.serialized_dock = Some(serialized_dock.clone());
 6432                        dock.restore_state(window, cx);
 6433                    });
 6434                }
 6435
 6436                cx.notify();
 6437            })?;
 6438
 6439            let _ = project
 6440                .update(cx, |project, cx| {
 6441                    project
 6442                        .breakpoint_store()
 6443                        .update(cx, |breakpoint_store, cx| {
 6444                            breakpoint_store
 6445                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6446                        })
 6447                })
 6448                .await;
 6449
 6450            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6451            // after loading the items, we might have different items and in order to avoid
 6452            // the database filling up, we delete items that haven't been loaded now.
 6453            //
 6454            // The items that have been loaded, have been saved after they've been added to the workspace.
 6455            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6456                item_ids_by_kind
 6457                    .into_iter()
 6458                    .map(|(item_kind, loaded_items)| {
 6459                        SerializableItemRegistry::cleanup(
 6460                            item_kind,
 6461                            serialized_workspace.id,
 6462                            loaded_items,
 6463                            window,
 6464                            cx,
 6465                        )
 6466                        .log_err()
 6467                    })
 6468                    .collect::<Vec<_>>()
 6469            })?;
 6470
 6471            futures::future::join_all(clean_up_tasks).await;
 6472
 6473            workspace
 6474                .update_in(cx, |workspace, window, cx| {
 6475                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6476                    workspace.serialize_workspace_internal(window, cx).detach();
 6477
 6478                    // Ensure that we mark the window as edited if we did load dirty items
 6479                    workspace.update_window_edited(window, cx);
 6480                })
 6481                .ok();
 6482
 6483            Ok(opened_items)
 6484        })
 6485    }
 6486
 6487    pub fn key_context(&self, cx: &App) -> KeyContext {
 6488        let mut context = KeyContext::new_with_defaults();
 6489        context.add("Workspace");
 6490        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6491        if let Some(status) = self
 6492            .debugger_provider
 6493            .as_ref()
 6494            .and_then(|provider| provider.active_thread_state(cx))
 6495        {
 6496            match status {
 6497                ThreadStatus::Running | ThreadStatus::Stepping => {
 6498                    context.add("debugger_running");
 6499                }
 6500                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6501                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6502            }
 6503        }
 6504
 6505        if self.left_dock.read(cx).is_open() {
 6506            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6507                context.set("left_dock", active_panel.panel_key());
 6508            }
 6509        }
 6510
 6511        if self.right_dock.read(cx).is_open() {
 6512            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6513                context.set("right_dock", active_panel.panel_key());
 6514            }
 6515        }
 6516
 6517        if self.bottom_dock.read(cx).is_open() {
 6518            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6519                context.set("bottom_dock", active_panel.panel_key());
 6520            }
 6521        }
 6522
 6523        context
 6524    }
 6525
 6526    /// Multiworkspace uses this to add workspace action handling to itself
 6527    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6528        self.add_workspace_actions_listeners(div, window, cx)
 6529            .on_action(cx.listener(
 6530                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6531                    for action in &action_sequence.0 {
 6532                        window.dispatch_action(action.boxed_clone(), cx);
 6533                    }
 6534                },
 6535            ))
 6536            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6537            .on_action(cx.listener(Self::close_all_items_and_panes))
 6538            .on_action(cx.listener(Self::close_item_in_all_panes))
 6539            .on_action(cx.listener(Self::save_all))
 6540            .on_action(cx.listener(Self::send_keystrokes))
 6541            .on_action(cx.listener(Self::add_folder_to_project))
 6542            .on_action(cx.listener(Self::follow_next_collaborator))
 6543            .on_action(cx.listener(Self::activate_pane_at_index))
 6544            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6545            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6546            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6547            .on_action(cx.listener(Self::toggle_theme_mode))
 6548            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6549                let pane = workspace.active_pane().clone();
 6550                workspace.unfollow_in_pane(&pane, window, cx);
 6551            }))
 6552            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6553                workspace
 6554                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6555                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6556            }))
 6557            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6558                workspace
 6559                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6560                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6561            }))
 6562            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6563                workspace
 6564                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6565                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6566            }))
 6567            .on_action(
 6568                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6569                    workspace.activate_previous_pane(window, cx)
 6570                }),
 6571            )
 6572            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6573                workspace.activate_next_pane(window, cx)
 6574            }))
 6575            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6576                workspace.activate_last_pane(window, cx)
 6577            }))
 6578            .on_action(
 6579                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6580                    workspace.activate_next_window(cx)
 6581                }),
 6582            )
 6583            .on_action(
 6584                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6585                    workspace.activate_previous_window(cx)
 6586                }),
 6587            )
 6588            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6589                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6590            }))
 6591            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6592                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6593            }))
 6594            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6595                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6596            }))
 6597            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6598                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6599            }))
 6600            .on_action(cx.listener(
 6601                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6602                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6603                },
 6604            ))
 6605            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6606                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6607            }))
 6608            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6609                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6610            }))
 6611            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6612                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6613            }))
 6614            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6615                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6616            }))
 6617            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6618                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6619                    SplitDirection::Down,
 6620                    SplitDirection::Up,
 6621                    SplitDirection::Right,
 6622                    SplitDirection::Left,
 6623                ];
 6624                for dir in DIRECTION_PRIORITY {
 6625                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6626                        workspace.swap_pane_in_direction(dir, cx);
 6627                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6628                        break;
 6629                    }
 6630                }
 6631            }))
 6632            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6633                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6634            }))
 6635            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6636                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6637            }))
 6638            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6639                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6640            }))
 6641            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6642                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6643            }))
 6644            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6645                this.toggle_dock(DockPosition::Left, window, cx);
 6646            }))
 6647            .on_action(cx.listener(
 6648                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6649                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6650                },
 6651            ))
 6652            .on_action(cx.listener(
 6653                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6654                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6655                },
 6656            ))
 6657            .on_action(cx.listener(
 6658                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6659                    if !workspace.close_active_dock(window, cx) {
 6660                        cx.propagate();
 6661                    }
 6662                },
 6663            ))
 6664            .on_action(
 6665                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6666                    workspace.close_all_docks(window, cx);
 6667                }),
 6668            )
 6669            .on_action(cx.listener(Self::toggle_all_docks))
 6670            .on_action(cx.listener(
 6671                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6672                    workspace.clear_all_notifications(cx);
 6673                },
 6674            ))
 6675            .on_action(cx.listener(
 6676                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6677                    workspace.clear_navigation_history(window, cx);
 6678                },
 6679            ))
 6680            .on_action(cx.listener(
 6681                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6682                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6683                        workspace.suppress_notification(&notification_id, cx);
 6684                    }
 6685                },
 6686            ))
 6687            .on_action(cx.listener(
 6688                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6689                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6690                },
 6691            ))
 6692            .on_action(
 6693                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6694                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6695                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6696                            trusted_worktrees.clear_trusted_paths()
 6697                        });
 6698                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6699                        cx.spawn(async move |_, cx| {
 6700                            if clear_task.await.log_err().is_some() {
 6701                                cx.update(|cx| reload(cx));
 6702                            }
 6703                        })
 6704                        .detach();
 6705                    }
 6706                }),
 6707            )
 6708            .on_action(cx.listener(
 6709                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6710                    workspace.reopen_closed_item(window, cx).detach();
 6711                },
 6712            ))
 6713            .on_action(cx.listener(
 6714                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6715                    for dock in workspace.all_docks() {
 6716                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6717                            let Some(panel) = dock.read(cx).active_panel() else {
 6718                                return;
 6719                            };
 6720
 6721                            // Set to `None`, then the size will fall back to the default.
 6722                            panel.clone().set_size(None, window, cx);
 6723
 6724                            return;
 6725                        }
 6726                    }
 6727                },
 6728            ))
 6729            .on_action(cx.listener(
 6730                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6731                    for dock in workspace.all_docks() {
 6732                        if let Some(panel) = dock.read(cx).visible_panel() {
 6733                            // Set to `None`, then the size will fall back to the default.
 6734                            panel.clone().set_size(None, window, cx);
 6735                        }
 6736                    }
 6737                },
 6738            ))
 6739            .on_action(cx.listener(
 6740                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6741                    adjust_active_dock_size_by_px(
 6742                        px_with_ui_font_fallback(act.px, cx),
 6743                        workspace,
 6744                        window,
 6745                        cx,
 6746                    );
 6747                },
 6748            ))
 6749            .on_action(cx.listener(
 6750                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6751                    adjust_active_dock_size_by_px(
 6752                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6753                        workspace,
 6754                        window,
 6755                        cx,
 6756                    );
 6757                },
 6758            ))
 6759            .on_action(cx.listener(
 6760                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6761                    adjust_open_docks_size_by_px(
 6762                        px_with_ui_font_fallback(act.px, cx),
 6763                        workspace,
 6764                        window,
 6765                        cx,
 6766                    );
 6767                },
 6768            ))
 6769            .on_action(cx.listener(
 6770                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6771                    adjust_open_docks_size_by_px(
 6772                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6773                        workspace,
 6774                        window,
 6775                        cx,
 6776                    );
 6777                },
 6778            ))
 6779            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6780            .on_action(cx.listener(
 6781                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6782                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6783                        let dock = active_dock.read(cx);
 6784                        if let Some(active_panel) = dock.active_panel() {
 6785                            if active_panel.pane(cx).is_none() {
 6786                                let mut recent_pane: Option<Entity<Pane>> = None;
 6787                                let mut recent_timestamp = 0;
 6788                                for pane_handle in workspace.panes() {
 6789                                    let pane = pane_handle.read(cx);
 6790                                    for entry in pane.activation_history() {
 6791                                        if entry.timestamp > recent_timestamp {
 6792                                            recent_timestamp = entry.timestamp;
 6793                                            recent_pane = Some(pane_handle.clone());
 6794                                        }
 6795                                    }
 6796                                }
 6797
 6798                                if let Some(pane) = recent_pane {
 6799                                    pane.update(cx, |pane, cx| {
 6800                                        let current_index = pane.active_item_index();
 6801                                        let items_len = pane.items_len();
 6802                                        if items_len > 0 {
 6803                                            let next_index = if current_index + 1 < items_len {
 6804                                                current_index + 1
 6805                                            } else {
 6806                                                0
 6807                                            };
 6808                                            pane.activate_item(
 6809                                                next_index, false, false, window, cx,
 6810                                            );
 6811                                        }
 6812                                    });
 6813                                    return;
 6814                                }
 6815                            }
 6816                        }
 6817                    }
 6818                    cx.propagate();
 6819                },
 6820            ))
 6821            .on_action(cx.listener(
 6822                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6823                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6824                        let dock = active_dock.read(cx);
 6825                        if let Some(active_panel) = dock.active_panel() {
 6826                            if active_panel.pane(cx).is_none() {
 6827                                let mut recent_pane: Option<Entity<Pane>> = None;
 6828                                let mut recent_timestamp = 0;
 6829                                for pane_handle in workspace.panes() {
 6830                                    let pane = pane_handle.read(cx);
 6831                                    for entry in pane.activation_history() {
 6832                                        if entry.timestamp > recent_timestamp {
 6833                                            recent_timestamp = entry.timestamp;
 6834                                            recent_pane = Some(pane_handle.clone());
 6835                                        }
 6836                                    }
 6837                                }
 6838
 6839                                if let Some(pane) = recent_pane {
 6840                                    pane.update(cx, |pane, cx| {
 6841                                        let current_index = pane.active_item_index();
 6842                                        let items_len = pane.items_len();
 6843                                        if items_len > 0 {
 6844                                            let prev_index = if current_index > 0 {
 6845                                                current_index - 1
 6846                                            } else {
 6847                                                items_len.saturating_sub(1)
 6848                                            };
 6849                                            pane.activate_item(
 6850                                                prev_index, false, false, window, cx,
 6851                                            );
 6852                                        }
 6853                                    });
 6854                                    return;
 6855                                }
 6856                            }
 6857                        }
 6858                    }
 6859                    cx.propagate();
 6860                },
 6861            ))
 6862            .on_action(cx.listener(
 6863                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6864                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6865                        let dock = active_dock.read(cx);
 6866                        if let Some(active_panel) = dock.active_panel() {
 6867                            if active_panel.pane(cx).is_none() {
 6868                                let active_pane = workspace.active_pane().clone();
 6869                                active_pane.update(cx, |pane, cx| {
 6870                                    pane.close_active_item(action, window, cx)
 6871                                        .detach_and_log_err(cx);
 6872                                });
 6873                                return;
 6874                            }
 6875                        }
 6876                    }
 6877                    cx.propagate();
 6878                },
 6879            ))
 6880            .on_action(
 6881                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6882                    let pane = workspace.active_pane().clone();
 6883                    if let Some(item) = pane.read(cx).active_item() {
 6884                        item.toggle_read_only(window, cx);
 6885                    }
 6886                }),
 6887            )
 6888            .on_action(cx.listener(Workspace::cancel))
 6889    }
 6890
 6891    #[cfg(any(test, feature = "test-support"))]
 6892    pub fn set_random_database_id(&mut self) {
 6893        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6894    }
 6895
 6896    #[cfg(any(test, feature = "test-support"))]
 6897    pub(crate) fn test_new(
 6898        project: Entity<Project>,
 6899        window: &mut Window,
 6900        cx: &mut Context<Self>,
 6901    ) -> Self {
 6902        use node_runtime::NodeRuntime;
 6903        use session::Session;
 6904
 6905        let client = project.read(cx).client();
 6906        let user_store = project.read(cx).user_store();
 6907        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6908        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6909        window.activate_window();
 6910        let app_state = Arc::new(AppState {
 6911            languages: project.read(cx).languages().clone(),
 6912            workspace_store,
 6913            client,
 6914            user_store,
 6915            fs: project.read(cx).fs().clone(),
 6916            build_window_options: |_, _| Default::default(),
 6917            node_runtime: NodeRuntime::unavailable(),
 6918            session,
 6919        });
 6920        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6921        workspace
 6922            .active_pane
 6923            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6924        workspace
 6925    }
 6926
 6927    pub fn register_action<A: Action>(
 6928        &mut self,
 6929        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6930    ) -> &mut Self {
 6931        let callback = Arc::new(callback);
 6932
 6933        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6934            let callback = callback.clone();
 6935            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6936                (callback)(workspace, event, window, cx)
 6937            }))
 6938        }));
 6939        self
 6940    }
 6941    pub fn register_action_renderer(
 6942        &mut self,
 6943        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6944    ) -> &mut Self {
 6945        self.workspace_actions.push(Box::new(callback));
 6946        self
 6947    }
 6948
 6949    fn add_workspace_actions_listeners(
 6950        &self,
 6951        mut div: Div,
 6952        window: &mut Window,
 6953        cx: &mut Context<Self>,
 6954    ) -> Div {
 6955        for action in self.workspace_actions.iter() {
 6956            div = (action)(div, self, window, cx)
 6957        }
 6958        div
 6959    }
 6960
 6961    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6962        self.modal_layer.read(cx).has_active_modal()
 6963    }
 6964
 6965    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6966        self.modal_layer.read(cx).active_modal()
 6967    }
 6968
 6969    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6970    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6971    /// If no modal is active, the new modal will be shown.
 6972    ///
 6973    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6974    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6975    /// will not be shown.
 6976    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6977    where
 6978        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6979    {
 6980        self.modal_layer.update(cx, |modal_layer, cx| {
 6981            modal_layer.toggle_modal(window, cx, build)
 6982        })
 6983    }
 6984
 6985    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6986        self.modal_layer
 6987            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6988    }
 6989
 6990    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6991        self.toast_layer
 6992            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6993    }
 6994
 6995    pub fn toggle_centered_layout(
 6996        &mut self,
 6997        _: &ToggleCenteredLayout,
 6998        _: &mut Window,
 6999        cx: &mut Context<Self>,
 7000    ) {
 7001        self.centered_layout = !self.centered_layout;
 7002        if let Some(database_id) = self.database_id() {
 7003            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 7004                .detach_and_log_err(cx);
 7005        }
 7006        cx.notify();
 7007    }
 7008
 7009    fn adjust_padding(padding: Option<f32>) -> f32 {
 7010        padding
 7011            .unwrap_or(CenteredPaddingSettings::default().0)
 7012            .clamp(
 7013                CenteredPaddingSettings::MIN_PADDING,
 7014                CenteredPaddingSettings::MAX_PADDING,
 7015            )
 7016    }
 7017
 7018    fn render_dock(
 7019        &self,
 7020        position: DockPosition,
 7021        dock: &Entity<Dock>,
 7022        window: &mut Window,
 7023        cx: &mut App,
 7024    ) -> Option<Div> {
 7025        if self.zoomed_position == Some(position) {
 7026            return None;
 7027        }
 7028
 7029        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7030            let pane = panel.pane(cx)?;
 7031            let follower_states = &self.follower_states;
 7032            leader_border_for_pane(follower_states, &pane, window, cx)
 7033        });
 7034
 7035        Some(
 7036            div()
 7037                .flex()
 7038                .flex_none()
 7039                .overflow_hidden()
 7040                .child(dock.clone())
 7041                .children(leader_border),
 7042        )
 7043    }
 7044
 7045    pub fn set_left_drawer<V: Render + Focusable + 'static>(
 7046        &mut self,
 7047        view: Entity<V>,
 7048        cx: &mut Context<Self>,
 7049    ) {
 7050        if let Some(drawer) = self.right_drawer.as_mut() {
 7051            if drawer.view.entity_id() == view.entity_id() {
 7052                self.right_drawer.take();
 7053            }
 7054        }
 7055        self.left_drawer = Some(Drawer::new(view));
 7056        cx.notify();
 7057    }
 7058
 7059    pub fn set_right_drawer<V: Render + Focusable + 'static>(
 7060        &mut self,
 7061        view: Entity<V>,
 7062        cx: &mut Context<Self>,
 7063    ) {
 7064        if let Some(drawer) = self.left_drawer.as_mut() {
 7065            if drawer.view.entity_id() == view.entity_id() {
 7066                self.left_drawer.take();
 7067            }
 7068        }
 7069        self.right_drawer = Some(Drawer::new(view));
 7070        cx.notify();
 7071    }
 7072
 7073    fn drawer_mut<T: 'static>(&mut self) -> Option<(Entity<T>, &mut Drawer)> {
 7074        if let Some(left) = self.left_drawer.as_mut() {
 7075            if let Some(drawer) = left.view.clone().downcast().ok() {
 7076                return Some((drawer, left));
 7077            }
 7078        }
 7079        if let Some(right) = self.right_drawer.as_mut() {
 7080            if let Some(drawer) = right.view.clone().downcast().ok() {
 7081                return Some((drawer, right));
 7082            }
 7083        }
 7084        None
 7085    }
 7086
 7087    fn drawer_ref<T: 'static>(&self) -> Option<(Entity<T>, &Drawer)> {
 7088        if let Some(left) = self.left_drawer.as_ref() {
 7089            if let Some(drawer) = left.view.clone().downcast().ok() {
 7090                return Some((drawer, left));
 7091            }
 7092        }
 7093        if let Some(right) = self.right_drawer.as_ref() {
 7094            if let Some(drawer) = right.view.clone().downcast().ok() {
 7095                return Some((drawer, right));
 7096            }
 7097        }
 7098        None
 7099    }
 7100
 7101    pub fn drawer<T: 'static>(&self) -> Option<Entity<T>> {
 7102        if let Some(left) = self.left_drawer.as_ref() {
 7103            if let Some(drawer) = left.view.clone().downcast().ok() {
 7104                return Some(drawer);
 7105            }
 7106        }
 7107        if let Some(right) = self.right_drawer.as_ref() {
 7108            if let Some(drawer) = right.view.clone().downcast().ok() {
 7109                return Some(drawer);
 7110            }
 7111        }
 7112        None
 7113    }
 7114
 7115    pub fn focus_drawer<T: Focusable>(
 7116        &mut self,
 7117        window: &mut Window,
 7118        cx: &mut Context<Self>,
 7119    ) -> Option<Entity<T>> {
 7120        if let Some((view, drawer)) = self.drawer_mut::<T>() {
 7121            drawer.open = true;
 7122            view.focus_handle(cx).focus(window, cx);
 7123            return Some(view);
 7124        }
 7125        None
 7126    }
 7127
 7128    pub fn toggle_drawer_focus<T: Focusable>(
 7129        &mut self,
 7130        window: &mut Window,
 7131        cx: &mut Context<Self>,
 7132    ) -> bool {
 7133        if let Some((view, drawer)) = self.drawer_mut::<T>() {
 7134            if view.focus_handle(cx).contains_focused(window, cx) {
 7135                self.active_pane
 7136                    .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7137                false
 7138            } else {
 7139                drawer.open = true;
 7140                view.focus_handle(cx).focus(window, cx);
 7141                cx.notify();
 7142                true
 7143            }
 7144        } else {
 7145            false
 7146        }
 7147    }
 7148
 7149    pub fn toggle_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) -> bool {
 7150        if let Some((_, drawer)) = self.drawer_mut::<T>() {
 7151            if drawer.open {
 7152                drawer.open = false;
 7153                cx.notify();
 7154                false
 7155            } else {
 7156                drawer.open = true;
 7157                cx.notify();
 7158                true
 7159            }
 7160        } else {
 7161            false
 7162        }
 7163    }
 7164
 7165    pub fn open_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) {
 7166        if let Some((_, drawer)) = self.drawer_mut::<T>() {
 7167            drawer.open = true;
 7168            cx.notify();
 7169        }
 7170    }
 7171
 7172    pub fn close_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) {
 7173        if let Some((_, drawer)) = self.drawer_mut::<T>() {
 7174            drawer.open = false;
 7175            cx.notify();
 7176        }
 7177    }
 7178
 7179    pub fn drawer_width<T: 'static>(&self) -> Option<Pixels> {
 7180        self.drawer_ref::<T>()
 7181            .and_then(|(_, drawer)| drawer.custom_width)
 7182    }
 7183
 7184    pub fn set_drawer_width<T: 'static>(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
 7185        if let Some((_, drawer)) = self.drawer_mut::<T>() {
 7186            drawer.custom_width = width;
 7187            cx.notify();
 7188        }
 7189    }
 7190
 7191    pub fn drawer_is_open<T: 'static>(&self) -> bool {
 7192        if let Some((_, drawer)) = self.drawer_ref::<T>() {
 7193            drawer.open
 7194        } else {
 7195            false
 7196        }
 7197    }
 7198
 7199    pub fn remove_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) {
 7200        if let Some(left) = self.left_drawer.as_mut() {
 7201            if left.view.clone().downcast::<T>().is_ok() {
 7202                self.left_drawer = None;
 7203                cx.notify();
 7204                return;
 7205            }
 7206        }
 7207        if let Some(right) = self.right_drawer.as_mut() {
 7208            if right.view.clone().downcast::<T>().is_ok() {
 7209                self.right_drawer = None;
 7210                cx.notify();
 7211                return;
 7212            }
 7213        }
 7214    }
 7215
 7216    pub fn left_drawer_view(&self) -> Option<&AnyView> {
 7217        self.left_drawer.as_ref().map(|d| &d.view)
 7218    }
 7219
 7220    pub fn right_drawer_view(&self) -> Option<&AnyView> {
 7221        self.right_drawer.as_ref().map(|d| &d.view)
 7222    }
 7223
 7224    pub fn is_left_drawer_open(&self) -> bool {
 7225        self.left_drawer.as_ref().is_some_and(|d| d.open)
 7226    }
 7227
 7228    pub fn is_right_drawer_open(&self) -> bool {
 7229        self.right_drawer.as_ref().is_some_and(|d| d.open)
 7230    }
 7231
 7232    pub fn remove_left_drawer(&mut self, cx: &mut Context<Self>) {
 7233        self.left_drawer = None;
 7234        cx.notify();
 7235    }
 7236
 7237    pub fn remove_right_drawer(&mut self, cx: &mut Context<Self>) {
 7238        self.right_drawer = None;
 7239        cx.notify();
 7240    }
 7241
 7242    fn resize_left_drawer(
 7243        &mut self,
 7244        cursor_offset_from_left: Pixels,
 7245        window: &mut Window,
 7246        cx: &mut Context<Self>,
 7247    ) {
 7248        let left_dock_width = self
 7249            .left_dock
 7250            .read(cx)
 7251            .active_panel_size(window, cx)
 7252            .unwrap_or(Pixels::ZERO);
 7253        let drawer_width = cursor_offset_from_left - left_dock_width;
 7254        let max_width = self.bounds.size.width * 0.8;
 7255        let width = drawer_width.max(px(100.)).min(max_width);
 7256        if let Some(drawer) = &mut self.left_drawer {
 7257            drawer.custom_width = Some(width);
 7258            cx.notify();
 7259        }
 7260    }
 7261
 7262    fn resize_right_drawer(
 7263        &mut self,
 7264        cursor_offset_from_right: Pixels,
 7265        window: &mut Window,
 7266        cx: &mut Context<Self>,
 7267    ) {
 7268        let right_dock_width = self
 7269            .right_dock
 7270            .read(cx)
 7271            .active_panel_size(window, cx)
 7272            .unwrap_or(Pixels::ZERO);
 7273        let drawer_width = cursor_offset_from_right - right_dock_width;
 7274        let max_width = self.bounds.size.width * 0.8;
 7275        let width = drawer_width.max(px(100.)).min(max_width);
 7276        if let Some(drawer) = &mut self.right_drawer {
 7277            drawer.custom_width = Some(width);
 7278            cx.notify();
 7279        }
 7280    }
 7281
 7282    fn render_drawer(&self, position: DrawerPosition, cx: &mut Context<Self>) -> Option<Div> {
 7283        let drawer = match position {
 7284            DrawerPosition::Left => self.left_drawer.as_ref()?,
 7285            DrawerPosition::Right => self.right_drawer.as_ref()?,
 7286        };
 7287        if !drawer.open {
 7288            return None;
 7289        }
 7290
 7291        let colors = cx.theme().colors();
 7292        let create_resize_handle = |position: DrawerPosition| {
 7293            let handle = div()
 7294                .id(match position {
 7295                    DrawerPosition::Left => "left-drawer-resize-handle",
 7296                    DrawerPosition::Right => "right-drawer-resize-handle",
 7297                })
 7298                .on_drag(DraggedDrawer(position), |drawer, _, _, cx| {
 7299                    cx.stop_propagation();
 7300                    cx.new(|_| drawer.clone())
 7301                })
 7302                .on_mouse_down(MouseButton::Left, |_, _, cx| {
 7303                    cx.stop_propagation();
 7304                })
 7305                .occlude();
 7306            match position {
 7307                DrawerPosition::Left => deferred(
 7308                    handle
 7309                        .absolute()
 7310                        .right(-RESIZE_HANDLE_SIZE / 2.)
 7311                        .top(px(0.))
 7312                        .h_full()
 7313                        .w(RESIZE_HANDLE_SIZE)
 7314                        .cursor_col_resize(),
 7315                ),
 7316                DrawerPosition::Right => deferred(
 7317                    handle
 7318                        .absolute()
 7319                        .top(px(0.))
 7320                        .left(-RESIZE_HANDLE_SIZE / 2.)
 7321                        .h_full()
 7322                        .w(RESIZE_HANDLE_SIZE)
 7323                        .cursor_col_resize(),
 7324                ),
 7325            }
 7326        };
 7327
 7328        let focus_handle = drawer.focus_handle(cx);
 7329        let base = div()
 7330            .track_focus(&focus_handle)
 7331            .flex()
 7332            .flex_col()
 7333            .overflow_hidden()
 7334            .border_color(colors.border)
 7335            .map(|this| match position {
 7336                DrawerPosition::Left => this.border_r_1(),
 7337                DrawerPosition::Right => this.border_l_1(),
 7338            });
 7339
 7340        let element = if let Some(width) = drawer.custom_width {
 7341            base.flex_none().w(width)
 7342        } else {
 7343            base.flex_1()
 7344        };
 7345
 7346        Some(
 7347            element
 7348                .child(drawer.view.clone())
 7349                .child(create_resize_handle(position)),
 7350        )
 7351    }
 7352
 7353    fn render_center_with_drawers(
 7354        &self,
 7355        paddings: (Option<Div>, Option<Div>),
 7356        window: &mut Window,
 7357        cx: &mut Context<Self>,
 7358    ) -> Div {
 7359        let center_element = div().flex().flex_col().flex_1().overflow_hidden().child(
 7360            h_flex()
 7361                .flex_1()
 7362                .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7363                .child(self.center.render(
 7364                    self.zoomed.as_ref(),
 7365                    &PaneRenderContext {
 7366                        follower_states: &self.follower_states,
 7367                        active_call: self.active_call(),
 7368                        active_pane: &self.active_pane,
 7369                        app_state: &self.app_state,
 7370                        project: &self.project,
 7371                        workspace: &self.weak_self,
 7372                    },
 7373                    window,
 7374                    cx,
 7375                ))
 7376                .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7377        );
 7378
 7379        let left_drawer = self.render_drawer(DrawerPosition::Left, cx);
 7380        let right_drawer = self.render_drawer(DrawerPosition::Right, cx);
 7381
 7382        let has_drawers = left_drawer.is_some() || right_drawer.is_some();
 7383
 7384        if has_drawers {
 7385            div()
 7386                .flex()
 7387                .flex_row()
 7388                .flex_1()
 7389                .overflow_hidden()
 7390                .children(left_drawer)
 7391                .child(center_element)
 7392                .children(right_drawer)
 7393        } else {
 7394            center_element
 7395        }
 7396    }
 7397
 7398    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7399        window
 7400            .root::<MultiWorkspace>()
 7401            .flatten()
 7402            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7403    }
 7404
 7405    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7406        self.zoomed.as_ref()
 7407    }
 7408
 7409    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7410        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7411            return;
 7412        };
 7413        let windows = cx.windows();
 7414        let next_window =
 7415            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7416                || {
 7417                    windows
 7418                        .iter()
 7419                        .cycle()
 7420                        .skip_while(|window| window.window_id() != current_window_id)
 7421                        .nth(1)
 7422                },
 7423            );
 7424
 7425        if let Some(window) = next_window {
 7426            window
 7427                .update(cx, |_, window, _| window.activate_window())
 7428                .ok();
 7429        }
 7430    }
 7431
 7432    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7433        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7434            return;
 7435        };
 7436        let windows = cx.windows();
 7437        let prev_window =
 7438            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7439                || {
 7440                    windows
 7441                        .iter()
 7442                        .rev()
 7443                        .cycle()
 7444                        .skip_while(|window| window.window_id() != current_window_id)
 7445                        .nth(1)
 7446                },
 7447            );
 7448
 7449        if let Some(window) = prev_window {
 7450            window
 7451                .update(cx, |_, window, _| window.activate_window())
 7452                .ok();
 7453        }
 7454    }
 7455
 7456    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7457        if cx.stop_active_drag(window) {
 7458        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7459            dismiss_app_notification(&notification_id, cx);
 7460        } else {
 7461            cx.propagate();
 7462        }
 7463    }
 7464
 7465    fn adjust_dock_size_by_px(
 7466        &mut self,
 7467        panel_size: Pixels,
 7468        dock_pos: DockPosition,
 7469        px: Pixels,
 7470        window: &mut Window,
 7471        cx: &mut Context<Self>,
 7472    ) {
 7473        match dock_pos {
 7474            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7475            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7476            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7477        }
 7478    }
 7479
 7480    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7481        let workspace_width = self.bounds.size.width;
 7482        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7483
 7484        self.right_dock.read_with(cx, |right_dock, cx| {
 7485            let right_dock_size = right_dock
 7486                .active_panel_size(window, cx)
 7487                .unwrap_or(Pixels::ZERO);
 7488            if right_dock_size + size > workspace_width {
 7489                size = workspace_width - right_dock_size
 7490            }
 7491        });
 7492
 7493        self.left_dock.update(cx, |left_dock, cx| {
 7494            if WorkspaceSettings::get_global(cx)
 7495                .resize_all_panels_in_dock
 7496                .contains(&DockPosition::Left)
 7497            {
 7498                left_dock.resize_all_panels(Some(size), window, cx);
 7499            } else {
 7500                left_dock.resize_active_panel(Some(size), window, cx);
 7501            }
 7502        });
 7503    }
 7504
 7505    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7506        let workspace_width = self.bounds.size.width;
 7507        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7508        self.left_dock.read_with(cx, |left_dock, cx| {
 7509            let left_dock_size = left_dock
 7510                .active_panel_size(window, cx)
 7511                .unwrap_or(Pixels::ZERO);
 7512            if left_dock_size + size > workspace_width {
 7513                size = workspace_width - left_dock_size
 7514            }
 7515        });
 7516        self.right_dock.update(cx, |right_dock, cx| {
 7517            if WorkspaceSettings::get_global(cx)
 7518                .resize_all_panels_in_dock
 7519                .contains(&DockPosition::Right)
 7520            {
 7521                right_dock.resize_all_panels(Some(size), window, cx);
 7522            } else {
 7523                right_dock.resize_active_panel(Some(size), window, cx);
 7524            }
 7525        });
 7526    }
 7527
 7528    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7529        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7530        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7531            if WorkspaceSettings::get_global(cx)
 7532                .resize_all_panels_in_dock
 7533                .contains(&DockPosition::Bottom)
 7534            {
 7535                bottom_dock.resize_all_panels(Some(size), window, cx);
 7536            } else {
 7537                bottom_dock.resize_active_panel(Some(size), window, cx);
 7538            }
 7539        });
 7540    }
 7541
 7542    fn toggle_edit_predictions_all_files(
 7543        &mut self,
 7544        _: &ToggleEditPrediction,
 7545        _window: &mut Window,
 7546        cx: &mut Context<Self>,
 7547    ) {
 7548        let fs = self.project().read(cx).fs().clone();
 7549        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7550        update_settings_file(fs, cx, move |file, _| {
 7551            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7552        });
 7553    }
 7554
 7555    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7556        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7557        let next_mode = match current_mode {
 7558            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7559            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7560            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7561                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7562                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7563            },
 7564        };
 7565
 7566        let fs = self.project().read(cx).fs().clone();
 7567        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7568            theme::set_mode(settings, next_mode);
 7569        });
 7570    }
 7571
 7572    pub fn show_worktree_trust_security_modal(
 7573        &mut self,
 7574        toggle: bool,
 7575        window: &mut Window,
 7576        cx: &mut Context<Self>,
 7577    ) {
 7578        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7579            if toggle {
 7580                security_modal.update(cx, |security_modal, cx| {
 7581                    security_modal.dismiss(cx);
 7582                })
 7583            } else {
 7584                security_modal.update(cx, |security_modal, cx| {
 7585                    security_modal.refresh_restricted_paths(cx);
 7586                });
 7587            }
 7588        } else {
 7589            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7590                .map(|trusted_worktrees| {
 7591                    trusted_worktrees
 7592                        .read(cx)
 7593                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7594                })
 7595                .unwrap_or(false);
 7596            if has_restricted_worktrees {
 7597                let project = self.project().read(cx);
 7598                let remote_host = project
 7599                    .remote_connection_options(cx)
 7600                    .map(RemoteHostLocation::from);
 7601                let worktree_store = project.worktree_store().downgrade();
 7602                self.toggle_modal(window, cx, |_, cx| {
 7603                    SecurityModal::new(worktree_store, remote_host, cx)
 7604                });
 7605            }
 7606        }
 7607    }
 7608}
 7609
 7610pub trait AnyActiveCall {
 7611    fn entity(&self) -> AnyEntity;
 7612    fn is_in_room(&self, _: &App) -> bool;
 7613    fn room_id(&self, _: &App) -> Option<u64>;
 7614    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7615    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7616    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7617    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7618    fn is_sharing_project(&self, _: &App) -> bool;
 7619    fn has_remote_participants(&self, _: &App) -> bool;
 7620    fn local_participant_is_guest(&self, _: &App) -> bool;
 7621    fn client(&self, _: &App) -> Arc<Client>;
 7622    fn share_on_join(&self, _: &App) -> bool;
 7623    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7624    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7625    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7626    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7627    fn join_project(
 7628        &self,
 7629        _: u64,
 7630        _: Arc<LanguageRegistry>,
 7631        _: Arc<dyn Fs>,
 7632        _: &mut App,
 7633    ) -> Task<Result<Entity<Project>>>;
 7634    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7635    fn subscribe(
 7636        &self,
 7637        _: &mut Window,
 7638        _: &mut Context<Workspace>,
 7639        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7640    ) -> Subscription;
 7641    fn create_shared_screen(
 7642        &self,
 7643        _: PeerId,
 7644        _: &Entity<Pane>,
 7645        _: &mut Window,
 7646        _: &mut App,
 7647    ) -> Option<Entity<SharedScreen>>;
 7648}
 7649
 7650#[derive(Clone)]
 7651pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7652impl Global for GlobalAnyActiveCall {}
 7653
 7654impl GlobalAnyActiveCall {
 7655    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7656        cx.try_global()
 7657    }
 7658
 7659    pub(crate) fn global(cx: &App) -> &Self {
 7660        cx.global()
 7661    }
 7662}
 7663
 7664pub fn merge_conflict_notification_id() -> NotificationId {
 7665    struct MergeConflictNotification;
 7666    NotificationId::unique::<MergeConflictNotification>()
 7667}
 7668
 7669/// Workspace-local view of a remote participant's location.
 7670#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7671pub enum ParticipantLocation {
 7672    SharedProject { project_id: u64 },
 7673    UnsharedProject,
 7674    External,
 7675}
 7676
 7677impl ParticipantLocation {
 7678    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7679        match location
 7680            .and_then(|l| l.variant)
 7681            .context("participant location was not provided")?
 7682        {
 7683            proto::participant_location::Variant::SharedProject(project) => {
 7684                Ok(Self::SharedProject {
 7685                    project_id: project.id,
 7686                })
 7687            }
 7688            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7689            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7690        }
 7691    }
 7692}
 7693/// Workspace-local view of a remote collaborator's state.
 7694/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7695#[derive(Clone)]
 7696pub struct RemoteCollaborator {
 7697    pub user: Arc<User>,
 7698    pub peer_id: PeerId,
 7699    pub location: ParticipantLocation,
 7700    pub participant_index: ParticipantIndex,
 7701}
 7702
 7703pub enum ActiveCallEvent {
 7704    ParticipantLocationChanged { participant_id: PeerId },
 7705    RemoteVideoTracksChanged { participant_id: PeerId },
 7706}
 7707
 7708fn leader_border_for_pane(
 7709    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7710    pane: &Entity<Pane>,
 7711    _: &Window,
 7712    cx: &App,
 7713) -> Option<Div> {
 7714    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7715        if state.pane() == pane {
 7716            Some((*leader_id, state))
 7717        } else {
 7718            None
 7719        }
 7720    })?;
 7721
 7722    let mut leader_color = match leader_id {
 7723        CollaboratorId::PeerId(leader_peer_id) => {
 7724            let leader = GlobalAnyActiveCall::try_global(cx)?
 7725                .0
 7726                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7727
 7728            cx.theme()
 7729                .players()
 7730                .color_for_participant(leader.participant_index.0)
 7731                .cursor
 7732        }
 7733        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7734    };
 7735    leader_color.fade_out(0.3);
 7736    Some(
 7737        div()
 7738            .absolute()
 7739            .size_full()
 7740            .left_0()
 7741            .top_0()
 7742            .border_2()
 7743            .border_color(leader_color),
 7744    )
 7745}
 7746
 7747fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7748    ZED_WINDOW_POSITION
 7749        .zip(*ZED_WINDOW_SIZE)
 7750        .map(|(position, size)| Bounds {
 7751            origin: position,
 7752            size,
 7753        })
 7754}
 7755
 7756fn open_items(
 7757    serialized_workspace: Option<SerializedWorkspace>,
 7758    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7759    window: &mut Window,
 7760    cx: &mut Context<Workspace>,
 7761) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7762    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7763        Workspace::load_workspace(
 7764            serialized_workspace,
 7765            project_paths_to_open
 7766                .iter()
 7767                .map(|(_, project_path)| project_path)
 7768                .cloned()
 7769                .collect(),
 7770            window,
 7771            cx,
 7772        )
 7773    });
 7774
 7775    cx.spawn_in(window, async move |workspace, cx| {
 7776        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7777
 7778        if let Some(restored_items) = restored_items {
 7779            let restored_items = restored_items.await?;
 7780
 7781            let restored_project_paths = restored_items
 7782                .iter()
 7783                .filter_map(|item| {
 7784                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7785                        .ok()
 7786                        .flatten()
 7787                })
 7788                .collect::<HashSet<_>>();
 7789
 7790            for restored_item in restored_items {
 7791                opened_items.push(restored_item.map(Ok));
 7792            }
 7793
 7794            project_paths_to_open
 7795                .iter_mut()
 7796                .for_each(|(_, project_path)| {
 7797                    if let Some(project_path_to_open) = project_path
 7798                        && restored_project_paths.contains(project_path_to_open)
 7799                    {
 7800                        *project_path = None;
 7801                    }
 7802                });
 7803        } else {
 7804            for _ in 0..project_paths_to_open.len() {
 7805                opened_items.push(None);
 7806            }
 7807        }
 7808        assert!(opened_items.len() == project_paths_to_open.len());
 7809
 7810        let tasks =
 7811            project_paths_to_open
 7812                .into_iter()
 7813                .enumerate()
 7814                .map(|(ix, (abs_path, project_path))| {
 7815                    let workspace = workspace.clone();
 7816                    cx.spawn(async move |cx| {
 7817                        let file_project_path = project_path?;
 7818                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7819                            workspace.project().update(cx, |project, cx| {
 7820                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7821                            })
 7822                        });
 7823
 7824                        // We only want to open file paths here. If one of the items
 7825                        // here is a directory, it was already opened further above
 7826                        // with a `find_or_create_worktree`.
 7827                        if let Ok(task) = abs_path_task
 7828                            && task.await.is_none_or(|p| p.is_file())
 7829                        {
 7830                            return Some((
 7831                                ix,
 7832                                workspace
 7833                                    .update_in(cx, |workspace, window, cx| {
 7834                                        workspace.open_path(
 7835                                            file_project_path,
 7836                                            None,
 7837                                            true,
 7838                                            window,
 7839                                            cx,
 7840                                        )
 7841                                    })
 7842                                    .log_err()?
 7843                                    .await,
 7844                            ));
 7845                        }
 7846                        None
 7847                    })
 7848                });
 7849
 7850        let tasks = tasks.collect::<Vec<_>>();
 7851
 7852        let tasks = futures::future::join_all(tasks);
 7853        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7854            opened_items[ix] = Some(path_open_result);
 7855        }
 7856
 7857        Ok(opened_items)
 7858    })
 7859}
 7860
 7861enum ActivateInDirectionTarget {
 7862    Pane(Entity<Pane>),
 7863    Dock(Entity<Dock>),
 7864}
 7865
 7866fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7867    window
 7868        .update(cx, |multi_workspace, _, cx| {
 7869            let workspace = multi_workspace.workspace().clone();
 7870            workspace.update(cx, |workspace, cx| {
 7871                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7872                    struct DatabaseFailedNotification;
 7873
 7874                    workspace.show_notification(
 7875                        NotificationId::unique::<DatabaseFailedNotification>(),
 7876                        cx,
 7877                        |cx| {
 7878                            cx.new(|cx| {
 7879                                MessageNotification::new("Failed to load the database file.", cx)
 7880                                    .primary_message("File an Issue")
 7881                                    .primary_icon(IconName::Plus)
 7882                                    .primary_on_click(|window, cx| {
 7883                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7884                                    })
 7885                            })
 7886                        },
 7887                    );
 7888                }
 7889            });
 7890        })
 7891        .log_err();
 7892}
 7893
 7894fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7895    if val == 0 {
 7896        ThemeSettings::get_global(cx).ui_font_size(cx)
 7897    } else {
 7898        px(val as f32)
 7899    }
 7900}
 7901
 7902fn adjust_active_dock_size_by_px(
 7903    px: Pixels,
 7904    workspace: &mut Workspace,
 7905    window: &mut Window,
 7906    cx: &mut Context<Workspace>,
 7907) {
 7908    let Some(active_dock) = workspace
 7909        .all_docks()
 7910        .into_iter()
 7911        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7912    else {
 7913        return;
 7914    };
 7915    let dock = active_dock.read(cx);
 7916    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7917        return;
 7918    };
 7919    let dock_pos = dock.position();
 7920    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7921}
 7922
 7923fn adjust_open_docks_size_by_px(
 7924    px: Pixels,
 7925    workspace: &mut Workspace,
 7926    window: &mut Window,
 7927    cx: &mut Context<Workspace>,
 7928) {
 7929    let docks = workspace
 7930        .all_docks()
 7931        .into_iter()
 7932        .filter_map(|dock| {
 7933            if dock.read(cx).is_open() {
 7934                let dock = dock.read(cx);
 7935                let panel_size = dock.active_panel_size(window, cx)?;
 7936                let dock_pos = dock.position();
 7937                Some((panel_size, dock_pos, px))
 7938            } else {
 7939                None
 7940            }
 7941        })
 7942        .collect::<Vec<_>>();
 7943
 7944    docks
 7945        .into_iter()
 7946        .for_each(|(panel_size, dock_pos, offset)| {
 7947            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7948        });
 7949}
 7950
 7951impl Focusable for Workspace {
 7952    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7953        self.active_pane.focus_handle(cx)
 7954    }
 7955}
 7956
 7957#[derive(Clone)]
 7958struct DraggedDock(DockPosition);
 7959
 7960impl Render for DraggedDock {
 7961    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7962        gpui::Empty
 7963    }
 7964}
 7965
 7966#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 7967pub enum DrawerPosition {
 7968    Left,
 7969    Right,
 7970}
 7971
 7972pub struct Drawer {
 7973    view: AnyView,
 7974    focus_handle_fn: Box<dyn Fn(&App) -> FocusHandle>,
 7975    open: bool,
 7976    custom_width: Option<Pixels>,
 7977}
 7978
 7979impl Drawer {
 7980    fn new<V: Render + Focusable + 'static>(view: Entity<V>) -> Self {
 7981        let entity = view.clone();
 7982        Self {
 7983            view: view.into(),
 7984            focus_handle_fn: Box::new(move |cx| entity.focus_handle(cx)),
 7985            open: false,
 7986            custom_width: None,
 7987        }
 7988    }
 7989
 7990    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7991        (self.focus_handle_fn)(cx)
 7992    }
 7993}
 7994
 7995#[derive(Clone)]
 7996struct DraggedDrawer(DrawerPosition);
 7997
 7998impl Render for DraggedDrawer {
 7999    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8000        gpui::Empty
 8001    }
 8002}
 8003
 8004impl Render for Workspace {
 8005    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8006        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8007        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8008            log::info!("Rendered first frame");
 8009        }
 8010
 8011        let centered_layout = self.centered_layout
 8012            && self.center.panes().len() == 1
 8013            && self.active_item(cx).is_some();
 8014        let render_padding = |size| {
 8015            (size > 0.0).then(|| {
 8016                div()
 8017                    .h_full()
 8018                    .w(relative(size))
 8019                    .bg(cx.theme().colors().editor_background)
 8020                    .border_color(cx.theme().colors().pane_group_border)
 8021            })
 8022        };
 8023        let paddings = if centered_layout {
 8024            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8025            (
 8026                render_padding(Self::adjust_padding(
 8027                    settings.left_padding.map(|padding| padding.0),
 8028                )),
 8029                render_padding(Self::adjust_padding(
 8030                    settings.right_padding.map(|padding| padding.0),
 8031                )),
 8032            )
 8033        } else {
 8034            (None, None)
 8035        };
 8036        let ui_font = theme::setup_ui_font(window, cx);
 8037
 8038        let theme = cx.theme().clone();
 8039        let colors = theme.colors();
 8040        let notification_entities = self
 8041            .notifications
 8042            .iter()
 8043            .map(|(_, notification)| notification.entity_id())
 8044            .collect::<Vec<_>>();
 8045        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8046
 8047        div()
 8048            .relative()
 8049            .size_full()
 8050            .flex()
 8051            .flex_col()
 8052            .font(ui_font)
 8053            .gap_0()
 8054            .justify_start()
 8055            .items_start()
 8056            .text_color(colors.text)
 8057            .overflow_hidden()
 8058            .children(self.titlebar_item.clone())
 8059            .on_modifiers_changed(move |_, _, cx| {
 8060                for &id in &notification_entities {
 8061                    cx.notify(id);
 8062                }
 8063            })
 8064            .child(
 8065                div()
 8066                    .size_full()
 8067                    .relative()
 8068                    .flex_1()
 8069                    .flex()
 8070                    .flex_col()
 8071                    .child(
 8072                        div()
 8073                            .id("workspace")
 8074                            .bg(colors.background)
 8075                            .relative()
 8076                            .flex_1()
 8077                            .w_full()
 8078                            .flex()
 8079                            .flex_col()
 8080                            .overflow_hidden()
 8081                            .border_t_1()
 8082                            .border_b_1()
 8083                            .border_color(colors.border)
 8084                            .child({
 8085                                let this = cx.entity();
 8086                                canvas(
 8087                                    move |bounds, window, cx| {
 8088                                        this.update(cx, |this, cx| {
 8089                                            let bounds_changed = this.bounds != bounds;
 8090                                            this.bounds = bounds;
 8091
 8092                                            if bounds_changed {
 8093                                                this.left_dock.update(cx, |dock, cx| {
 8094                                                    dock.clamp_panel_size(
 8095                                                        bounds.size.width,
 8096                                                        window,
 8097                                                        cx,
 8098                                                    )
 8099                                                });
 8100
 8101                                                this.right_dock.update(cx, |dock, cx| {
 8102                                                    dock.clamp_panel_size(
 8103                                                        bounds.size.width,
 8104                                                        window,
 8105                                                        cx,
 8106                                                    )
 8107                                                });
 8108
 8109                                                this.bottom_dock.update(cx, |dock, cx| {
 8110                                                    dock.clamp_panel_size(
 8111                                                        bounds.size.height,
 8112                                                        window,
 8113                                                        cx,
 8114                                                    )
 8115                                                });
 8116                                            }
 8117                                        })
 8118                                    },
 8119                                    |_, _, _, _| {},
 8120                                )
 8121                                .absolute()
 8122                                .size_full()
 8123                            })
 8124                            .when(self.zoomed.is_none(), |this| {
 8125                                this.on_drag_move(cx.listener(
 8126                                    move |workspace, e: &DragMoveEvent<DraggedDock>, window, cx| {
 8127                                        if workspace.previous_dock_drag_coordinates
 8128                                            != Some(e.event.position)
 8129                                        {
 8130                                            workspace.previous_dock_drag_coordinates =
 8131                                                Some(e.event.position);
 8132
 8133                                            match e.drag(cx).0 {
 8134                                                DockPosition::Left => {
 8135                                                    workspace.resize_left_dock(
 8136                                                        e.event.position.x
 8137                                                            - workspace.bounds.left(),
 8138                                                        window,
 8139                                                        cx,
 8140                                                    );
 8141                                                }
 8142                                                DockPosition::Right => {
 8143                                                    workspace.resize_right_dock(
 8144                                                        workspace.bounds.right()
 8145                                                            - e.event.position.x,
 8146                                                        window,
 8147                                                        cx,
 8148                                                    );
 8149                                                }
 8150                                                DockPosition::Bottom => {
 8151                                                    workspace.resize_bottom_dock(
 8152                                                        workspace.bounds.bottom()
 8153                                                            - e.event.position.y,
 8154                                                        window,
 8155                                                        cx,
 8156                                                    );
 8157                                                }
 8158                                            };
 8159                                            workspace.serialize_workspace(window, cx);
 8160                                        }
 8161                                    },
 8162                                ))
 8163                                .on_drag_move(cx.listener(
 8164                                    move |workspace,
 8165                                          e: &DragMoveEvent<DraggedDrawer>,
 8166                                          window,
 8167                                          cx| {
 8168                                        match e.drag(cx).0 {
 8169                                            DrawerPosition::Left => {
 8170                                                workspace.resize_left_drawer(
 8171                                                    e.event.position.x - workspace.bounds.left(),
 8172                                                    window,
 8173                                                    cx,
 8174                                                );
 8175                                            }
 8176                                            DrawerPosition::Right => {
 8177                                                workspace.resize_right_drawer(
 8178                                                    workspace.bounds.right() - e.event.position.x,
 8179                                                    window,
 8180                                                    cx,
 8181                                                );
 8182                                            }
 8183                                        }
 8184                                        workspace.serialize_workspace(window, cx);
 8185                                    },
 8186                                ))
 8187                            })
 8188                            .child({
 8189                                match bottom_dock_layout {
 8190                                    BottomDockLayout::Full => div()
 8191                                        .flex()
 8192                                        .flex_col()
 8193                                        .h_full()
 8194                                        .child(
 8195                                            div()
 8196                                                .flex()
 8197                                                .flex_row()
 8198                                                .flex_1()
 8199                                                .overflow_hidden()
 8200                                                .children(self.render_dock(
 8201                                                    DockPosition::Left,
 8202                                                    &self.left_dock,
 8203                                                    window,
 8204                                                    cx,
 8205                                                ))
 8206                                                .child(self.render_center_with_drawers(
 8207                                                    paddings, window, cx,
 8208                                                ))
 8209                                                .children(self.render_dock(
 8210                                                    DockPosition::Right,
 8211                                                    &self.right_dock,
 8212                                                    window,
 8213                                                    cx,
 8214                                                )),
 8215                                        )
 8216                                        .child(div().w_full().children(self.render_dock(
 8217                                            DockPosition::Bottom,
 8218                                            &self.bottom_dock,
 8219                                            window,
 8220                                            cx,
 8221                                        ))),
 8222
 8223                                    BottomDockLayout::LeftAligned => div()
 8224                                        .flex()
 8225                                        .flex_row()
 8226                                        .h_full()
 8227                                        .child(
 8228                                            div()
 8229                                                .flex()
 8230                                                .flex_col()
 8231                                                .flex_1()
 8232                                                .h_full()
 8233                                                .child(
 8234                                                    div()
 8235                                                        .flex()
 8236                                                        .flex_row()
 8237                                                        .flex_1()
 8238                                                        .children(self.render_dock(
 8239                                                            DockPosition::Left,
 8240                                                            &self.left_dock,
 8241                                                            window,
 8242                                                            cx,
 8243                                                        ))
 8244                                                        .child(self.render_center_with_drawers(
 8245                                                            paddings, window, cx,
 8246                                                        )),
 8247                                                )
 8248                                                .child(div().w_full().children(self.render_dock(
 8249                                                    DockPosition::Bottom,
 8250                                                    &self.bottom_dock,
 8251                                                    window,
 8252                                                    cx,
 8253                                                ))),
 8254                                        )
 8255                                        .children(self.render_dock(
 8256                                            DockPosition::Right,
 8257                                            &self.right_dock,
 8258                                            window,
 8259                                            cx,
 8260                                        )),
 8261
 8262                                    BottomDockLayout::RightAligned => div()
 8263                                        .flex()
 8264                                        .flex_row()
 8265                                        .h_full()
 8266                                        .children(self.render_dock(
 8267                                            DockPosition::Left,
 8268                                            &self.left_dock,
 8269                                            window,
 8270                                            cx,
 8271                                        ))
 8272                                        .child(
 8273                                            div()
 8274                                                .flex()
 8275                                                .flex_col()
 8276                                                .flex_1()
 8277                                                .h_full()
 8278                                                .child(
 8279                                                    div()
 8280                                                        .flex()
 8281                                                        .flex_row()
 8282                                                        .flex_1()
 8283                                                        .child(self.render_center_with_drawers(
 8284                                                            paddings, window, cx,
 8285                                                        ))
 8286                                                        .children(self.render_dock(
 8287                                                            DockPosition::Right,
 8288                                                            &self.right_dock,
 8289                                                            window,
 8290                                                            cx,
 8291                                                        )),
 8292                                                )
 8293                                                .child(div().w_full().children(self.render_dock(
 8294                                                    DockPosition::Bottom,
 8295                                                    &self.bottom_dock,
 8296                                                    window,
 8297                                                    cx,
 8298                                                ))),
 8299                                        ),
 8300
 8301                                    BottomDockLayout::Contained => div()
 8302                                        .flex()
 8303                                        .flex_row()
 8304                                        .h_full()
 8305                                        .children(self.render_dock(
 8306                                            DockPosition::Left,
 8307                                            &self.left_dock,
 8308                                            window,
 8309                                            cx,
 8310                                        ))
 8311                                        .child(
 8312                                            div()
 8313                                                .flex()
 8314                                                .flex_col()
 8315                                                .flex_1()
 8316                                                .overflow_hidden()
 8317                                                .child(self.render_center_with_drawers(
 8318                                                    paddings, window, cx,
 8319                                                ))
 8320                                                .children(self.render_dock(
 8321                                                    DockPosition::Bottom,
 8322                                                    &self.bottom_dock,
 8323                                                    window,
 8324                                                    cx,
 8325                                                )),
 8326                                        )
 8327                                        .children(self.render_dock(
 8328                                            DockPosition::Right,
 8329                                            &self.right_dock,
 8330                                            window,
 8331                                            cx,
 8332                                        )),
 8333                                }
 8334                            })
 8335                            .children(self.zoomed.as_ref().and_then(|view| {
 8336                                let zoomed_view = view.upgrade()?;
 8337                                let div = div()
 8338                                    .occlude()
 8339                                    .absolute()
 8340                                    .overflow_hidden()
 8341                                    .border_color(colors.border)
 8342                                    .bg(colors.background)
 8343                                    .child(zoomed_view)
 8344                                    .inset_0()
 8345                                    .shadow_lg();
 8346
 8347                                if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8348                                    return Some(div);
 8349                                }
 8350
 8351                                Some(match self.zoomed_position {
 8352                                    Some(DockPosition::Left) => div.right_2().border_r_1(),
 8353                                    Some(DockPosition::Right) => div.left_2().border_l_1(),
 8354                                    Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8355                                    None => div.top_2().bottom_2().left_2().right_2().border_1(),
 8356                                })
 8357                            }))
 8358                            .children(self.render_notifications(window, cx)),
 8359                    )
 8360                    .when(self.status_bar_visible(cx), |parent| {
 8361                        parent.child(self.status_bar.clone())
 8362                    })
 8363                    .child(self.toast_layer.clone()),
 8364            )
 8365    }
 8366}
 8367
 8368impl WorkspaceStore {
 8369    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8370        Self {
 8371            workspaces: Default::default(),
 8372            _subscriptions: vec![
 8373                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8374                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8375            ],
 8376            client,
 8377        }
 8378    }
 8379
 8380    pub fn update_followers(
 8381        &self,
 8382        project_id: Option<u64>,
 8383        update: proto::update_followers::Variant,
 8384        cx: &App,
 8385    ) -> Option<()> {
 8386        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8387        let room_id = active_call.0.room_id(cx)?;
 8388        self.client
 8389            .send(proto::UpdateFollowers {
 8390                room_id,
 8391                project_id,
 8392                variant: Some(update),
 8393            })
 8394            .log_err()
 8395    }
 8396
 8397    pub async fn handle_follow(
 8398        this: Entity<Self>,
 8399        envelope: TypedEnvelope<proto::Follow>,
 8400        mut cx: AsyncApp,
 8401    ) -> Result<proto::FollowResponse> {
 8402        this.update(&mut cx, |this, cx| {
 8403            let follower = Follower {
 8404                project_id: envelope.payload.project_id,
 8405                peer_id: envelope.original_sender_id()?,
 8406            };
 8407
 8408            let mut response = proto::FollowResponse::default();
 8409
 8410            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8411                let Some(workspace) = weak_workspace.upgrade() else {
 8412                    return false;
 8413                };
 8414                window_handle
 8415                    .update(cx, |_, window, cx| {
 8416                        workspace.update(cx, |workspace, cx| {
 8417                            let handler_response =
 8418                                workspace.handle_follow(follower.project_id, window, cx);
 8419                            if let Some(active_view) = handler_response.active_view
 8420                                && workspace.project.read(cx).remote_id() == follower.project_id
 8421                            {
 8422                                response.active_view = Some(active_view)
 8423                            }
 8424                        });
 8425                    })
 8426                    .is_ok()
 8427            });
 8428
 8429            Ok(response)
 8430        })
 8431    }
 8432
 8433    async fn handle_update_followers(
 8434        this: Entity<Self>,
 8435        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8436        mut cx: AsyncApp,
 8437    ) -> Result<()> {
 8438        let leader_id = envelope.original_sender_id()?;
 8439        let update = envelope.payload;
 8440
 8441        this.update(&mut cx, |this, cx| {
 8442            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8443                let Some(workspace) = weak_workspace.upgrade() else {
 8444                    return false;
 8445                };
 8446                window_handle
 8447                    .update(cx, |_, window, cx| {
 8448                        workspace.update(cx, |workspace, cx| {
 8449                            let project_id = workspace.project.read(cx).remote_id();
 8450                            if update.project_id != project_id && update.project_id.is_some() {
 8451                                return;
 8452                            }
 8453                            workspace.handle_update_followers(
 8454                                leader_id,
 8455                                update.clone(),
 8456                                window,
 8457                                cx,
 8458                            );
 8459                        });
 8460                    })
 8461                    .is_ok()
 8462            });
 8463            Ok(())
 8464        })
 8465    }
 8466
 8467    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8468        self.workspaces.iter().map(|(_, weak)| weak)
 8469    }
 8470
 8471    pub fn workspaces_with_windows(
 8472        &self,
 8473    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8474        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8475    }
 8476}
 8477
 8478impl ViewId {
 8479    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8480        Ok(Self {
 8481            creator: message
 8482                .creator
 8483                .map(CollaboratorId::PeerId)
 8484                .context("creator is missing")?,
 8485            id: message.id,
 8486        })
 8487    }
 8488
 8489    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8490        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8491            Some(proto::ViewId {
 8492                creator: Some(peer_id),
 8493                id: self.id,
 8494            })
 8495        } else {
 8496            None
 8497        }
 8498    }
 8499}
 8500
 8501impl FollowerState {
 8502    fn pane(&self) -> &Entity<Pane> {
 8503        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8504    }
 8505}
 8506
 8507pub trait WorkspaceHandle {
 8508    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8509}
 8510
 8511impl WorkspaceHandle for Entity<Workspace> {
 8512    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8513        self.read(cx)
 8514            .worktrees(cx)
 8515            .flat_map(|worktree| {
 8516                let worktree_id = worktree.read(cx).id();
 8517                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8518                    worktree_id,
 8519                    path: f.path.clone(),
 8520                })
 8521            })
 8522            .collect::<Vec<_>>()
 8523    }
 8524}
 8525
 8526pub async fn last_opened_workspace_location(
 8527    fs: &dyn fs::Fs,
 8528) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8529    DB.last_workspace(fs)
 8530        .await
 8531        .log_err()
 8532        .flatten()
 8533        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8534}
 8535
 8536pub async fn last_session_workspace_locations(
 8537    last_session_id: &str,
 8538    last_session_window_stack: Option<Vec<WindowId>>,
 8539    fs: &dyn fs::Fs,
 8540) -> Option<Vec<SessionWorkspace>> {
 8541    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8542        .await
 8543        .log_err()
 8544}
 8545
 8546pub struct MultiWorkspaceRestoreResult {
 8547    pub window_handle: WindowHandle<MultiWorkspace>,
 8548    pub errors: Vec<anyhow::Error>,
 8549}
 8550
 8551pub async fn restore_multiworkspace(
 8552    multi_workspace: SerializedMultiWorkspace,
 8553    app_state: Arc<AppState>,
 8554    cx: &mut AsyncApp,
 8555) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8556    let SerializedMultiWorkspace {
 8557        workspaces,
 8558        state,
 8559        id: window_id,
 8560    } = multi_workspace;
 8561    let mut group_iter = workspaces.into_iter();
 8562    let first = group_iter
 8563        .next()
 8564        .context("window group must not be empty")?;
 8565
 8566    let window_handle = if first.paths.is_empty() {
 8567        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8568            .await?
 8569    } else {
 8570        let OpenResult { window, .. } = cx
 8571            .update(|cx| {
 8572                Workspace::new_local(
 8573                    first.paths.paths().to_vec(),
 8574                    app_state.clone(),
 8575                    None,
 8576                    None,
 8577                    None,
 8578                    true,
 8579                    cx,
 8580                )
 8581            })
 8582            .await?;
 8583        window
 8584    };
 8585
 8586    let mut errors = Vec::new();
 8587
 8588    for session_workspace in group_iter {
 8589        let error = if session_workspace.paths.is_empty() {
 8590            cx.update(|cx| {
 8591                open_workspace_by_id(
 8592                    session_workspace.workspace_id,
 8593                    app_state.clone(),
 8594                    Some(window_handle),
 8595                    cx,
 8596                )
 8597            })
 8598            .await
 8599            .err()
 8600        } else {
 8601            cx.update(|cx| {
 8602                Workspace::new_local(
 8603                    session_workspace.paths.paths().to_vec(),
 8604                    app_state.clone(),
 8605                    Some(window_handle),
 8606                    None,
 8607                    None,
 8608                    true,
 8609                    cx,
 8610                )
 8611            })
 8612            .await
 8613            .err()
 8614        };
 8615
 8616        if let Some(error) = error {
 8617            errors.push(error);
 8618        }
 8619    }
 8620
 8621    if let Some(target_id) = state.active_workspace_id {
 8622        window_handle
 8623            .update(cx, |multi_workspace, window, cx| {
 8624                multi_workspace.set_database_id(window_id);
 8625                let target_index = multi_workspace
 8626                    .workspaces()
 8627                    .iter()
 8628                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8629                if let Some(index) = target_index {
 8630                    multi_workspace.activate_index(index, window, cx);
 8631                } else if !multi_workspace.workspaces().is_empty() {
 8632                    multi_workspace.activate_index(0, window, cx);
 8633                }
 8634            })
 8635            .ok();
 8636    } else {
 8637        window_handle
 8638            .update(cx, |multi_workspace, window, cx| {
 8639                if !multi_workspace.workspaces().is_empty() {
 8640                    multi_workspace.activate_index(0, window, cx);
 8641                }
 8642            })
 8643            .ok();
 8644    }
 8645
 8646    window_handle
 8647        .update(cx, |_, window, _cx| {
 8648            window.activate_window();
 8649        })
 8650        .ok();
 8651
 8652    Ok(MultiWorkspaceRestoreResult {
 8653        window_handle,
 8654        errors,
 8655    })
 8656}
 8657
 8658actions!(
 8659    collab,
 8660    [
 8661        /// Opens the channel notes for the current call.
 8662        ///
 8663        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8664        /// channel in the collab panel.
 8665        ///
 8666        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8667        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8668        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8669        OpenChannelNotes,
 8670        /// Mutes your microphone.
 8671        Mute,
 8672        /// Deafens yourself (mute both microphone and speakers).
 8673        Deafen,
 8674        /// Leaves the current call.
 8675        LeaveCall,
 8676        /// Shares the current project with collaborators.
 8677        ShareProject,
 8678        /// Shares your screen with collaborators.
 8679        ScreenShare,
 8680        /// Copies the current room name and session id for debugging purposes.
 8681        CopyRoomId,
 8682    ]
 8683);
 8684
 8685/// Opens the channel notes for a specific channel by its ID.
 8686#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8687#[action(namespace = collab)]
 8688#[serde(deny_unknown_fields)]
 8689pub struct OpenChannelNotesById {
 8690    pub channel_id: u64,
 8691}
 8692
 8693actions!(
 8694    zed,
 8695    [
 8696        /// Opens the Zed log file.
 8697        OpenLog,
 8698        /// Reveals the Zed log file in the system file manager.
 8699        RevealLogInFileManager
 8700    ]
 8701);
 8702
 8703async fn join_channel_internal(
 8704    channel_id: ChannelId,
 8705    app_state: &Arc<AppState>,
 8706    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8707    requesting_workspace: Option<WeakEntity<Workspace>>,
 8708    active_call: &dyn AnyActiveCall,
 8709    cx: &mut AsyncApp,
 8710) -> Result<bool> {
 8711    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8712        if !active_call.is_in_room(cx) {
 8713            return (false, false);
 8714        }
 8715
 8716        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8717        let should_prompt = active_call.is_sharing_project(cx)
 8718            && active_call.has_remote_participants(cx)
 8719            && !already_in_channel;
 8720        (should_prompt, already_in_channel)
 8721    });
 8722
 8723    if already_in_channel {
 8724        let task = cx.update(|cx| {
 8725            if let Some((project, host)) = active_call.most_active_project(cx) {
 8726                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8727            } else {
 8728                None
 8729            }
 8730        });
 8731        if let Some(task) = task {
 8732            task.await?;
 8733        }
 8734        return anyhow::Ok(true);
 8735    }
 8736
 8737    if should_prompt {
 8738        if let Some(multi_workspace) = requesting_window {
 8739            let answer = multi_workspace
 8740                .update(cx, |_, window, cx| {
 8741                    window.prompt(
 8742                        PromptLevel::Warning,
 8743                        "Do you want to switch channels?",
 8744                        Some("Leaving this call will unshare your current project."),
 8745                        &["Yes, Join Channel", "Cancel"],
 8746                        cx,
 8747                    )
 8748                })?
 8749                .await;
 8750
 8751            if answer == Ok(1) {
 8752                return Ok(false);
 8753            }
 8754        } else {
 8755            return Ok(false);
 8756        }
 8757    }
 8758
 8759    let client = cx.update(|cx| active_call.client(cx));
 8760
 8761    let mut client_status = client.status();
 8762
 8763    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8764    'outer: loop {
 8765        let Some(status) = client_status.recv().await else {
 8766            anyhow::bail!("error connecting");
 8767        };
 8768
 8769        match status {
 8770            Status::Connecting
 8771            | Status::Authenticating
 8772            | Status::Authenticated
 8773            | Status::Reconnecting
 8774            | Status::Reauthenticating
 8775            | Status::Reauthenticated => continue,
 8776            Status::Connected { .. } => break 'outer,
 8777            Status::SignedOut | Status::AuthenticationError => {
 8778                return Err(ErrorCode::SignedOut.into());
 8779            }
 8780            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8781            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8782                return Err(ErrorCode::Disconnected.into());
 8783            }
 8784        }
 8785    }
 8786
 8787    let joined = cx
 8788        .update(|cx| active_call.join_channel(channel_id, cx))
 8789        .await?;
 8790
 8791    if !joined {
 8792        return anyhow::Ok(true);
 8793    }
 8794
 8795    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8796
 8797    let task = cx.update(|cx| {
 8798        if let Some((project, host)) = active_call.most_active_project(cx) {
 8799            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8800        }
 8801
 8802        // If you are the first to join a channel, see if you should share your project.
 8803        if !active_call.has_remote_participants(cx)
 8804            && !active_call.local_participant_is_guest(cx)
 8805            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8806        {
 8807            let project = workspace.update(cx, |workspace, cx| {
 8808                let project = workspace.project.read(cx);
 8809
 8810                if !active_call.share_on_join(cx) {
 8811                    return None;
 8812                }
 8813
 8814                if (project.is_local() || project.is_via_remote_server())
 8815                    && project.visible_worktrees(cx).any(|tree| {
 8816                        tree.read(cx)
 8817                            .root_entry()
 8818                            .is_some_and(|entry| entry.is_dir())
 8819                    })
 8820                {
 8821                    Some(workspace.project.clone())
 8822                } else {
 8823                    None
 8824                }
 8825            });
 8826            if let Some(project) = project {
 8827                let share_task = active_call.share_project(project, cx);
 8828                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8829                    share_task.await?;
 8830                    Ok(())
 8831                }));
 8832            }
 8833        }
 8834
 8835        None
 8836    });
 8837    if let Some(task) = task {
 8838        task.await?;
 8839        return anyhow::Ok(true);
 8840    }
 8841    anyhow::Ok(false)
 8842}
 8843
 8844pub fn join_channel(
 8845    channel_id: ChannelId,
 8846    app_state: Arc<AppState>,
 8847    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8848    requesting_workspace: Option<WeakEntity<Workspace>>,
 8849    cx: &mut App,
 8850) -> Task<Result<()>> {
 8851    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8852    cx.spawn(async move |cx| {
 8853        let result = join_channel_internal(
 8854            channel_id,
 8855            &app_state,
 8856            requesting_window,
 8857            requesting_workspace,
 8858            &*active_call.0,
 8859            cx,
 8860        )
 8861        .await;
 8862
 8863        // join channel succeeded, and opened a window
 8864        if matches!(result, Ok(true)) {
 8865            return anyhow::Ok(());
 8866        }
 8867
 8868        // find an existing workspace to focus and show call controls
 8869        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8870        if active_window.is_none() {
 8871            // no open workspaces, make one to show the error in (blergh)
 8872            let OpenResult {
 8873                window: window_handle,
 8874                ..
 8875            } = cx
 8876                .update(|cx| {
 8877                    Workspace::new_local(
 8878                        vec![],
 8879                        app_state.clone(),
 8880                        requesting_window,
 8881                        None,
 8882                        None,
 8883                        true,
 8884                        cx,
 8885                    )
 8886                })
 8887                .await?;
 8888
 8889            window_handle
 8890                .update(cx, |_, window, _cx| {
 8891                    window.activate_window();
 8892                })
 8893                .ok();
 8894
 8895            if result.is_ok() {
 8896                cx.update(|cx| {
 8897                    cx.dispatch_action(&OpenChannelNotes);
 8898                });
 8899            }
 8900
 8901            active_window = Some(window_handle);
 8902        }
 8903
 8904        if let Err(err) = result {
 8905            log::error!("failed to join channel: {}", err);
 8906            if let Some(active_window) = active_window {
 8907                active_window
 8908                    .update(cx, |_, window, cx| {
 8909                        let detail: SharedString = match err.error_code() {
 8910                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8911                            ErrorCode::UpgradeRequired => concat!(
 8912                                "Your are running an unsupported version of Zed. ",
 8913                                "Please update to continue."
 8914                            )
 8915                            .into(),
 8916                            ErrorCode::NoSuchChannel => concat!(
 8917                                "No matching channel was found. ",
 8918                                "Please check the link and try again."
 8919                            )
 8920                            .into(),
 8921                            ErrorCode::Forbidden => concat!(
 8922                                "This channel is private, and you do not have access. ",
 8923                                "Please ask someone to add you and try again."
 8924                            )
 8925                            .into(),
 8926                            ErrorCode::Disconnected => {
 8927                                "Please check your internet connection and try again.".into()
 8928                            }
 8929                            _ => format!("{}\n\nPlease try again.", err).into(),
 8930                        };
 8931                        window.prompt(
 8932                            PromptLevel::Critical,
 8933                            "Failed to join channel",
 8934                            Some(&detail),
 8935                            &["Ok"],
 8936                            cx,
 8937                        )
 8938                    })?
 8939                    .await
 8940                    .ok();
 8941            }
 8942        }
 8943
 8944        // return ok, we showed the error to the user.
 8945        anyhow::Ok(())
 8946    })
 8947}
 8948
 8949pub async fn get_any_active_multi_workspace(
 8950    app_state: Arc<AppState>,
 8951    mut cx: AsyncApp,
 8952) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8953    // find an existing workspace to focus and show call controls
 8954    let active_window = activate_any_workspace_window(&mut cx);
 8955    if active_window.is_none() {
 8956        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8957            .await?;
 8958    }
 8959    activate_any_workspace_window(&mut cx).context("could not open zed")
 8960}
 8961
 8962fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8963    cx.update(|cx| {
 8964        if let Some(workspace_window) = cx
 8965            .active_window()
 8966            .and_then(|window| window.downcast::<MultiWorkspace>())
 8967        {
 8968            return Some(workspace_window);
 8969        }
 8970
 8971        for window in cx.windows() {
 8972            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8973                workspace_window
 8974                    .update(cx, |_, window, _| window.activate_window())
 8975                    .ok();
 8976                return Some(workspace_window);
 8977            }
 8978        }
 8979        None
 8980    })
 8981}
 8982
 8983pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8984    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8985}
 8986
 8987pub fn workspace_windows_for_location(
 8988    serialized_location: &SerializedWorkspaceLocation,
 8989    cx: &App,
 8990) -> Vec<WindowHandle<MultiWorkspace>> {
 8991    cx.windows()
 8992        .into_iter()
 8993        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8994        .filter(|multi_workspace| {
 8995            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8996                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8997                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8998                }
 8999                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9000                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9001                    a.distro_name == b.distro_name
 9002                }
 9003                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9004                    a.container_id == b.container_id
 9005                }
 9006                #[cfg(any(test, feature = "test-support"))]
 9007                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9008                    a.id == b.id
 9009                }
 9010                _ => false,
 9011            };
 9012
 9013            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9014                multi_workspace.workspaces().iter().any(|workspace| {
 9015                    match workspace.read(cx).workspace_location(cx) {
 9016                        WorkspaceLocation::Location(location, _) => {
 9017                            match (&location, serialized_location) {
 9018                                (
 9019                                    SerializedWorkspaceLocation::Local,
 9020                                    SerializedWorkspaceLocation::Local,
 9021                                ) => true,
 9022                                (
 9023                                    SerializedWorkspaceLocation::Remote(a),
 9024                                    SerializedWorkspaceLocation::Remote(b),
 9025                                ) => same_host(a, b),
 9026                                _ => false,
 9027                            }
 9028                        }
 9029                        _ => false,
 9030                    }
 9031                })
 9032            })
 9033        })
 9034        .collect()
 9035}
 9036
 9037pub async fn find_existing_workspace(
 9038    abs_paths: &[PathBuf],
 9039    open_options: &OpenOptions,
 9040    location: &SerializedWorkspaceLocation,
 9041    cx: &mut AsyncApp,
 9042) -> (
 9043    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9044    OpenVisible,
 9045) {
 9046    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9047    let mut open_visible = OpenVisible::All;
 9048    let mut best_match = None;
 9049
 9050    if open_options.open_new_workspace != Some(true) {
 9051        cx.update(|cx| {
 9052            for window in workspace_windows_for_location(location, cx) {
 9053                if let Ok(multi_workspace) = window.read(cx) {
 9054                    for workspace in multi_workspace.workspaces() {
 9055                        let project = workspace.read(cx).project.read(cx);
 9056                        let m = project.visibility_for_paths(
 9057                            abs_paths,
 9058                            open_options.open_new_workspace == None,
 9059                            cx,
 9060                        );
 9061                        if m > best_match {
 9062                            existing = Some((window, workspace.clone()));
 9063                            best_match = m;
 9064                        } else if best_match.is_none()
 9065                            && open_options.open_new_workspace == Some(false)
 9066                        {
 9067                            existing = Some((window, workspace.clone()))
 9068                        }
 9069                    }
 9070                }
 9071            }
 9072        });
 9073
 9074        let all_paths_are_files = existing
 9075            .as_ref()
 9076            .and_then(|(_, target_workspace)| {
 9077                cx.update(|cx| {
 9078                    let workspace = target_workspace.read(cx);
 9079                    let project = workspace.project.read(cx);
 9080                    let path_style = workspace.path_style(cx);
 9081                    Some(!abs_paths.iter().any(|path| {
 9082                        let path = util::paths::SanitizedPath::new(path);
 9083                        project.worktrees(cx).any(|worktree| {
 9084                            let worktree = worktree.read(cx);
 9085                            let abs_path = worktree.abs_path();
 9086                            path_style
 9087                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9088                                .and_then(|rel| worktree.entry_for_path(&rel))
 9089                                .is_some_and(|e| e.is_dir())
 9090                        })
 9091                    }))
 9092                })
 9093            })
 9094            .unwrap_or(false);
 9095
 9096        if open_options.open_new_workspace.is_none()
 9097            && existing.is_some()
 9098            && open_options.wait
 9099            && all_paths_are_files
 9100        {
 9101            cx.update(|cx| {
 9102                let windows = workspace_windows_for_location(location, cx);
 9103                let window = cx
 9104                    .active_window()
 9105                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9106                    .filter(|window| windows.contains(window))
 9107                    .or_else(|| windows.into_iter().next());
 9108                if let Some(window) = window {
 9109                    if let Ok(multi_workspace) = window.read(cx) {
 9110                        let active_workspace = multi_workspace.workspace().clone();
 9111                        existing = Some((window, active_workspace));
 9112                        open_visible = OpenVisible::None;
 9113                    }
 9114                }
 9115            });
 9116        }
 9117    }
 9118    (existing, open_visible)
 9119}
 9120
 9121#[derive(Default, Clone)]
 9122pub struct OpenOptions {
 9123    pub visible: Option<OpenVisible>,
 9124    pub focus: Option<bool>,
 9125    pub open_new_workspace: Option<bool>,
 9126    pub wait: bool,
 9127    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 9128    pub env: Option<HashMap<String, String>>,
 9129}
 9130
 9131/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9132/// or [`Workspace::open_workspace_for_paths`].
 9133pub struct OpenResult {
 9134    pub window: WindowHandle<MultiWorkspace>,
 9135    pub workspace: Entity<Workspace>,
 9136    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9137}
 9138
 9139/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9140pub fn open_workspace_by_id(
 9141    workspace_id: WorkspaceId,
 9142    app_state: Arc<AppState>,
 9143    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9144    cx: &mut App,
 9145) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9146    let project_handle = Project::local(
 9147        app_state.client.clone(),
 9148        app_state.node_runtime.clone(),
 9149        app_state.user_store.clone(),
 9150        app_state.languages.clone(),
 9151        app_state.fs.clone(),
 9152        None,
 9153        project::LocalProjectFlags {
 9154            init_worktree_trust: true,
 9155            ..project::LocalProjectFlags::default()
 9156        },
 9157        cx,
 9158    );
 9159
 9160    cx.spawn(async move |cx| {
 9161        let serialized_workspace = persistence::DB
 9162            .workspace_for_id(workspace_id)
 9163            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9164
 9165        let centered_layout = serialized_workspace.centered_layout;
 9166
 9167        let (window, workspace) = if let Some(window) = requesting_window {
 9168            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9169                let workspace = cx.new(|cx| {
 9170                    let mut workspace = Workspace::new(
 9171                        Some(workspace_id),
 9172                        project_handle.clone(),
 9173                        app_state.clone(),
 9174                        window,
 9175                        cx,
 9176                    );
 9177                    workspace.centered_layout = centered_layout;
 9178                    workspace
 9179                });
 9180                multi_workspace.add_workspace(workspace.clone(), cx);
 9181                workspace
 9182            })?;
 9183            (window, workspace)
 9184        } else {
 9185            let window_bounds_override = window_bounds_env_override();
 9186
 9187            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9188                (Some(WindowBounds::Windowed(bounds)), None)
 9189            } else if let Some(display) = serialized_workspace.display
 9190                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9191            {
 9192                (Some(bounds.0), Some(display))
 9193            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 9194                (Some(bounds), Some(display))
 9195            } else {
 9196                (None, None)
 9197            };
 9198
 9199            let options = cx.update(|cx| {
 9200                let mut options = (app_state.build_window_options)(display, cx);
 9201                options.window_bounds = window_bounds;
 9202                options
 9203            });
 9204
 9205            let window = cx.open_window(options, {
 9206                let app_state = app_state.clone();
 9207                let project_handle = project_handle.clone();
 9208                move |window, cx| {
 9209                    let workspace = cx.new(|cx| {
 9210                        let mut workspace = Workspace::new(
 9211                            Some(workspace_id),
 9212                            project_handle,
 9213                            app_state,
 9214                            window,
 9215                            cx,
 9216                        );
 9217                        workspace.centered_layout = centered_layout;
 9218                        workspace
 9219                    });
 9220                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9221                }
 9222            })?;
 9223
 9224            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9225                multi_workspace.workspace().clone()
 9226            })?;
 9227
 9228            (window, workspace)
 9229        };
 9230
 9231        notify_if_database_failed(window, cx);
 9232
 9233        // Restore items from the serialized workspace
 9234        window
 9235            .update(cx, |_, window, cx| {
 9236                workspace.update(cx, |_workspace, cx| {
 9237                    open_items(Some(serialized_workspace), vec![], window, cx)
 9238                })
 9239            })?
 9240            .await?;
 9241
 9242        window.update(cx, |_, window, cx| {
 9243            workspace.update(cx, |workspace, cx| {
 9244                workspace.serialize_workspace(window, cx);
 9245            });
 9246        })?;
 9247
 9248        Ok(window)
 9249    })
 9250}
 9251
 9252#[allow(clippy::type_complexity)]
 9253pub fn open_paths(
 9254    abs_paths: &[PathBuf],
 9255    app_state: Arc<AppState>,
 9256    open_options: OpenOptions,
 9257    cx: &mut App,
 9258) -> Task<anyhow::Result<OpenResult>> {
 9259    let abs_paths = abs_paths.to_vec();
 9260    #[cfg(target_os = "windows")]
 9261    let wsl_path = abs_paths
 9262        .iter()
 9263        .find_map(|p| util::paths::WslPath::from_path(p));
 9264
 9265    cx.spawn(async move |cx| {
 9266        let (mut existing, mut open_visible) = find_existing_workspace(
 9267            &abs_paths,
 9268            &open_options,
 9269            &SerializedWorkspaceLocation::Local,
 9270            cx,
 9271        )
 9272        .await;
 9273
 9274        // Fallback: if no workspace contains the paths and all paths are files,
 9275        // prefer an existing local workspace window (active window first).
 9276        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9277            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9278            let all_metadatas = futures::future::join_all(all_paths)
 9279                .await
 9280                .into_iter()
 9281                .filter_map(|result| result.ok().flatten())
 9282                .collect::<Vec<_>>();
 9283
 9284            if all_metadatas.iter().all(|file| !file.is_dir) {
 9285                cx.update(|cx| {
 9286                    let windows = workspace_windows_for_location(
 9287                        &SerializedWorkspaceLocation::Local,
 9288                        cx,
 9289                    );
 9290                    let window = cx
 9291                        .active_window()
 9292                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9293                        .filter(|window| windows.contains(window))
 9294                        .or_else(|| windows.into_iter().next());
 9295                    if let Some(window) = window {
 9296                        if let Ok(multi_workspace) = window.read(cx) {
 9297                            let active_workspace = multi_workspace.workspace().clone();
 9298                            existing = Some((window, active_workspace));
 9299                            open_visible = OpenVisible::None;
 9300                        }
 9301                    }
 9302                });
 9303            }
 9304        }
 9305
 9306        let result = if let Some((existing, target_workspace)) = existing {
 9307            let open_task = existing
 9308                .update(cx, |multi_workspace, window, cx| {
 9309                    window.activate_window();
 9310                    multi_workspace.activate(target_workspace.clone(), cx);
 9311                    target_workspace.update(cx, |workspace, cx| {
 9312                        workspace.open_paths(
 9313                            abs_paths,
 9314                            OpenOptions {
 9315                                visible: Some(open_visible),
 9316                                ..Default::default()
 9317                            },
 9318                            None,
 9319                            window,
 9320                            cx,
 9321                        )
 9322                    })
 9323                })?
 9324                .await;
 9325
 9326            _ = existing.update(cx, |multi_workspace, _, cx| {
 9327                let workspace = multi_workspace.workspace().clone();
 9328                workspace.update(cx, |workspace, cx| {
 9329                    for item in open_task.iter().flatten() {
 9330                        if let Err(e) = item {
 9331                            workspace.show_error(&e, cx);
 9332                        }
 9333                    }
 9334                });
 9335            });
 9336
 9337            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9338        } else {
 9339            let result = cx
 9340                .update(move |cx| {
 9341                    Workspace::new_local(
 9342                        abs_paths,
 9343                        app_state.clone(),
 9344                        open_options.replace_window,
 9345                        open_options.env,
 9346                        None,
 9347                        true,
 9348                        cx,
 9349                    )
 9350                })
 9351                .await;
 9352
 9353            if let Ok(ref result) = result {
 9354                result.window
 9355                    .update(cx, |_, window, _cx| {
 9356                        window.activate_window();
 9357                    })
 9358                    .log_err();
 9359            }
 9360
 9361            result
 9362        };
 9363
 9364        #[cfg(target_os = "windows")]
 9365        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9366            && let Ok(ref result) = result
 9367        {
 9368            result.window
 9369                .update(cx, move |multi_workspace, _window, cx| {
 9370                    struct OpenInWsl;
 9371                    let workspace = multi_workspace.workspace().clone();
 9372                    workspace.update(cx, |workspace, cx| {
 9373                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9374                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9375                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9376                            cx.new(move |cx| {
 9377                                MessageNotification::new(msg, cx)
 9378                                    .primary_message("Open in WSL")
 9379                                    .primary_icon(IconName::FolderOpen)
 9380                                    .primary_on_click(move |window, cx| {
 9381                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9382                                                distro: remote::WslConnectionOptions {
 9383                                                        distro_name: distro.clone(),
 9384                                                    user: None,
 9385                                                },
 9386                                                paths: vec![path.clone().into()],
 9387                                            }), cx)
 9388                                    })
 9389                            })
 9390                        });
 9391                    });
 9392                })
 9393                .unwrap();
 9394        };
 9395        result
 9396    })
 9397}
 9398
 9399pub fn open_new(
 9400    open_options: OpenOptions,
 9401    app_state: Arc<AppState>,
 9402    cx: &mut App,
 9403    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9404) -> Task<anyhow::Result<()>> {
 9405    let task = Workspace::new_local(
 9406        Vec::new(),
 9407        app_state,
 9408        open_options.replace_window,
 9409        open_options.env,
 9410        Some(Box::new(init)),
 9411        true,
 9412        cx,
 9413    );
 9414    cx.spawn(async move |cx| {
 9415        let OpenResult { window, .. } = task.await?;
 9416        window
 9417            .update(cx, |_, window, _cx| {
 9418                window.activate_window();
 9419            })
 9420            .ok();
 9421        Ok(())
 9422    })
 9423}
 9424
 9425pub fn create_and_open_local_file(
 9426    path: &'static Path,
 9427    window: &mut Window,
 9428    cx: &mut Context<Workspace>,
 9429    default_content: impl 'static + Send + FnOnce() -> Rope,
 9430) -> Task<Result<Box<dyn ItemHandle>>> {
 9431    cx.spawn_in(window, async move |workspace, cx| {
 9432        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9433        if !fs.is_file(path).await {
 9434            fs.create_file(path, Default::default()).await?;
 9435            fs.save(path, &default_content(), Default::default())
 9436                .await?;
 9437        }
 9438
 9439        workspace
 9440            .update_in(cx, |workspace, window, cx| {
 9441                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9442                    let path = workspace
 9443                        .project
 9444                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9445                    cx.spawn_in(window, async move |workspace, cx| {
 9446                        let path = path.await?;
 9447                        let mut items = workspace
 9448                            .update_in(cx, |workspace, window, cx| {
 9449                                workspace.open_paths(
 9450                                    vec![path.to_path_buf()],
 9451                                    OpenOptions {
 9452                                        visible: Some(OpenVisible::None),
 9453                                        ..Default::default()
 9454                                    },
 9455                                    None,
 9456                                    window,
 9457                                    cx,
 9458                                )
 9459                            })?
 9460                            .await;
 9461                        let item = items.pop().flatten();
 9462                        item.with_context(|| format!("path {path:?} is not a file"))?
 9463                    })
 9464                })
 9465            })?
 9466            .await?
 9467            .await
 9468    })
 9469}
 9470
 9471pub fn open_remote_project_with_new_connection(
 9472    window: WindowHandle<MultiWorkspace>,
 9473    remote_connection: Arc<dyn RemoteConnection>,
 9474    cancel_rx: oneshot::Receiver<()>,
 9475    delegate: Arc<dyn RemoteClientDelegate>,
 9476    app_state: Arc<AppState>,
 9477    paths: Vec<PathBuf>,
 9478    cx: &mut App,
 9479) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9480    cx.spawn(async move |cx| {
 9481        let (workspace_id, serialized_workspace) =
 9482            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9483                .await?;
 9484
 9485        let session = match cx
 9486            .update(|cx| {
 9487                remote::RemoteClient::new(
 9488                    ConnectionIdentifier::Workspace(workspace_id.0),
 9489                    remote_connection,
 9490                    cancel_rx,
 9491                    delegate,
 9492                    cx,
 9493                )
 9494            })
 9495            .await?
 9496        {
 9497            Some(result) => result,
 9498            None => return Ok(Vec::new()),
 9499        };
 9500
 9501        let project = cx.update(|cx| {
 9502            project::Project::remote(
 9503                session,
 9504                app_state.client.clone(),
 9505                app_state.node_runtime.clone(),
 9506                app_state.user_store.clone(),
 9507                app_state.languages.clone(),
 9508                app_state.fs.clone(),
 9509                true,
 9510                cx,
 9511            )
 9512        });
 9513
 9514        open_remote_project_inner(
 9515            project,
 9516            paths,
 9517            workspace_id,
 9518            serialized_workspace,
 9519            app_state,
 9520            window,
 9521            cx,
 9522        )
 9523        .await
 9524    })
 9525}
 9526
 9527pub fn open_remote_project_with_existing_connection(
 9528    connection_options: RemoteConnectionOptions,
 9529    project: Entity<Project>,
 9530    paths: Vec<PathBuf>,
 9531    app_state: Arc<AppState>,
 9532    window: WindowHandle<MultiWorkspace>,
 9533    cx: &mut AsyncApp,
 9534) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9535    cx.spawn(async move |cx| {
 9536        let (workspace_id, serialized_workspace) =
 9537            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9538
 9539        open_remote_project_inner(
 9540            project,
 9541            paths,
 9542            workspace_id,
 9543            serialized_workspace,
 9544            app_state,
 9545            window,
 9546            cx,
 9547        )
 9548        .await
 9549    })
 9550}
 9551
 9552async fn open_remote_project_inner(
 9553    project: Entity<Project>,
 9554    paths: Vec<PathBuf>,
 9555    workspace_id: WorkspaceId,
 9556    serialized_workspace: Option<SerializedWorkspace>,
 9557    app_state: Arc<AppState>,
 9558    window: WindowHandle<MultiWorkspace>,
 9559    cx: &mut AsyncApp,
 9560) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9561    let toolchains = DB.toolchains(workspace_id).await?;
 9562    for (toolchain, worktree_path, path) in toolchains {
 9563        project
 9564            .update(cx, |this, cx| {
 9565                let Some(worktree_id) =
 9566                    this.find_worktree(&worktree_path, cx)
 9567                        .and_then(|(worktree, rel_path)| {
 9568                            if rel_path.is_empty() {
 9569                                Some(worktree.read(cx).id())
 9570                            } else {
 9571                                None
 9572                            }
 9573                        })
 9574                else {
 9575                    return Task::ready(None);
 9576                };
 9577
 9578                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9579            })
 9580            .await;
 9581    }
 9582    let mut project_paths_to_open = vec![];
 9583    let mut project_path_errors = vec![];
 9584
 9585    for path in paths {
 9586        let result = cx
 9587            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9588            .await;
 9589        match result {
 9590            Ok((_, project_path)) => {
 9591                project_paths_to_open.push((path.clone(), Some(project_path)));
 9592            }
 9593            Err(error) => {
 9594                project_path_errors.push(error);
 9595            }
 9596        };
 9597    }
 9598
 9599    if project_paths_to_open.is_empty() {
 9600        return Err(project_path_errors.pop().context("no paths given")?);
 9601    }
 9602
 9603    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9604        telemetry::event!("SSH Project Opened");
 9605
 9606        let new_workspace = cx.new(|cx| {
 9607            let mut workspace =
 9608                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9609            workspace.update_history(cx);
 9610
 9611            if let Some(ref serialized) = serialized_workspace {
 9612                workspace.centered_layout = serialized.centered_layout;
 9613            }
 9614
 9615            workspace
 9616        });
 9617
 9618        multi_workspace.activate(new_workspace.clone(), cx);
 9619        new_workspace
 9620    })?;
 9621
 9622    let items = window
 9623        .update(cx, |_, window, cx| {
 9624            window.activate_window();
 9625            workspace.update(cx, |_workspace, cx| {
 9626                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9627            })
 9628        })?
 9629        .await?;
 9630
 9631    workspace.update(cx, |workspace, cx| {
 9632        for error in project_path_errors {
 9633            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9634                if let Some(path) = error.error_tag("path") {
 9635                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9636                }
 9637            } else {
 9638                workspace.show_error(&error, cx)
 9639            }
 9640        }
 9641    });
 9642
 9643    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9644}
 9645
 9646fn deserialize_remote_project(
 9647    connection_options: RemoteConnectionOptions,
 9648    paths: Vec<PathBuf>,
 9649    cx: &AsyncApp,
 9650) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9651    cx.background_spawn(async move {
 9652        let remote_connection_id = persistence::DB
 9653            .get_or_create_remote_connection(connection_options)
 9654            .await?;
 9655
 9656        let serialized_workspace =
 9657            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9658
 9659        let workspace_id = if let Some(workspace_id) =
 9660            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9661        {
 9662            workspace_id
 9663        } else {
 9664            persistence::DB.next_id().await?
 9665        };
 9666
 9667        Ok((workspace_id, serialized_workspace))
 9668    })
 9669}
 9670
 9671pub fn join_in_room_project(
 9672    project_id: u64,
 9673    follow_user_id: u64,
 9674    app_state: Arc<AppState>,
 9675    cx: &mut App,
 9676) -> Task<Result<()>> {
 9677    let windows = cx.windows();
 9678    cx.spawn(async move |cx| {
 9679        let existing_window_and_workspace: Option<(
 9680            WindowHandle<MultiWorkspace>,
 9681            Entity<Workspace>,
 9682        )> = windows.into_iter().find_map(|window_handle| {
 9683            window_handle
 9684                .downcast::<MultiWorkspace>()
 9685                .and_then(|window_handle| {
 9686                    window_handle
 9687                        .update(cx, |multi_workspace, _window, cx| {
 9688                            for workspace in multi_workspace.workspaces() {
 9689                                if workspace.read(cx).project().read(cx).remote_id()
 9690                                    == Some(project_id)
 9691                                {
 9692                                    return Some((window_handle, workspace.clone()));
 9693                                }
 9694                            }
 9695                            None
 9696                        })
 9697                        .unwrap_or(None)
 9698                })
 9699        });
 9700
 9701        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9702            existing_window_and_workspace
 9703        {
 9704            existing_window
 9705                .update(cx, |multi_workspace, _, cx| {
 9706                    multi_workspace.activate(target_workspace, cx);
 9707                })
 9708                .ok();
 9709            existing_window
 9710        } else {
 9711            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9712            let project = cx
 9713                .update(|cx| {
 9714                    active_call.0.join_project(
 9715                        project_id,
 9716                        app_state.languages.clone(),
 9717                        app_state.fs.clone(),
 9718                        cx,
 9719                    )
 9720                })
 9721                .await?;
 9722
 9723            let window_bounds_override = window_bounds_env_override();
 9724            cx.update(|cx| {
 9725                let mut options = (app_state.build_window_options)(None, cx);
 9726                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9727                cx.open_window(options, |window, cx| {
 9728                    let workspace = cx.new(|cx| {
 9729                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9730                    });
 9731                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9732                })
 9733            })?
 9734        };
 9735
 9736        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9737            cx.activate(true);
 9738            window.activate_window();
 9739
 9740            // We set the active workspace above, so this is the correct workspace.
 9741            let workspace = multi_workspace.workspace().clone();
 9742            workspace.update(cx, |workspace, cx| {
 9743                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9744                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9745                    .or_else(|| {
 9746                        // If we couldn't follow the given user, follow the host instead.
 9747                        let collaborator = workspace
 9748                            .project()
 9749                            .read(cx)
 9750                            .collaborators()
 9751                            .values()
 9752                            .find(|collaborator| collaborator.is_host)?;
 9753                        Some(collaborator.peer_id)
 9754                    });
 9755
 9756                if let Some(follow_peer_id) = follow_peer_id {
 9757                    workspace.follow(follow_peer_id, window, cx);
 9758                }
 9759            });
 9760        })?;
 9761
 9762        anyhow::Ok(())
 9763    })
 9764}
 9765
 9766pub fn reload(cx: &mut App) {
 9767    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9768    let mut workspace_windows = cx
 9769        .windows()
 9770        .into_iter()
 9771        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9772        .collect::<Vec<_>>();
 9773
 9774    // If multiple windows have unsaved changes, and need a save prompt,
 9775    // prompt in the active window before switching to a different window.
 9776    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9777
 9778    let mut prompt = None;
 9779    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9780        prompt = window
 9781            .update(cx, |_, window, cx| {
 9782                window.prompt(
 9783                    PromptLevel::Info,
 9784                    "Are you sure you want to restart?",
 9785                    None,
 9786                    &["Restart", "Cancel"],
 9787                    cx,
 9788                )
 9789            })
 9790            .ok();
 9791    }
 9792
 9793    cx.spawn(async move |cx| {
 9794        if let Some(prompt) = prompt {
 9795            let answer = prompt.await?;
 9796            if answer != 0 {
 9797                return anyhow::Ok(());
 9798            }
 9799        }
 9800
 9801        // If the user cancels any save prompt, then keep the app open.
 9802        for window in workspace_windows {
 9803            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9804                let workspace = multi_workspace.workspace().clone();
 9805                workspace.update(cx, |workspace, cx| {
 9806                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9807                })
 9808            }) && !should_close.await?
 9809            {
 9810                return anyhow::Ok(());
 9811            }
 9812        }
 9813        cx.update(|cx| cx.restart());
 9814        anyhow::Ok(())
 9815    })
 9816    .detach_and_log_err(cx);
 9817}
 9818
 9819fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9820    let mut parts = value.split(',');
 9821    let x: usize = parts.next()?.parse().ok()?;
 9822    let y: usize = parts.next()?.parse().ok()?;
 9823    Some(point(px(x as f32), px(y as f32)))
 9824}
 9825
 9826fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9827    let mut parts = value.split(',');
 9828    let width: usize = parts.next()?.parse().ok()?;
 9829    let height: usize = parts.next()?.parse().ok()?;
 9830    Some(size(px(width as f32), px(height as f32)))
 9831}
 9832
 9833/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9834/// appropriate.
 9835///
 9836/// The `border_radius_tiling` parameter allows overriding which corners get
 9837/// rounded, independently of the actual window tiling state. This is used
 9838/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9839/// we want square corners on the left (so the sidebar appears flush with the
 9840/// window edge) but we still need the shadow padding for proper visual
 9841/// appearance. Unlike actual window tiling, this only affects border radius -
 9842/// not padding or shadows.
 9843pub fn client_side_decorations(
 9844    element: impl IntoElement,
 9845    window: &mut Window,
 9846    cx: &mut App,
 9847    border_radius_tiling: Tiling,
 9848) -> Stateful<Div> {
 9849    const BORDER_SIZE: Pixels = px(1.0);
 9850    let decorations = window.window_decorations();
 9851    let tiling = match decorations {
 9852        Decorations::Server => Tiling::default(),
 9853        Decorations::Client { tiling } => tiling,
 9854    };
 9855
 9856    match decorations {
 9857        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9858        Decorations::Server => window.set_client_inset(px(0.0)),
 9859    }
 9860
 9861    struct GlobalResizeEdge(ResizeEdge);
 9862    impl Global for GlobalResizeEdge {}
 9863
 9864    div()
 9865        .id("window-backdrop")
 9866        .bg(transparent_black())
 9867        .map(|div| match decorations {
 9868            Decorations::Server => div,
 9869            Decorations::Client { .. } => div
 9870                .when(
 9871                    !(tiling.top
 9872                        || tiling.right
 9873                        || border_radius_tiling.top
 9874                        || border_radius_tiling.right),
 9875                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9876                )
 9877                .when(
 9878                    !(tiling.top
 9879                        || tiling.left
 9880                        || border_radius_tiling.top
 9881                        || border_radius_tiling.left),
 9882                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9883                )
 9884                .when(
 9885                    !(tiling.bottom
 9886                        || tiling.right
 9887                        || border_radius_tiling.bottom
 9888                        || border_radius_tiling.right),
 9889                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9890                )
 9891                .when(
 9892                    !(tiling.bottom
 9893                        || tiling.left
 9894                        || border_radius_tiling.bottom
 9895                        || border_radius_tiling.left),
 9896                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9897                )
 9898                .when(!tiling.top, |div| {
 9899                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9900                })
 9901                .when(!tiling.bottom, |div| {
 9902                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9903                })
 9904                .when(!tiling.left, |div| {
 9905                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9906                })
 9907                .when(!tiling.right, |div| {
 9908                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9909                })
 9910                .on_mouse_move(move |e, window, cx| {
 9911                    let size = window.window_bounds().get_bounds().size;
 9912                    let pos = e.position;
 9913
 9914                    let new_edge =
 9915                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9916
 9917                    let edge = cx.try_global::<GlobalResizeEdge>();
 9918                    if new_edge != edge.map(|edge| edge.0) {
 9919                        window
 9920                            .window_handle()
 9921                            .update(cx, |workspace, _, cx| {
 9922                                cx.notify(workspace.entity_id());
 9923                            })
 9924                            .ok();
 9925                    }
 9926                })
 9927                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9928                    let size = window.window_bounds().get_bounds().size;
 9929                    let pos = e.position;
 9930
 9931                    let edge = match resize_edge(
 9932                        pos,
 9933                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9934                        size,
 9935                        tiling,
 9936                    ) {
 9937                        Some(value) => value,
 9938                        None => return,
 9939                    };
 9940
 9941                    window.start_window_resize(edge);
 9942                }),
 9943        })
 9944        .size_full()
 9945        .child(
 9946            div()
 9947                .cursor(CursorStyle::Arrow)
 9948                .map(|div| match decorations {
 9949                    Decorations::Server => div,
 9950                    Decorations::Client { .. } => div
 9951                        .border_color(cx.theme().colors().border)
 9952                        .when(
 9953                            !(tiling.top
 9954                                || tiling.right
 9955                                || border_radius_tiling.top
 9956                                || border_radius_tiling.right),
 9957                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9958                        )
 9959                        .when(
 9960                            !(tiling.top
 9961                                || tiling.left
 9962                                || border_radius_tiling.top
 9963                                || border_radius_tiling.left),
 9964                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9965                        )
 9966                        .when(
 9967                            !(tiling.bottom
 9968                                || tiling.right
 9969                                || border_radius_tiling.bottom
 9970                                || border_radius_tiling.right),
 9971                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9972                        )
 9973                        .when(
 9974                            !(tiling.bottom
 9975                                || tiling.left
 9976                                || border_radius_tiling.bottom
 9977                                || border_radius_tiling.left),
 9978                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9979                        )
 9980                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9981                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9982                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9983                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9984                        .when(!tiling.is_tiled(), |div| {
 9985                            div.shadow(vec![gpui::BoxShadow {
 9986                                color: Hsla {
 9987                                    h: 0.,
 9988                                    s: 0.,
 9989                                    l: 0.,
 9990                                    a: 0.4,
 9991                                },
 9992                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9993                                spread_radius: px(0.),
 9994                                offset: point(px(0.0), px(0.0)),
 9995                            }])
 9996                        }),
 9997                })
 9998                .on_mouse_move(|_e, _, cx| {
 9999                    cx.stop_propagation();
10000                })
10001                .size_full()
10002                .child(element),
10003        )
10004        .map(|div| match decorations {
10005            Decorations::Server => div,
10006            Decorations::Client { tiling, .. } => div.child(
10007                canvas(
10008                    |_bounds, window, _| {
10009                        window.insert_hitbox(
10010                            Bounds::new(
10011                                point(px(0.0), px(0.0)),
10012                                window.window_bounds().get_bounds().size,
10013                            ),
10014                            HitboxBehavior::Normal,
10015                        )
10016                    },
10017                    move |_bounds, hitbox, window, cx| {
10018                        let mouse = window.mouse_position();
10019                        let size = window.window_bounds().get_bounds().size;
10020                        let Some(edge) =
10021                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10022                        else {
10023                            return;
10024                        };
10025                        cx.set_global(GlobalResizeEdge(edge));
10026                        window.set_cursor_style(
10027                            match edge {
10028                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10029                                ResizeEdge::Left | ResizeEdge::Right => {
10030                                    CursorStyle::ResizeLeftRight
10031                                }
10032                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10033                                    CursorStyle::ResizeUpLeftDownRight
10034                                }
10035                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10036                                    CursorStyle::ResizeUpRightDownLeft
10037                                }
10038                            },
10039                            &hitbox,
10040                        );
10041                    },
10042                )
10043                .size_full()
10044                .absolute(),
10045            ),
10046        })
10047}
10048
10049fn resize_edge(
10050    pos: Point<Pixels>,
10051    shadow_size: Pixels,
10052    window_size: Size<Pixels>,
10053    tiling: Tiling,
10054) -> Option<ResizeEdge> {
10055    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10056    if bounds.contains(&pos) {
10057        return None;
10058    }
10059
10060    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10061    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10062    if !tiling.top && top_left_bounds.contains(&pos) {
10063        return Some(ResizeEdge::TopLeft);
10064    }
10065
10066    let top_right_bounds = Bounds::new(
10067        Point::new(window_size.width - corner_size.width, px(0.)),
10068        corner_size,
10069    );
10070    if !tiling.top && top_right_bounds.contains(&pos) {
10071        return Some(ResizeEdge::TopRight);
10072    }
10073
10074    let bottom_left_bounds = Bounds::new(
10075        Point::new(px(0.), window_size.height - corner_size.height),
10076        corner_size,
10077    );
10078    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10079        return Some(ResizeEdge::BottomLeft);
10080    }
10081
10082    let bottom_right_bounds = Bounds::new(
10083        Point::new(
10084            window_size.width - corner_size.width,
10085            window_size.height - corner_size.height,
10086        ),
10087        corner_size,
10088    );
10089    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10090        return Some(ResizeEdge::BottomRight);
10091    }
10092
10093    if !tiling.top && pos.y < shadow_size {
10094        Some(ResizeEdge::Top)
10095    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10096        Some(ResizeEdge::Bottom)
10097    } else if !tiling.left && pos.x < shadow_size {
10098        Some(ResizeEdge::Left)
10099    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10100        Some(ResizeEdge::Right)
10101    } else {
10102        None
10103    }
10104}
10105
10106fn join_pane_into_active(
10107    active_pane: &Entity<Pane>,
10108    pane: &Entity<Pane>,
10109    window: &mut Window,
10110    cx: &mut App,
10111) {
10112    if pane == active_pane {
10113    } else if pane.read(cx).items_len() == 0 {
10114        pane.update(cx, |_, cx| {
10115            cx.emit(pane::Event::Remove {
10116                focus_on_pane: None,
10117            });
10118        })
10119    } else {
10120        move_all_items(pane, active_pane, window, cx);
10121    }
10122}
10123
10124fn move_all_items(
10125    from_pane: &Entity<Pane>,
10126    to_pane: &Entity<Pane>,
10127    window: &mut Window,
10128    cx: &mut App,
10129) {
10130    let destination_is_different = from_pane != to_pane;
10131    let mut moved_items = 0;
10132    for (item_ix, item_handle) in from_pane
10133        .read(cx)
10134        .items()
10135        .enumerate()
10136        .map(|(ix, item)| (ix, item.clone()))
10137        .collect::<Vec<_>>()
10138    {
10139        let ix = item_ix - moved_items;
10140        if destination_is_different {
10141            // Close item from previous pane
10142            from_pane.update(cx, |source, cx| {
10143                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10144            });
10145            moved_items += 1;
10146        }
10147
10148        // This automatically removes duplicate items in the pane
10149        to_pane.update(cx, |destination, cx| {
10150            destination.add_item(item_handle, true, true, None, window, cx);
10151            window.focus(&destination.focus_handle(cx), cx)
10152        });
10153    }
10154}
10155
10156pub fn move_item(
10157    source: &Entity<Pane>,
10158    destination: &Entity<Pane>,
10159    item_id_to_move: EntityId,
10160    destination_index: usize,
10161    activate: bool,
10162    window: &mut Window,
10163    cx: &mut App,
10164) {
10165    let Some((item_ix, item_handle)) = source
10166        .read(cx)
10167        .items()
10168        .enumerate()
10169        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10170        .map(|(ix, item)| (ix, item.clone()))
10171    else {
10172        // Tab was closed during drag
10173        return;
10174    };
10175
10176    if source != destination {
10177        // Close item from previous pane
10178        source.update(cx, |source, cx| {
10179            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10180        });
10181    }
10182
10183    // This automatically removes duplicate items in the pane
10184    destination.update(cx, |destination, cx| {
10185        destination.add_item_inner(
10186            item_handle,
10187            activate,
10188            activate,
10189            activate,
10190            Some(destination_index),
10191            window,
10192            cx,
10193        );
10194        if activate {
10195            window.focus(&destination.focus_handle(cx), cx)
10196        }
10197    });
10198}
10199
10200pub fn move_active_item(
10201    source: &Entity<Pane>,
10202    destination: &Entity<Pane>,
10203    focus_destination: bool,
10204    close_if_empty: bool,
10205    window: &mut Window,
10206    cx: &mut App,
10207) {
10208    if source == destination {
10209        return;
10210    }
10211    let Some(active_item) = source.read(cx).active_item() else {
10212        return;
10213    };
10214    source.update(cx, |source_pane, cx| {
10215        let item_id = active_item.item_id();
10216        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10217        destination.update(cx, |target_pane, cx| {
10218            target_pane.add_item(
10219                active_item,
10220                focus_destination,
10221                focus_destination,
10222                Some(target_pane.items_len()),
10223                window,
10224                cx,
10225            );
10226        });
10227    });
10228}
10229
10230pub fn clone_active_item(
10231    workspace_id: Option<WorkspaceId>,
10232    source: &Entity<Pane>,
10233    destination: &Entity<Pane>,
10234    focus_destination: bool,
10235    window: &mut Window,
10236    cx: &mut App,
10237) {
10238    if source == destination {
10239        return;
10240    }
10241    let Some(active_item) = source.read(cx).active_item() else {
10242        return;
10243    };
10244    if !active_item.can_split(cx) {
10245        return;
10246    }
10247    let destination = destination.downgrade();
10248    let task = active_item.clone_on_split(workspace_id, window, cx);
10249    window
10250        .spawn(cx, async move |cx| {
10251            let Some(clone) = task.await else {
10252                return;
10253            };
10254            destination
10255                .update_in(cx, |target_pane, window, cx| {
10256                    target_pane.add_item(
10257                        clone,
10258                        focus_destination,
10259                        focus_destination,
10260                        Some(target_pane.items_len()),
10261                        window,
10262                        cx,
10263                    );
10264                })
10265                .log_err();
10266        })
10267        .detach();
10268}
10269
10270#[derive(Debug)]
10271pub struct WorkspacePosition {
10272    pub window_bounds: Option<WindowBounds>,
10273    pub display: Option<Uuid>,
10274    pub centered_layout: bool,
10275}
10276
10277pub fn remote_workspace_position_from_db(
10278    connection_options: RemoteConnectionOptions,
10279    paths_to_open: &[PathBuf],
10280    cx: &App,
10281) -> Task<Result<WorkspacePosition>> {
10282    let paths = paths_to_open.to_vec();
10283
10284    cx.background_spawn(async move {
10285        let remote_connection_id = persistence::DB
10286            .get_or_create_remote_connection(connection_options)
10287            .await
10288            .context("fetching serialized ssh project")?;
10289        let serialized_workspace =
10290            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
10291
10292        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10293            (Some(WindowBounds::Windowed(bounds)), None)
10294        } else {
10295            let restorable_bounds = serialized_workspace
10296                .as_ref()
10297                .and_then(|workspace| {
10298                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10299                })
10300                .or_else(|| persistence::read_default_window_bounds());
10301
10302            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10303                (Some(serialized_bounds), Some(serialized_display))
10304            } else {
10305                (None, None)
10306            }
10307        };
10308
10309        let centered_layout = serialized_workspace
10310            .as_ref()
10311            .map(|w| w.centered_layout)
10312            .unwrap_or(false);
10313
10314        Ok(WorkspacePosition {
10315            window_bounds,
10316            display,
10317            centered_layout,
10318        })
10319    })
10320}
10321
10322pub fn with_active_or_new_workspace(
10323    cx: &mut App,
10324    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10325) {
10326    match cx
10327        .active_window()
10328        .and_then(|w| w.downcast::<MultiWorkspace>())
10329    {
10330        Some(multi_workspace) => {
10331            cx.defer(move |cx| {
10332                multi_workspace
10333                    .update(cx, |multi_workspace, window, cx| {
10334                        let workspace = multi_workspace.workspace().clone();
10335                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10336                    })
10337                    .log_err();
10338            });
10339        }
10340        None => {
10341            let app_state = AppState::global(cx);
10342            if let Some(app_state) = app_state.upgrade() {
10343                open_new(
10344                    OpenOptions::default(),
10345                    app_state,
10346                    cx,
10347                    move |workspace, window, cx| f(workspace, window, cx),
10348                )
10349                .detach_and_log_err(cx);
10350            }
10351        }
10352    }
10353}
10354
10355#[cfg(test)]
10356mod tests {
10357    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10358
10359    use super::*;
10360    use crate::{
10361        dock::{PanelEvent, test::TestPanel},
10362        item::{
10363            ItemBufferKind, ItemEvent,
10364            test::{TestItem, TestProjectItem},
10365        },
10366    };
10367    use fs::FakeFs;
10368    use gpui::{
10369        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10370        UpdateGlobal, VisualTestContext, px,
10371    };
10372    use project::{Project, ProjectEntryId};
10373    use serde_json::json;
10374    use settings::SettingsStore;
10375    use util::path;
10376    use util::rel_path::rel_path;
10377
10378    #[gpui::test]
10379    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10380        init_test(cx);
10381
10382        let fs = FakeFs::new(cx.executor());
10383        let project = Project::test(fs, [], cx).await;
10384        let (workspace, cx) =
10385            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10386
10387        // Adding an item with no ambiguity renders the tab without detail.
10388        let item1 = cx.new(|cx| {
10389            let mut item = TestItem::new(cx);
10390            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10391            item
10392        });
10393        workspace.update_in(cx, |workspace, window, cx| {
10394            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10395        });
10396        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10397
10398        // Adding an item that creates ambiguity increases the level of detail on
10399        // both tabs.
10400        let item2 = cx.new_window_entity(|_window, cx| {
10401            let mut item = TestItem::new(cx);
10402            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10403            item
10404        });
10405        workspace.update_in(cx, |workspace, window, cx| {
10406            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10407        });
10408        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10409        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10410
10411        // Adding an item that creates ambiguity increases the level of detail only
10412        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10413        // we stop at the highest detail available.
10414        let item3 = cx.new(|cx| {
10415            let mut item = TestItem::new(cx);
10416            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10417            item
10418        });
10419        workspace.update_in(cx, |workspace, window, cx| {
10420            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10421        });
10422        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10423        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10424        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10425    }
10426
10427    #[gpui::test]
10428    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10429        init_test(cx);
10430
10431        let fs = FakeFs::new(cx.executor());
10432        fs.insert_tree(
10433            "/root1",
10434            json!({
10435                "one.txt": "",
10436                "two.txt": "",
10437            }),
10438        )
10439        .await;
10440        fs.insert_tree(
10441            "/root2",
10442            json!({
10443                "three.txt": "",
10444            }),
10445        )
10446        .await;
10447
10448        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10449        let (workspace, cx) =
10450            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10451        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10452        let worktree_id = project.update(cx, |project, cx| {
10453            project.worktrees(cx).next().unwrap().read(cx).id()
10454        });
10455
10456        let item1 = cx.new(|cx| {
10457            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10458        });
10459        let item2 = cx.new(|cx| {
10460            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10461        });
10462
10463        // Add an item to an empty pane
10464        workspace.update_in(cx, |workspace, window, cx| {
10465            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10466        });
10467        project.update(cx, |project, cx| {
10468            assert_eq!(
10469                project.active_entry(),
10470                project
10471                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10472                    .map(|e| e.id)
10473            );
10474        });
10475        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10476
10477        // Add a second item to a non-empty pane
10478        workspace.update_in(cx, |workspace, window, cx| {
10479            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10480        });
10481        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10482        project.update(cx, |project, cx| {
10483            assert_eq!(
10484                project.active_entry(),
10485                project
10486                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10487                    .map(|e| e.id)
10488            );
10489        });
10490
10491        // Close the active item
10492        pane.update_in(cx, |pane, window, cx| {
10493            pane.close_active_item(&Default::default(), window, cx)
10494        })
10495        .await
10496        .unwrap();
10497        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10498        project.update(cx, |project, cx| {
10499            assert_eq!(
10500                project.active_entry(),
10501                project
10502                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10503                    .map(|e| e.id)
10504            );
10505        });
10506
10507        // Add a project folder
10508        project
10509            .update(cx, |project, cx| {
10510                project.find_or_create_worktree("root2", true, cx)
10511            })
10512            .await
10513            .unwrap();
10514        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10515
10516        // Remove a project folder
10517        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10518        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10519    }
10520
10521    #[gpui::test]
10522    async fn test_close_window(cx: &mut TestAppContext) {
10523        init_test(cx);
10524
10525        let fs = FakeFs::new(cx.executor());
10526        fs.insert_tree("/root", json!({ "one": "" })).await;
10527
10528        let project = Project::test(fs, ["root".as_ref()], cx).await;
10529        let (workspace, cx) =
10530            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10531
10532        // When there are no dirty items, there's nothing to do.
10533        let item1 = cx.new(TestItem::new);
10534        workspace.update_in(cx, |w, window, cx| {
10535            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10536        });
10537        let task = workspace.update_in(cx, |w, window, cx| {
10538            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10539        });
10540        assert!(task.await.unwrap());
10541
10542        // When there are dirty untitled items, prompt to save each one. If the user
10543        // cancels any prompt, then abort.
10544        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10545        let item3 = cx.new(|cx| {
10546            TestItem::new(cx)
10547                .with_dirty(true)
10548                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10549        });
10550        workspace.update_in(cx, |w, window, cx| {
10551            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10552            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10553        });
10554        let task = workspace.update_in(cx, |w, window, cx| {
10555            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10556        });
10557        cx.executor().run_until_parked();
10558        cx.simulate_prompt_answer("Cancel"); // cancel save all
10559        cx.executor().run_until_parked();
10560        assert!(!cx.has_pending_prompt());
10561        assert!(!task.await.unwrap());
10562    }
10563
10564    #[gpui::test]
10565    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10566        init_test(cx);
10567
10568        let fs = FakeFs::new(cx.executor());
10569        fs.insert_tree("/root", json!({ "one": "" })).await;
10570
10571        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10572        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10573        let multi_workspace_handle =
10574            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10575        cx.run_until_parked();
10576
10577        let workspace_a = multi_workspace_handle
10578            .read_with(cx, |mw, _| mw.workspace().clone())
10579            .unwrap();
10580
10581        let workspace_b = multi_workspace_handle
10582            .update(cx, |mw, window, cx| {
10583                mw.test_add_workspace(project_b, window, cx)
10584            })
10585            .unwrap();
10586
10587        // Activate workspace A
10588        multi_workspace_handle
10589            .update(cx, |mw, window, cx| {
10590                mw.activate_index(0, window, cx);
10591            })
10592            .unwrap();
10593
10594        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10595
10596        // Workspace A has a clean item
10597        let item_a = cx.new(TestItem::new);
10598        workspace_a.update_in(cx, |w, window, cx| {
10599            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10600        });
10601
10602        // Workspace B has a dirty item
10603        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10604        workspace_b.update_in(cx, |w, window, cx| {
10605            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10606        });
10607
10608        // Verify workspace A is active
10609        multi_workspace_handle
10610            .read_with(cx, |mw, _| {
10611                assert_eq!(mw.active_workspace_index(), 0);
10612            })
10613            .unwrap();
10614
10615        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10616        multi_workspace_handle
10617            .update(cx, |mw, window, cx| {
10618                mw.close_window(&CloseWindow, window, cx);
10619            })
10620            .unwrap();
10621        cx.run_until_parked();
10622
10623        // Workspace B should now be active since it has dirty items that need attention
10624        multi_workspace_handle
10625            .read_with(cx, |mw, _| {
10626                assert_eq!(
10627                    mw.active_workspace_index(),
10628                    1,
10629                    "workspace B should be activated when it prompts"
10630                );
10631            })
10632            .unwrap();
10633
10634        // User cancels the save prompt from workspace B
10635        cx.simulate_prompt_answer("Cancel");
10636        cx.run_until_parked();
10637
10638        // Window should still exist because workspace B's close was cancelled
10639        assert!(
10640            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10641            "window should still exist after cancelling one workspace's close"
10642        );
10643    }
10644
10645    #[gpui::test]
10646    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10647        init_test(cx);
10648
10649        // Register TestItem as a serializable item
10650        cx.update(|cx| {
10651            register_serializable_item::<TestItem>(cx);
10652        });
10653
10654        let fs = FakeFs::new(cx.executor());
10655        fs.insert_tree("/root", json!({ "one": "" })).await;
10656
10657        let project = Project::test(fs, ["root".as_ref()], cx).await;
10658        let (workspace, cx) =
10659            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10660
10661        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10662        let item1 = cx.new(|cx| {
10663            TestItem::new(cx)
10664                .with_dirty(true)
10665                .with_serialize(|| Some(Task::ready(Ok(()))))
10666        });
10667        let item2 = cx.new(|cx| {
10668            TestItem::new(cx)
10669                .with_dirty(true)
10670                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10671                .with_serialize(|| Some(Task::ready(Ok(()))))
10672        });
10673        workspace.update_in(cx, |w, window, cx| {
10674            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10675            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10676        });
10677        let task = workspace.update_in(cx, |w, window, cx| {
10678            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10679        });
10680        assert!(task.await.unwrap());
10681    }
10682
10683    #[gpui::test]
10684    async fn test_close_pane_items(cx: &mut TestAppContext) {
10685        init_test(cx);
10686
10687        let fs = FakeFs::new(cx.executor());
10688
10689        let project = Project::test(fs, None, cx).await;
10690        let (workspace, cx) =
10691            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10692
10693        let item1 = cx.new(|cx| {
10694            TestItem::new(cx)
10695                .with_dirty(true)
10696                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10697        });
10698        let item2 = cx.new(|cx| {
10699            TestItem::new(cx)
10700                .with_dirty(true)
10701                .with_conflict(true)
10702                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10703        });
10704        let item3 = cx.new(|cx| {
10705            TestItem::new(cx)
10706                .with_dirty(true)
10707                .with_conflict(true)
10708                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10709        });
10710        let item4 = cx.new(|cx| {
10711            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10712                let project_item = TestProjectItem::new_untitled(cx);
10713                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10714                project_item
10715            }])
10716        });
10717        let pane = workspace.update_in(cx, |workspace, window, cx| {
10718            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10719            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10720            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10721            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10722            workspace.active_pane().clone()
10723        });
10724
10725        let close_items = pane.update_in(cx, |pane, window, cx| {
10726            pane.activate_item(1, true, true, window, cx);
10727            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10728            let item1_id = item1.item_id();
10729            let item3_id = item3.item_id();
10730            let item4_id = item4.item_id();
10731            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10732                [item1_id, item3_id, item4_id].contains(&id)
10733            })
10734        });
10735        cx.executor().run_until_parked();
10736
10737        assert!(cx.has_pending_prompt());
10738        cx.simulate_prompt_answer("Save all");
10739
10740        cx.executor().run_until_parked();
10741
10742        // Item 1 is saved. There's a prompt to save item 3.
10743        pane.update(cx, |pane, cx| {
10744            assert_eq!(item1.read(cx).save_count, 1);
10745            assert_eq!(item1.read(cx).save_as_count, 0);
10746            assert_eq!(item1.read(cx).reload_count, 0);
10747            assert_eq!(pane.items_len(), 3);
10748            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10749        });
10750        assert!(cx.has_pending_prompt());
10751
10752        // Cancel saving item 3.
10753        cx.simulate_prompt_answer("Discard");
10754        cx.executor().run_until_parked();
10755
10756        // Item 3 is reloaded. There's a prompt to save item 4.
10757        pane.update(cx, |pane, cx| {
10758            assert_eq!(item3.read(cx).save_count, 0);
10759            assert_eq!(item3.read(cx).save_as_count, 0);
10760            assert_eq!(item3.read(cx).reload_count, 1);
10761            assert_eq!(pane.items_len(), 2);
10762            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10763        });
10764
10765        // There's a prompt for a path for item 4.
10766        cx.simulate_new_path_selection(|_| Some(Default::default()));
10767        close_items.await.unwrap();
10768
10769        // The requested items are closed.
10770        pane.update(cx, |pane, cx| {
10771            assert_eq!(item4.read(cx).save_count, 0);
10772            assert_eq!(item4.read(cx).save_as_count, 1);
10773            assert_eq!(item4.read(cx).reload_count, 0);
10774            assert_eq!(pane.items_len(), 1);
10775            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10776        });
10777    }
10778
10779    #[gpui::test]
10780    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10781        init_test(cx);
10782
10783        let fs = FakeFs::new(cx.executor());
10784        let project = Project::test(fs, [], cx).await;
10785        let (workspace, cx) =
10786            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10787
10788        // Create several workspace items with single project entries, and two
10789        // workspace items with multiple project entries.
10790        let single_entry_items = (0..=4)
10791            .map(|project_entry_id| {
10792                cx.new(|cx| {
10793                    TestItem::new(cx)
10794                        .with_dirty(true)
10795                        .with_project_items(&[dirty_project_item(
10796                            project_entry_id,
10797                            &format!("{project_entry_id}.txt"),
10798                            cx,
10799                        )])
10800                })
10801            })
10802            .collect::<Vec<_>>();
10803        let item_2_3 = cx.new(|cx| {
10804            TestItem::new(cx)
10805                .with_dirty(true)
10806                .with_buffer_kind(ItemBufferKind::Multibuffer)
10807                .with_project_items(&[
10808                    single_entry_items[2].read(cx).project_items[0].clone(),
10809                    single_entry_items[3].read(cx).project_items[0].clone(),
10810                ])
10811        });
10812        let item_3_4 = cx.new(|cx| {
10813            TestItem::new(cx)
10814                .with_dirty(true)
10815                .with_buffer_kind(ItemBufferKind::Multibuffer)
10816                .with_project_items(&[
10817                    single_entry_items[3].read(cx).project_items[0].clone(),
10818                    single_entry_items[4].read(cx).project_items[0].clone(),
10819                ])
10820        });
10821
10822        // Create two panes that contain the following project entries:
10823        //   left pane:
10824        //     multi-entry items:   (2, 3)
10825        //     single-entry items:  0, 2, 3, 4
10826        //   right pane:
10827        //     single-entry items:  4, 1
10828        //     multi-entry items:   (3, 4)
10829        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10830            let left_pane = workspace.active_pane().clone();
10831            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10832            workspace.add_item_to_active_pane(
10833                single_entry_items[0].boxed_clone(),
10834                None,
10835                true,
10836                window,
10837                cx,
10838            );
10839            workspace.add_item_to_active_pane(
10840                single_entry_items[2].boxed_clone(),
10841                None,
10842                true,
10843                window,
10844                cx,
10845            );
10846            workspace.add_item_to_active_pane(
10847                single_entry_items[3].boxed_clone(),
10848                None,
10849                true,
10850                window,
10851                cx,
10852            );
10853            workspace.add_item_to_active_pane(
10854                single_entry_items[4].boxed_clone(),
10855                None,
10856                true,
10857                window,
10858                cx,
10859            );
10860
10861            let right_pane =
10862                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10863
10864            let boxed_clone = single_entry_items[1].boxed_clone();
10865            let right_pane = window.spawn(cx, async move |cx| {
10866                right_pane.await.inspect(|right_pane| {
10867                    right_pane
10868                        .update_in(cx, |pane, window, cx| {
10869                            pane.add_item(boxed_clone, true, true, None, window, cx);
10870                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10871                        })
10872                        .unwrap();
10873                })
10874            });
10875
10876            (left_pane, right_pane)
10877        });
10878        let right_pane = right_pane.await.unwrap();
10879        cx.focus(&right_pane);
10880
10881        let close = right_pane.update_in(cx, |pane, window, cx| {
10882            pane.close_all_items(&CloseAllItems::default(), window, cx)
10883                .unwrap()
10884        });
10885        cx.executor().run_until_parked();
10886
10887        let msg = cx.pending_prompt().unwrap().0;
10888        assert!(msg.contains("1.txt"));
10889        assert!(!msg.contains("2.txt"));
10890        assert!(!msg.contains("3.txt"));
10891        assert!(!msg.contains("4.txt"));
10892
10893        // With best-effort close, cancelling item 1 keeps it open but items 4
10894        // and (3,4) still close since their entries exist in left pane.
10895        cx.simulate_prompt_answer("Cancel");
10896        close.await;
10897
10898        right_pane.read_with(cx, |pane, _| {
10899            assert_eq!(pane.items_len(), 1);
10900        });
10901
10902        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10903        left_pane
10904            .update_in(cx, |left_pane, window, cx| {
10905                left_pane.close_item_by_id(
10906                    single_entry_items[3].entity_id(),
10907                    SaveIntent::Skip,
10908                    window,
10909                    cx,
10910                )
10911            })
10912            .await
10913            .unwrap();
10914
10915        let close = left_pane.update_in(cx, |pane, window, cx| {
10916            pane.close_all_items(&CloseAllItems::default(), window, cx)
10917                .unwrap()
10918        });
10919        cx.executor().run_until_parked();
10920
10921        let details = cx.pending_prompt().unwrap().1;
10922        assert!(details.contains("0.txt"));
10923        assert!(details.contains("3.txt"));
10924        assert!(details.contains("4.txt"));
10925        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10926        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10927        // assert!(!details.contains("2.txt"));
10928
10929        cx.simulate_prompt_answer("Save all");
10930        cx.executor().run_until_parked();
10931        close.await;
10932
10933        left_pane.read_with(cx, |pane, _| {
10934            assert_eq!(pane.items_len(), 0);
10935        });
10936    }
10937
10938    #[gpui::test]
10939    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10940        init_test(cx);
10941
10942        let fs = FakeFs::new(cx.executor());
10943        let project = Project::test(fs, [], cx).await;
10944        let (workspace, cx) =
10945            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10946        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10947
10948        let item = cx.new(|cx| {
10949            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10950        });
10951        let item_id = item.entity_id();
10952        workspace.update_in(cx, |workspace, window, cx| {
10953            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10954        });
10955
10956        // Autosave on window change.
10957        item.update(cx, |item, cx| {
10958            SettingsStore::update_global(cx, |settings, cx| {
10959                settings.update_user_settings(cx, |settings| {
10960                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10961                })
10962            });
10963            item.is_dirty = true;
10964        });
10965
10966        // Deactivating the window saves the file.
10967        cx.deactivate_window();
10968        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10969
10970        // Re-activating the window doesn't save the file.
10971        cx.update(|window, _| window.activate_window());
10972        cx.executor().run_until_parked();
10973        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10974
10975        // Autosave on focus change.
10976        item.update_in(cx, |item, window, cx| {
10977            cx.focus_self(window);
10978            SettingsStore::update_global(cx, |settings, cx| {
10979                settings.update_user_settings(cx, |settings| {
10980                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10981                })
10982            });
10983            item.is_dirty = true;
10984        });
10985        // Blurring the item saves the file.
10986        item.update_in(cx, |_, window, _| window.blur());
10987        cx.executor().run_until_parked();
10988        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10989
10990        // Deactivating the window still saves the file.
10991        item.update_in(cx, |item, window, cx| {
10992            cx.focus_self(window);
10993            item.is_dirty = true;
10994        });
10995        cx.deactivate_window();
10996        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10997
10998        // Autosave after delay.
10999        item.update(cx, |item, cx| {
11000            SettingsStore::update_global(cx, |settings, cx| {
11001                settings.update_user_settings(cx, |settings| {
11002                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11003                        milliseconds: 500.into(),
11004                    });
11005                })
11006            });
11007            item.is_dirty = true;
11008            cx.emit(ItemEvent::Edit);
11009        });
11010
11011        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11012        cx.executor().advance_clock(Duration::from_millis(250));
11013        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11014
11015        // After delay expires, the file is saved.
11016        cx.executor().advance_clock(Duration::from_millis(250));
11017        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11018
11019        // Autosave after delay, should save earlier than delay if tab is closed
11020        item.update(cx, |item, cx| {
11021            item.is_dirty = true;
11022            cx.emit(ItemEvent::Edit);
11023        });
11024        cx.executor().advance_clock(Duration::from_millis(250));
11025        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11026
11027        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11028        pane.update_in(cx, |pane, window, cx| {
11029            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11030        })
11031        .await
11032        .unwrap();
11033        assert!(!cx.has_pending_prompt());
11034        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11035
11036        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11037        workspace.update_in(cx, |workspace, window, cx| {
11038            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11039        });
11040        item.update_in(cx, |item, _window, cx| {
11041            item.is_dirty = true;
11042            for project_item in &mut item.project_items {
11043                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11044            }
11045        });
11046        cx.run_until_parked();
11047        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11048
11049        // Autosave on focus change, ensuring closing the tab counts as such.
11050        item.update(cx, |item, cx| {
11051            SettingsStore::update_global(cx, |settings, cx| {
11052                settings.update_user_settings(cx, |settings| {
11053                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11054                })
11055            });
11056            item.is_dirty = true;
11057            for project_item in &mut item.project_items {
11058                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11059            }
11060        });
11061
11062        pane.update_in(cx, |pane, window, cx| {
11063            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11064        })
11065        .await
11066        .unwrap();
11067        assert!(!cx.has_pending_prompt());
11068        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11069
11070        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11071        workspace.update_in(cx, |workspace, window, cx| {
11072            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11073        });
11074        item.update_in(cx, |item, window, cx| {
11075            item.project_items[0].update(cx, |item, _| {
11076                item.entry_id = None;
11077            });
11078            item.is_dirty = true;
11079            window.blur();
11080        });
11081        cx.run_until_parked();
11082        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11083
11084        // Ensure autosave is prevented for deleted files also when closing the buffer.
11085        let _close_items = pane.update_in(cx, |pane, window, cx| {
11086            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11087        });
11088        cx.run_until_parked();
11089        assert!(cx.has_pending_prompt());
11090        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11091    }
11092
11093    #[gpui::test]
11094    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11095        init_test(cx);
11096
11097        let fs = FakeFs::new(cx.executor());
11098        let project = Project::test(fs, [], cx).await;
11099        let (workspace, cx) =
11100            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11101
11102        // Create a multibuffer-like item with two child focus handles,
11103        // simulating individual buffer editors within a multibuffer.
11104        let item = cx.new(|cx| {
11105            TestItem::new(cx)
11106                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11107                .with_child_focus_handles(2, cx)
11108        });
11109        workspace.update_in(cx, |workspace, window, cx| {
11110            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11111        });
11112
11113        // Set autosave to OnFocusChange and focus the first child handle,
11114        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11115        item.update_in(cx, |item, window, cx| {
11116            SettingsStore::update_global(cx, |settings, cx| {
11117                settings.update_user_settings(cx, |settings| {
11118                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11119                })
11120            });
11121            item.is_dirty = true;
11122            window.focus(&item.child_focus_handles[0], cx);
11123        });
11124        cx.executor().run_until_parked();
11125        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11126
11127        // Moving focus from one child to another within the same item should
11128        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11129        item.update_in(cx, |item, window, cx| {
11130            window.focus(&item.child_focus_handles[1], cx);
11131        });
11132        cx.executor().run_until_parked();
11133        item.read_with(cx, |item, _| {
11134            assert_eq!(
11135                item.save_count, 0,
11136                "Switching focus between children within the same item should not autosave"
11137            );
11138        });
11139
11140        // Blurring the item saves the file. This is the core regression scenario:
11141        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11142        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11143        // the leaf is always a child focus handle, so `on_blur` never detected
11144        // focus leaving the item.
11145        item.update_in(cx, |_, window, _| window.blur());
11146        cx.executor().run_until_parked();
11147        item.read_with(cx, |item, _| {
11148            assert_eq!(
11149                item.save_count, 1,
11150                "Blurring should trigger autosave when focus was on a child of the item"
11151            );
11152        });
11153
11154        // Deactivating the window should also trigger autosave when a child of
11155        // the multibuffer item currently owns focus.
11156        item.update_in(cx, |item, window, cx| {
11157            item.is_dirty = true;
11158            window.focus(&item.child_focus_handles[0], cx);
11159        });
11160        cx.executor().run_until_parked();
11161        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11162
11163        cx.deactivate_window();
11164        item.read_with(cx, |item, _| {
11165            assert_eq!(
11166                item.save_count, 2,
11167                "Deactivating window should trigger autosave when focus was on a child"
11168            );
11169        });
11170    }
11171
11172    #[gpui::test]
11173    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11174        init_test(cx);
11175
11176        let fs = FakeFs::new(cx.executor());
11177
11178        let project = Project::test(fs, [], cx).await;
11179        let (workspace, cx) =
11180            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11181
11182        let item = cx.new(|cx| {
11183            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11184        });
11185        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11186        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11187        let toolbar_notify_count = Rc::new(RefCell::new(0));
11188
11189        workspace.update_in(cx, |workspace, window, cx| {
11190            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11191            let toolbar_notification_count = toolbar_notify_count.clone();
11192            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11193                *toolbar_notification_count.borrow_mut() += 1
11194            })
11195            .detach();
11196        });
11197
11198        pane.read_with(cx, |pane, _| {
11199            assert!(!pane.can_navigate_backward());
11200            assert!(!pane.can_navigate_forward());
11201        });
11202
11203        item.update_in(cx, |item, _, cx| {
11204            item.set_state("one".to_string(), cx);
11205        });
11206
11207        // Toolbar must be notified to re-render the navigation buttons
11208        assert_eq!(*toolbar_notify_count.borrow(), 1);
11209
11210        pane.read_with(cx, |pane, _| {
11211            assert!(pane.can_navigate_backward());
11212            assert!(!pane.can_navigate_forward());
11213        });
11214
11215        workspace
11216            .update_in(cx, |workspace, window, cx| {
11217                workspace.go_back(pane.downgrade(), window, cx)
11218            })
11219            .await
11220            .unwrap();
11221
11222        assert_eq!(*toolbar_notify_count.borrow(), 2);
11223        pane.read_with(cx, |pane, _| {
11224            assert!(!pane.can_navigate_backward());
11225            assert!(pane.can_navigate_forward());
11226        });
11227    }
11228
11229    #[gpui::test]
11230    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11231        init_test(cx);
11232        let fs = FakeFs::new(cx.executor());
11233        let project = Project::test(fs, [], cx).await;
11234        let (multi_workspace, cx) =
11235            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11236        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11237
11238        workspace.update_in(cx, |workspace, window, cx| {
11239            let first_item = cx.new(|cx| {
11240                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11241            });
11242            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11243            workspace.split_pane(
11244                workspace.active_pane().clone(),
11245                SplitDirection::Right,
11246                window,
11247                cx,
11248            );
11249            workspace.split_pane(
11250                workspace.active_pane().clone(),
11251                SplitDirection::Right,
11252                window,
11253                cx,
11254            );
11255        });
11256
11257        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11258            let panes = workspace.center.panes();
11259            assert!(panes.len() >= 2);
11260            (
11261                panes.first().expect("at least one pane").entity_id(),
11262                panes.last().expect("at least one pane").entity_id(),
11263            )
11264        });
11265
11266        workspace.update_in(cx, |workspace, window, cx| {
11267            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11268        });
11269        workspace.update(cx, |workspace, _| {
11270            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11271            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11272        });
11273
11274        cx.dispatch_action(ActivateLastPane);
11275
11276        workspace.update(cx, |workspace, _| {
11277            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11278        });
11279    }
11280
11281    #[gpui::test]
11282    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11283        init_test(cx);
11284        let fs = FakeFs::new(cx.executor());
11285
11286        let project = Project::test(fs, [], cx).await;
11287        let (workspace, cx) =
11288            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11289
11290        let panel = workspace.update_in(cx, |workspace, window, cx| {
11291            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11292            workspace.add_panel(panel.clone(), window, cx);
11293
11294            workspace
11295                .right_dock()
11296                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11297
11298            panel
11299        });
11300
11301        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11302        pane.update_in(cx, |pane, window, cx| {
11303            let item = cx.new(TestItem::new);
11304            pane.add_item(Box::new(item), true, true, None, window, cx);
11305        });
11306
11307        // Transfer focus from center to panel
11308        workspace.update_in(cx, |workspace, window, cx| {
11309            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11310        });
11311
11312        workspace.update_in(cx, |workspace, window, cx| {
11313            assert!(workspace.right_dock().read(cx).is_open());
11314            assert!(!panel.is_zoomed(window, cx));
11315            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11316        });
11317
11318        // Transfer focus from panel to center
11319        workspace.update_in(cx, |workspace, window, cx| {
11320            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11321        });
11322
11323        workspace.update_in(cx, |workspace, window, cx| {
11324            assert!(workspace.right_dock().read(cx).is_open());
11325            assert!(!panel.is_zoomed(window, cx));
11326            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11327        });
11328
11329        // Close the dock
11330        workspace.update_in(cx, |workspace, window, cx| {
11331            workspace.toggle_dock(DockPosition::Right, window, cx);
11332        });
11333
11334        workspace.update_in(cx, |workspace, window, cx| {
11335            assert!(!workspace.right_dock().read(cx).is_open());
11336            assert!(!panel.is_zoomed(window, cx));
11337            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11338        });
11339
11340        // Open the dock
11341        workspace.update_in(cx, |workspace, window, cx| {
11342            workspace.toggle_dock(DockPosition::Right, window, cx);
11343        });
11344
11345        workspace.update_in(cx, |workspace, window, cx| {
11346            assert!(workspace.right_dock().read(cx).is_open());
11347            assert!(!panel.is_zoomed(window, cx));
11348            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11349        });
11350
11351        // Focus and zoom panel
11352        panel.update_in(cx, |panel, window, cx| {
11353            cx.focus_self(window);
11354            panel.set_zoomed(true, window, cx)
11355        });
11356
11357        workspace.update_in(cx, |workspace, window, cx| {
11358            assert!(workspace.right_dock().read(cx).is_open());
11359            assert!(panel.is_zoomed(window, cx));
11360            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11361        });
11362
11363        // Transfer focus to the center closes the dock
11364        workspace.update_in(cx, |workspace, window, cx| {
11365            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11366        });
11367
11368        workspace.update_in(cx, |workspace, window, cx| {
11369            assert!(!workspace.right_dock().read(cx).is_open());
11370            assert!(panel.is_zoomed(window, cx));
11371            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11372        });
11373
11374        // Transferring focus back to the panel keeps it zoomed
11375        workspace.update_in(cx, |workspace, window, cx| {
11376            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11377        });
11378
11379        workspace.update_in(cx, |workspace, window, cx| {
11380            assert!(workspace.right_dock().read(cx).is_open());
11381            assert!(panel.is_zoomed(window, cx));
11382            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11383        });
11384
11385        // Close the dock while it is zoomed
11386        workspace.update_in(cx, |workspace, window, cx| {
11387            workspace.toggle_dock(DockPosition::Right, window, cx)
11388        });
11389
11390        workspace.update_in(cx, |workspace, window, cx| {
11391            assert!(!workspace.right_dock().read(cx).is_open());
11392            assert!(panel.is_zoomed(window, cx));
11393            assert!(workspace.zoomed.is_none());
11394            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11395        });
11396
11397        // Opening the dock, when it's zoomed, retains focus
11398        workspace.update_in(cx, |workspace, window, cx| {
11399            workspace.toggle_dock(DockPosition::Right, window, cx)
11400        });
11401
11402        workspace.update_in(cx, |workspace, window, cx| {
11403            assert!(workspace.right_dock().read(cx).is_open());
11404            assert!(panel.is_zoomed(window, cx));
11405            assert!(workspace.zoomed.is_some());
11406            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11407        });
11408
11409        // Unzoom and close the panel, zoom the active pane.
11410        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11411        workspace.update_in(cx, |workspace, window, cx| {
11412            workspace.toggle_dock(DockPosition::Right, window, cx)
11413        });
11414        pane.update_in(cx, |pane, window, cx| {
11415            pane.toggle_zoom(&Default::default(), window, cx)
11416        });
11417
11418        // Opening a dock unzooms the pane.
11419        workspace.update_in(cx, |workspace, window, cx| {
11420            workspace.toggle_dock(DockPosition::Right, window, cx)
11421        });
11422        workspace.update_in(cx, |workspace, window, cx| {
11423            let pane = pane.read(cx);
11424            assert!(!pane.is_zoomed());
11425            assert!(!pane.focus_handle(cx).is_focused(window));
11426            assert!(workspace.right_dock().read(cx).is_open());
11427            assert!(workspace.zoomed.is_none());
11428        });
11429    }
11430
11431    #[gpui::test]
11432    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11433        init_test(cx);
11434        let fs = FakeFs::new(cx.executor());
11435
11436        let project = Project::test(fs, [], cx).await;
11437        let (workspace, cx) =
11438            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11439
11440        let panel = workspace.update_in(cx, |workspace, window, cx| {
11441            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11442            workspace.add_panel(panel.clone(), window, cx);
11443            panel
11444        });
11445
11446        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11447        pane.update_in(cx, |pane, window, cx| {
11448            let item = cx.new(TestItem::new);
11449            pane.add_item(Box::new(item), true, true, None, window, cx);
11450        });
11451
11452        // Enable close_panel_on_toggle
11453        cx.update_global(|store: &mut SettingsStore, cx| {
11454            store.update_user_settings(cx, |settings| {
11455                settings.workspace.close_panel_on_toggle = Some(true);
11456            });
11457        });
11458
11459        // Panel starts closed. Toggling should open and focus it.
11460        workspace.update_in(cx, |workspace, window, cx| {
11461            assert!(!workspace.right_dock().read(cx).is_open());
11462            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11463        });
11464
11465        workspace.update_in(cx, |workspace, window, cx| {
11466            assert!(
11467                workspace.right_dock().read(cx).is_open(),
11468                "Dock should be open after toggling from center"
11469            );
11470            assert!(
11471                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11472                "Panel should be focused after toggling from center"
11473            );
11474        });
11475
11476        // Panel is open and focused. Toggling should close the panel and
11477        // return focus to the center.
11478        workspace.update_in(cx, |workspace, window, cx| {
11479            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11480        });
11481
11482        workspace.update_in(cx, |workspace, window, cx| {
11483            assert!(
11484                !workspace.right_dock().read(cx).is_open(),
11485                "Dock should be closed after toggling from focused panel"
11486            );
11487            assert!(
11488                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11489                "Panel should not be focused after toggling from focused panel"
11490            );
11491        });
11492
11493        // Open the dock and focus something else so the panel is open but not
11494        // focused. Toggling should focus the panel (not close it).
11495        workspace.update_in(cx, |workspace, window, cx| {
11496            workspace
11497                .right_dock()
11498                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11499            window.focus(&pane.read(cx).focus_handle(cx), cx);
11500        });
11501
11502        workspace.update_in(cx, |workspace, window, cx| {
11503            assert!(workspace.right_dock().read(cx).is_open());
11504            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11505            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11506        });
11507
11508        workspace.update_in(cx, |workspace, window, cx| {
11509            assert!(
11510                workspace.right_dock().read(cx).is_open(),
11511                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11512            );
11513            assert!(
11514                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11515                "Panel should be focused after toggling an open-but-unfocused panel"
11516            );
11517        });
11518
11519        // Now disable the setting and verify the original behavior: toggling
11520        // from a focused panel moves focus to center but leaves the dock open.
11521        cx.update_global(|store: &mut SettingsStore, cx| {
11522            store.update_user_settings(cx, |settings| {
11523                settings.workspace.close_panel_on_toggle = Some(false);
11524            });
11525        });
11526
11527        workspace.update_in(cx, |workspace, window, cx| {
11528            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11529        });
11530
11531        workspace.update_in(cx, |workspace, window, cx| {
11532            assert!(
11533                workspace.right_dock().read(cx).is_open(),
11534                "Dock should remain open when setting is disabled"
11535            );
11536            assert!(
11537                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11538                "Panel should not be focused after toggling with setting disabled"
11539            );
11540        });
11541    }
11542
11543    #[gpui::test]
11544    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11545        init_test(cx);
11546        let fs = FakeFs::new(cx.executor());
11547
11548        let project = Project::test(fs, [], cx).await;
11549        let (workspace, cx) =
11550            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11551
11552        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11553            workspace.active_pane().clone()
11554        });
11555
11556        // Add an item to the pane so it can be zoomed
11557        workspace.update_in(cx, |workspace, window, cx| {
11558            let item = cx.new(TestItem::new);
11559            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11560        });
11561
11562        // Initially not zoomed
11563        workspace.update_in(cx, |workspace, _window, cx| {
11564            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11565            assert!(
11566                workspace.zoomed.is_none(),
11567                "Workspace should track no zoomed pane"
11568            );
11569            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11570        });
11571
11572        // Zoom In
11573        pane.update_in(cx, |pane, window, cx| {
11574            pane.zoom_in(&crate::ZoomIn, window, cx);
11575        });
11576
11577        workspace.update_in(cx, |workspace, window, cx| {
11578            assert!(
11579                pane.read(cx).is_zoomed(),
11580                "Pane should be zoomed after ZoomIn"
11581            );
11582            assert!(
11583                workspace.zoomed.is_some(),
11584                "Workspace should track the zoomed pane"
11585            );
11586            assert!(
11587                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11588                "ZoomIn should focus the pane"
11589            );
11590        });
11591
11592        // Zoom In again is a no-op
11593        pane.update_in(cx, |pane, window, cx| {
11594            pane.zoom_in(&crate::ZoomIn, window, cx);
11595        });
11596
11597        workspace.update_in(cx, |workspace, window, cx| {
11598            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11599            assert!(
11600                workspace.zoomed.is_some(),
11601                "Workspace still tracks zoomed pane"
11602            );
11603            assert!(
11604                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11605                "Pane remains focused after repeated ZoomIn"
11606            );
11607        });
11608
11609        // Zoom Out
11610        pane.update_in(cx, |pane, window, cx| {
11611            pane.zoom_out(&crate::ZoomOut, window, cx);
11612        });
11613
11614        workspace.update_in(cx, |workspace, _window, cx| {
11615            assert!(
11616                !pane.read(cx).is_zoomed(),
11617                "Pane should unzoom after ZoomOut"
11618            );
11619            assert!(
11620                workspace.zoomed.is_none(),
11621                "Workspace clears zoom tracking after ZoomOut"
11622            );
11623        });
11624
11625        // Zoom Out again is a no-op
11626        pane.update_in(cx, |pane, window, cx| {
11627            pane.zoom_out(&crate::ZoomOut, window, cx);
11628        });
11629
11630        workspace.update_in(cx, |workspace, _window, cx| {
11631            assert!(
11632                !pane.read(cx).is_zoomed(),
11633                "Second ZoomOut keeps pane unzoomed"
11634            );
11635            assert!(
11636                workspace.zoomed.is_none(),
11637                "Workspace remains without zoomed pane"
11638            );
11639        });
11640    }
11641
11642    #[gpui::test]
11643    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11644        init_test(cx);
11645        let fs = FakeFs::new(cx.executor());
11646
11647        let project = Project::test(fs, [], cx).await;
11648        let (workspace, cx) =
11649            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11650        workspace.update_in(cx, |workspace, window, cx| {
11651            // Open two docks
11652            let left_dock = workspace.dock_at_position(DockPosition::Left);
11653            let right_dock = workspace.dock_at_position(DockPosition::Right);
11654
11655            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11656            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11657
11658            assert!(left_dock.read(cx).is_open());
11659            assert!(right_dock.read(cx).is_open());
11660        });
11661
11662        workspace.update_in(cx, |workspace, window, cx| {
11663            // Toggle all docks - should close both
11664            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11665
11666            let left_dock = workspace.dock_at_position(DockPosition::Left);
11667            let right_dock = workspace.dock_at_position(DockPosition::Right);
11668            assert!(!left_dock.read(cx).is_open());
11669            assert!(!right_dock.read(cx).is_open());
11670        });
11671
11672        workspace.update_in(cx, |workspace, window, cx| {
11673            // Toggle again - should reopen both
11674            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11675
11676            let left_dock = workspace.dock_at_position(DockPosition::Left);
11677            let right_dock = workspace.dock_at_position(DockPosition::Right);
11678            assert!(left_dock.read(cx).is_open());
11679            assert!(right_dock.read(cx).is_open());
11680        });
11681    }
11682
11683    #[gpui::test]
11684    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11685        init_test(cx);
11686        let fs = FakeFs::new(cx.executor());
11687
11688        let project = Project::test(fs, [], cx).await;
11689        let (workspace, cx) =
11690            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11691        workspace.update_in(cx, |workspace, window, cx| {
11692            // Open two docks
11693            let left_dock = workspace.dock_at_position(DockPosition::Left);
11694            let right_dock = workspace.dock_at_position(DockPosition::Right);
11695
11696            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11697            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11698
11699            assert!(left_dock.read(cx).is_open());
11700            assert!(right_dock.read(cx).is_open());
11701        });
11702
11703        workspace.update_in(cx, |workspace, window, cx| {
11704            // Close them manually
11705            workspace.toggle_dock(DockPosition::Left, window, cx);
11706            workspace.toggle_dock(DockPosition::Right, window, cx);
11707
11708            let left_dock = workspace.dock_at_position(DockPosition::Left);
11709            let right_dock = workspace.dock_at_position(DockPosition::Right);
11710            assert!(!left_dock.read(cx).is_open());
11711            assert!(!right_dock.read(cx).is_open());
11712        });
11713
11714        workspace.update_in(cx, |workspace, window, cx| {
11715            // Toggle all docks - only last closed (right dock) should reopen
11716            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11717
11718            let left_dock = workspace.dock_at_position(DockPosition::Left);
11719            let right_dock = workspace.dock_at_position(DockPosition::Right);
11720            assert!(!left_dock.read(cx).is_open());
11721            assert!(right_dock.read(cx).is_open());
11722        });
11723    }
11724
11725    #[gpui::test]
11726    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11727        init_test(cx);
11728        let fs = FakeFs::new(cx.executor());
11729        let project = Project::test(fs, [], cx).await;
11730        let (multi_workspace, cx) =
11731            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11732        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11733
11734        // Open two docks (left and right) with one panel each
11735        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11736            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11737            workspace.add_panel(left_panel.clone(), window, cx);
11738
11739            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11740            workspace.add_panel(right_panel.clone(), window, cx);
11741
11742            workspace.toggle_dock(DockPosition::Left, window, cx);
11743            workspace.toggle_dock(DockPosition::Right, window, cx);
11744
11745            // Verify initial state
11746            assert!(
11747                workspace.left_dock().read(cx).is_open(),
11748                "Left dock should be open"
11749            );
11750            assert_eq!(
11751                workspace
11752                    .left_dock()
11753                    .read(cx)
11754                    .visible_panel()
11755                    .unwrap()
11756                    .panel_id(),
11757                left_panel.panel_id(),
11758                "Left panel should be visible in left dock"
11759            );
11760            assert!(
11761                workspace.right_dock().read(cx).is_open(),
11762                "Right dock should be open"
11763            );
11764            assert_eq!(
11765                workspace
11766                    .right_dock()
11767                    .read(cx)
11768                    .visible_panel()
11769                    .unwrap()
11770                    .panel_id(),
11771                right_panel.panel_id(),
11772                "Right panel should be visible in right dock"
11773            );
11774            assert!(
11775                !workspace.bottom_dock().read(cx).is_open(),
11776                "Bottom dock should be closed"
11777            );
11778
11779            (left_panel, right_panel)
11780        });
11781
11782        // Focus the left panel and move it to the next position (bottom dock)
11783        workspace.update_in(cx, |workspace, window, cx| {
11784            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11785            assert!(
11786                left_panel.read(cx).focus_handle(cx).is_focused(window),
11787                "Left panel should be focused"
11788            );
11789        });
11790
11791        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11792
11793        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11794        workspace.update(cx, |workspace, cx| {
11795            assert!(
11796                !workspace.left_dock().read(cx).is_open(),
11797                "Left dock should be closed"
11798            );
11799            assert!(
11800                workspace.bottom_dock().read(cx).is_open(),
11801                "Bottom dock should now be open"
11802            );
11803            assert_eq!(
11804                left_panel.read(cx).position,
11805                DockPosition::Bottom,
11806                "Left panel should now be in the bottom dock"
11807            );
11808            assert_eq!(
11809                workspace
11810                    .bottom_dock()
11811                    .read(cx)
11812                    .visible_panel()
11813                    .unwrap()
11814                    .panel_id(),
11815                left_panel.panel_id(),
11816                "Left panel should be the visible panel in the bottom dock"
11817            );
11818        });
11819
11820        // Toggle all docks off
11821        workspace.update_in(cx, |workspace, window, cx| {
11822            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11823            assert!(
11824                !workspace.left_dock().read(cx).is_open(),
11825                "Left dock should be closed"
11826            );
11827            assert!(
11828                !workspace.right_dock().read(cx).is_open(),
11829                "Right dock should be closed"
11830            );
11831            assert!(
11832                !workspace.bottom_dock().read(cx).is_open(),
11833                "Bottom dock should be closed"
11834            );
11835        });
11836
11837        // Toggle all docks back on and verify positions are restored
11838        workspace.update_in(cx, |workspace, window, cx| {
11839            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11840            assert!(
11841                !workspace.left_dock().read(cx).is_open(),
11842                "Left dock should remain closed"
11843            );
11844            assert!(
11845                workspace.right_dock().read(cx).is_open(),
11846                "Right dock should remain open"
11847            );
11848            assert!(
11849                workspace.bottom_dock().read(cx).is_open(),
11850                "Bottom dock should remain open"
11851            );
11852            assert_eq!(
11853                left_panel.read(cx).position,
11854                DockPosition::Bottom,
11855                "Left panel should remain in the bottom dock"
11856            );
11857            assert_eq!(
11858                right_panel.read(cx).position,
11859                DockPosition::Right,
11860                "Right panel should remain in the right dock"
11861            );
11862            assert_eq!(
11863                workspace
11864                    .bottom_dock()
11865                    .read(cx)
11866                    .visible_panel()
11867                    .unwrap()
11868                    .panel_id(),
11869                left_panel.panel_id(),
11870                "Left panel should be the visible panel in the right dock"
11871            );
11872        });
11873    }
11874
11875    #[gpui::test]
11876    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11877        init_test(cx);
11878
11879        let fs = FakeFs::new(cx.executor());
11880
11881        let project = Project::test(fs, None, cx).await;
11882        let (workspace, cx) =
11883            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11884
11885        // Let's arrange the panes like this:
11886        //
11887        // +-----------------------+
11888        // |         top           |
11889        // +------+--------+-------+
11890        // | left | center | right |
11891        // +------+--------+-------+
11892        // |        bottom         |
11893        // +-----------------------+
11894
11895        let top_item = cx.new(|cx| {
11896            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11897        });
11898        let bottom_item = cx.new(|cx| {
11899            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11900        });
11901        let left_item = cx.new(|cx| {
11902            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11903        });
11904        let right_item = cx.new(|cx| {
11905            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11906        });
11907        let center_item = cx.new(|cx| {
11908            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11909        });
11910
11911        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11912            let top_pane_id = workspace.active_pane().entity_id();
11913            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11914            workspace.split_pane(
11915                workspace.active_pane().clone(),
11916                SplitDirection::Down,
11917                window,
11918                cx,
11919            );
11920            top_pane_id
11921        });
11922        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11923            let bottom_pane_id = workspace.active_pane().entity_id();
11924            workspace.add_item_to_active_pane(
11925                Box::new(bottom_item.clone()),
11926                None,
11927                false,
11928                window,
11929                cx,
11930            );
11931            workspace.split_pane(
11932                workspace.active_pane().clone(),
11933                SplitDirection::Up,
11934                window,
11935                cx,
11936            );
11937            bottom_pane_id
11938        });
11939        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11940            let left_pane_id = workspace.active_pane().entity_id();
11941            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11942            workspace.split_pane(
11943                workspace.active_pane().clone(),
11944                SplitDirection::Right,
11945                window,
11946                cx,
11947            );
11948            left_pane_id
11949        });
11950        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11951            let right_pane_id = workspace.active_pane().entity_id();
11952            workspace.add_item_to_active_pane(
11953                Box::new(right_item.clone()),
11954                None,
11955                false,
11956                window,
11957                cx,
11958            );
11959            workspace.split_pane(
11960                workspace.active_pane().clone(),
11961                SplitDirection::Left,
11962                window,
11963                cx,
11964            );
11965            right_pane_id
11966        });
11967        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11968            let center_pane_id = workspace.active_pane().entity_id();
11969            workspace.add_item_to_active_pane(
11970                Box::new(center_item.clone()),
11971                None,
11972                false,
11973                window,
11974                cx,
11975            );
11976            center_pane_id
11977        });
11978        cx.executor().run_until_parked();
11979
11980        workspace.update_in(cx, |workspace, window, cx| {
11981            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11982
11983            // Join into next from center pane into right
11984            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11985        });
11986
11987        workspace.update_in(cx, |workspace, window, cx| {
11988            let active_pane = workspace.active_pane();
11989            assert_eq!(right_pane_id, active_pane.entity_id());
11990            assert_eq!(2, active_pane.read(cx).items_len());
11991            let item_ids_in_pane =
11992                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11993            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11994            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11995
11996            // Join into next from right pane into bottom
11997            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11998        });
11999
12000        workspace.update_in(cx, |workspace, window, cx| {
12001            let active_pane = workspace.active_pane();
12002            assert_eq!(bottom_pane_id, active_pane.entity_id());
12003            assert_eq!(3, active_pane.read(cx).items_len());
12004            let item_ids_in_pane =
12005                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12006            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12007            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12008            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12009
12010            // Join into next from bottom pane into left
12011            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12012        });
12013
12014        workspace.update_in(cx, |workspace, window, cx| {
12015            let active_pane = workspace.active_pane();
12016            assert_eq!(left_pane_id, active_pane.entity_id());
12017            assert_eq!(4, active_pane.read(cx).items_len());
12018            let item_ids_in_pane =
12019                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12020            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12021            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12022            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12023            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12024
12025            // Join into next from left pane into top
12026            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12027        });
12028
12029        workspace.update_in(cx, |workspace, window, cx| {
12030            let active_pane = workspace.active_pane();
12031            assert_eq!(top_pane_id, active_pane.entity_id());
12032            assert_eq!(5, active_pane.read(cx).items_len());
12033            let item_ids_in_pane =
12034                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12035            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12036            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12037            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12038            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12039            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12040
12041            // Single pane left: no-op
12042            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12043        });
12044
12045        workspace.update(cx, |workspace, _cx| {
12046            let active_pane = workspace.active_pane();
12047            assert_eq!(top_pane_id, active_pane.entity_id());
12048        });
12049    }
12050
12051    fn add_an_item_to_active_pane(
12052        cx: &mut VisualTestContext,
12053        workspace: &Entity<Workspace>,
12054        item_id: u64,
12055    ) -> Entity<TestItem> {
12056        let item = cx.new(|cx| {
12057            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12058                item_id,
12059                "item{item_id}.txt",
12060                cx,
12061            )])
12062        });
12063        workspace.update_in(cx, |workspace, window, cx| {
12064            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12065        });
12066        item
12067    }
12068
12069    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12070        workspace.update_in(cx, |workspace, window, cx| {
12071            workspace.split_pane(
12072                workspace.active_pane().clone(),
12073                SplitDirection::Right,
12074                window,
12075                cx,
12076            )
12077        })
12078    }
12079
12080    #[gpui::test]
12081    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12082        init_test(cx);
12083        let fs = FakeFs::new(cx.executor());
12084        let project = Project::test(fs, None, cx).await;
12085        let (workspace, cx) =
12086            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12087
12088        add_an_item_to_active_pane(cx, &workspace, 1);
12089        split_pane(cx, &workspace);
12090        add_an_item_to_active_pane(cx, &workspace, 2);
12091        split_pane(cx, &workspace); // empty pane
12092        split_pane(cx, &workspace);
12093        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12094
12095        cx.executor().run_until_parked();
12096
12097        workspace.update(cx, |workspace, cx| {
12098            let num_panes = workspace.panes().len();
12099            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12100            let active_item = workspace
12101                .active_pane()
12102                .read(cx)
12103                .active_item()
12104                .expect("item is in focus");
12105
12106            assert_eq!(num_panes, 4);
12107            assert_eq!(num_items_in_current_pane, 1);
12108            assert_eq!(active_item.item_id(), last_item.item_id());
12109        });
12110
12111        workspace.update_in(cx, |workspace, window, cx| {
12112            workspace.join_all_panes(window, cx);
12113        });
12114
12115        workspace.update(cx, |workspace, cx| {
12116            let num_panes = workspace.panes().len();
12117            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12118            let active_item = workspace
12119                .active_pane()
12120                .read(cx)
12121                .active_item()
12122                .expect("item is in focus");
12123
12124            assert_eq!(num_panes, 1);
12125            assert_eq!(num_items_in_current_pane, 3);
12126            assert_eq!(active_item.item_id(), last_item.item_id());
12127        });
12128    }
12129    struct TestModal(FocusHandle);
12130
12131    impl TestModal {
12132        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12133            Self(cx.focus_handle())
12134        }
12135    }
12136
12137    impl EventEmitter<DismissEvent> for TestModal {}
12138
12139    impl Focusable for TestModal {
12140        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12141            self.0.clone()
12142        }
12143    }
12144
12145    impl ModalView for TestModal {}
12146
12147    impl Render for TestModal {
12148        fn render(
12149            &mut self,
12150            _window: &mut Window,
12151            _cx: &mut Context<TestModal>,
12152        ) -> impl IntoElement {
12153            div().track_focus(&self.0)
12154        }
12155    }
12156
12157    #[gpui::test]
12158    async fn test_panels(cx: &mut gpui::TestAppContext) {
12159        init_test(cx);
12160        let fs = FakeFs::new(cx.executor());
12161
12162        let project = Project::test(fs, [], cx).await;
12163        let (multi_workspace, cx) =
12164            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12165        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12166
12167        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12168            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12169            workspace.add_panel(panel_1.clone(), window, cx);
12170            workspace.toggle_dock(DockPosition::Left, window, cx);
12171            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12172            workspace.add_panel(panel_2.clone(), window, cx);
12173            workspace.toggle_dock(DockPosition::Right, window, cx);
12174
12175            let left_dock = workspace.left_dock();
12176            assert_eq!(
12177                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12178                panel_1.panel_id()
12179            );
12180            assert_eq!(
12181                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12182                panel_1.size(window, cx)
12183            );
12184
12185            left_dock.update(cx, |left_dock, cx| {
12186                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
12187            });
12188            assert_eq!(
12189                workspace
12190                    .right_dock()
12191                    .read(cx)
12192                    .visible_panel()
12193                    .unwrap()
12194                    .panel_id(),
12195                panel_2.panel_id(),
12196            );
12197
12198            (panel_1, panel_2)
12199        });
12200
12201        // Move panel_1 to the right
12202        panel_1.update_in(cx, |panel_1, window, cx| {
12203            panel_1.set_position(DockPosition::Right, window, cx)
12204        });
12205
12206        workspace.update_in(cx, |workspace, window, cx| {
12207            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12208            // Since it was the only panel on the left, the left dock should now be closed.
12209            assert!(!workspace.left_dock().read(cx).is_open());
12210            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12211            let right_dock = workspace.right_dock();
12212            assert_eq!(
12213                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12214                panel_1.panel_id()
12215            );
12216            assert_eq!(
12217                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12218                px(1337.)
12219            );
12220
12221            // Now we move panel_2 to the left
12222            panel_2.set_position(DockPosition::Left, window, cx);
12223        });
12224
12225        workspace.update(cx, |workspace, cx| {
12226            // Since panel_2 was not visible on the right, we don't open the left dock.
12227            assert!(!workspace.left_dock().read(cx).is_open());
12228            // And the right dock is unaffected in its displaying of panel_1
12229            assert!(workspace.right_dock().read(cx).is_open());
12230            assert_eq!(
12231                workspace
12232                    .right_dock()
12233                    .read(cx)
12234                    .visible_panel()
12235                    .unwrap()
12236                    .panel_id(),
12237                panel_1.panel_id(),
12238            );
12239        });
12240
12241        // Move panel_1 back to the left
12242        panel_1.update_in(cx, |panel_1, window, cx| {
12243            panel_1.set_position(DockPosition::Left, window, cx)
12244        });
12245
12246        workspace.update_in(cx, |workspace, window, cx| {
12247            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12248            let left_dock = workspace.left_dock();
12249            assert!(left_dock.read(cx).is_open());
12250            assert_eq!(
12251                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12252                panel_1.panel_id()
12253            );
12254            assert_eq!(
12255                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12256                px(1337.)
12257            );
12258            // And the right dock should be closed as it no longer has any panels.
12259            assert!(!workspace.right_dock().read(cx).is_open());
12260
12261            // Now we move panel_1 to the bottom
12262            panel_1.set_position(DockPosition::Bottom, window, cx);
12263        });
12264
12265        workspace.update_in(cx, |workspace, window, cx| {
12266            // Since panel_1 was visible on the left, we close the left dock.
12267            assert!(!workspace.left_dock().read(cx).is_open());
12268            // The bottom dock is sized based on the panel's default size,
12269            // since the panel orientation changed from vertical to horizontal.
12270            let bottom_dock = workspace.bottom_dock();
12271            assert_eq!(
12272                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12273                panel_1.size(window, cx),
12274            );
12275            // Close bottom dock and move panel_1 back to the left.
12276            bottom_dock.update(cx, |bottom_dock, cx| {
12277                bottom_dock.set_open(false, window, cx)
12278            });
12279            panel_1.set_position(DockPosition::Left, window, cx);
12280        });
12281
12282        // Emit activated event on panel 1
12283        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12284
12285        // Now the left dock is open and panel_1 is active and focused.
12286        workspace.update_in(cx, |workspace, window, cx| {
12287            let left_dock = workspace.left_dock();
12288            assert!(left_dock.read(cx).is_open());
12289            assert_eq!(
12290                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12291                panel_1.panel_id(),
12292            );
12293            assert!(panel_1.focus_handle(cx).is_focused(window));
12294        });
12295
12296        // Emit closed event on panel 2, which is not active
12297        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12298
12299        // Wo don't close the left dock, because panel_2 wasn't the active panel
12300        workspace.update(cx, |workspace, cx| {
12301            let left_dock = workspace.left_dock();
12302            assert!(left_dock.read(cx).is_open());
12303            assert_eq!(
12304                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12305                panel_1.panel_id(),
12306            );
12307        });
12308
12309        // Emitting a ZoomIn event shows the panel as zoomed.
12310        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12311        workspace.read_with(cx, |workspace, _| {
12312            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12313            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12314        });
12315
12316        // Move panel to another dock while it is zoomed
12317        panel_1.update_in(cx, |panel, window, cx| {
12318            panel.set_position(DockPosition::Right, window, cx)
12319        });
12320        workspace.read_with(cx, |workspace, _| {
12321            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12322
12323            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12324        });
12325
12326        // This is a helper for getting a:
12327        // - valid focus on an element,
12328        // - that isn't a part of the panes and panels system of the Workspace,
12329        // - and doesn't trigger the 'on_focus_lost' API.
12330        let focus_other_view = {
12331            let workspace = workspace.clone();
12332            move |cx: &mut VisualTestContext| {
12333                workspace.update_in(cx, |workspace, window, cx| {
12334                    if workspace.active_modal::<TestModal>(cx).is_some() {
12335                        workspace.toggle_modal(window, cx, TestModal::new);
12336                        workspace.toggle_modal(window, cx, TestModal::new);
12337                    } else {
12338                        workspace.toggle_modal(window, cx, TestModal::new);
12339                    }
12340                })
12341            }
12342        };
12343
12344        // If focus is transferred to another view that's not a panel or another pane, we still show
12345        // the panel as zoomed.
12346        focus_other_view(cx);
12347        workspace.read_with(cx, |workspace, _| {
12348            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12349            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12350        });
12351
12352        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12353        workspace.update_in(cx, |_workspace, window, cx| {
12354            cx.focus_self(window);
12355        });
12356        workspace.read_with(cx, |workspace, _| {
12357            assert_eq!(workspace.zoomed, None);
12358            assert_eq!(workspace.zoomed_position, None);
12359        });
12360
12361        // If focus is transferred again to another view that's not a panel or a pane, we won't
12362        // show the panel as zoomed because it wasn't zoomed before.
12363        focus_other_view(cx);
12364        workspace.read_with(cx, |workspace, _| {
12365            assert_eq!(workspace.zoomed, None);
12366            assert_eq!(workspace.zoomed_position, None);
12367        });
12368
12369        // When the panel is activated, it is zoomed again.
12370        cx.dispatch_action(ToggleRightDock);
12371        workspace.read_with(cx, |workspace, _| {
12372            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12373            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12374        });
12375
12376        // Emitting a ZoomOut event unzooms the panel.
12377        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12378        workspace.read_with(cx, |workspace, _| {
12379            assert_eq!(workspace.zoomed, None);
12380            assert_eq!(workspace.zoomed_position, None);
12381        });
12382
12383        // Emit closed event on panel 1, which is active
12384        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12385
12386        // Now the left dock is closed, because panel_1 was the active panel
12387        workspace.update(cx, |workspace, cx| {
12388            let right_dock = workspace.right_dock();
12389            assert!(!right_dock.read(cx).is_open());
12390        });
12391    }
12392
12393    #[gpui::test]
12394    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12395        init_test(cx);
12396
12397        let fs = FakeFs::new(cx.background_executor.clone());
12398        let project = Project::test(fs, [], cx).await;
12399        let (workspace, cx) =
12400            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12401        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12402
12403        let dirty_regular_buffer = cx.new(|cx| {
12404            TestItem::new(cx)
12405                .with_dirty(true)
12406                .with_label("1.txt")
12407                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12408        });
12409        let dirty_regular_buffer_2 = cx.new(|cx| {
12410            TestItem::new(cx)
12411                .with_dirty(true)
12412                .with_label("2.txt")
12413                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12414        });
12415        let dirty_multi_buffer_with_both = cx.new(|cx| {
12416            TestItem::new(cx)
12417                .with_dirty(true)
12418                .with_buffer_kind(ItemBufferKind::Multibuffer)
12419                .with_label("Fake Project Search")
12420                .with_project_items(&[
12421                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12422                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12423                ])
12424        });
12425        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12426        workspace.update_in(cx, |workspace, window, cx| {
12427            workspace.add_item(
12428                pane.clone(),
12429                Box::new(dirty_regular_buffer.clone()),
12430                None,
12431                false,
12432                false,
12433                window,
12434                cx,
12435            );
12436            workspace.add_item(
12437                pane.clone(),
12438                Box::new(dirty_regular_buffer_2.clone()),
12439                None,
12440                false,
12441                false,
12442                window,
12443                cx,
12444            );
12445            workspace.add_item(
12446                pane.clone(),
12447                Box::new(dirty_multi_buffer_with_both.clone()),
12448                None,
12449                false,
12450                false,
12451                window,
12452                cx,
12453            );
12454        });
12455
12456        pane.update_in(cx, |pane, window, cx| {
12457            pane.activate_item(2, true, true, window, cx);
12458            assert_eq!(
12459                pane.active_item().unwrap().item_id(),
12460                multi_buffer_with_both_files_id,
12461                "Should select the multi buffer in the pane"
12462            );
12463        });
12464        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12465            pane.close_other_items(
12466                &CloseOtherItems {
12467                    save_intent: Some(SaveIntent::Save),
12468                    close_pinned: true,
12469                },
12470                None,
12471                window,
12472                cx,
12473            )
12474        });
12475        cx.background_executor.run_until_parked();
12476        assert!(!cx.has_pending_prompt());
12477        close_all_but_multi_buffer_task
12478            .await
12479            .expect("Closing all buffers but the multi buffer failed");
12480        pane.update(cx, |pane, cx| {
12481            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12482            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12483            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12484            assert_eq!(pane.items_len(), 1);
12485            assert_eq!(
12486                pane.active_item().unwrap().item_id(),
12487                multi_buffer_with_both_files_id,
12488                "Should have only the multi buffer left in the pane"
12489            );
12490            assert!(
12491                dirty_multi_buffer_with_both.read(cx).is_dirty,
12492                "The multi buffer containing the unsaved buffer should still be dirty"
12493            );
12494        });
12495
12496        dirty_regular_buffer.update(cx, |buffer, cx| {
12497            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12498        });
12499
12500        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12501            pane.close_active_item(
12502                &CloseActiveItem {
12503                    save_intent: Some(SaveIntent::Close),
12504                    close_pinned: false,
12505                },
12506                window,
12507                cx,
12508            )
12509        });
12510        cx.background_executor.run_until_parked();
12511        assert!(
12512            cx.has_pending_prompt(),
12513            "Dirty multi buffer should prompt a save dialog"
12514        );
12515        cx.simulate_prompt_answer("Save");
12516        cx.background_executor.run_until_parked();
12517        close_multi_buffer_task
12518            .await
12519            .expect("Closing the multi buffer failed");
12520        pane.update(cx, |pane, cx| {
12521            assert_eq!(
12522                dirty_multi_buffer_with_both.read(cx).save_count,
12523                1,
12524                "Multi buffer item should get be saved"
12525            );
12526            // Test impl does not save inner items, so we do not assert them
12527            assert_eq!(
12528                pane.items_len(),
12529                0,
12530                "No more items should be left in the pane"
12531            );
12532            assert!(pane.active_item().is_none());
12533        });
12534    }
12535
12536    #[gpui::test]
12537    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12538        cx: &mut TestAppContext,
12539    ) {
12540        init_test(cx);
12541
12542        let fs = FakeFs::new(cx.background_executor.clone());
12543        let project = Project::test(fs, [], cx).await;
12544        let (workspace, cx) =
12545            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12546        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12547
12548        let dirty_regular_buffer = cx.new(|cx| {
12549            TestItem::new(cx)
12550                .with_dirty(true)
12551                .with_label("1.txt")
12552                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12553        });
12554        let dirty_regular_buffer_2 = cx.new(|cx| {
12555            TestItem::new(cx)
12556                .with_dirty(true)
12557                .with_label("2.txt")
12558                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12559        });
12560        let clear_regular_buffer = cx.new(|cx| {
12561            TestItem::new(cx)
12562                .with_label("3.txt")
12563                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12564        });
12565
12566        let dirty_multi_buffer_with_both = cx.new(|cx| {
12567            TestItem::new(cx)
12568                .with_dirty(true)
12569                .with_buffer_kind(ItemBufferKind::Multibuffer)
12570                .with_label("Fake Project Search")
12571                .with_project_items(&[
12572                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12573                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12574                    clear_regular_buffer.read(cx).project_items[0].clone(),
12575                ])
12576        });
12577        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12578        workspace.update_in(cx, |workspace, window, cx| {
12579            workspace.add_item(
12580                pane.clone(),
12581                Box::new(dirty_regular_buffer.clone()),
12582                None,
12583                false,
12584                false,
12585                window,
12586                cx,
12587            );
12588            workspace.add_item(
12589                pane.clone(),
12590                Box::new(dirty_multi_buffer_with_both.clone()),
12591                None,
12592                false,
12593                false,
12594                window,
12595                cx,
12596            );
12597        });
12598
12599        pane.update_in(cx, |pane, window, cx| {
12600            pane.activate_item(1, true, true, window, cx);
12601            assert_eq!(
12602                pane.active_item().unwrap().item_id(),
12603                multi_buffer_with_both_files_id,
12604                "Should select the multi buffer in the pane"
12605            );
12606        });
12607        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12608            pane.close_active_item(
12609                &CloseActiveItem {
12610                    save_intent: None,
12611                    close_pinned: false,
12612                },
12613                window,
12614                cx,
12615            )
12616        });
12617        cx.background_executor.run_until_parked();
12618        assert!(
12619            cx.has_pending_prompt(),
12620            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12621        );
12622    }
12623
12624    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12625    /// closed when they are deleted from disk.
12626    #[gpui::test]
12627    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12628        init_test(cx);
12629
12630        // Enable the close_on_disk_deletion setting
12631        cx.update_global(|store: &mut SettingsStore, cx| {
12632            store.update_user_settings(cx, |settings| {
12633                settings.workspace.close_on_file_delete = Some(true);
12634            });
12635        });
12636
12637        let fs = FakeFs::new(cx.background_executor.clone());
12638        let project = Project::test(fs, [], cx).await;
12639        let (workspace, cx) =
12640            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12641        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12642
12643        // Create a test item that simulates a file
12644        let item = cx.new(|cx| {
12645            TestItem::new(cx)
12646                .with_label("test.txt")
12647                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12648        });
12649
12650        // Add item to workspace
12651        workspace.update_in(cx, |workspace, window, cx| {
12652            workspace.add_item(
12653                pane.clone(),
12654                Box::new(item.clone()),
12655                None,
12656                false,
12657                false,
12658                window,
12659                cx,
12660            );
12661        });
12662
12663        // Verify the item is in the pane
12664        pane.read_with(cx, |pane, _| {
12665            assert_eq!(pane.items().count(), 1);
12666        });
12667
12668        // Simulate file deletion by setting the item's deleted state
12669        item.update(cx, |item, _| {
12670            item.set_has_deleted_file(true);
12671        });
12672
12673        // Emit UpdateTab event to trigger the close behavior
12674        cx.run_until_parked();
12675        item.update(cx, |_, cx| {
12676            cx.emit(ItemEvent::UpdateTab);
12677        });
12678
12679        // Allow the close operation to complete
12680        cx.run_until_parked();
12681
12682        // Verify the item was automatically closed
12683        pane.read_with(cx, |pane, _| {
12684            assert_eq!(
12685                pane.items().count(),
12686                0,
12687                "Item should be automatically closed when file is deleted"
12688            );
12689        });
12690    }
12691
12692    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12693    /// open with a strikethrough when they are deleted from disk.
12694    #[gpui::test]
12695    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12696        init_test(cx);
12697
12698        // Ensure close_on_disk_deletion is disabled (default)
12699        cx.update_global(|store: &mut SettingsStore, cx| {
12700            store.update_user_settings(cx, |settings| {
12701                settings.workspace.close_on_file_delete = Some(false);
12702            });
12703        });
12704
12705        let fs = FakeFs::new(cx.background_executor.clone());
12706        let project = Project::test(fs, [], cx).await;
12707        let (workspace, cx) =
12708            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12709        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12710
12711        // Create a test item that simulates a file
12712        let item = cx.new(|cx| {
12713            TestItem::new(cx)
12714                .with_label("test.txt")
12715                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12716        });
12717
12718        // Add item to workspace
12719        workspace.update_in(cx, |workspace, window, cx| {
12720            workspace.add_item(
12721                pane.clone(),
12722                Box::new(item.clone()),
12723                None,
12724                false,
12725                false,
12726                window,
12727                cx,
12728            );
12729        });
12730
12731        // Verify the item is in the pane
12732        pane.read_with(cx, |pane, _| {
12733            assert_eq!(pane.items().count(), 1);
12734        });
12735
12736        // Simulate file deletion
12737        item.update(cx, |item, _| {
12738            item.set_has_deleted_file(true);
12739        });
12740
12741        // Emit UpdateTab event
12742        cx.run_until_parked();
12743        item.update(cx, |_, cx| {
12744            cx.emit(ItemEvent::UpdateTab);
12745        });
12746
12747        // Allow any potential close operation to complete
12748        cx.run_until_parked();
12749
12750        // Verify the item remains open (with strikethrough)
12751        pane.read_with(cx, |pane, _| {
12752            assert_eq!(
12753                pane.items().count(),
12754                1,
12755                "Item should remain open when close_on_disk_deletion is disabled"
12756            );
12757        });
12758
12759        // Verify the item shows as deleted
12760        item.read_with(cx, |item, _| {
12761            assert!(
12762                item.has_deleted_file,
12763                "Item should be marked as having deleted file"
12764            );
12765        });
12766    }
12767
12768    /// Tests that dirty files are not automatically closed when deleted from disk,
12769    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12770    /// unsaved changes without being prompted.
12771    #[gpui::test]
12772    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12773        init_test(cx);
12774
12775        // Enable the close_on_file_delete setting
12776        cx.update_global(|store: &mut SettingsStore, cx| {
12777            store.update_user_settings(cx, |settings| {
12778                settings.workspace.close_on_file_delete = Some(true);
12779            });
12780        });
12781
12782        let fs = FakeFs::new(cx.background_executor.clone());
12783        let project = Project::test(fs, [], cx).await;
12784        let (workspace, cx) =
12785            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12786        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12787
12788        // Create a dirty test item
12789        let item = cx.new(|cx| {
12790            TestItem::new(cx)
12791                .with_dirty(true)
12792                .with_label("test.txt")
12793                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12794        });
12795
12796        // Add item to workspace
12797        workspace.update_in(cx, |workspace, window, cx| {
12798            workspace.add_item(
12799                pane.clone(),
12800                Box::new(item.clone()),
12801                None,
12802                false,
12803                false,
12804                window,
12805                cx,
12806            );
12807        });
12808
12809        // Simulate file deletion
12810        item.update(cx, |item, _| {
12811            item.set_has_deleted_file(true);
12812        });
12813
12814        // Emit UpdateTab event to trigger the close behavior
12815        cx.run_until_parked();
12816        item.update(cx, |_, cx| {
12817            cx.emit(ItemEvent::UpdateTab);
12818        });
12819
12820        // Allow any potential close operation to complete
12821        cx.run_until_parked();
12822
12823        // Verify the item remains open (dirty files are not auto-closed)
12824        pane.read_with(cx, |pane, _| {
12825            assert_eq!(
12826                pane.items().count(),
12827                1,
12828                "Dirty items should not be automatically closed even when file is deleted"
12829            );
12830        });
12831
12832        // Verify the item is marked as deleted and still dirty
12833        item.read_with(cx, |item, _| {
12834            assert!(
12835                item.has_deleted_file,
12836                "Item should be marked as having deleted file"
12837            );
12838            assert!(item.is_dirty, "Item should still be dirty");
12839        });
12840    }
12841
12842    /// Tests that navigation history is cleaned up when files are auto-closed
12843    /// due to deletion from disk.
12844    #[gpui::test]
12845    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12846        init_test(cx);
12847
12848        // Enable the close_on_file_delete setting
12849        cx.update_global(|store: &mut SettingsStore, cx| {
12850            store.update_user_settings(cx, |settings| {
12851                settings.workspace.close_on_file_delete = Some(true);
12852            });
12853        });
12854
12855        let fs = FakeFs::new(cx.background_executor.clone());
12856        let project = Project::test(fs, [], cx).await;
12857        let (workspace, cx) =
12858            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12859        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12860
12861        // Create test items
12862        let item1 = cx.new(|cx| {
12863            TestItem::new(cx)
12864                .with_label("test1.txt")
12865                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12866        });
12867        let item1_id = item1.item_id();
12868
12869        let item2 = cx.new(|cx| {
12870            TestItem::new(cx)
12871                .with_label("test2.txt")
12872                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12873        });
12874
12875        // Add items to workspace
12876        workspace.update_in(cx, |workspace, window, cx| {
12877            workspace.add_item(
12878                pane.clone(),
12879                Box::new(item1.clone()),
12880                None,
12881                false,
12882                false,
12883                window,
12884                cx,
12885            );
12886            workspace.add_item(
12887                pane.clone(),
12888                Box::new(item2.clone()),
12889                None,
12890                false,
12891                false,
12892                window,
12893                cx,
12894            );
12895        });
12896
12897        // Activate item1 to ensure it gets navigation entries
12898        pane.update_in(cx, |pane, window, cx| {
12899            pane.activate_item(0, true, true, window, cx);
12900        });
12901
12902        // Switch to item2 and back to create navigation history
12903        pane.update_in(cx, |pane, window, cx| {
12904            pane.activate_item(1, true, true, window, cx);
12905        });
12906        cx.run_until_parked();
12907
12908        pane.update_in(cx, |pane, window, cx| {
12909            pane.activate_item(0, true, true, window, cx);
12910        });
12911        cx.run_until_parked();
12912
12913        // Simulate file deletion for item1
12914        item1.update(cx, |item, _| {
12915            item.set_has_deleted_file(true);
12916        });
12917
12918        // Emit UpdateTab event to trigger the close behavior
12919        item1.update(cx, |_, cx| {
12920            cx.emit(ItemEvent::UpdateTab);
12921        });
12922        cx.run_until_parked();
12923
12924        // Verify item1 was closed
12925        pane.read_with(cx, |pane, _| {
12926            assert_eq!(
12927                pane.items().count(),
12928                1,
12929                "Should have 1 item remaining after auto-close"
12930            );
12931        });
12932
12933        // Check navigation history after close
12934        let has_item = pane.read_with(cx, |pane, cx| {
12935            let mut has_item = false;
12936            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12937                if entry.item.id() == item1_id {
12938                    has_item = true;
12939                }
12940            });
12941            has_item
12942        });
12943
12944        assert!(
12945            !has_item,
12946            "Navigation history should not contain closed item entries"
12947        );
12948    }
12949
12950    #[gpui::test]
12951    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12952        cx: &mut TestAppContext,
12953    ) {
12954        init_test(cx);
12955
12956        let fs = FakeFs::new(cx.background_executor.clone());
12957        let project = Project::test(fs, [], cx).await;
12958        let (workspace, cx) =
12959            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12960        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12961
12962        let dirty_regular_buffer = cx.new(|cx| {
12963            TestItem::new(cx)
12964                .with_dirty(true)
12965                .with_label("1.txt")
12966                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12967        });
12968        let dirty_regular_buffer_2 = cx.new(|cx| {
12969            TestItem::new(cx)
12970                .with_dirty(true)
12971                .with_label("2.txt")
12972                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12973        });
12974        let clear_regular_buffer = cx.new(|cx| {
12975            TestItem::new(cx)
12976                .with_label("3.txt")
12977                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12978        });
12979
12980        let dirty_multi_buffer = cx.new(|cx| {
12981            TestItem::new(cx)
12982                .with_dirty(true)
12983                .with_buffer_kind(ItemBufferKind::Multibuffer)
12984                .with_label("Fake Project Search")
12985                .with_project_items(&[
12986                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12987                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12988                    clear_regular_buffer.read(cx).project_items[0].clone(),
12989                ])
12990        });
12991        workspace.update_in(cx, |workspace, window, cx| {
12992            workspace.add_item(
12993                pane.clone(),
12994                Box::new(dirty_regular_buffer.clone()),
12995                None,
12996                false,
12997                false,
12998                window,
12999                cx,
13000            );
13001            workspace.add_item(
13002                pane.clone(),
13003                Box::new(dirty_regular_buffer_2.clone()),
13004                None,
13005                false,
13006                false,
13007                window,
13008                cx,
13009            );
13010            workspace.add_item(
13011                pane.clone(),
13012                Box::new(dirty_multi_buffer.clone()),
13013                None,
13014                false,
13015                false,
13016                window,
13017                cx,
13018            );
13019        });
13020
13021        pane.update_in(cx, |pane, window, cx| {
13022            pane.activate_item(2, true, true, window, cx);
13023            assert_eq!(
13024                pane.active_item().unwrap().item_id(),
13025                dirty_multi_buffer.item_id(),
13026                "Should select the multi buffer in the pane"
13027            );
13028        });
13029        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13030            pane.close_active_item(
13031                &CloseActiveItem {
13032                    save_intent: None,
13033                    close_pinned: false,
13034                },
13035                window,
13036                cx,
13037            )
13038        });
13039        cx.background_executor.run_until_parked();
13040        assert!(
13041            !cx.has_pending_prompt(),
13042            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13043        );
13044        close_multi_buffer_task
13045            .await
13046            .expect("Closing multi buffer failed");
13047        pane.update(cx, |pane, cx| {
13048            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13049            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13050            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13051            assert_eq!(
13052                pane.items()
13053                    .map(|item| item.item_id())
13054                    .sorted()
13055                    .collect::<Vec<_>>(),
13056                vec![
13057                    dirty_regular_buffer.item_id(),
13058                    dirty_regular_buffer_2.item_id(),
13059                ],
13060                "Should have no multi buffer left in the pane"
13061            );
13062            assert!(dirty_regular_buffer.read(cx).is_dirty);
13063            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13064        });
13065    }
13066
13067    #[gpui::test]
13068    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13069        init_test(cx);
13070        let fs = FakeFs::new(cx.executor());
13071        let project = Project::test(fs, [], cx).await;
13072        let (multi_workspace, cx) =
13073            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13074        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13075
13076        // Add a new panel to the right dock, opening the dock and setting the
13077        // focus to the new panel.
13078        let panel = workspace.update_in(cx, |workspace, window, cx| {
13079            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13080            workspace.add_panel(panel.clone(), window, cx);
13081
13082            workspace
13083                .right_dock()
13084                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13085
13086            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13087
13088            panel
13089        });
13090
13091        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13092        // panel to the next valid position which, in this case, is the left
13093        // dock.
13094        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13095        workspace.update(cx, |workspace, cx| {
13096            assert!(workspace.left_dock().read(cx).is_open());
13097            assert_eq!(panel.read(cx).position, DockPosition::Left);
13098        });
13099
13100        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13101        // panel to the next valid position which, in this case, is the bottom
13102        // dock.
13103        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13104        workspace.update(cx, |workspace, cx| {
13105            assert!(workspace.bottom_dock().read(cx).is_open());
13106            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13107        });
13108
13109        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13110        // around moving the panel to its initial position, the right dock.
13111        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13112        workspace.update(cx, |workspace, cx| {
13113            assert!(workspace.right_dock().read(cx).is_open());
13114            assert_eq!(panel.read(cx).position, DockPosition::Right);
13115        });
13116
13117        // Remove focus from the panel, ensuring that, if the panel is not
13118        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13119        // the panel's position, so the panel is still in the right dock.
13120        workspace.update_in(cx, |workspace, window, cx| {
13121            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13122        });
13123
13124        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13125        workspace.update(cx, |workspace, cx| {
13126            assert!(workspace.right_dock().read(cx).is_open());
13127            assert_eq!(panel.read(cx).position, DockPosition::Right);
13128        });
13129    }
13130
13131    #[gpui::test]
13132    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13133        init_test(cx);
13134
13135        let fs = FakeFs::new(cx.executor());
13136        let project = Project::test(fs, [], cx).await;
13137        let (workspace, cx) =
13138            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13139
13140        let item_1 = cx.new(|cx| {
13141            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13142        });
13143        workspace.update_in(cx, |workspace, window, cx| {
13144            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13145            workspace.move_item_to_pane_in_direction(
13146                &MoveItemToPaneInDirection {
13147                    direction: SplitDirection::Right,
13148                    focus: true,
13149                    clone: false,
13150                },
13151                window,
13152                cx,
13153            );
13154            workspace.move_item_to_pane_at_index(
13155                &MoveItemToPane {
13156                    destination: 3,
13157                    focus: true,
13158                    clone: false,
13159                },
13160                window,
13161                cx,
13162            );
13163
13164            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13165            assert_eq!(
13166                pane_items_paths(&workspace.active_pane, cx),
13167                vec!["first.txt".to_string()],
13168                "Single item was not moved anywhere"
13169            );
13170        });
13171
13172        let item_2 = cx.new(|cx| {
13173            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13174        });
13175        workspace.update_in(cx, |workspace, window, cx| {
13176            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13177            assert_eq!(
13178                pane_items_paths(&workspace.panes[0], cx),
13179                vec!["first.txt".to_string(), "second.txt".to_string()],
13180            );
13181            workspace.move_item_to_pane_in_direction(
13182                &MoveItemToPaneInDirection {
13183                    direction: SplitDirection::Right,
13184                    focus: true,
13185                    clone: false,
13186                },
13187                window,
13188                cx,
13189            );
13190
13191            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13192            assert_eq!(
13193                pane_items_paths(&workspace.panes[0], cx),
13194                vec!["first.txt".to_string()],
13195                "After moving, one item should be left in the original pane"
13196            );
13197            assert_eq!(
13198                pane_items_paths(&workspace.panes[1], cx),
13199                vec!["second.txt".to_string()],
13200                "New item should have been moved to the new pane"
13201            );
13202        });
13203
13204        let item_3 = cx.new(|cx| {
13205            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13206        });
13207        workspace.update_in(cx, |workspace, window, cx| {
13208            let original_pane = workspace.panes[0].clone();
13209            workspace.set_active_pane(&original_pane, window, cx);
13210            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13211            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13212            assert_eq!(
13213                pane_items_paths(&workspace.active_pane, cx),
13214                vec!["first.txt".to_string(), "third.txt".to_string()],
13215                "New pane should be ready to move one item out"
13216            );
13217
13218            workspace.move_item_to_pane_at_index(
13219                &MoveItemToPane {
13220                    destination: 3,
13221                    focus: true,
13222                    clone: false,
13223                },
13224                window,
13225                cx,
13226            );
13227            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13228            assert_eq!(
13229                pane_items_paths(&workspace.active_pane, cx),
13230                vec!["first.txt".to_string()],
13231                "After moving, one item should be left in the original pane"
13232            );
13233            assert_eq!(
13234                pane_items_paths(&workspace.panes[1], cx),
13235                vec!["second.txt".to_string()],
13236                "Previously created pane should be unchanged"
13237            );
13238            assert_eq!(
13239                pane_items_paths(&workspace.panes[2], cx),
13240                vec!["third.txt".to_string()],
13241                "New item should have been moved to the new pane"
13242            );
13243        });
13244    }
13245
13246    #[gpui::test]
13247    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13248        init_test(cx);
13249
13250        let fs = FakeFs::new(cx.executor());
13251        let project = Project::test(fs, [], cx).await;
13252        let (workspace, cx) =
13253            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13254
13255        let item_1 = cx.new(|cx| {
13256            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13257        });
13258        workspace.update_in(cx, |workspace, window, cx| {
13259            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13260            workspace.move_item_to_pane_in_direction(
13261                &MoveItemToPaneInDirection {
13262                    direction: SplitDirection::Right,
13263                    focus: true,
13264                    clone: true,
13265                },
13266                window,
13267                cx,
13268            );
13269        });
13270        cx.run_until_parked();
13271        workspace.update_in(cx, |workspace, window, cx| {
13272            workspace.move_item_to_pane_at_index(
13273                &MoveItemToPane {
13274                    destination: 3,
13275                    focus: true,
13276                    clone: true,
13277                },
13278                window,
13279                cx,
13280            );
13281        });
13282        cx.run_until_parked();
13283
13284        workspace.update(cx, |workspace, cx| {
13285            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13286            for pane in workspace.panes() {
13287                assert_eq!(
13288                    pane_items_paths(pane, cx),
13289                    vec!["first.txt".to_string()],
13290                    "Single item exists in all panes"
13291                );
13292            }
13293        });
13294
13295        // verify that the active pane has been updated after waiting for the
13296        // pane focus event to fire and resolve
13297        workspace.read_with(cx, |workspace, _app| {
13298            assert_eq!(
13299                workspace.active_pane(),
13300                &workspace.panes[2],
13301                "The third pane should be the active one: {:?}",
13302                workspace.panes
13303            );
13304        })
13305    }
13306
13307    #[gpui::test]
13308    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13309        init_test(cx);
13310
13311        let fs = FakeFs::new(cx.executor());
13312        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13313
13314        let project = Project::test(fs, ["root".as_ref()], cx).await;
13315        let (workspace, cx) =
13316            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13317
13318        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13319        // Add item to pane A with project path
13320        let item_a = cx.new(|cx| {
13321            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13322        });
13323        workspace.update_in(cx, |workspace, window, cx| {
13324            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13325        });
13326
13327        // Split to create pane B
13328        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13329            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13330        });
13331
13332        // Add item with SAME project path to pane B, and pin it
13333        let item_b = cx.new(|cx| {
13334            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13335        });
13336        pane_b.update_in(cx, |pane, window, cx| {
13337            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13338            pane.set_pinned_count(1);
13339        });
13340
13341        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13342        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13343
13344        // close_pinned: false should only close the unpinned copy
13345        workspace.update_in(cx, |workspace, window, cx| {
13346            workspace.close_item_in_all_panes(
13347                &CloseItemInAllPanes {
13348                    save_intent: Some(SaveIntent::Close),
13349                    close_pinned: false,
13350                },
13351                window,
13352                cx,
13353            )
13354        });
13355        cx.executor().run_until_parked();
13356
13357        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13358        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13359        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13360        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13361
13362        // Split again, seeing as closing the previous item also closed its
13363        // pane, so only pane remains, which does not allow us to properly test
13364        // that both items close when `close_pinned: true`.
13365        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13366            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13367        });
13368
13369        // Add an item with the same project path to pane C so that
13370        // close_item_in_all_panes can determine what to close across all panes
13371        // (it reads the active item from the active pane, and split_pane
13372        // creates an empty pane).
13373        let item_c = cx.new(|cx| {
13374            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13375        });
13376        pane_c.update_in(cx, |pane, window, cx| {
13377            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13378        });
13379
13380        // close_pinned: true should close the pinned copy too
13381        workspace.update_in(cx, |workspace, window, cx| {
13382            let panes_count = workspace.panes().len();
13383            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13384
13385            workspace.close_item_in_all_panes(
13386                &CloseItemInAllPanes {
13387                    save_intent: Some(SaveIntent::Close),
13388                    close_pinned: true,
13389                },
13390                window,
13391                cx,
13392            )
13393        });
13394        cx.executor().run_until_parked();
13395
13396        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13397        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13398        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13399        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13400    }
13401
13402    mod register_project_item_tests {
13403
13404        use super::*;
13405
13406        // View
13407        struct TestPngItemView {
13408            focus_handle: FocusHandle,
13409        }
13410        // Model
13411        struct TestPngItem {}
13412
13413        impl project::ProjectItem for TestPngItem {
13414            fn try_open(
13415                _project: &Entity<Project>,
13416                path: &ProjectPath,
13417                cx: &mut App,
13418            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13419                if path.path.extension().unwrap() == "png" {
13420                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13421                } else {
13422                    None
13423                }
13424            }
13425
13426            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13427                None
13428            }
13429
13430            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13431                None
13432            }
13433
13434            fn is_dirty(&self) -> bool {
13435                false
13436            }
13437        }
13438
13439        impl Item for TestPngItemView {
13440            type Event = ();
13441            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13442                "".into()
13443            }
13444        }
13445        impl EventEmitter<()> for TestPngItemView {}
13446        impl Focusable for TestPngItemView {
13447            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13448                self.focus_handle.clone()
13449            }
13450        }
13451
13452        impl Render for TestPngItemView {
13453            fn render(
13454                &mut self,
13455                _window: &mut Window,
13456                _cx: &mut Context<Self>,
13457            ) -> impl IntoElement {
13458                Empty
13459            }
13460        }
13461
13462        impl ProjectItem for TestPngItemView {
13463            type Item = TestPngItem;
13464
13465            fn for_project_item(
13466                _project: Entity<Project>,
13467                _pane: Option<&Pane>,
13468                _item: Entity<Self::Item>,
13469                _: &mut Window,
13470                cx: &mut Context<Self>,
13471            ) -> Self
13472            where
13473                Self: Sized,
13474            {
13475                Self {
13476                    focus_handle: cx.focus_handle(),
13477                }
13478            }
13479        }
13480
13481        // View
13482        struct TestIpynbItemView {
13483            focus_handle: FocusHandle,
13484        }
13485        // Model
13486        struct TestIpynbItem {}
13487
13488        impl project::ProjectItem for TestIpynbItem {
13489            fn try_open(
13490                _project: &Entity<Project>,
13491                path: &ProjectPath,
13492                cx: &mut App,
13493            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13494                if path.path.extension().unwrap() == "ipynb" {
13495                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13496                } else {
13497                    None
13498                }
13499            }
13500
13501            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13502                None
13503            }
13504
13505            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13506                None
13507            }
13508
13509            fn is_dirty(&self) -> bool {
13510                false
13511            }
13512        }
13513
13514        impl Item for TestIpynbItemView {
13515            type Event = ();
13516            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13517                "".into()
13518            }
13519        }
13520        impl EventEmitter<()> for TestIpynbItemView {}
13521        impl Focusable for TestIpynbItemView {
13522            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13523                self.focus_handle.clone()
13524            }
13525        }
13526
13527        impl Render for TestIpynbItemView {
13528            fn render(
13529                &mut self,
13530                _window: &mut Window,
13531                _cx: &mut Context<Self>,
13532            ) -> impl IntoElement {
13533                Empty
13534            }
13535        }
13536
13537        impl ProjectItem for TestIpynbItemView {
13538            type Item = TestIpynbItem;
13539
13540            fn for_project_item(
13541                _project: Entity<Project>,
13542                _pane: Option<&Pane>,
13543                _item: Entity<Self::Item>,
13544                _: &mut Window,
13545                cx: &mut Context<Self>,
13546            ) -> Self
13547            where
13548                Self: Sized,
13549            {
13550                Self {
13551                    focus_handle: cx.focus_handle(),
13552                }
13553            }
13554        }
13555
13556        struct TestAlternatePngItemView {
13557            focus_handle: FocusHandle,
13558        }
13559
13560        impl Item for TestAlternatePngItemView {
13561            type Event = ();
13562            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13563                "".into()
13564            }
13565        }
13566
13567        impl EventEmitter<()> for TestAlternatePngItemView {}
13568        impl Focusable for TestAlternatePngItemView {
13569            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13570                self.focus_handle.clone()
13571            }
13572        }
13573
13574        impl Render for TestAlternatePngItemView {
13575            fn render(
13576                &mut self,
13577                _window: &mut Window,
13578                _cx: &mut Context<Self>,
13579            ) -> impl IntoElement {
13580                Empty
13581            }
13582        }
13583
13584        impl ProjectItem for TestAlternatePngItemView {
13585            type Item = TestPngItem;
13586
13587            fn for_project_item(
13588                _project: Entity<Project>,
13589                _pane: Option<&Pane>,
13590                _item: Entity<Self::Item>,
13591                _: &mut Window,
13592                cx: &mut Context<Self>,
13593            ) -> Self
13594            where
13595                Self: Sized,
13596            {
13597                Self {
13598                    focus_handle: cx.focus_handle(),
13599                }
13600            }
13601        }
13602
13603        #[gpui::test]
13604        async fn test_register_project_item(cx: &mut TestAppContext) {
13605            init_test(cx);
13606
13607            cx.update(|cx| {
13608                register_project_item::<TestPngItemView>(cx);
13609                register_project_item::<TestIpynbItemView>(cx);
13610            });
13611
13612            let fs = FakeFs::new(cx.executor());
13613            fs.insert_tree(
13614                "/root1",
13615                json!({
13616                    "one.png": "BINARYDATAHERE",
13617                    "two.ipynb": "{ totally a notebook }",
13618                    "three.txt": "editing text, sure why not?"
13619                }),
13620            )
13621            .await;
13622
13623            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13624            let (workspace, cx) =
13625                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13626
13627            let worktree_id = project.update(cx, |project, cx| {
13628                project.worktrees(cx).next().unwrap().read(cx).id()
13629            });
13630
13631            let handle = workspace
13632                .update_in(cx, |workspace, window, cx| {
13633                    let project_path = (worktree_id, rel_path("one.png"));
13634                    workspace.open_path(project_path, None, true, window, cx)
13635                })
13636                .await
13637                .unwrap();
13638
13639            // Now we can check if the handle we got back errored or not
13640            assert_eq!(
13641                handle.to_any_view().entity_type(),
13642                TypeId::of::<TestPngItemView>()
13643            );
13644
13645            let handle = workspace
13646                .update_in(cx, |workspace, window, cx| {
13647                    let project_path = (worktree_id, rel_path("two.ipynb"));
13648                    workspace.open_path(project_path, None, true, window, cx)
13649                })
13650                .await
13651                .unwrap();
13652
13653            assert_eq!(
13654                handle.to_any_view().entity_type(),
13655                TypeId::of::<TestIpynbItemView>()
13656            );
13657
13658            let handle = workspace
13659                .update_in(cx, |workspace, window, cx| {
13660                    let project_path = (worktree_id, rel_path("three.txt"));
13661                    workspace.open_path(project_path, None, true, window, cx)
13662                })
13663                .await;
13664            assert!(handle.is_err());
13665        }
13666
13667        #[gpui::test]
13668        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13669            init_test(cx);
13670
13671            cx.update(|cx| {
13672                register_project_item::<TestPngItemView>(cx);
13673                register_project_item::<TestAlternatePngItemView>(cx);
13674            });
13675
13676            let fs = FakeFs::new(cx.executor());
13677            fs.insert_tree(
13678                "/root1",
13679                json!({
13680                    "one.png": "BINARYDATAHERE",
13681                    "two.ipynb": "{ totally a notebook }",
13682                    "three.txt": "editing text, sure why not?"
13683                }),
13684            )
13685            .await;
13686            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13687            let (workspace, cx) =
13688                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13689            let worktree_id = project.update(cx, |project, cx| {
13690                project.worktrees(cx).next().unwrap().read(cx).id()
13691            });
13692
13693            let handle = workspace
13694                .update_in(cx, |workspace, window, cx| {
13695                    let project_path = (worktree_id, rel_path("one.png"));
13696                    workspace.open_path(project_path, None, true, window, cx)
13697                })
13698                .await
13699                .unwrap();
13700
13701            // This _must_ be the second item registered
13702            assert_eq!(
13703                handle.to_any_view().entity_type(),
13704                TypeId::of::<TestAlternatePngItemView>()
13705            );
13706
13707            let handle = workspace
13708                .update_in(cx, |workspace, window, cx| {
13709                    let project_path = (worktree_id, rel_path("three.txt"));
13710                    workspace.open_path(project_path, None, true, window, cx)
13711                })
13712                .await;
13713            assert!(handle.is_err());
13714        }
13715    }
13716
13717    #[gpui::test]
13718    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13719        init_test(cx);
13720
13721        let fs = FakeFs::new(cx.executor());
13722        let project = Project::test(fs, [], cx).await;
13723        let (workspace, _cx) =
13724            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13725
13726        // Test with status bar shown (default)
13727        workspace.read_with(cx, |workspace, cx| {
13728            let visible = workspace.status_bar_visible(cx);
13729            assert!(visible, "Status bar should be visible by default");
13730        });
13731
13732        // Test with status bar hidden
13733        cx.update_global(|store: &mut SettingsStore, cx| {
13734            store.update_user_settings(cx, |settings| {
13735                settings.status_bar.get_or_insert_default().show = Some(false);
13736            });
13737        });
13738
13739        workspace.read_with(cx, |workspace, cx| {
13740            let visible = workspace.status_bar_visible(cx);
13741            assert!(!visible, "Status bar should be hidden when show is false");
13742        });
13743
13744        // Test with status bar shown explicitly
13745        cx.update_global(|store: &mut SettingsStore, cx| {
13746            store.update_user_settings(cx, |settings| {
13747                settings.status_bar.get_or_insert_default().show = Some(true);
13748            });
13749        });
13750
13751        workspace.read_with(cx, |workspace, cx| {
13752            let visible = workspace.status_bar_visible(cx);
13753            assert!(visible, "Status bar should be visible when show is true");
13754        });
13755    }
13756
13757    #[gpui::test]
13758    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13759        init_test(cx);
13760
13761        let fs = FakeFs::new(cx.executor());
13762        let project = Project::test(fs, [], cx).await;
13763        let (multi_workspace, cx) =
13764            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13765        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13766        let panel = workspace.update_in(cx, |workspace, window, cx| {
13767            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13768            workspace.add_panel(panel.clone(), window, cx);
13769
13770            workspace
13771                .right_dock()
13772                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13773
13774            panel
13775        });
13776
13777        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13778        let item_a = cx.new(TestItem::new);
13779        let item_b = cx.new(TestItem::new);
13780        let item_a_id = item_a.entity_id();
13781        let item_b_id = item_b.entity_id();
13782
13783        pane.update_in(cx, |pane, window, cx| {
13784            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13785            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13786        });
13787
13788        pane.read_with(cx, |pane, _| {
13789            assert_eq!(pane.items_len(), 2);
13790            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13791        });
13792
13793        workspace.update_in(cx, |workspace, window, cx| {
13794            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13795        });
13796
13797        workspace.update_in(cx, |_, window, cx| {
13798            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13799        });
13800
13801        // Assert that the `pane::CloseActiveItem` action is handled at the
13802        // workspace level when one of the dock panels is focused and, in that
13803        // case, the center pane's active item is closed but the focus is not
13804        // moved.
13805        cx.dispatch_action(pane::CloseActiveItem::default());
13806        cx.run_until_parked();
13807
13808        pane.read_with(cx, |pane, _| {
13809            assert_eq!(pane.items_len(), 1);
13810            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13811        });
13812
13813        workspace.update_in(cx, |workspace, window, cx| {
13814            assert!(workspace.right_dock().read(cx).is_open());
13815            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13816        });
13817    }
13818
13819    #[gpui::test]
13820    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13821        init_test(cx);
13822        let fs = FakeFs::new(cx.executor());
13823
13824        let project_a = Project::test(fs.clone(), [], cx).await;
13825        let project_b = Project::test(fs, [], cx).await;
13826
13827        let multi_workspace_handle =
13828            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13829        cx.run_until_parked();
13830
13831        let workspace_a = multi_workspace_handle
13832            .read_with(cx, |mw, _| mw.workspace().clone())
13833            .unwrap();
13834
13835        let _workspace_b = multi_workspace_handle
13836            .update(cx, |mw, window, cx| {
13837                mw.test_add_workspace(project_b, window, cx)
13838            })
13839            .unwrap();
13840
13841        // Switch to workspace A
13842        multi_workspace_handle
13843            .update(cx, |mw, window, cx| {
13844                mw.activate_index(0, window, cx);
13845            })
13846            .unwrap();
13847
13848        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13849
13850        // Add a panel to workspace A's right dock and open the dock
13851        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13852            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13853            workspace.add_panel(panel.clone(), window, cx);
13854            workspace
13855                .right_dock()
13856                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13857            panel
13858        });
13859
13860        // Focus the panel through the workspace (matching existing test pattern)
13861        workspace_a.update_in(cx, |workspace, window, cx| {
13862            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13863        });
13864
13865        // Zoom the panel
13866        panel.update_in(cx, |panel, window, cx| {
13867            panel.set_zoomed(true, window, cx);
13868        });
13869
13870        // Verify the panel is zoomed and the dock is open
13871        workspace_a.update_in(cx, |workspace, window, cx| {
13872            assert!(
13873                workspace.right_dock().read(cx).is_open(),
13874                "dock should be open before switch"
13875            );
13876            assert!(
13877                panel.is_zoomed(window, cx),
13878                "panel should be zoomed before switch"
13879            );
13880            assert!(
13881                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13882                "panel should be focused before switch"
13883            );
13884        });
13885
13886        // Switch to workspace B
13887        multi_workspace_handle
13888            .update(cx, |mw, window, cx| {
13889                mw.activate_index(1, window, cx);
13890            })
13891            .unwrap();
13892        cx.run_until_parked();
13893
13894        // Switch back to workspace A
13895        multi_workspace_handle
13896            .update(cx, |mw, window, cx| {
13897                mw.activate_index(0, window, cx);
13898            })
13899            .unwrap();
13900        cx.run_until_parked();
13901
13902        // Verify the panel is still zoomed and the dock is still open
13903        workspace_a.update_in(cx, |workspace, window, cx| {
13904            assert!(
13905                workspace.right_dock().read(cx).is_open(),
13906                "dock should still be open after switching back"
13907            );
13908            assert!(
13909                panel.is_zoomed(window, cx),
13910                "panel should still be zoomed after switching back"
13911            );
13912        });
13913    }
13914
13915    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13916        pane.read(cx)
13917            .items()
13918            .flat_map(|item| {
13919                item.project_paths(cx)
13920                    .into_iter()
13921                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13922            })
13923            .collect()
13924    }
13925
13926    pub fn init_test(cx: &mut TestAppContext) {
13927        cx.update(|cx| {
13928            let settings_store = SettingsStore::test(cx);
13929            cx.set_global(settings_store);
13930            theme::init(theme::LoadThemes::JustBase, cx);
13931        });
13932    }
13933
13934    #[gpui::test]
13935    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13936        use settings::{ThemeName, ThemeSelection};
13937        use theme::SystemAppearance;
13938        use zed_actions::theme::ToggleMode;
13939
13940        init_test(cx);
13941
13942        let fs = FakeFs::new(cx.executor());
13943        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13944
13945        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13946            .await;
13947
13948        // Build a test project and workspace view so the test can invoke
13949        // the workspace action handler the same way the UI would.
13950        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13951        let (workspace, cx) =
13952            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13953
13954        // Seed the settings file with a plain static light theme so the
13955        // first toggle always starts from a known persisted state.
13956        workspace.update_in(cx, |_workspace, _window, cx| {
13957            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13958            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13959                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13960            });
13961        });
13962        cx.executor().advance_clock(Duration::from_millis(200));
13963        cx.run_until_parked();
13964
13965        // Confirm the initial persisted settings contain the static theme
13966        // we just wrote before any toggling happens.
13967        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13968        assert!(settings_text.contains(r#""theme": "One Light""#));
13969
13970        // Toggle once. This should migrate the persisted theme settings
13971        // into light/dark slots and enable system mode.
13972        workspace.update_in(cx, |workspace, window, cx| {
13973            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13974        });
13975        cx.executor().advance_clock(Duration::from_millis(200));
13976        cx.run_until_parked();
13977
13978        // 1. Static -> Dynamic
13979        // this assertion checks theme changed from static to dynamic.
13980        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13981        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13982        assert_eq!(
13983            parsed["theme"],
13984            serde_json::json!({
13985                "mode": "system",
13986                "light": "One Light",
13987                "dark": "One Dark"
13988            })
13989        );
13990
13991        // 2. Toggle again, suppose it will change the mode to light
13992        workspace.update_in(cx, |workspace, window, cx| {
13993            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13994        });
13995        cx.executor().advance_clock(Duration::from_millis(200));
13996        cx.run_until_parked();
13997
13998        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13999        assert!(settings_text.contains(r#""mode": "light""#));
14000    }
14001
14002    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14003        let item = TestProjectItem::new(id, path, cx);
14004        item.update(cx, |item, _| {
14005            item.is_dirty = true;
14006        });
14007        item
14008    }
14009
14010    #[gpui::test]
14011    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14012        cx: &mut gpui::TestAppContext,
14013    ) {
14014        init_test(cx);
14015        let fs = FakeFs::new(cx.executor());
14016
14017        let project = Project::test(fs, [], cx).await;
14018        let (workspace, cx) =
14019            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14020
14021        let panel = workspace.update_in(cx, |workspace, window, cx| {
14022            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14023            workspace.add_panel(panel.clone(), window, cx);
14024            workspace
14025                .right_dock()
14026                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14027            panel
14028        });
14029
14030        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14031        pane.update_in(cx, |pane, window, cx| {
14032            let item = cx.new(TestItem::new);
14033            pane.add_item(Box::new(item), true, true, None, window, cx);
14034        });
14035
14036        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14037        // mirrors the real-world flow and avoids side effects from directly
14038        // focusing the panel while the center pane is active.
14039        workspace.update_in(cx, |workspace, window, cx| {
14040            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14041        });
14042
14043        panel.update_in(cx, |panel, window, cx| {
14044            panel.set_zoomed(true, window, cx);
14045        });
14046
14047        workspace.update_in(cx, |workspace, window, cx| {
14048            assert!(workspace.right_dock().read(cx).is_open());
14049            assert!(panel.is_zoomed(window, cx));
14050            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14051        });
14052
14053        // Simulate a spurious pane::Event::Focus on the center pane while the
14054        // panel still has focus. This mirrors what happens during macOS window
14055        // activation: the center pane fires a focus event even though actual
14056        // focus remains on the dock panel.
14057        pane.update_in(cx, |_, _, cx| {
14058            cx.emit(pane::Event::Focus);
14059        });
14060
14061        // The dock must remain open because the panel had focus at the time the
14062        // event was processed. Before the fix, dock_to_preserve was None for
14063        // panels that don't implement pane(), causing the dock to close.
14064        workspace.update_in(cx, |workspace, window, cx| {
14065            assert!(
14066                workspace.right_dock().read(cx).is_open(),
14067                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14068            );
14069            assert!(panel.is_zoomed(window, cx));
14070        });
14071    }
14072}