workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8pub mod notifications;
    9pub mod pane;
   10pub mod pane_group;
   11pub mod path_list {
   12    pub use util::path_list::{PathList, SerializedPathList};
   13}
   14mod persistence;
   15pub mod searchable;
   16mod security_modal;
   17pub mod shared_screen;
   18use db::smol::future::yield_now;
   19pub use shared_screen::SharedScreen;
   20mod status_bar;
   21pub mod tasks;
   22mod theme_preview;
   23mod toast_layer;
   24mod toolbar;
   25pub mod welcome;
   26mod workspace_settings;
   27
   28pub use crate::notifications::NotificationFrame;
   29pub use dock::Panel;
   30pub use multi_workspace::{
   31    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   32    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
   33    SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
   34};
   35pub use path_list::{PathList, SerializedPathList};
   36pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   37
   38use anyhow::{Context as _, Result, anyhow};
   39use client::{
   40    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   41    proto::{self, ErrorCode, PanelId, PeerId},
   42};
   43use collections::{HashMap, HashSet, hash_map};
   44use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   45use fs::Fs;
   46use futures::{
   47    Future, FutureExt, StreamExt,
   48    channel::{
   49        mpsc::{self, UnboundedReceiver, UnboundedSender},
   50        oneshot,
   51    },
   52    future::{Shared, try_join_all},
   53};
   54use gpui::{
   55    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   56    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   57    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   58    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   59    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   60    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   61};
   62pub use history_manager::*;
   63pub use item::{
   64    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   65    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   66};
   67use itertools::Itertools;
   68use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   69pub use modal_layer::*;
   70use node_runtime::NodeRuntime;
   71use notifications::{
   72    DetachAndPromptErr, Notifications, dismiss_app_notification,
   73    simple_message_notification::MessageNotification,
   74};
   75pub use pane::*;
   76pub use pane_group::{
   77    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   78    SplitDirection,
   79};
   80use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   81pub use persistence::{
   82    WorkspaceDb, delete_unloaded_items,
   83    model::{
   84        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   85        SessionWorkspace,
   86    },
   87    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   88};
   89use postage::stream::Stream;
   90use project::{
   91    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   92    WorktreeSettings,
   93    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   94    project_settings::ProjectSettings,
   95    toolchain_store::ToolchainStoreEvent,
   96    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   97};
   98use remote::{
   99    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  100    remote_client::ConnectionIdentifier,
  101};
  102use schemars::JsonSchema;
  103use serde::Deserialize;
  104use session::AppSession;
  105use settings::{
  106    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  107};
  108
  109use sqlez::{
  110    bindable::{Bind, Column, StaticColumnCount},
  111    statement::Statement,
  112};
  113use status_bar::StatusBar;
  114pub use status_bar::StatusItemView;
  115use std::{
  116    any::TypeId,
  117    borrow::Cow,
  118    cell::RefCell,
  119    cmp,
  120    collections::VecDeque,
  121    env,
  122    hash::Hash,
  123    path::{Path, PathBuf},
  124    process::ExitStatus,
  125    rc::Rc,
  126    sync::{
  127        Arc, LazyLock,
  128        atomic::{AtomicBool, AtomicUsize},
  129    },
  130    time::Duration,
  131};
  132use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  133use theme::{ActiveTheme, SystemAppearance};
  134use theme_settings::ThemeSettings;
  135pub use toolbar::{
  136    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  137};
  138pub use ui;
  139use ui::{Window, prelude::*};
  140use util::{
  141    ResultExt, TryFutureExt,
  142    paths::{PathStyle, SanitizedPath},
  143    rel_path::RelPath,
  144    serde::default_true,
  145};
  146use uuid::Uuid;
  147pub use workspace_settings::{
  148    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  149    WorkspaceSettings,
  150};
  151use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  152
  153use crate::{item::ItemBufferKind, notifications::NotificationId};
  154use crate::{
  155    persistence::{
  156        SerializedAxis,
  157        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  158    },
  159    security_modal::SecurityModal,
  160};
  161
  162pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  163
  164static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  165    env::var("ZED_WINDOW_SIZE")
  166        .ok()
  167        .as_deref()
  168        .and_then(parse_pixel_size_env_var)
  169});
  170
  171static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  172    env::var("ZED_WINDOW_POSITION")
  173        .ok()
  174        .as_deref()
  175        .and_then(parse_pixel_position_env_var)
  176});
  177
  178pub trait TerminalProvider {
  179    fn spawn(
  180        &self,
  181        task: SpawnInTerminal,
  182        window: &mut Window,
  183        cx: &mut App,
  184    ) -> Task<Option<Result<ExitStatus>>>;
  185}
  186
  187pub trait DebuggerProvider {
  188    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  189    fn start_session(
  190        &self,
  191        definition: DebugScenario,
  192        task_context: SharedTaskContext,
  193        active_buffer: Option<Entity<Buffer>>,
  194        worktree_id: Option<WorktreeId>,
  195        window: &mut Window,
  196        cx: &mut App,
  197    );
  198
  199    fn spawn_task_or_modal(
  200        &self,
  201        workspace: &mut Workspace,
  202        action: &Spawn,
  203        window: &mut Window,
  204        cx: &mut Context<Workspace>,
  205    );
  206
  207    fn task_scheduled(&self, cx: &mut App);
  208    fn debug_scenario_scheduled(&self, cx: &mut App);
  209    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  210
  211    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  212}
  213
  214/// Opens a file or directory.
  215#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  216#[action(namespace = workspace)]
  217pub struct Open {
  218    /// When true, opens in a new window. When false, adds to the current
  219    /// window as a new workspace (multi-workspace).
  220    #[serde(default = "Open::default_create_new_window")]
  221    pub create_new_window: bool,
  222}
  223
  224impl Open {
  225    pub const DEFAULT: Self = Self {
  226        create_new_window: true,
  227    };
  228
  229    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  230    /// the serde default and `Open::DEFAULT` stay in sync.
  231    fn default_create_new_window() -> bool {
  232        Self::DEFAULT.create_new_window
  233    }
  234}
  235
  236impl Default for Open {
  237    fn default() -> Self {
  238        Self::DEFAULT
  239    }
  240}
  241
  242actions!(
  243    workspace,
  244    [
  245        /// Activates the next pane in the workspace.
  246        ActivateNextPane,
  247        /// Activates the previous pane in the workspace.
  248        ActivatePreviousPane,
  249        /// Activates the last pane in the workspace.
  250        ActivateLastPane,
  251        /// Switches to the next window.
  252        ActivateNextWindow,
  253        /// Switches to the previous window.
  254        ActivatePreviousWindow,
  255        /// Adds a folder to the current project.
  256        AddFolderToProject,
  257        /// Clears all notifications.
  258        ClearAllNotifications,
  259        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  260        ClearNavigationHistory,
  261        /// Closes the active dock.
  262        CloseActiveDock,
  263        /// Closes all docks.
  264        CloseAllDocks,
  265        /// Toggles all docks.
  266        ToggleAllDocks,
  267        /// Closes the current window.
  268        CloseWindow,
  269        /// Closes the current project.
  270        CloseProject,
  271        /// Opens the feedback dialog.
  272        Feedback,
  273        /// Follows the next collaborator in the session.
  274        FollowNextCollaborator,
  275        /// Moves the focused panel to the next position.
  276        MoveFocusedPanelToNextPosition,
  277        /// Creates a new file.
  278        NewFile,
  279        /// Creates a new file in a vertical split.
  280        NewFileSplitVertical,
  281        /// Creates a new file in a horizontal split.
  282        NewFileSplitHorizontal,
  283        /// Opens a new search.
  284        NewSearch,
  285        /// Opens a new window.
  286        NewWindow,
  287        /// Opens multiple files.
  288        OpenFiles,
  289        /// Opens the current location in terminal.
  290        OpenInTerminal,
  291        /// Opens the component preview.
  292        OpenComponentPreview,
  293        /// Reloads the active item.
  294        ReloadActiveItem,
  295        /// Resets the active dock to its default size.
  296        ResetActiveDockSize,
  297        /// Resets all open docks to their default sizes.
  298        ResetOpenDocksSize,
  299        /// Reloads the application
  300        Reload,
  301        /// Saves the current file with a new name.
  302        SaveAs,
  303        /// Saves without formatting.
  304        SaveWithoutFormat,
  305        /// Shuts down all debug adapters.
  306        ShutdownDebugAdapters,
  307        /// Suppresses the current notification.
  308        SuppressNotification,
  309        /// Toggles the bottom dock.
  310        ToggleBottomDock,
  311        /// Toggles centered layout mode.
  312        ToggleCenteredLayout,
  313        /// Toggles edit prediction feature globally for all files.
  314        ToggleEditPrediction,
  315        /// Toggles the left dock.
  316        ToggleLeftDock,
  317        /// Toggles the right dock.
  318        ToggleRightDock,
  319        /// Toggles zoom on the active pane.
  320        ToggleZoom,
  321        /// Toggles read-only mode for the active item (if supported by that item).
  322        ToggleReadOnlyFile,
  323        /// Zooms in on the active pane.
  324        ZoomIn,
  325        /// Zooms out of the active pane.
  326        ZoomOut,
  327        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  328        /// If the modal is shown already, closes it without trusting any worktree.
  329        ToggleWorktreeSecurity,
  330        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  331        /// Requires restart to take effect on already opened projects.
  332        ClearTrustedWorktrees,
  333        /// Stops following a collaborator.
  334        Unfollow,
  335        /// Restores the banner.
  336        RestoreBanner,
  337        /// Toggles expansion of the selected item.
  338        ToggleExpandItem,
  339    ]
  340);
  341
  342/// Activates a specific pane by its index.
  343#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  344#[action(namespace = workspace)]
  345pub struct ActivatePane(pub usize);
  346
  347/// Moves an item to a specific pane by index.
  348#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  349#[action(namespace = workspace)]
  350#[serde(deny_unknown_fields)]
  351pub struct MoveItemToPane {
  352    #[serde(default = "default_1")]
  353    pub destination: usize,
  354    #[serde(default = "default_true")]
  355    pub focus: bool,
  356    #[serde(default)]
  357    pub clone: bool,
  358}
  359
  360fn default_1() -> usize {
  361    1
  362}
  363
  364/// Moves an item to a pane in the specified direction.
  365#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  366#[action(namespace = workspace)]
  367#[serde(deny_unknown_fields)]
  368pub struct MoveItemToPaneInDirection {
  369    #[serde(default = "default_right")]
  370    pub direction: SplitDirection,
  371    #[serde(default = "default_true")]
  372    pub focus: bool,
  373    #[serde(default)]
  374    pub clone: bool,
  375}
  376
  377/// Creates a new file in a split of the desired direction.
  378#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  379#[action(namespace = workspace)]
  380#[serde(deny_unknown_fields)]
  381pub struct NewFileSplit(pub SplitDirection);
  382
  383fn default_right() -> SplitDirection {
  384    SplitDirection::Right
  385}
  386
  387/// Saves all open files in the workspace.
  388#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  389#[action(namespace = workspace)]
  390#[serde(deny_unknown_fields)]
  391pub struct SaveAll {
  392    #[serde(default)]
  393    pub save_intent: Option<SaveIntent>,
  394}
  395
  396/// Saves the current file with the specified options.
  397#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  398#[action(namespace = workspace)]
  399#[serde(deny_unknown_fields)]
  400pub struct Save {
  401    #[serde(default)]
  402    pub save_intent: Option<SaveIntent>,
  403}
  404
  405/// Moves Focus to the central panes in the workspace.
  406#[derive(Clone, Debug, PartialEq, Eq, Action)]
  407#[action(namespace = workspace)]
  408pub struct FocusCenterPane;
  409
  410///  Closes all items and panes in the workspace.
  411#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  412#[action(namespace = workspace)]
  413#[serde(deny_unknown_fields)]
  414pub struct CloseAllItemsAndPanes {
  415    #[serde(default)]
  416    pub save_intent: Option<SaveIntent>,
  417}
  418
  419/// Closes all inactive tabs and panes in the workspace.
  420#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  421#[action(namespace = workspace)]
  422#[serde(deny_unknown_fields)]
  423pub struct CloseInactiveTabsAndPanes {
  424    #[serde(default)]
  425    pub save_intent: Option<SaveIntent>,
  426}
  427
  428/// Closes the active item across all panes.
  429#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  430#[action(namespace = workspace)]
  431#[serde(deny_unknown_fields)]
  432pub struct CloseItemInAllPanes {
  433    #[serde(default)]
  434    pub save_intent: Option<SaveIntent>,
  435    #[serde(default)]
  436    pub close_pinned: bool,
  437}
  438
  439/// Sends a sequence of keystrokes to the active element.
  440#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  441#[action(namespace = workspace)]
  442pub struct SendKeystrokes(pub String);
  443
  444actions!(
  445    project_symbols,
  446    [
  447        /// Toggles the project symbols search.
  448        #[action(name = "Toggle")]
  449        ToggleProjectSymbols
  450    ]
  451);
  452
  453/// Toggles the file finder interface.
  454#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  455#[action(namespace = file_finder, name = "Toggle")]
  456#[serde(deny_unknown_fields)]
  457pub struct ToggleFileFinder {
  458    #[serde(default)]
  459    pub separate_history: bool,
  460}
  461
  462/// Opens a new terminal in the center.
  463#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  464#[action(namespace = workspace)]
  465#[serde(deny_unknown_fields)]
  466pub struct NewCenterTerminal {
  467    /// If true, creates a local terminal even in remote projects.
  468    #[serde(default)]
  469    pub local: bool,
  470}
  471
  472/// Opens a new terminal.
  473#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  474#[action(namespace = workspace)]
  475#[serde(deny_unknown_fields)]
  476pub struct NewTerminal {
  477    /// If true, creates a local terminal even in remote projects.
  478    #[serde(default)]
  479    pub local: bool,
  480}
  481
  482/// Increases size of a currently focused dock by a given amount of pixels.
  483#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  484#[action(namespace = workspace)]
  485#[serde(deny_unknown_fields)]
  486pub struct IncreaseActiveDockSize {
  487    /// For 0px parameter, uses UI font size value.
  488    #[serde(default)]
  489    pub px: u32,
  490}
  491
  492/// Decreases size of a currently focused dock by a given amount of pixels.
  493#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  494#[action(namespace = workspace)]
  495#[serde(deny_unknown_fields)]
  496pub struct DecreaseActiveDockSize {
  497    /// For 0px parameter, uses UI font size value.
  498    #[serde(default)]
  499    pub px: u32,
  500}
  501
  502/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  503#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  504#[action(namespace = workspace)]
  505#[serde(deny_unknown_fields)]
  506pub struct IncreaseOpenDocksSize {
  507    /// For 0px parameter, uses UI font size value.
  508    #[serde(default)]
  509    pub px: u32,
  510}
  511
  512/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  513#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  514#[action(namespace = workspace)]
  515#[serde(deny_unknown_fields)]
  516pub struct DecreaseOpenDocksSize {
  517    /// For 0px parameter, uses UI font size value.
  518    #[serde(default)]
  519    pub px: u32,
  520}
  521
  522actions!(
  523    workspace,
  524    [
  525        /// Activates the pane to the left.
  526        ActivatePaneLeft,
  527        /// Activates the pane to the right.
  528        ActivatePaneRight,
  529        /// Activates the pane above.
  530        ActivatePaneUp,
  531        /// Activates the pane below.
  532        ActivatePaneDown,
  533        /// Swaps the current pane with the one to the left.
  534        SwapPaneLeft,
  535        /// Swaps the current pane with the one to the right.
  536        SwapPaneRight,
  537        /// Swaps the current pane with the one above.
  538        SwapPaneUp,
  539        /// Swaps the current pane with the one below.
  540        SwapPaneDown,
  541        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  542        SwapPaneAdjacent,
  543        /// Move the current pane to be at the far left.
  544        MovePaneLeft,
  545        /// Move the current pane to be at the far right.
  546        MovePaneRight,
  547        /// Move the current pane to be at the very top.
  548        MovePaneUp,
  549        /// Move the current pane to be at the very bottom.
  550        MovePaneDown,
  551    ]
  552);
  553
  554#[derive(PartialEq, Eq, Debug)]
  555pub enum CloseIntent {
  556    /// Quit the program entirely.
  557    Quit,
  558    /// Close a window.
  559    CloseWindow,
  560    /// Replace the workspace in an existing window.
  561    ReplaceWindow,
  562}
  563
  564#[derive(Clone)]
  565pub struct Toast {
  566    id: NotificationId,
  567    msg: Cow<'static, str>,
  568    autohide: bool,
  569    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  570}
  571
  572impl Toast {
  573    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  574        Toast {
  575            id,
  576            msg: msg.into(),
  577            on_click: None,
  578            autohide: false,
  579        }
  580    }
  581
  582    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  583    where
  584        M: Into<Cow<'static, str>>,
  585        F: Fn(&mut Window, &mut App) + 'static,
  586    {
  587        self.on_click = Some((message.into(), Arc::new(on_click)));
  588        self
  589    }
  590
  591    pub fn autohide(mut self) -> Self {
  592        self.autohide = true;
  593        self
  594    }
  595}
  596
  597impl PartialEq for Toast {
  598    fn eq(&self, other: &Self) -> bool {
  599        self.id == other.id
  600            && self.msg == other.msg
  601            && self.on_click.is_some() == other.on_click.is_some()
  602    }
  603}
  604
  605/// Opens a new terminal with the specified working directory.
  606#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  607#[action(namespace = workspace)]
  608#[serde(deny_unknown_fields)]
  609pub struct OpenTerminal {
  610    pub working_directory: PathBuf,
  611    /// If true, creates a local terminal even in remote projects.
  612    #[serde(default)]
  613    pub local: bool,
  614}
  615
  616#[derive(
  617    Clone,
  618    Copy,
  619    Debug,
  620    Default,
  621    Hash,
  622    PartialEq,
  623    Eq,
  624    PartialOrd,
  625    Ord,
  626    serde::Serialize,
  627    serde::Deserialize,
  628)]
  629pub struct WorkspaceId(i64);
  630
  631impl WorkspaceId {
  632    pub fn from_i64(value: i64) -> Self {
  633        Self(value)
  634    }
  635}
  636
  637impl StaticColumnCount for WorkspaceId {}
  638impl Bind for WorkspaceId {
  639    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  640        self.0.bind(statement, start_index)
  641    }
  642}
  643impl Column for WorkspaceId {
  644    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  645        i64::column(statement, start_index)
  646            .map(|(i, next_index)| (Self(i), next_index))
  647            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  648    }
  649}
  650impl From<WorkspaceId> for i64 {
  651    fn from(val: WorkspaceId) -> Self {
  652        val.0
  653    }
  654}
  655
  656fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  657    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  658        workspace_window
  659            .update(cx, |multi_workspace, window, cx| {
  660                let workspace = multi_workspace.workspace().clone();
  661                workspace.update(cx, |workspace, cx| {
  662                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  663                });
  664            })
  665            .ok();
  666    } else {
  667        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  668        cx.spawn(async move |cx| {
  669            let OpenResult { window, .. } = task.await?;
  670            window.update(cx, |multi_workspace, window, cx| {
  671                window.activate_window();
  672                let workspace = multi_workspace.workspace().clone();
  673                workspace.update(cx, |workspace, cx| {
  674                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  675                });
  676            })?;
  677            anyhow::Ok(())
  678        })
  679        .detach_and_log_err(cx);
  680    }
  681}
  682
  683pub fn prompt_for_open_path_and_open(
  684    workspace: &mut Workspace,
  685    app_state: Arc<AppState>,
  686    options: PathPromptOptions,
  687    create_new_window: bool,
  688    window: &mut Window,
  689    cx: &mut Context<Workspace>,
  690) {
  691    let paths = workspace.prompt_for_open_path(
  692        options,
  693        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  694        window,
  695        cx,
  696    );
  697    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  698    cx.spawn_in(window, async move |this, cx| {
  699        let Some(paths) = paths.await.log_err().flatten() else {
  700            return;
  701        };
  702        if !create_new_window {
  703            if let Some(handle) = multi_workspace_handle {
  704                if let Some(task) = handle
  705                    .update(cx, |multi_workspace, window, cx| {
  706                        multi_workspace.open_project(paths, window, cx)
  707                    })
  708                    .log_err()
  709                {
  710                    task.await.log_err();
  711                }
  712                return;
  713            }
  714        }
  715        if let Some(task) = this
  716            .update_in(cx, |this, window, cx| {
  717                this.open_workspace_for_paths(false, paths, window, cx)
  718            })
  719            .log_err()
  720        {
  721            task.await.log_err();
  722        }
  723    })
  724    .detach();
  725}
  726
  727pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  728    component::init();
  729    theme_preview::init(cx);
  730    toast_layer::init(cx);
  731    history_manager::init(app_state.fs.clone(), cx);
  732
  733    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  734        .on_action(|_: &Reload, cx| reload(cx))
  735        .on_action(|_: &Open, cx: &mut App| {
  736            let app_state = AppState::global(cx);
  737            prompt_and_open_paths(
  738                app_state,
  739                PathPromptOptions {
  740                    files: true,
  741                    directories: true,
  742                    multiple: true,
  743                    prompt: None,
  744                },
  745                cx,
  746            );
  747        })
  748        .on_action(|_: &OpenFiles, cx: &mut App| {
  749            let directories = cx.can_select_mixed_files_and_dirs();
  750            let app_state = AppState::global(cx);
  751            prompt_and_open_paths(
  752                app_state,
  753                PathPromptOptions {
  754                    files: true,
  755                    directories,
  756                    multiple: true,
  757                    prompt: None,
  758                },
  759                cx,
  760            );
  761        });
  762}
  763
  764type BuildProjectItemFn =
  765    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  766
  767type BuildProjectItemForPathFn =
  768    fn(
  769        &Entity<Project>,
  770        &ProjectPath,
  771        &mut Window,
  772        &mut App,
  773    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  774
  775#[derive(Clone, Default)]
  776struct ProjectItemRegistry {
  777    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  778    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  779}
  780
  781impl ProjectItemRegistry {
  782    fn register<T: ProjectItem>(&mut self) {
  783        self.build_project_item_fns_by_type.insert(
  784            TypeId::of::<T::Item>(),
  785            |item, project, pane, window, cx| {
  786                let item = item.downcast().unwrap();
  787                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  788                    as Box<dyn ItemHandle>
  789            },
  790        );
  791        self.build_project_item_for_path_fns
  792            .push(|project, project_path, window, cx| {
  793                let project_path = project_path.clone();
  794                let is_file = project
  795                    .read(cx)
  796                    .entry_for_path(&project_path, cx)
  797                    .is_some_and(|entry| entry.is_file());
  798                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  799                let is_local = project.read(cx).is_local();
  800                let project_item =
  801                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  802                let project = project.clone();
  803                Some(window.spawn(cx, async move |cx| {
  804                    match project_item.await.with_context(|| {
  805                        format!(
  806                            "opening project path {:?}",
  807                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  808                        )
  809                    }) {
  810                        Ok(project_item) => {
  811                            let project_item = project_item;
  812                            let project_entry_id: Option<ProjectEntryId> =
  813                                project_item.read_with(cx, project::ProjectItem::entry_id);
  814                            let build_workspace_item = Box::new(
  815                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  816                                    Box::new(cx.new(|cx| {
  817                                        T::for_project_item(
  818                                            project,
  819                                            Some(pane),
  820                                            project_item,
  821                                            window,
  822                                            cx,
  823                                        )
  824                                    })) as Box<dyn ItemHandle>
  825                                },
  826                            ) as Box<_>;
  827                            Ok((project_entry_id, build_workspace_item))
  828                        }
  829                        Err(e) => {
  830                            log::warn!("Failed to open a project item: {e:#}");
  831                            if e.error_code() == ErrorCode::Internal {
  832                                if let Some(abs_path) =
  833                                    entry_abs_path.as_deref().filter(|_| is_file)
  834                                {
  835                                    if let Some(broken_project_item_view) =
  836                                        cx.update(|window, cx| {
  837                                            T::for_broken_project_item(
  838                                                abs_path, is_local, &e, window, cx,
  839                                            )
  840                                        })?
  841                                    {
  842                                        let build_workspace_item = Box::new(
  843                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  844                                                cx.new(|_| broken_project_item_view).boxed_clone()
  845                                            },
  846                                        )
  847                                        as Box<_>;
  848                                        return Ok((None, build_workspace_item));
  849                                    }
  850                                }
  851                            }
  852                            Err(e)
  853                        }
  854                    }
  855                }))
  856            });
  857    }
  858
  859    fn open_path(
  860        &self,
  861        project: &Entity<Project>,
  862        path: &ProjectPath,
  863        window: &mut Window,
  864        cx: &mut App,
  865    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  866        let Some(open_project_item) = self
  867            .build_project_item_for_path_fns
  868            .iter()
  869            .rev()
  870            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  871        else {
  872            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  873        };
  874        open_project_item
  875    }
  876
  877    fn build_item<T: project::ProjectItem>(
  878        &self,
  879        item: Entity<T>,
  880        project: Entity<Project>,
  881        pane: Option<&Pane>,
  882        window: &mut Window,
  883        cx: &mut App,
  884    ) -> Option<Box<dyn ItemHandle>> {
  885        let build = self
  886            .build_project_item_fns_by_type
  887            .get(&TypeId::of::<T>())?;
  888        Some(build(item.into_any(), project, pane, window, cx))
  889    }
  890}
  891
  892type WorkspaceItemBuilder =
  893    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  894
  895impl Global for ProjectItemRegistry {}
  896
  897/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  898/// items will get a chance to open the file, starting from the project item that
  899/// was added last.
  900pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  901    cx.default_global::<ProjectItemRegistry>().register::<I>();
  902}
  903
  904#[derive(Default)]
  905pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  906
  907struct FollowableViewDescriptor {
  908    from_state_proto: fn(
  909        Entity<Workspace>,
  910        ViewId,
  911        &mut Option<proto::view::Variant>,
  912        &mut Window,
  913        &mut App,
  914    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  915    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  916}
  917
  918impl Global for FollowableViewRegistry {}
  919
  920impl FollowableViewRegistry {
  921    pub fn register<I: FollowableItem>(cx: &mut App) {
  922        cx.default_global::<Self>().0.insert(
  923            TypeId::of::<I>(),
  924            FollowableViewDescriptor {
  925                from_state_proto: |workspace, id, state, window, cx| {
  926                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  927                        cx.foreground_executor()
  928                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  929                    })
  930                },
  931                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  932            },
  933        );
  934    }
  935
  936    pub fn from_state_proto(
  937        workspace: Entity<Workspace>,
  938        view_id: ViewId,
  939        mut state: Option<proto::view::Variant>,
  940        window: &mut Window,
  941        cx: &mut App,
  942    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  943        cx.update_default_global(|this: &mut Self, cx| {
  944            this.0.values().find_map(|descriptor| {
  945                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  946            })
  947        })
  948    }
  949
  950    pub fn to_followable_view(
  951        view: impl Into<AnyView>,
  952        cx: &App,
  953    ) -> Option<Box<dyn FollowableItemHandle>> {
  954        let this = cx.try_global::<Self>()?;
  955        let view = view.into();
  956        let descriptor = this.0.get(&view.entity_type())?;
  957        Some((descriptor.to_followable_view)(&view))
  958    }
  959}
  960
  961#[derive(Copy, Clone)]
  962struct SerializableItemDescriptor {
  963    deserialize: fn(
  964        Entity<Project>,
  965        WeakEntity<Workspace>,
  966        WorkspaceId,
  967        ItemId,
  968        &mut Window,
  969        &mut Context<Pane>,
  970    ) -> Task<Result<Box<dyn ItemHandle>>>,
  971    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  972    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  973}
  974
  975#[derive(Default)]
  976struct SerializableItemRegistry {
  977    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  978    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  979}
  980
  981impl Global for SerializableItemRegistry {}
  982
  983impl SerializableItemRegistry {
  984    fn deserialize(
  985        item_kind: &str,
  986        project: Entity<Project>,
  987        workspace: WeakEntity<Workspace>,
  988        workspace_id: WorkspaceId,
  989        item_item: ItemId,
  990        window: &mut Window,
  991        cx: &mut Context<Pane>,
  992    ) -> Task<Result<Box<dyn ItemHandle>>> {
  993        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  994            return Task::ready(Err(anyhow!(
  995                "cannot deserialize {}, descriptor not found",
  996                item_kind
  997            )));
  998        };
  999
 1000        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1001    }
 1002
 1003    fn cleanup(
 1004        item_kind: &str,
 1005        workspace_id: WorkspaceId,
 1006        loaded_items: Vec<ItemId>,
 1007        window: &mut Window,
 1008        cx: &mut App,
 1009    ) -> Task<Result<()>> {
 1010        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1011            return Task::ready(Err(anyhow!(
 1012                "cannot cleanup {}, descriptor not found",
 1013                item_kind
 1014            )));
 1015        };
 1016
 1017        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1018    }
 1019
 1020    fn view_to_serializable_item_handle(
 1021        view: AnyView,
 1022        cx: &App,
 1023    ) -> Option<Box<dyn SerializableItemHandle>> {
 1024        let this = cx.try_global::<Self>()?;
 1025        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1026        Some((descriptor.view_to_serializable_item)(view))
 1027    }
 1028
 1029    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1030        let this = cx.try_global::<Self>()?;
 1031        this.descriptors_by_kind.get(item_kind).copied()
 1032    }
 1033}
 1034
 1035pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1036    let serialized_item_kind = I::serialized_item_kind();
 1037
 1038    let registry = cx.default_global::<SerializableItemRegistry>();
 1039    let descriptor = SerializableItemDescriptor {
 1040        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1041            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1042            cx.foreground_executor()
 1043                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1044        },
 1045        cleanup: |workspace_id, loaded_items, window, cx| {
 1046            I::cleanup(workspace_id, loaded_items, window, cx)
 1047        },
 1048        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1049    };
 1050    registry
 1051        .descriptors_by_kind
 1052        .insert(Arc::from(serialized_item_kind), descriptor);
 1053    registry
 1054        .descriptors_by_type
 1055        .insert(TypeId::of::<I>(), descriptor);
 1056}
 1057
 1058pub struct AppState {
 1059    pub languages: Arc<LanguageRegistry>,
 1060    pub client: Arc<Client>,
 1061    pub user_store: Entity<UserStore>,
 1062    pub workspace_store: Entity<WorkspaceStore>,
 1063    pub fs: Arc<dyn fs::Fs>,
 1064    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1065    pub node_runtime: NodeRuntime,
 1066    pub session: Entity<AppSession>,
 1067}
 1068
 1069struct GlobalAppState(Arc<AppState>);
 1070
 1071impl Global for GlobalAppState {}
 1072
 1073pub struct WorkspaceStore {
 1074    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1075    client: Arc<Client>,
 1076    _subscriptions: Vec<client::Subscription>,
 1077}
 1078
 1079#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1080pub enum CollaboratorId {
 1081    PeerId(PeerId),
 1082    Agent,
 1083}
 1084
 1085impl From<PeerId> for CollaboratorId {
 1086    fn from(peer_id: PeerId) -> Self {
 1087        CollaboratorId::PeerId(peer_id)
 1088    }
 1089}
 1090
 1091impl From<&PeerId> for CollaboratorId {
 1092    fn from(peer_id: &PeerId) -> Self {
 1093        CollaboratorId::PeerId(*peer_id)
 1094    }
 1095}
 1096
 1097#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1098struct Follower {
 1099    project_id: Option<u64>,
 1100    peer_id: PeerId,
 1101}
 1102
 1103impl AppState {
 1104    #[track_caller]
 1105    pub fn global(cx: &App) -> Arc<Self> {
 1106        cx.global::<GlobalAppState>().0.clone()
 1107    }
 1108    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1109        cx.try_global::<GlobalAppState>()
 1110            .map(|state| state.0.clone())
 1111    }
 1112    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1113        cx.set_global(GlobalAppState(state));
 1114    }
 1115
 1116    #[cfg(any(test, feature = "test-support"))]
 1117    pub fn test(cx: &mut App) -> Arc<Self> {
 1118        use fs::Fs;
 1119        use node_runtime::NodeRuntime;
 1120        use session::Session;
 1121        use settings::SettingsStore;
 1122
 1123        if !cx.has_global::<SettingsStore>() {
 1124            let settings_store = SettingsStore::test(cx);
 1125            cx.set_global(settings_store);
 1126        }
 1127
 1128        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1129        <dyn Fs>::set_global(fs.clone(), cx);
 1130        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1131        let clock = Arc::new(clock::FakeSystemClock::new());
 1132        let http_client = http_client::FakeHttpClient::with_404_response();
 1133        let client = Client::new(clock, http_client, cx);
 1134        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1135        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1136        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1137
 1138        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1139        client::init(&client, cx);
 1140
 1141        Arc::new(Self {
 1142            client,
 1143            fs,
 1144            languages,
 1145            user_store,
 1146            workspace_store,
 1147            node_runtime: NodeRuntime::unavailable(),
 1148            build_window_options: |_, _| Default::default(),
 1149            session,
 1150        })
 1151    }
 1152}
 1153
 1154struct DelayedDebouncedEditAction {
 1155    task: Option<Task<()>>,
 1156    cancel_channel: Option<oneshot::Sender<()>>,
 1157}
 1158
 1159impl DelayedDebouncedEditAction {
 1160    fn new() -> DelayedDebouncedEditAction {
 1161        DelayedDebouncedEditAction {
 1162            task: None,
 1163            cancel_channel: None,
 1164        }
 1165    }
 1166
 1167    fn fire_new<F>(
 1168        &mut self,
 1169        delay: Duration,
 1170        window: &mut Window,
 1171        cx: &mut Context<Workspace>,
 1172        func: F,
 1173    ) where
 1174        F: 'static
 1175            + Send
 1176            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1177    {
 1178        if let Some(channel) = self.cancel_channel.take() {
 1179            _ = channel.send(());
 1180        }
 1181
 1182        let (sender, mut receiver) = oneshot::channel::<()>();
 1183        self.cancel_channel = Some(sender);
 1184
 1185        let previous_task = self.task.take();
 1186        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1187            let mut timer = cx.background_executor().timer(delay).fuse();
 1188            if let Some(previous_task) = previous_task {
 1189                previous_task.await;
 1190            }
 1191
 1192            futures::select_biased! {
 1193                _ = receiver => return,
 1194                    _ = timer => {}
 1195            }
 1196
 1197            if let Some(result) = workspace
 1198                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1199                .log_err()
 1200            {
 1201                result.await.log_err();
 1202            }
 1203        }));
 1204    }
 1205}
 1206
 1207pub enum Event {
 1208    PaneAdded(Entity<Pane>),
 1209    PaneRemoved,
 1210    ItemAdded {
 1211        item: Box<dyn ItemHandle>,
 1212    },
 1213    ActiveItemChanged,
 1214    ItemRemoved {
 1215        item_id: EntityId,
 1216    },
 1217    UserSavedItem {
 1218        pane: WeakEntity<Pane>,
 1219        item: Box<dyn WeakItemHandle>,
 1220        save_intent: SaveIntent,
 1221    },
 1222    ContactRequestedJoin(u64),
 1223    WorkspaceCreated(WeakEntity<Workspace>),
 1224    OpenBundledFile {
 1225        text: Cow<'static, str>,
 1226        title: &'static str,
 1227        language: &'static str,
 1228    },
 1229    ZoomChanged,
 1230    ModalOpened,
 1231    Activate,
 1232    PanelAdded(AnyView),
 1233}
 1234
 1235#[derive(Debug, Clone)]
 1236pub enum OpenVisible {
 1237    All,
 1238    None,
 1239    OnlyFiles,
 1240    OnlyDirectories,
 1241}
 1242
 1243enum WorkspaceLocation {
 1244    // Valid local paths or SSH project to serialize
 1245    Location(SerializedWorkspaceLocation, PathList),
 1246    // No valid location found hence clear session id
 1247    DetachFromSession,
 1248    // No valid location found to serialize
 1249    None,
 1250}
 1251
 1252type PromptForNewPath = Box<
 1253    dyn Fn(
 1254        &mut Workspace,
 1255        DirectoryLister,
 1256        Option<String>,
 1257        &mut Window,
 1258        &mut Context<Workspace>,
 1259    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1260>;
 1261
 1262type PromptForOpenPath = Box<
 1263    dyn Fn(
 1264        &mut Workspace,
 1265        DirectoryLister,
 1266        &mut Window,
 1267        &mut Context<Workspace>,
 1268    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1269>;
 1270
 1271#[derive(Default)]
 1272struct DispatchingKeystrokes {
 1273    dispatched: HashSet<Vec<Keystroke>>,
 1274    queue: VecDeque<Keystroke>,
 1275    task: Option<Shared<Task<()>>>,
 1276}
 1277
 1278/// Collects everything project-related for a certain window opened.
 1279/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1280///
 1281/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1282/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1283/// that can be used to register a global action to be triggered from any place in the window.
 1284pub struct Workspace {
 1285    weak_self: WeakEntity<Self>,
 1286    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1287    zoomed: Option<AnyWeakView>,
 1288    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1289    zoomed_position: Option<DockPosition>,
 1290    center: PaneGroup,
 1291    left_dock: Entity<Dock>,
 1292    bottom_dock: Entity<Dock>,
 1293    right_dock: Entity<Dock>,
 1294    panes: Vec<Entity<Pane>>,
 1295    active_worktree_override: Option<WorktreeId>,
 1296    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1297    active_pane: Entity<Pane>,
 1298    last_active_center_pane: Option<WeakEntity<Pane>>,
 1299    last_active_view_id: Option<proto::ViewId>,
 1300    status_bar: Entity<StatusBar>,
 1301    pub(crate) modal_layer: Entity<ModalLayer>,
 1302    toast_layer: Entity<ToastLayer>,
 1303    titlebar_item: Option<AnyView>,
 1304    notifications: Notifications,
 1305    suppressed_notifications: HashSet<NotificationId>,
 1306    project: Entity<Project>,
 1307    follower_states: HashMap<CollaboratorId, FollowerState>,
 1308    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1309    window_edited: bool,
 1310    last_window_title: Option<String>,
 1311    dirty_items: HashMap<EntityId, Subscription>,
 1312    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1313    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1314    database_id: Option<WorkspaceId>,
 1315    app_state: Arc<AppState>,
 1316    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1317    _subscriptions: Vec<Subscription>,
 1318    _apply_leader_updates: Task<Result<()>>,
 1319    _observe_current_user: Task<Result<()>>,
 1320    _schedule_serialize_workspace: Option<Task<()>>,
 1321    _serialize_workspace_task: Option<Task<()>>,
 1322    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1323    pane_history_timestamp: Arc<AtomicUsize>,
 1324    bounds: Bounds<Pixels>,
 1325    pub centered_layout: bool,
 1326    bounds_save_task_queued: Option<Task<()>>,
 1327    on_prompt_for_new_path: Option<PromptForNewPath>,
 1328    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1329    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1330    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1331    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1332    _items_serializer: Task<Result<()>>,
 1333    session_id: Option<String>,
 1334    scheduled_tasks: Vec<Task<()>>,
 1335    last_open_dock_positions: Vec<DockPosition>,
 1336    removing: bool,
 1337    _panels_task: Option<Task<Result<()>>>,
 1338    sidebar_focus_handle: Option<FocusHandle>,
 1339    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1340}
 1341
 1342impl EventEmitter<Event> for Workspace {}
 1343
 1344#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1345pub struct ViewId {
 1346    pub creator: CollaboratorId,
 1347    pub id: u64,
 1348}
 1349
 1350pub struct FollowerState {
 1351    center_pane: Entity<Pane>,
 1352    dock_pane: Option<Entity<Pane>>,
 1353    active_view_id: Option<ViewId>,
 1354    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1355}
 1356
 1357struct FollowerView {
 1358    view: Box<dyn FollowableItemHandle>,
 1359    location: Option<proto::PanelId>,
 1360}
 1361
 1362impl Workspace {
 1363    pub fn new(
 1364        workspace_id: Option<WorkspaceId>,
 1365        project: Entity<Project>,
 1366        app_state: Arc<AppState>,
 1367        window: &mut Window,
 1368        cx: &mut Context<Self>,
 1369    ) -> Self {
 1370        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1371            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1372                if let TrustedWorktreesEvent::Trusted(..) = e {
 1373                    // Do not persist auto trusted worktrees
 1374                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1375                        worktrees_store.update(cx, |worktrees_store, cx| {
 1376                            worktrees_store.schedule_serialization(
 1377                                cx,
 1378                                |new_trusted_worktrees, cx| {
 1379                                    let timeout =
 1380                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1381                                    let db = WorkspaceDb::global(cx);
 1382                                    cx.background_spawn(async move {
 1383                                        timeout.await;
 1384                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1385                                            .await
 1386                                            .log_err();
 1387                                    })
 1388                                },
 1389                            )
 1390                        });
 1391                    }
 1392                }
 1393            })
 1394            .detach();
 1395
 1396            cx.observe_global::<SettingsStore>(|_, cx| {
 1397                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1398                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1399                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1400                            trusted_worktrees.auto_trust_all(cx);
 1401                        })
 1402                    }
 1403                }
 1404            })
 1405            .detach();
 1406        }
 1407
 1408        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1409            match event {
 1410                project::Event::RemoteIdChanged(_) => {
 1411                    this.update_window_title(window, cx);
 1412                }
 1413
 1414                project::Event::CollaboratorLeft(peer_id) => {
 1415                    this.collaborator_left(*peer_id, window, cx);
 1416                }
 1417
 1418                &project::Event::WorktreeRemoved(_) => {
 1419                    this.update_window_title(window, cx);
 1420                    this.serialize_workspace(window, cx);
 1421                    this.update_history(cx);
 1422                }
 1423
 1424                &project::Event::WorktreeAdded(id) => {
 1425                    this.update_window_title(window, cx);
 1426                    if this
 1427                        .project()
 1428                        .read(cx)
 1429                        .worktree_for_id(id, cx)
 1430                        .is_some_and(|wt| wt.read(cx).is_visible())
 1431                    {
 1432                        this.serialize_workspace(window, cx);
 1433                        this.update_history(cx);
 1434                    }
 1435                }
 1436                project::Event::WorktreeUpdatedEntries(..) => {
 1437                    this.update_window_title(window, cx);
 1438                    this.serialize_workspace(window, cx);
 1439                }
 1440
 1441                project::Event::DisconnectedFromHost => {
 1442                    this.update_window_edited(window, cx);
 1443                    let leaders_to_unfollow =
 1444                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1445                    for leader_id in leaders_to_unfollow {
 1446                        this.unfollow(leader_id, window, cx);
 1447                    }
 1448                }
 1449
 1450                project::Event::DisconnectedFromRemote {
 1451                    server_not_running: _,
 1452                } => {
 1453                    this.update_window_edited(window, cx);
 1454                }
 1455
 1456                project::Event::Closed => {
 1457                    window.remove_window();
 1458                }
 1459
 1460                project::Event::DeletedEntry(_, entry_id) => {
 1461                    for pane in this.panes.iter() {
 1462                        pane.update(cx, |pane, cx| {
 1463                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1464                        });
 1465                    }
 1466                }
 1467
 1468                project::Event::Toast {
 1469                    notification_id,
 1470                    message,
 1471                    link,
 1472                } => this.show_notification(
 1473                    NotificationId::named(notification_id.clone()),
 1474                    cx,
 1475                    |cx| {
 1476                        let mut notification = MessageNotification::new(message.clone(), cx);
 1477                        if let Some(link) = link {
 1478                            notification = notification
 1479                                .more_info_message(link.label)
 1480                                .more_info_url(link.url);
 1481                        }
 1482
 1483                        cx.new(|_| notification)
 1484                    },
 1485                ),
 1486
 1487                project::Event::HideToast { notification_id } => {
 1488                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1489                }
 1490
 1491                project::Event::LanguageServerPrompt(request) => {
 1492                    struct LanguageServerPrompt;
 1493
 1494                    this.show_notification(
 1495                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1496                        cx,
 1497                        |cx| {
 1498                            cx.new(|cx| {
 1499                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1500                            })
 1501                        },
 1502                    );
 1503                }
 1504
 1505                project::Event::AgentLocationChanged => {
 1506                    this.handle_agent_location_changed(window, cx)
 1507                }
 1508
 1509                _ => {}
 1510            }
 1511            cx.notify()
 1512        })
 1513        .detach();
 1514
 1515        cx.subscribe_in(
 1516            &project.read(cx).breakpoint_store(),
 1517            window,
 1518            |workspace, _, event, window, cx| match event {
 1519                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1520                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1521                    workspace.serialize_workspace(window, cx);
 1522                }
 1523                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1524            },
 1525        )
 1526        .detach();
 1527        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1528            cx.subscribe_in(
 1529                &toolchain_store,
 1530                window,
 1531                |workspace, _, event, window, cx| match event {
 1532                    ToolchainStoreEvent::CustomToolchainsModified => {
 1533                        workspace.serialize_workspace(window, cx);
 1534                    }
 1535                    _ => {}
 1536                },
 1537            )
 1538            .detach();
 1539        }
 1540
 1541        cx.on_focus_lost(window, |this, window, cx| {
 1542            let focus_handle = this.focus_handle(cx);
 1543            window.focus(&focus_handle, cx);
 1544        })
 1545        .detach();
 1546
 1547        let weak_handle = cx.entity().downgrade();
 1548        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1549
 1550        let center_pane = cx.new(|cx| {
 1551            let mut center_pane = Pane::new(
 1552                weak_handle.clone(),
 1553                project.clone(),
 1554                pane_history_timestamp.clone(),
 1555                None,
 1556                NewFile.boxed_clone(),
 1557                true,
 1558                window,
 1559                cx,
 1560            );
 1561            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1562            center_pane.set_should_display_welcome_page(true);
 1563            center_pane
 1564        });
 1565        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1566            .detach();
 1567
 1568        window.focus(&center_pane.focus_handle(cx), cx);
 1569
 1570        cx.emit(Event::PaneAdded(center_pane.clone()));
 1571
 1572        let any_window_handle = window.window_handle();
 1573        app_state.workspace_store.update(cx, |store, _| {
 1574            store
 1575                .workspaces
 1576                .insert((any_window_handle, weak_handle.clone()));
 1577        });
 1578
 1579        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1580        let mut connection_status = app_state.client.status();
 1581        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1582            current_user.next().await;
 1583            connection_status.next().await;
 1584            let mut stream =
 1585                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1586
 1587            while stream.recv().await.is_some() {
 1588                this.update(cx, |_, cx| cx.notify())?;
 1589            }
 1590            anyhow::Ok(())
 1591        });
 1592
 1593        // All leader updates are enqueued and then processed in a single task, so
 1594        // that each asynchronous operation can be run in order.
 1595        let (leader_updates_tx, mut leader_updates_rx) =
 1596            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1597        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1598            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1599                Self::process_leader_update(&this, leader_id, update, cx)
 1600                    .await
 1601                    .log_err();
 1602            }
 1603
 1604            Ok(())
 1605        });
 1606
 1607        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1608        let modal_layer = cx.new(|_| ModalLayer::new());
 1609        let toast_layer = cx.new(|_| ToastLayer::new());
 1610        cx.subscribe(
 1611            &modal_layer,
 1612            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1613                cx.emit(Event::ModalOpened);
 1614            },
 1615        )
 1616        .detach();
 1617
 1618        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1619        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1620        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1621        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1622        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1623        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1624        let multi_workspace = window
 1625            .root::<MultiWorkspace>()
 1626            .flatten()
 1627            .map(|mw| mw.downgrade());
 1628        let status_bar = cx.new(|cx| {
 1629            let mut status_bar =
 1630                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1631            status_bar.add_left_item(left_dock_buttons, window, cx);
 1632            status_bar.add_right_item(right_dock_buttons, window, cx);
 1633            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1634            status_bar
 1635        });
 1636
 1637        let session_id = app_state.session.read(cx).id().to_owned();
 1638
 1639        let mut active_call = None;
 1640        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1641            let subscriptions =
 1642                vec![
 1643                    call.0
 1644                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1645                ];
 1646            active_call = Some((call, subscriptions));
 1647        }
 1648
 1649        let (serializable_items_tx, serializable_items_rx) =
 1650            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1651        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1652            Self::serialize_items(&this, serializable_items_rx, cx).await
 1653        });
 1654
 1655        let subscriptions = vec![
 1656            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1657            cx.observe_window_bounds(window, move |this, window, cx| {
 1658                if this.bounds_save_task_queued.is_some() {
 1659                    return;
 1660                }
 1661                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1662                    cx.background_executor()
 1663                        .timer(Duration::from_millis(100))
 1664                        .await;
 1665                    this.update_in(cx, |this, window, cx| {
 1666                        this.save_window_bounds(window, cx).detach();
 1667                        this.bounds_save_task_queued.take();
 1668                    })
 1669                    .ok();
 1670                }));
 1671                cx.notify();
 1672            }),
 1673            cx.observe_window_appearance(window, |_, window, cx| {
 1674                let window_appearance = window.appearance();
 1675
 1676                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1677
 1678                theme_settings::reload_theme(cx);
 1679                theme_settings::reload_icon_theme(cx);
 1680            }),
 1681            cx.on_release({
 1682                let weak_handle = weak_handle.clone();
 1683                move |this, cx| {
 1684                    this.app_state.workspace_store.update(cx, move |store, _| {
 1685                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1686                    })
 1687                }
 1688            }),
 1689        ];
 1690
 1691        cx.defer_in(window, move |this, window, cx| {
 1692            this.update_window_title(window, cx);
 1693            this.show_initial_notifications(cx);
 1694        });
 1695
 1696        let mut center = PaneGroup::new(center_pane.clone());
 1697        center.set_is_center(true);
 1698        center.mark_positions(cx);
 1699
 1700        Workspace {
 1701            weak_self: weak_handle.clone(),
 1702            zoomed: None,
 1703            zoomed_position: None,
 1704            previous_dock_drag_coordinates: None,
 1705            center,
 1706            panes: vec![center_pane.clone()],
 1707            panes_by_item: Default::default(),
 1708            active_pane: center_pane.clone(),
 1709            last_active_center_pane: Some(center_pane.downgrade()),
 1710            last_active_view_id: None,
 1711            status_bar,
 1712            modal_layer,
 1713            toast_layer,
 1714            titlebar_item: None,
 1715            active_worktree_override: None,
 1716            notifications: Notifications::default(),
 1717            suppressed_notifications: HashSet::default(),
 1718            left_dock,
 1719            bottom_dock,
 1720            right_dock,
 1721            _panels_task: None,
 1722            project: project.clone(),
 1723            follower_states: Default::default(),
 1724            last_leaders_by_pane: Default::default(),
 1725            dispatching_keystrokes: Default::default(),
 1726            window_edited: false,
 1727            last_window_title: None,
 1728            dirty_items: Default::default(),
 1729            active_call,
 1730            database_id: workspace_id,
 1731            app_state,
 1732            _observe_current_user,
 1733            _apply_leader_updates,
 1734            _schedule_serialize_workspace: None,
 1735            _serialize_workspace_task: None,
 1736            _schedule_serialize_ssh_paths: None,
 1737            leader_updates_tx,
 1738            _subscriptions: subscriptions,
 1739            pane_history_timestamp,
 1740            workspace_actions: Default::default(),
 1741            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1742            bounds: Default::default(),
 1743            centered_layout: false,
 1744            bounds_save_task_queued: None,
 1745            on_prompt_for_new_path: None,
 1746            on_prompt_for_open_path: None,
 1747            terminal_provider: None,
 1748            debugger_provider: None,
 1749            serializable_items_tx,
 1750            _items_serializer,
 1751            session_id: Some(session_id),
 1752
 1753            scheduled_tasks: Vec::new(),
 1754            last_open_dock_positions: Vec::new(),
 1755            removing: false,
 1756            sidebar_focus_handle: None,
 1757            multi_workspace,
 1758        }
 1759    }
 1760
 1761    pub fn new_local(
 1762        abs_paths: Vec<PathBuf>,
 1763        app_state: Arc<AppState>,
 1764        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1765        env: Option<HashMap<String, String>>,
 1766        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1767        activate: bool,
 1768        cx: &mut App,
 1769    ) -> Task<anyhow::Result<OpenResult>> {
 1770        let project_handle = Project::local(
 1771            app_state.client.clone(),
 1772            app_state.node_runtime.clone(),
 1773            app_state.user_store.clone(),
 1774            app_state.languages.clone(),
 1775            app_state.fs.clone(),
 1776            env,
 1777            Default::default(),
 1778            cx,
 1779        );
 1780
 1781        let db = WorkspaceDb::global(cx);
 1782        let kvp = db::kvp::KeyValueStore::global(cx);
 1783        cx.spawn(async move |cx| {
 1784            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1785            for path in abs_paths.into_iter() {
 1786                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1787                    paths_to_open.push(canonical)
 1788                } else {
 1789                    paths_to_open.push(path)
 1790                }
 1791            }
 1792
 1793            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1794
 1795            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1796                paths_to_open = paths.ordered_paths().cloned().collect();
 1797                if !paths.is_lexicographically_ordered() {
 1798                    project_handle.update(cx, |project, cx| {
 1799                        project.set_worktrees_reordered(true, cx);
 1800                    });
 1801                }
 1802            }
 1803
 1804            // Get project paths for all of the abs_paths
 1805            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1806                Vec::with_capacity(paths_to_open.len());
 1807
 1808            for path in paths_to_open.into_iter() {
 1809                if let Some((_, project_entry)) = cx
 1810                    .update(|cx| {
 1811                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1812                    })
 1813                    .await
 1814                    .log_err()
 1815                {
 1816                    project_paths.push((path, Some(project_entry)));
 1817                } else {
 1818                    project_paths.push((path, None));
 1819                }
 1820            }
 1821
 1822            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1823                serialized_workspace.id
 1824            } else {
 1825                db.next_id().await.unwrap_or_else(|_| Default::default())
 1826            };
 1827
 1828            let toolchains = db.toolchains(workspace_id).await?;
 1829
 1830            for (toolchain, worktree_path, path) in toolchains {
 1831                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1832                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1833                    this.find_worktree(&worktree_path, cx)
 1834                        .and_then(|(worktree, rel_path)| {
 1835                            if rel_path.is_empty() {
 1836                                Some(worktree.read(cx).id())
 1837                            } else {
 1838                                None
 1839                            }
 1840                        })
 1841                }) else {
 1842                    // We did not find a worktree with a given path, but that's whatever.
 1843                    continue;
 1844                };
 1845                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1846                    continue;
 1847                }
 1848
 1849                project_handle
 1850                    .update(cx, |this, cx| {
 1851                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1852                    })
 1853                    .await;
 1854            }
 1855            if let Some(workspace) = serialized_workspace.as_ref() {
 1856                project_handle.update(cx, |this, cx| {
 1857                    for (scope, toolchains) in &workspace.user_toolchains {
 1858                        for toolchain in toolchains {
 1859                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1860                        }
 1861                    }
 1862                });
 1863            }
 1864
 1865            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1866                if let Some(window) = requesting_window {
 1867                    let centered_layout = serialized_workspace
 1868                        .as_ref()
 1869                        .map(|w| w.centered_layout)
 1870                        .unwrap_or(false);
 1871
 1872                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1873                        let workspace = cx.new(|cx| {
 1874                            let mut workspace = Workspace::new(
 1875                                Some(workspace_id),
 1876                                project_handle.clone(),
 1877                                app_state.clone(),
 1878                                window,
 1879                                cx,
 1880                            );
 1881
 1882                            workspace.centered_layout = centered_layout;
 1883
 1884                            // Call init callback to add items before window renders
 1885                            if let Some(init) = init {
 1886                                init(&mut workspace, window, cx);
 1887                            }
 1888
 1889                            workspace
 1890                        });
 1891                        if activate {
 1892                            multi_workspace.activate(workspace.clone(), cx);
 1893                        } else {
 1894                            multi_workspace.add_workspace(workspace.clone(), cx);
 1895                        }
 1896                        workspace
 1897                    })?;
 1898                    (window, workspace)
 1899                } else {
 1900                    let window_bounds_override = window_bounds_env_override();
 1901
 1902                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1903                        (Some(WindowBounds::Windowed(bounds)), None)
 1904                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1905                        && let Some(display) = workspace.display
 1906                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1907                    {
 1908                        // Reopening an existing workspace - restore its saved bounds
 1909                        (Some(bounds.0), Some(display))
 1910                    } else if let Some((display, bounds)) =
 1911                        persistence::read_default_window_bounds(&kvp)
 1912                    {
 1913                        // New or empty workspace - use the last known window bounds
 1914                        (Some(bounds), Some(display))
 1915                    } else {
 1916                        // New window - let GPUI's default_bounds() handle cascading
 1917                        (None, None)
 1918                    };
 1919
 1920                    // Use the serialized workspace to construct the new window
 1921                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1922                    options.window_bounds = window_bounds;
 1923                    let centered_layout = serialized_workspace
 1924                        .as_ref()
 1925                        .map(|w| w.centered_layout)
 1926                        .unwrap_or(false);
 1927                    let window = cx.open_window(options, {
 1928                        let app_state = app_state.clone();
 1929                        let project_handle = project_handle.clone();
 1930                        move |window, cx| {
 1931                            let workspace = cx.new(|cx| {
 1932                                let mut workspace = Workspace::new(
 1933                                    Some(workspace_id),
 1934                                    project_handle,
 1935                                    app_state,
 1936                                    window,
 1937                                    cx,
 1938                                );
 1939                                workspace.centered_layout = centered_layout;
 1940
 1941                                // Call init callback to add items before window renders
 1942                                if let Some(init) = init {
 1943                                    init(&mut workspace, window, cx);
 1944                                }
 1945
 1946                                workspace
 1947                            });
 1948                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1949                        }
 1950                    })?;
 1951                    let workspace =
 1952                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1953                            multi_workspace.workspace().clone()
 1954                        })?;
 1955                    (window, workspace)
 1956                };
 1957
 1958            notify_if_database_failed(window, cx);
 1959            // Check if this is an empty workspace (no paths to open)
 1960            // An empty workspace is one where project_paths is empty
 1961            let is_empty_workspace = project_paths.is_empty();
 1962            // Check if serialized workspace has paths before it's moved
 1963            let serialized_workspace_has_paths = serialized_workspace
 1964                .as_ref()
 1965                .map(|ws| !ws.paths.is_empty())
 1966                .unwrap_or(false);
 1967
 1968            let opened_items = window
 1969                .update(cx, |_, window, cx| {
 1970                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1971                        open_items(serialized_workspace, project_paths, window, cx)
 1972                    })
 1973                })?
 1974                .await
 1975                .unwrap_or_default();
 1976
 1977            // Restore default dock state for empty workspaces
 1978            // Only restore if:
 1979            // 1. This is an empty workspace (no paths), AND
 1980            // 2. The serialized workspace either doesn't exist or has no paths
 1981            if is_empty_workspace && !serialized_workspace_has_paths {
 1982                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 1983                    window
 1984                        .update(cx, |_, window, cx| {
 1985                            workspace.update(cx, |workspace, cx| {
 1986                                for (dock, serialized_dock) in [
 1987                                    (&workspace.right_dock, &default_docks.right),
 1988                                    (&workspace.left_dock, &default_docks.left),
 1989                                    (&workspace.bottom_dock, &default_docks.bottom),
 1990                                ] {
 1991                                    dock.update(cx, |dock, cx| {
 1992                                        dock.serialized_dock = Some(serialized_dock.clone());
 1993                                        dock.restore_state(window, cx);
 1994                                    });
 1995                                }
 1996                                cx.notify();
 1997                            });
 1998                        })
 1999                        .log_err();
 2000                }
 2001            }
 2002
 2003            window
 2004                .update(cx, |_, _window, cx| {
 2005                    workspace.update(cx, |this: &mut Workspace, cx| {
 2006                        this.update_history(cx);
 2007                    });
 2008                })
 2009                .log_err();
 2010            Ok(OpenResult {
 2011                window,
 2012                workspace,
 2013                opened_items,
 2014            })
 2015        })
 2016    }
 2017
 2018    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2019        self.weak_self.clone()
 2020    }
 2021
 2022    pub fn left_dock(&self) -> &Entity<Dock> {
 2023        &self.left_dock
 2024    }
 2025
 2026    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2027        &self.bottom_dock
 2028    }
 2029
 2030    pub fn set_bottom_dock_layout(
 2031        &mut self,
 2032        layout: BottomDockLayout,
 2033        window: &mut Window,
 2034        cx: &mut Context<Self>,
 2035    ) {
 2036        let fs = self.project().read(cx).fs();
 2037        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2038            content.workspace.bottom_dock_layout = Some(layout);
 2039        });
 2040
 2041        cx.notify();
 2042        self.serialize_workspace(window, cx);
 2043    }
 2044
 2045    pub fn right_dock(&self) -> &Entity<Dock> {
 2046        &self.right_dock
 2047    }
 2048
 2049    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2050        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2051    }
 2052
 2053    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2054        let left_dock = self.left_dock.read(cx);
 2055        let left_visible = left_dock.is_open();
 2056        let left_active_panel = left_dock
 2057            .active_panel()
 2058            .map(|panel| panel.persistent_name().to_string());
 2059        // `zoomed_position` is kept in sync with individual panel zoom state
 2060        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2061        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2062
 2063        let right_dock = self.right_dock.read(cx);
 2064        let right_visible = right_dock.is_open();
 2065        let right_active_panel = right_dock
 2066            .active_panel()
 2067            .map(|panel| panel.persistent_name().to_string());
 2068        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2069
 2070        let bottom_dock = self.bottom_dock.read(cx);
 2071        let bottom_visible = bottom_dock.is_open();
 2072        let bottom_active_panel = bottom_dock
 2073            .active_panel()
 2074            .map(|panel| panel.persistent_name().to_string());
 2075        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2076
 2077        DockStructure {
 2078            left: DockData {
 2079                visible: left_visible,
 2080                active_panel: left_active_panel,
 2081                zoom: left_dock_zoom,
 2082            },
 2083            right: DockData {
 2084                visible: right_visible,
 2085                active_panel: right_active_panel,
 2086                zoom: right_dock_zoom,
 2087            },
 2088            bottom: DockData {
 2089                visible: bottom_visible,
 2090                active_panel: bottom_active_panel,
 2091                zoom: bottom_dock_zoom,
 2092            },
 2093        }
 2094    }
 2095
 2096    pub fn set_dock_structure(
 2097        &self,
 2098        docks: DockStructure,
 2099        window: &mut Window,
 2100        cx: &mut Context<Self>,
 2101    ) {
 2102        for (dock, data) in [
 2103            (&self.left_dock, docks.left),
 2104            (&self.bottom_dock, docks.bottom),
 2105            (&self.right_dock, docks.right),
 2106        ] {
 2107            dock.update(cx, |dock, cx| {
 2108                dock.serialized_dock = Some(data);
 2109                dock.restore_state(window, cx);
 2110            });
 2111        }
 2112    }
 2113
 2114    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2115        self.items(cx)
 2116            .filter_map(|item| {
 2117                let project_path = item.project_path(cx)?;
 2118                self.project.read(cx).absolute_path(&project_path, cx)
 2119            })
 2120            .collect()
 2121    }
 2122
 2123    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2124        match position {
 2125            DockPosition::Left => &self.left_dock,
 2126            DockPosition::Bottom => &self.bottom_dock,
 2127            DockPosition::Right => &self.right_dock,
 2128        }
 2129    }
 2130
 2131    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2132        self.all_docks().into_iter().find_map(|dock| {
 2133            let dock = dock.read(cx);
 2134            dock.has_agent_panel(cx).then_some(dock.position())
 2135        })
 2136    }
 2137
 2138    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2139        self.all_docks().into_iter().find_map(|dock| {
 2140            let dock = dock.read(cx);
 2141            let panel = dock.panel::<T>()?;
 2142            dock.stored_panel_size_state(&panel)
 2143        })
 2144    }
 2145
 2146    pub fn persisted_panel_size_state(
 2147        &self,
 2148        panel_key: &'static str,
 2149        cx: &App,
 2150    ) -> Option<dock::PanelSizeState> {
 2151        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2152    }
 2153
 2154    pub fn persist_panel_size_state(
 2155        &self,
 2156        panel_key: &str,
 2157        size_state: dock::PanelSizeState,
 2158        cx: &mut App,
 2159    ) {
 2160        let Some(workspace_id) = self
 2161            .database_id()
 2162            .map(|id| i64::from(id).to_string())
 2163            .or(self.session_id())
 2164        else {
 2165            return;
 2166        };
 2167
 2168        let kvp = db::kvp::KeyValueStore::global(cx);
 2169        let panel_key = panel_key.to_string();
 2170        cx.background_spawn(async move {
 2171            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2172            scope
 2173                .write(
 2174                    format!("{workspace_id}:{panel_key}"),
 2175                    serde_json::to_string(&size_state)?,
 2176                )
 2177                .await
 2178        })
 2179        .detach_and_log_err(cx);
 2180    }
 2181
 2182    pub fn set_panel_size_state<T: Panel>(
 2183        &mut self,
 2184        size_state: dock::PanelSizeState,
 2185        window: &mut Window,
 2186        cx: &mut Context<Self>,
 2187    ) -> bool {
 2188        let Some(panel) = self.panel::<T>(cx) else {
 2189            return false;
 2190        };
 2191
 2192        let dock = self.dock_at_position(panel.position(window, cx));
 2193        let did_set = dock.update(cx, |dock, cx| {
 2194            dock.set_panel_size_state(&panel, size_state, cx)
 2195        });
 2196
 2197        if did_set {
 2198            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2199        }
 2200
 2201        did_set
 2202    }
 2203
 2204    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2205        let panel = dock.active_panel()?;
 2206        let size_state = dock
 2207            .stored_panel_size_state(panel.as_ref())
 2208            .unwrap_or_default();
 2209        let position = dock.position();
 2210
 2211        if position.axis() == Axis::Horizontal
 2212            && panel.supports_flexible_size(window, cx)
 2213            && let Some(ratio) = size_state
 2214                .flexible_size_ratio
 2215                .or_else(|| self.default_flexible_dock_ratio(position))
 2216            && let Some(available_width) =
 2217                self.available_width_for_horizontal_dock(position, window, cx)
 2218        {
 2219            return Some((available_width * ratio.clamp(0.0, 1.0)).max(RESIZE_HANDLE_SIZE));
 2220        }
 2221
 2222        Some(
 2223            size_state
 2224                .size
 2225                .unwrap_or_else(|| panel.default_size(window, cx)),
 2226        )
 2227    }
 2228
 2229    pub fn flexible_dock_ratio_for_size(
 2230        &self,
 2231        position: DockPosition,
 2232        size: Pixels,
 2233        window: &Window,
 2234        cx: &App,
 2235    ) -> Option<f32> {
 2236        if position.axis() != Axis::Horizontal {
 2237            return None;
 2238        }
 2239
 2240        let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
 2241        let available_width = available_width.max(RESIZE_HANDLE_SIZE);
 2242        Some((size / available_width).clamp(0.0, 1.0))
 2243    }
 2244
 2245    fn available_width_for_horizontal_dock(
 2246        &self,
 2247        position: DockPosition,
 2248        window: &Window,
 2249        cx: &App,
 2250    ) -> Option<Pixels> {
 2251        let workspace_width = self.bounds.size.width;
 2252        if workspace_width <= Pixels::ZERO {
 2253            return None;
 2254        }
 2255
 2256        let opposite_position = match position {
 2257            DockPosition::Left => DockPosition::Right,
 2258            DockPosition::Right => DockPosition::Left,
 2259            DockPosition::Bottom => return None,
 2260        };
 2261
 2262        let opposite_width = self
 2263            .dock_at_position(opposite_position)
 2264            .read(cx)
 2265            .stored_active_panel_size(window, cx)
 2266            .unwrap_or(Pixels::ZERO);
 2267
 2268        Some((workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE))
 2269    }
 2270
 2271    pub fn default_flexible_dock_ratio(&self, position: DockPosition) -> Option<f32> {
 2272        if position.axis() != Axis::Horizontal {
 2273            return None;
 2274        }
 2275
 2276        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2277        let pane_fraction = self.center.width_fraction_for_pane(&pane).unwrap_or(1.0);
 2278        Some((pane_fraction / (1.0 + pane_fraction)).clamp(0.0, 1.0))
 2279    }
 2280
 2281    pub fn is_edited(&self) -> bool {
 2282        self.window_edited
 2283    }
 2284
 2285    pub fn add_panel<T: Panel>(
 2286        &mut self,
 2287        panel: Entity<T>,
 2288        window: &mut Window,
 2289        cx: &mut Context<Self>,
 2290    ) {
 2291        let focus_handle = panel.panel_focus_handle(cx);
 2292        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2293            .detach();
 2294
 2295        let dock_position = panel.position(window, cx);
 2296        let dock = self.dock_at_position(dock_position);
 2297        let any_panel = panel.to_any();
 2298        let persisted_size_state =
 2299            self.persisted_panel_size_state(T::panel_key(), cx)
 2300                .or_else(|| {
 2301                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2302                        let state = dock::PanelSizeState {
 2303                            size: Some(size),
 2304                            flexible_size_ratio: None,
 2305                        };
 2306                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2307                        state
 2308                    })
 2309                });
 2310
 2311        dock.update(cx, |dock, cx| {
 2312            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2313            if let Some(size_state) = persisted_size_state {
 2314                dock.set_panel_size_state(&panel, size_state, cx);
 2315            }
 2316            index
 2317        });
 2318
 2319        cx.emit(Event::PanelAdded(any_panel));
 2320    }
 2321
 2322    pub fn remove_panel<T: Panel>(
 2323        &mut self,
 2324        panel: &Entity<T>,
 2325        window: &mut Window,
 2326        cx: &mut Context<Self>,
 2327    ) {
 2328        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2329            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2330        }
 2331    }
 2332
 2333    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2334        &self.status_bar
 2335    }
 2336
 2337    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2338        self.sidebar_focus_handle = handle;
 2339    }
 2340
 2341    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2342        StatusBarSettings::get_global(cx).show
 2343    }
 2344
 2345    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2346        self.multi_workspace.as_ref()
 2347    }
 2348
 2349    pub fn set_multi_workspace(
 2350        &mut self,
 2351        multi_workspace: WeakEntity<MultiWorkspace>,
 2352        cx: &mut App,
 2353    ) {
 2354        self.status_bar.update(cx, |status_bar, cx| {
 2355            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2356        });
 2357        self.multi_workspace = Some(multi_workspace);
 2358    }
 2359
 2360    pub fn app_state(&self) -> &Arc<AppState> {
 2361        &self.app_state
 2362    }
 2363
 2364    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2365        self._panels_task = Some(task);
 2366    }
 2367
 2368    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2369        self._panels_task.take()
 2370    }
 2371
 2372    pub fn user_store(&self) -> &Entity<UserStore> {
 2373        &self.app_state.user_store
 2374    }
 2375
 2376    pub fn project(&self) -> &Entity<Project> {
 2377        &self.project
 2378    }
 2379
 2380    pub fn path_style(&self, cx: &App) -> PathStyle {
 2381        self.project.read(cx).path_style(cx)
 2382    }
 2383
 2384    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2385        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2386
 2387        for pane_handle in &self.panes {
 2388            let pane = pane_handle.read(cx);
 2389
 2390            for entry in pane.activation_history() {
 2391                history.insert(
 2392                    entry.entity_id,
 2393                    history
 2394                        .get(&entry.entity_id)
 2395                        .cloned()
 2396                        .unwrap_or(0)
 2397                        .max(entry.timestamp),
 2398                );
 2399            }
 2400        }
 2401
 2402        history
 2403    }
 2404
 2405    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2406        let mut recent_item: Option<Entity<T>> = None;
 2407        let mut recent_timestamp = 0;
 2408        for pane_handle in &self.panes {
 2409            let pane = pane_handle.read(cx);
 2410            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2411                pane.items().map(|item| (item.item_id(), item)).collect();
 2412            for entry in pane.activation_history() {
 2413                if entry.timestamp > recent_timestamp
 2414                    && let Some(&item) = item_map.get(&entry.entity_id)
 2415                    && let Some(typed_item) = item.act_as::<T>(cx)
 2416                {
 2417                    recent_timestamp = entry.timestamp;
 2418                    recent_item = Some(typed_item);
 2419                }
 2420            }
 2421        }
 2422        recent_item
 2423    }
 2424
 2425    pub fn recent_navigation_history_iter(
 2426        &self,
 2427        cx: &App,
 2428    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2429        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2430        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2431
 2432        for pane in &self.panes {
 2433            let pane = pane.read(cx);
 2434
 2435            pane.nav_history()
 2436                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2437                    if let Some(fs_path) = &fs_path {
 2438                        abs_paths_opened
 2439                            .entry(fs_path.clone())
 2440                            .or_default()
 2441                            .insert(project_path.clone());
 2442                    }
 2443                    let timestamp = entry.timestamp;
 2444                    match history.entry(project_path) {
 2445                        hash_map::Entry::Occupied(mut entry) => {
 2446                            let (_, old_timestamp) = entry.get();
 2447                            if &timestamp > old_timestamp {
 2448                                entry.insert((fs_path, timestamp));
 2449                            }
 2450                        }
 2451                        hash_map::Entry::Vacant(entry) => {
 2452                            entry.insert((fs_path, timestamp));
 2453                        }
 2454                    }
 2455                });
 2456
 2457            if let Some(item) = pane.active_item()
 2458                && let Some(project_path) = item.project_path(cx)
 2459            {
 2460                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2461
 2462                if let Some(fs_path) = &fs_path {
 2463                    abs_paths_opened
 2464                        .entry(fs_path.clone())
 2465                        .or_default()
 2466                        .insert(project_path.clone());
 2467                }
 2468
 2469                history.insert(project_path, (fs_path, std::usize::MAX));
 2470            }
 2471        }
 2472
 2473        history
 2474            .into_iter()
 2475            .sorted_by_key(|(_, (_, order))| *order)
 2476            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2477            .rev()
 2478            .filter(move |(history_path, abs_path)| {
 2479                let latest_project_path_opened = abs_path
 2480                    .as_ref()
 2481                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2482                    .and_then(|project_paths| {
 2483                        project_paths
 2484                            .iter()
 2485                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2486                    });
 2487
 2488                latest_project_path_opened.is_none_or(|path| path == history_path)
 2489            })
 2490    }
 2491
 2492    pub fn recent_navigation_history(
 2493        &self,
 2494        limit: Option<usize>,
 2495        cx: &App,
 2496    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2497        self.recent_navigation_history_iter(cx)
 2498            .take(limit.unwrap_or(usize::MAX))
 2499            .collect()
 2500    }
 2501
 2502    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2503        for pane in &self.panes {
 2504            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2505        }
 2506    }
 2507
 2508    fn navigate_history(
 2509        &mut self,
 2510        pane: WeakEntity<Pane>,
 2511        mode: NavigationMode,
 2512        window: &mut Window,
 2513        cx: &mut Context<Workspace>,
 2514    ) -> Task<Result<()>> {
 2515        self.navigate_history_impl(
 2516            pane,
 2517            mode,
 2518            window,
 2519            &mut |history, cx| history.pop(mode, cx),
 2520            cx,
 2521        )
 2522    }
 2523
 2524    fn navigate_tag_history(
 2525        &mut self,
 2526        pane: WeakEntity<Pane>,
 2527        mode: TagNavigationMode,
 2528        window: &mut Window,
 2529        cx: &mut Context<Workspace>,
 2530    ) -> Task<Result<()>> {
 2531        self.navigate_history_impl(
 2532            pane,
 2533            NavigationMode::Normal,
 2534            window,
 2535            &mut |history, _cx| history.pop_tag(mode),
 2536            cx,
 2537        )
 2538    }
 2539
 2540    fn navigate_history_impl(
 2541        &mut self,
 2542        pane: WeakEntity<Pane>,
 2543        mode: NavigationMode,
 2544        window: &mut Window,
 2545        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2546        cx: &mut Context<Workspace>,
 2547    ) -> Task<Result<()>> {
 2548        let to_load = if let Some(pane) = pane.upgrade() {
 2549            pane.update(cx, |pane, cx| {
 2550                window.focus(&pane.focus_handle(cx), cx);
 2551                loop {
 2552                    // Retrieve the weak item handle from the history.
 2553                    let entry = cb(pane.nav_history_mut(), cx)?;
 2554
 2555                    // If the item is still present in this pane, then activate it.
 2556                    if let Some(index) = entry
 2557                        .item
 2558                        .upgrade()
 2559                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2560                    {
 2561                        let prev_active_item_index = pane.active_item_index();
 2562                        pane.nav_history_mut().set_mode(mode);
 2563                        pane.activate_item(index, true, true, window, cx);
 2564                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2565
 2566                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2567                        if let Some(data) = entry.data {
 2568                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2569                        }
 2570
 2571                        if navigated {
 2572                            break None;
 2573                        }
 2574                    } else {
 2575                        // If the item is no longer present in this pane, then retrieve its
 2576                        // path info in order to reopen it.
 2577                        break pane
 2578                            .nav_history()
 2579                            .path_for_item(entry.item.id())
 2580                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2581                    }
 2582                }
 2583            })
 2584        } else {
 2585            None
 2586        };
 2587
 2588        if let Some((project_path, abs_path, entry)) = to_load {
 2589            // If the item was no longer present, then load it again from its previous path, first try the local path
 2590            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2591
 2592            cx.spawn_in(window, async move  |workspace, cx| {
 2593                let open_by_project_path = open_by_project_path.await;
 2594                let mut navigated = false;
 2595                match open_by_project_path
 2596                    .with_context(|| format!("Navigating to {project_path:?}"))
 2597                {
 2598                    Ok((project_entry_id, build_item)) => {
 2599                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2600                            pane.nav_history_mut().set_mode(mode);
 2601                            pane.active_item().map(|p| p.item_id())
 2602                        })?;
 2603
 2604                        pane.update_in(cx, |pane, window, cx| {
 2605                            let item = pane.open_item(
 2606                                project_entry_id,
 2607                                project_path,
 2608                                true,
 2609                                entry.is_preview,
 2610                                true,
 2611                                None,
 2612                                window, cx,
 2613                                build_item,
 2614                            );
 2615                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2616                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2617                            if let Some(data) = entry.data {
 2618                                navigated |= item.navigate(data, window, cx);
 2619                            }
 2620                        })?;
 2621                    }
 2622                    Err(open_by_project_path_e) => {
 2623                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2624                        // and its worktree is now dropped
 2625                        if let Some(abs_path) = abs_path {
 2626                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2627                                pane.nav_history_mut().set_mode(mode);
 2628                                pane.active_item().map(|p| p.item_id())
 2629                            })?;
 2630                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2631                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2632                            })?;
 2633                            match open_by_abs_path
 2634                                .await
 2635                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2636                            {
 2637                                Ok(item) => {
 2638                                    pane.update_in(cx, |pane, window, cx| {
 2639                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2640                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2641                                        if let Some(data) = entry.data {
 2642                                            navigated |= item.navigate(data, window, cx);
 2643                                        }
 2644                                    })?;
 2645                                }
 2646                                Err(open_by_abs_path_e) => {
 2647                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2648                                }
 2649                            }
 2650                        }
 2651                    }
 2652                }
 2653
 2654                if !navigated {
 2655                    workspace
 2656                        .update_in(cx, |workspace, window, cx| {
 2657                            Self::navigate_history(workspace, pane, mode, window, cx)
 2658                        })?
 2659                        .await?;
 2660                }
 2661
 2662                Ok(())
 2663            })
 2664        } else {
 2665            Task::ready(Ok(()))
 2666        }
 2667    }
 2668
 2669    pub fn go_back(
 2670        &mut self,
 2671        pane: WeakEntity<Pane>,
 2672        window: &mut Window,
 2673        cx: &mut Context<Workspace>,
 2674    ) -> Task<Result<()>> {
 2675        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2676    }
 2677
 2678    pub fn go_forward(
 2679        &mut self,
 2680        pane: WeakEntity<Pane>,
 2681        window: &mut Window,
 2682        cx: &mut Context<Workspace>,
 2683    ) -> Task<Result<()>> {
 2684        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2685    }
 2686
 2687    pub fn reopen_closed_item(
 2688        &mut self,
 2689        window: &mut Window,
 2690        cx: &mut Context<Workspace>,
 2691    ) -> Task<Result<()>> {
 2692        self.navigate_history(
 2693            self.active_pane().downgrade(),
 2694            NavigationMode::ReopeningClosedItem,
 2695            window,
 2696            cx,
 2697        )
 2698    }
 2699
 2700    pub fn client(&self) -> &Arc<Client> {
 2701        &self.app_state.client
 2702    }
 2703
 2704    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2705        self.titlebar_item = Some(item);
 2706        cx.notify();
 2707    }
 2708
 2709    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2710        self.on_prompt_for_new_path = Some(prompt)
 2711    }
 2712
 2713    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2714        self.on_prompt_for_open_path = Some(prompt)
 2715    }
 2716
 2717    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2718        self.terminal_provider = Some(Box::new(provider));
 2719    }
 2720
 2721    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2722        self.debugger_provider = Some(Arc::new(provider));
 2723    }
 2724
 2725    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2726        self.debugger_provider.clone()
 2727    }
 2728
 2729    pub fn prompt_for_open_path(
 2730        &mut self,
 2731        path_prompt_options: PathPromptOptions,
 2732        lister: DirectoryLister,
 2733        window: &mut Window,
 2734        cx: &mut Context<Self>,
 2735    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2736        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2737            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2738            let rx = prompt(self, lister, window, cx);
 2739            self.on_prompt_for_open_path = Some(prompt);
 2740            rx
 2741        } else {
 2742            let (tx, rx) = oneshot::channel();
 2743            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2744
 2745            cx.spawn_in(window, async move |workspace, cx| {
 2746                let Ok(result) = abs_path.await else {
 2747                    return Ok(());
 2748                };
 2749
 2750                match result {
 2751                    Ok(result) => {
 2752                        tx.send(result).ok();
 2753                    }
 2754                    Err(err) => {
 2755                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2756                            workspace.show_portal_error(err.to_string(), cx);
 2757                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2758                            let rx = prompt(workspace, lister, window, cx);
 2759                            workspace.on_prompt_for_open_path = Some(prompt);
 2760                            rx
 2761                        })?;
 2762                        if let Ok(path) = rx.await {
 2763                            tx.send(path).ok();
 2764                        }
 2765                    }
 2766                };
 2767                anyhow::Ok(())
 2768            })
 2769            .detach();
 2770
 2771            rx
 2772        }
 2773    }
 2774
 2775    pub fn prompt_for_new_path(
 2776        &mut self,
 2777        lister: DirectoryLister,
 2778        suggested_name: Option<String>,
 2779        window: &mut Window,
 2780        cx: &mut Context<Self>,
 2781    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2782        if self.project.read(cx).is_via_collab()
 2783            || self.project.read(cx).is_via_remote_server()
 2784            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2785        {
 2786            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2787            let rx = prompt(self, lister, suggested_name, window, cx);
 2788            self.on_prompt_for_new_path = Some(prompt);
 2789            return rx;
 2790        }
 2791
 2792        let (tx, rx) = oneshot::channel();
 2793        cx.spawn_in(window, async move |workspace, cx| {
 2794            let abs_path = workspace.update(cx, |workspace, cx| {
 2795                let relative_to = workspace
 2796                    .most_recent_active_path(cx)
 2797                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2798                    .or_else(|| {
 2799                        let project = workspace.project.read(cx);
 2800                        project.visible_worktrees(cx).find_map(|worktree| {
 2801                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2802                        })
 2803                    })
 2804                    .or_else(std::env::home_dir)
 2805                    .unwrap_or_else(|| PathBuf::from(""));
 2806                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2807            })?;
 2808            let abs_path = match abs_path.await? {
 2809                Ok(path) => path,
 2810                Err(err) => {
 2811                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2812                        workspace.show_portal_error(err.to_string(), cx);
 2813
 2814                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2815                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2816                        workspace.on_prompt_for_new_path = Some(prompt);
 2817                        rx
 2818                    })?;
 2819                    if let Ok(path) = rx.await {
 2820                        tx.send(path).ok();
 2821                    }
 2822                    return anyhow::Ok(());
 2823                }
 2824            };
 2825
 2826            tx.send(abs_path.map(|path| vec![path])).ok();
 2827            anyhow::Ok(())
 2828        })
 2829        .detach();
 2830
 2831        rx
 2832    }
 2833
 2834    pub fn titlebar_item(&self) -> Option<AnyView> {
 2835        self.titlebar_item.clone()
 2836    }
 2837
 2838    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2839    /// When set, git-related operations should use this worktree instead of deriving
 2840    /// the active worktree from the focused file.
 2841    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2842        self.active_worktree_override
 2843    }
 2844
 2845    pub fn set_active_worktree_override(
 2846        &mut self,
 2847        worktree_id: Option<WorktreeId>,
 2848        cx: &mut Context<Self>,
 2849    ) {
 2850        self.active_worktree_override = worktree_id;
 2851        cx.notify();
 2852    }
 2853
 2854    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2855        self.active_worktree_override = None;
 2856        cx.notify();
 2857    }
 2858
 2859    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2860    ///
 2861    /// If the given workspace has a local project, then it will be passed
 2862    /// to the callback. Otherwise, a new empty window will be created.
 2863    pub fn with_local_workspace<T, F>(
 2864        &mut self,
 2865        window: &mut Window,
 2866        cx: &mut Context<Self>,
 2867        callback: F,
 2868    ) -> Task<Result<T>>
 2869    where
 2870        T: 'static,
 2871        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2872    {
 2873        if self.project.read(cx).is_local() {
 2874            Task::ready(Ok(callback(self, window, cx)))
 2875        } else {
 2876            let env = self.project.read(cx).cli_environment(cx);
 2877            let task = Self::new_local(
 2878                Vec::new(),
 2879                self.app_state.clone(),
 2880                None,
 2881                env,
 2882                None,
 2883                true,
 2884                cx,
 2885            );
 2886            cx.spawn_in(window, async move |_vh, cx| {
 2887                let OpenResult {
 2888                    window: multi_workspace_window,
 2889                    ..
 2890                } = task.await?;
 2891                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2892                    let workspace = multi_workspace.workspace().clone();
 2893                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2894                })
 2895            })
 2896        }
 2897    }
 2898
 2899    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2900    ///
 2901    /// If the given workspace has a local project, then it will be passed
 2902    /// to the callback. Otherwise, a new empty window will be created.
 2903    pub fn with_local_or_wsl_workspace<T, F>(
 2904        &mut self,
 2905        window: &mut Window,
 2906        cx: &mut Context<Self>,
 2907        callback: F,
 2908    ) -> Task<Result<T>>
 2909    where
 2910        T: 'static,
 2911        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2912    {
 2913        let project = self.project.read(cx);
 2914        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2915            Task::ready(Ok(callback(self, window, cx)))
 2916        } else {
 2917            let env = self.project.read(cx).cli_environment(cx);
 2918            let task = Self::new_local(
 2919                Vec::new(),
 2920                self.app_state.clone(),
 2921                None,
 2922                env,
 2923                None,
 2924                true,
 2925                cx,
 2926            );
 2927            cx.spawn_in(window, async move |_vh, cx| {
 2928                let OpenResult {
 2929                    window: multi_workspace_window,
 2930                    ..
 2931                } = task.await?;
 2932                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2933                    let workspace = multi_workspace.workspace().clone();
 2934                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2935                })
 2936            })
 2937        }
 2938    }
 2939
 2940    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2941        self.project.read(cx).worktrees(cx)
 2942    }
 2943
 2944    pub fn visible_worktrees<'a>(
 2945        &self,
 2946        cx: &'a App,
 2947    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2948        self.project.read(cx).visible_worktrees(cx)
 2949    }
 2950
 2951    #[cfg(any(test, feature = "test-support"))]
 2952    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2953        let futures = self
 2954            .worktrees(cx)
 2955            .filter_map(|worktree| worktree.read(cx).as_local())
 2956            .map(|worktree| worktree.scan_complete())
 2957            .collect::<Vec<_>>();
 2958        async move {
 2959            for future in futures {
 2960                future.await;
 2961            }
 2962        }
 2963    }
 2964
 2965    pub fn close_global(cx: &mut App) {
 2966        cx.defer(|cx| {
 2967            cx.windows().iter().find(|window| {
 2968                window
 2969                    .update(cx, |_, window, _| {
 2970                        if window.is_window_active() {
 2971                            //This can only get called when the window's project connection has been lost
 2972                            //so we don't need to prompt the user for anything and instead just close the window
 2973                            window.remove_window();
 2974                            true
 2975                        } else {
 2976                            false
 2977                        }
 2978                    })
 2979                    .unwrap_or(false)
 2980            });
 2981        });
 2982    }
 2983
 2984    pub fn move_focused_panel_to_next_position(
 2985        &mut self,
 2986        _: &MoveFocusedPanelToNextPosition,
 2987        window: &mut Window,
 2988        cx: &mut Context<Self>,
 2989    ) {
 2990        let docks = self.all_docks();
 2991        let active_dock = docks
 2992            .into_iter()
 2993            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2994
 2995        if let Some(dock) = active_dock {
 2996            dock.update(cx, |dock, cx| {
 2997                let active_panel = dock
 2998                    .active_panel()
 2999                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3000
 3001                if let Some(panel) = active_panel {
 3002                    panel.move_to_next_position(window, cx);
 3003                }
 3004            })
 3005        }
 3006    }
 3007
 3008    pub fn prepare_to_close(
 3009        &mut self,
 3010        close_intent: CloseIntent,
 3011        window: &mut Window,
 3012        cx: &mut Context<Self>,
 3013    ) -> Task<Result<bool>> {
 3014        let active_call = self.active_global_call();
 3015
 3016        cx.spawn_in(window, async move |this, cx| {
 3017            this.update(cx, |this, _| {
 3018                if close_intent == CloseIntent::CloseWindow {
 3019                    this.removing = true;
 3020                }
 3021            })?;
 3022
 3023            let workspace_count = cx.update(|_window, cx| {
 3024                cx.windows()
 3025                    .iter()
 3026                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3027                    .count()
 3028            })?;
 3029
 3030            #[cfg(target_os = "macos")]
 3031            let save_last_workspace = false;
 3032
 3033            // On Linux and Windows, closing the last window should restore the last workspace.
 3034            #[cfg(not(target_os = "macos"))]
 3035            let save_last_workspace = {
 3036                let remaining_workspaces = cx.update(|_window, cx| {
 3037                    cx.windows()
 3038                        .iter()
 3039                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3040                        .filter_map(|multi_workspace| {
 3041                            multi_workspace
 3042                                .update(cx, |multi_workspace, _, cx| {
 3043                                    multi_workspace.workspace().read(cx).removing
 3044                                })
 3045                                .ok()
 3046                        })
 3047                        .filter(|removing| !removing)
 3048                        .count()
 3049                })?;
 3050
 3051                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3052            };
 3053
 3054            if let Some(active_call) = active_call
 3055                && workspace_count == 1
 3056                && cx
 3057                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3058                    .unwrap_or(false)
 3059            {
 3060                if close_intent == CloseIntent::CloseWindow {
 3061                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3062                    let answer = cx.update(|window, cx| {
 3063                        window.prompt(
 3064                            PromptLevel::Warning,
 3065                            "Do you want to leave the current call?",
 3066                            None,
 3067                            &["Close window and hang up", "Cancel"],
 3068                            cx,
 3069                        )
 3070                    })?;
 3071
 3072                    if answer.await.log_err() == Some(1) {
 3073                        return anyhow::Ok(false);
 3074                    } else {
 3075                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3076                            task.await.log_err();
 3077                        }
 3078                    }
 3079                }
 3080                if close_intent == CloseIntent::ReplaceWindow {
 3081                    _ = cx.update(|_window, cx| {
 3082                        let multi_workspace = cx
 3083                            .windows()
 3084                            .iter()
 3085                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3086                            .next()
 3087                            .unwrap();
 3088                        let project = multi_workspace
 3089                            .read(cx)?
 3090                            .workspace()
 3091                            .read(cx)
 3092                            .project
 3093                            .clone();
 3094                        if project.read(cx).is_shared() {
 3095                            active_call.0.unshare_project(project, cx)?;
 3096                        }
 3097                        Ok::<_, anyhow::Error>(())
 3098                    });
 3099                }
 3100            }
 3101
 3102            let save_result = this
 3103                .update_in(cx, |this, window, cx| {
 3104                    this.save_all_internal(SaveIntent::Close, window, cx)
 3105                })?
 3106                .await;
 3107
 3108            // If we're not quitting, but closing, we remove the workspace from
 3109            // the current session.
 3110            if close_intent != CloseIntent::Quit
 3111                && !save_last_workspace
 3112                && save_result.as_ref().is_ok_and(|&res| res)
 3113            {
 3114                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3115                    .await;
 3116            }
 3117
 3118            save_result
 3119        })
 3120    }
 3121
 3122    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3123        self.save_all_internal(
 3124            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3125            window,
 3126            cx,
 3127        )
 3128        .detach_and_log_err(cx);
 3129    }
 3130
 3131    fn send_keystrokes(
 3132        &mut self,
 3133        action: &SendKeystrokes,
 3134        window: &mut Window,
 3135        cx: &mut Context<Self>,
 3136    ) {
 3137        let keystrokes: Vec<Keystroke> = action
 3138            .0
 3139            .split(' ')
 3140            .flat_map(|k| Keystroke::parse(k).log_err())
 3141            .map(|k| {
 3142                cx.keyboard_mapper()
 3143                    .map_key_equivalent(k, false)
 3144                    .inner()
 3145                    .clone()
 3146            })
 3147            .collect();
 3148        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3149    }
 3150
 3151    pub fn send_keystrokes_impl(
 3152        &mut self,
 3153        keystrokes: Vec<Keystroke>,
 3154        window: &mut Window,
 3155        cx: &mut Context<Self>,
 3156    ) -> Shared<Task<()>> {
 3157        let mut state = self.dispatching_keystrokes.borrow_mut();
 3158        if !state.dispatched.insert(keystrokes.clone()) {
 3159            cx.propagate();
 3160            return state.task.clone().unwrap();
 3161        }
 3162
 3163        state.queue.extend(keystrokes);
 3164
 3165        let keystrokes = self.dispatching_keystrokes.clone();
 3166        if state.task.is_none() {
 3167            state.task = Some(
 3168                window
 3169                    .spawn(cx, async move |cx| {
 3170                        // limit to 100 keystrokes to avoid infinite recursion.
 3171                        for _ in 0..100 {
 3172                            let keystroke = {
 3173                                let mut state = keystrokes.borrow_mut();
 3174                                let Some(keystroke) = state.queue.pop_front() else {
 3175                                    state.dispatched.clear();
 3176                                    state.task.take();
 3177                                    return;
 3178                                };
 3179                                keystroke
 3180                            };
 3181                            cx.update(|window, cx| {
 3182                                let focused = window.focused(cx);
 3183                                window.dispatch_keystroke(keystroke.clone(), cx);
 3184                                if window.focused(cx) != focused {
 3185                                    // dispatch_keystroke may cause the focus to change.
 3186                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3187                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3188                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3189                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3190                                    // )
 3191                                    window.draw(cx).clear();
 3192                                }
 3193                            })
 3194                            .ok();
 3195
 3196                            // Yield between synthetic keystrokes so deferred focus and
 3197                            // other effects can settle before dispatching the next key.
 3198                            yield_now().await;
 3199                        }
 3200
 3201                        *keystrokes.borrow_mut() = Default::default();
 3202                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3203                    })
 3204                    .shared(),
 3205            );
 3206        }
 3207        state.task.clone().unwrap()
 3208    }
 3209
 3210    fn save_all_internal(
 3211        &mut self,
 3212        mut save_intent: SaveIntent,
 3213        window: &mut Window,
 3214        cx: &mut Context<Self>,
 3215    ) -> Task<Result<bool>> {
 3216        if self.project.read(cx).is_disconnected(cx) {
 3217            return Task::ready(Ok(true));
 3218        }
 3219        let dirty_items = self
 3220            .panes
 3221            .iter()
 3222            .flat_map(|pane| {
 3223                pane.read(cx).items().filter_map(|item| {
 3224                    if item.is_dirty(cx) {
 3225                        item.tab_content_text(0, cx);
 3226                        Some((pane.downgrade(), item.boxed_clone()))
 3227                    } else {
 3228                        None
 3229                    }
 3230                })
 3231            })
 3232            .collect::<Vec<_>>();
 3233
 3234        let project = self.project.clone();
 3235        cx.spawn_in(window, async move |workspace, cx| {
 3236            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3237                let (serialize_tasks, remaining_dirty_items) =
 3238                    workspace.update_in(cx, |workspace, window, cx| {
 3239                        let mut remaining_dirty_items = Vec::new();
 3240                        let mut serialize_tasks = Vec::new();
 3241                        for (pane, item) in dirty_items {
 3242                            if let Some(task) = item
 3243                                .to_serializable_item_handle(cx)
 3244                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3245                            {
 3246                                serialize_tasks.push(task);
 3247                            } else {
 3248                                remaining_dirty_items.push((pane, item));
 3249                            }
 3250                        }
 3251                        (serialize_tasks, remaining_dirty_items)
 3252                    })?;
 3253
 3254                futures::future::try_join_all(serialize_tasks).await?;
 3255
 3256                if !remaining_dirty_items.is_empty() {
 3257                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3258                }
 3259
 3260                if remaining_dirty_items.len() > 1 {
 3261                    let answer = workspace.update_in(cx, |_, window, cx| {
 3262                        let detail = Pane::file_names_for_prompt(
 3263                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3264                            cx,
 3265                        );
 3266                        window.prompt(
 3267                            PromptLevel::Warning,
 3268                            "Do you want to save all changes in the following files?",
 3269                            Some(&detail),
 3270                            &["Save all", "Discard all", "Cancel"],
 3271                            cx,
 3272                        )
 3273                    })?;
 3274                    match answer.await.log_err() {
 3275                        Some(0) => save_intent = SaveIntent::SaveAll,
 3276                        Some(1) => save_intent = SaveIntent::Skip,
 3277                        Some(2) => return Ok(false),
 3278                        _ => {}
 3279                    }
 3280                }
 3281
 3282                remaining_dirty_items
 3283            } else {
 3284                dirty_items
 3285            };
 3286
 3287            for (pane, item) in dirty_items {
 3288                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3289                    (
 3290                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3291                        item.project_entry_ids(cx),
 3292                    )
 3293                })?;
 3294                if (singleton || !project_entry_ids.is_empty())
 3295                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3296                {
 3297                    return Ok(false);
 3298                }
 3299            }
 3300            Ok(true)
 3301        })
 3302    }
 3303
 3304    pub fn open_workspace_for_paths(
 3305        &mut self,
 3306        replace_current_window: bool,
 3307        paths: Vec<PathBuf>,
 3308        window: &mut Window,
 3309        cx: &mut Context<Self>,
 3310    ) -> Task<Result<Entity<Workspace>>> {
 3311        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3312        let is_remote = self.project.read(cx).is_via_collab();
 3313        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3314        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3315
 3316        let window_to_replace = if replace_current_window {
 3317            window_handle
 3318        } else if is_remote || has_worktree || has_dirty_items {
 3319            None
 3320        } else {
 3321            window_handle
 3322        };
 3323        let app_state = self.app_state.clone();
 3324
 3325        cx.spawn(async move |_, cx| {
 3326            let OpenResult { workspace, .. } = cx
 3327                .update(|cx| {
 3328                    open_paths(
 3329                        &paths,
 3330                        app_state,
 3331                        OpenOptions {
 3332                            replace_window: window_to_replace,
 3333                            ..Default::default()
 3334                        },
 3335                        cx,
 3336                    )
 3337                })
 3338                .await?;
 3339            Ok(workspace)
 3340        })
 3341    }
 3342
 3343    #[allow(clippy::type_complexity)]
 3344    pub fn open_paths(
 3345        &mut self,
 3346        mut abs_paths: Vec<PathBuf>,
 3347        options: OpenOptions,
 3348        pane: Option<WeakEntity<Pane>>,
 3349        window: &mut Window,
 3350        cx: &mut Context<Self>,
 3351    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3352        let fs = self.app_state.fs.clone();
 3353
 3354        let caller_ordered_abs_paths = abs_paths.clone();
 3355
 3356        // Sort the paths to ensure we add worktrees for parents before their children.
 3357        abs_paths.sort_unstable();
 3358        cx.spawn_in(window, async move |this, cx| {
 3359            let mut tasks = Vec::with_capacity(abs_paths.len());
 3360
 3361            for abs_path in &abs_paths {
 3362                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3363                    OpenVisible::All => Some(true),
 3364                    OpenVisible::None => Some(false),
 3365                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3366                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3367                        Some(None) => Some(true),
 3368                        None => None,
 3369                    },
 3370                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3371                        Some(Some(metadata)) => Some(metadata.is_dir),
 3372                        Some(None) => Some(false),
 3373                        None => None,
 3374                    },
 3375                };
 3376                let project_path = match visible {
 3377                    Some(visible) => match this
 3378                        .update(cx, |this, cx| {
 3379                            Workspace::project_path_for_path(
 3380                                this.project.clone(),
 3381                                abs_path,
 3382                                visible,
 3383                                cx,
 3384                            )
 3385                        })
 3386                        .log_err()
 3387                    {
 3388                        Some(project_path) => project_path.await.log_err(),
 3389                        None => None,
 3390                    },
 3391                    None => None,
 3392                };
 3393
 3394                let this = this.clone();
 3395                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3396                let fs = fs.clone();
 3397                let pane = pane.clone();
 3398                let task = cx.spawn(async move |cx| {
 3399                    let (_worktree, project_path) = project_path?;
 3400                    if fs.is_dir(&abs_path).await {
 3401                        // Opening a directory should not race to update the active entry.
 3402                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3403                        None
 3404                    } else {
 3405                        Some(
 3406                            this.update_in(cx, |this, window, cx| {
 3407                                this.open_path(
 3408                                    project_path,
 3409                                    pane,
 3410                                    options.focus.unwrap_or(true),
 3411                                    window,
 3412                                    cx,
 3413                                )
 3414                            })
 3415                            .ok()?
 3416                            .await,
 3417                        )
 3418                    }
 3419                });
 3420                tasks.push(task);
 3421            }
 3422
 3423            let results = futures::future::join_all(tasks).await;
 3424
 3425            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3426            let mut winner: Option<(PathBuf, bool)> = None;
 3427            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3428                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3429                    if !metadata.is_dir {
 3430                        winner = Some((abs_path, false));
 3431                        break;
 3432                    }
 3433                    if winner.is_none() {
 3434                        winner = Some((abs_path, true));
 3435                    }
 3436                } else if winner.is_none() {
 3437                    winner = Some((abs_path, false));
 3438                }
 3439            }
 3440
 3441            // Compute the winner entry id on the foreground thread and emit once, after all
 3442            // paths finish opening. This avoids races between concurrently-opening paths
 3443            // (directories in particular) and makes the resulting project panel selection
 3444            // deterministic.
 3445            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3446                'emit_winner: {
 3447                    let winner_abs_path: Arc<Path> =
 3448                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3449
 3450                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3451                        OpenVisible::All => true,
 3452                        OpenVisible::None => false,
 3453                        OpenVisible::OnlyFiles => !winner_is_dir,
 3454                        OpenVisible::OnlyDirectories => winner_is_dir,
 3455                    };
 3456
 3457                    let Some(worktree_task) = this
 3458                        .update(cx, |workspace, cx| {
 3459                            workspace.project.update(cx, |project, cx| {
 3460                                project.find_or_create_worktree(
 3461                                    winner_abs_path.as_ref(),
 3462                                    visible,
 3463                                    cx,
 3464                                )
 3465                            })
 3466                        })
 3467                        .ok()
 3468                    else {
 3469                        break 'emit_winner;
 3470                    };
 3471
 3472                    let Ok((worktree, _)) = worktree_task.await else {
 3473                        break 'emit_winner;
 3474                    };
 3475
 3476                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3477                        let worktree = worktree.read(cx);
 3478                        let worktree_abs_path = worktree.abs_path();
 3479                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3480                            worktree.root_entry()
 3481                        } else {
 3482                            winner_abs_path
 3483                                .strip_prefix(worktree_abs_path.as_ref())
 3484                                .ok()
 3485                                .and_then(|relative_path| {
 3486                                    let relative_path =
 3487                                        RelPath::new(relative_path, PathStyle::local())
 3488                                            .log_err()?;
 3489                                    worktree.entry_for_path(&relative_path)
 3490                                })
 3491                        }?;
 3492                        Some(entry.id)
 3493                    }) else {
 3494                        break 'emit_winner;
 3495                    };
 3496
 3497                    this.update(cx, |workspace, cx| {
 3498                        workspace.project.update(cx, |_, cx| {
 3499                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3500                        });
 3501                    })
 3502                    .ok();
 3503                }
 3504            }
 3505
 3506            results
 3507        })
 3508    }
 3509
 3510    pub fn open_resolved_path(
 3511        &mut self,
 3512        path: ResolvedPath,
 3513        window: &mut Window,
 3514        cx: &mut Context<Self>,
 3515    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3516        match path {
 3517            ResolvedPath::ProjectPath { project_path, .. } => {
 3518                self.open_path(project_path, None, true, window, cx)
 3519            }
 3520            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3521                PathBuf::from(path),
 3522                OpenOptions {
 3523                    visible: Some(OpenVisible::None),
 3524                    ..Default::default()
 3525                },
 3526                window,
 3527                cx,
 3528            ),
 3529        }
 3530    }
 3531
 3532    pub fn absolute_path_of_worktree(
 3533        &self,
 3534        worktree_id: WorktreeId,
 3535        cx: &mut Context<Self>,
 3536    ) -> Option<PathBuf> {
 3537        self.project
 3538            .read(cx)
 3539            .worktree_for_id(worktree_id, cx)
 3540            // TODO: use `abs_path` or `root_dir`
 3541            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3542    }
 3543
 3544    pub fn add_folder_to_project(
 3545        &mut self,
 3546        _: &AddFolderToProject,
 3547        window: &mut Window,
 3548        cx: &mut Context<Self>,
 3549    ) {
 3550        let project = self.project.read(cx);
 3551        if project.is_via_collab() {
 3552            self.show_error(
 3553                &anyhow!("You cannot add folders to someone else's project"),
 3554                cx,
 3555            );
 3556            return;
 3557        }
 3558        let paths = self.prompt_for_open_path(
 3559            PathPromptOptions {
 3560                files: false,
 3561                directories: true,
 3562                multiple: true,
 3563                prompt: None,
 3564            },
 3565            DirectoryLister::Project(self.project.clone()),
 3566            window,
 3567            cx,
 3568        );
 3569        cx.spawn_in(window, async move |this, cx| {
 3570            if let Some(paths) = paths.await.log_err().flatten() {
 3571                let results = this
 3572                    .update_in(cx, |this, window, cx| {
 3573                        this.open_paths(
 3574                            paths,
 3575                            OpenOptions {
 3576                                visible: Some(OpenVisible::All),
 3577                                ..Default::default()
 3578                            },
 3579                            None,
 3580                            window,
 3581                            cx,
 3582                        )
 3583                    })?
 3584                    .await;
 3585                for result in results.into_iter().flatten() {
 3586                    result.log_err();
 3587                }
 3588            }
 3589            anyhow::Ok(())
 3590        })
 3591        .detach_and_log_err(cx);
 3592    }
 3593
 3594    pub fn project_path_for_path(
 3595        project: Entity<Project>,
 3596        abs_path: &Path,
 3597        visible: bool,
 3598        cx: &mut App,
 3599    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3600        let entry = project.update(cx, |project, cx| {
 3601            project.find_or_create_worktree(abs_path, visible, cx)
 3602        });
 3603        cx.spawn(async move |cx| {
 3604            let (worktree, path) = entry.await?;
 3605            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3606            Ok((worktree, ProjectPath { worktree_id, path }))
 3607        })
 3608    }
 3609
 3610    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3611        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3612    }
 3613
 3614    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3615        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3616    }
 3617
 3618    pub fn items_of_type<'a, T: Item>(
 3619        &'a self,
 3620        cx: &'a App,
 3621    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3622        self.panes
 3623            .iter()
 3624            .flat_map(|pane| pane.read(cx).items_of_type())
 3625    }
 3626
 3627    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3628        self.active_pane().read(cx).active_item()
 3629    }
 3630
 3631    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3632        let item = self.active_item(cx)?;
 3633        item.to_any_view().downcast::<I>().ok()
 3634    }
 3635
 3636    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3637        self.active_item(cx).and_then(|item| item.project_path(cx))
 3638    }
 3639
 3640    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3641        self.recent_navigation_history_iter(cx)
 3642            .filter_map(|(path, abs_path)| {
 3643                let worktree = self
 3644                    .project
 3645                    .read(cx)
 3646                    .worktree_for_id(path.worktree_id, cx)?;
 3647                if worktree.read(cx).is_visible() {
 3648                    abs_path
 3649                } else {
 3650                    None
 3651                }
 3652            })
 3653            .next()
 3654    }
 3655
 3656    pub fn save_active_item(
 3657        &mut self,
 3658        save_intent: SaveIntent,
 3659        window: &mut Window,
 3660        cx: &mut App,
 3661    ) -> Task<Result<()>> {
 3662        let project = self.project.clone();
 3663        let pane = self.active_pane();
 3664        let item = pane.read(cx).active_item();
 3665        let pane = pane.downgrade();
 3666
 3667        window.spawn(cx, async move |cx| {
 3668            if let Some(item) = item {
 3669                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3670                    .await
 3671                    .map(|_| ())
 3672            } else {
 3673                Ok(())
 3674            }
 3675        })
 3676    }
 3677
 3678    pub fn close_inactive_items_and_panes(
 3679        &mut self,
 3680        action: &CloseInactiveTabsAndPanes,
 3681        window: &mut Window,
 3682        cx: &mut Context<Self>,
 3683    ) {
 3684        if let Some(task) = self.close_all_internal(
 3685            true,
 3686            action.save_intent.unwrap_or(SaveIntent::Close),
 3687            window,
 3688            cx,
 3689        ) {
 3690            task.detach_and_log_err(cx)
 3691        }
 3692    }
 3693
 3694    pub fn close_all_items_and_panes(
 3695        &mut self,
 3696        action: &CloseAllItemsAndPanes,
 3697        window: &mut Window,
 3698        cx: &mut Context<Self>,
 3699    ) {
 3700        if let Some(task) = self.close_all_internal(
 3701            false,
 3702            action.save_intent.unwrap_or(SaveIntent::Close),
 3703            window,
 3704            cx,
 3705        ) {
 3706            task.detach_and_log_err(cx)
 3707        }
 3708    }
 3709
 3710    /// Closes the active item across all panes.
 3711    pub fn close_item_in_all_panes(
 3712        &mut self,
 3713        action: &CloseItemInAllPanes,
 3714        window: &mut Window,
 3715        cx: &mut Context<Self>,
 3716    ) {
 3717        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3718            return;
 3719        };
 3720
 3721        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3722        let close_pinned = action.close_pinned;
 3723
 3724        if let Some(project_path) = active_item.project_path(cx) {
 3725            self.close_items_with_project_path(
 3726                &project_path,
 3727                save_intent,
 3728                close_pinned,
 3729                window,
 3730                cx,
 3731            );
 3732        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3733            let item_id = active_item.item_id();
 3734            self.active_pane().update(cx, |pane, cx| {
 3735                pane.close_item_by_id(item_id, save_intent, window, cx)
 3736                    .detach_and_log_err(cx);
 3737            });
 3738        }
 3739    }
 3740
 3741    /// Closes all items with the given project path across all panes.
 3742    pub fn close_items_with_project_path(
 3743        &mut self,
 3744        project_path: &ProjectPath,
 3745        save_intent: SaveIntent,
 3746        close_pinned: bool,
 3747        window: &mut Window,
 3748        cx: &mut Context<Self>,
 3749    ) {
 3750        let panes = self.panes().to_vec();
 3751        for pane in panes {
 3752            pane.update(cx, |pane, cx| {
 3753                pane.close_items_for_project_path(
 3754                    project_path,
 3755                    save_intent,
 3756                    close_pinned,
 3757                    window,
 3758                    cx,
 3759                )
 3760                .detach_and_log_err(cx);
 3761            });
 3762        }
 3763    }
 3764
 3765    fn close_all_internal(
 3766        &mut self,
 3767        retain_active_pane: bool,
 3768        save_intent: SaveIntent,
 3769        window: &mut Window,
 3770        cx: &mut Context<Self>,
 3771    ) -> Option<Task<Result<()>>> {
 3772        let current_pane = self.active_pane();
 3773
 3774        let mut tasks = Vec::new();
 3775
 3776        if retain_active_pane {
 3777            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3778                pane.close_other_items(
 3779                    &CloseOtherItems {
 3780                        save_intent: None,
 3781                        close_pinned: false,
 3782                    },
 3783                    None,
 3784                    window,
 3785                    cx,
 3786                )
 3787            });
 3788
 3789            tasks.push(current_pane_close);
 3790        }
 3791
 3792        for pane in self.panes() {
 3793            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3794                continue;
 3795            }
 3796
 3797            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3798                pane.close_all_items(
 3799                    &CloseAllItems {
 3800                        save_intent: Some(save_intent),
 3801                        close_pinned: false,
 3802                    },
 3803                    window,
 3804                    cx,
 3805                )
 3806            });
 3807
 3808            tasks.push(close_pane_items)
 3809        }
 3810
 3811        if tasks.is_empty() {
 3812            None
 3813        } else {
 3814            Some(cx.spawn_in(window, async move |_, _| {
 3815                for task in tasks {
 3816                    task.await?
 3817                }
 3818                Ok(())
 3819            }))
 3820        }
 3821    }
 3822
 3823    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3824        self.dock_at_position(position).read(cx).is_open()
 3825    }
 3826
 3827    pub fn toggle_dock(
 3828        &mut self,
 3829        dock_side: DockPosition,
 3830        window: &mut Window,
 3831        cx: &mut Context<Self>,
 3832    ) {
 3833        let mut focus_center = false;
 3834        let mut reveal_dock = false;
 3835
 3836        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3837        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3838
 3839        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3840            telemetry::event!(
 3841                "Panel Button Clicked",
 3842                name = panel.persistent_name(),
 3843                toggle_state = !was_visible
 3844            );
 3845        }
 3846        if was_visible {
 3847            self.save_open_dock_positions(cx);
 3848        }
 3849
 3850        let dock = self.dock_at_position(dock_side);
 3851        dock.update(cx, |dock, cx| {
 3852            dock.set_open(!was_visible, window, cx);
 3853
 3854            if dock.active_panel().is_none() {
 3855                let Some(panel_ix) = dock
 3856                    .first_enabled_panel_idx(cx)
 3857                    .log_with_level(log::Level::Info)
 3858                else {
 3859                    return;
 3860                };
 3861                dock.activate_panel(panel_ix, window, cx);
 3862            }
 3863
 3864            if let Some(active_panel) = dock.active_panel() {
 3865                if was_visible {
 3866                    if active_panel
 3867                        .panel_focus_handle(cx)
 3868                        .contains_focused(window, cx)
 3869                    {
 3870                        focus_center = true;
 3871                    }
 3872                } else {
 3873                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3874                    window.focus(focus_handle, cx);
 3875                    reveal_dock = true;
 3876                }
 3877            }
 3878        });
 3879
 3880        if reveal_dock {
 3881            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3882        }
 3883
 3884        if focus_center {
 3885            self.active_pane
 3886                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3887        }
 3888
 3889        cx.notify();
 3890        self.serialize_workspace(window, cx);
 3891    }
 3892
 3893    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3894        self.all_docks().into_iter().find(|&dock| {
 3895            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3896        })
 3897    }
 3898
 3899    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3900        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3901            self.save_open_dock_positions(cx);
 3902            dock.update(cx, |dock, cx| {
 3903                dock.set_open(false, window, cx);
 3904            });
 3905            return true;
 3906        }
 3907        false
 3908    }
 3909
 3910    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3911        self.save_open_dock_positions(cx);
 3912        for dock in self.all_docks() {
 3913            dock.update(cx, |dock, cx| {
 3914                dock.set_open(false, window, cx);
 3915            });
 3916        }
 3917
 3918        cx.focus_self(window);
 3919        cx.notify();
 3920        self.serialize_workspace(window, cx);
 3921    }
 3922
 3923    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3924        self.all_docks()
 3925            .into_iter()
 3926            .filter_map(|dock| {
 3927                let dock_ref = dock.read(cx);
 3928                if dock_ref.is_open() {
 3929                    Some(dock_ref.position())
 3930                } else {
 3931                    None
 3932                }
 3933            })
 3934            .collect()
 3935    }
 3936
 3937    /// Saves the positions of currently open docks.
 3938    ///
 3939    /// Updates `last_open_dock_positions` with positions of all currently open
 3940    /// docks, to later be restored by the 'Toggle All Docks' action.
 3941    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3942        let open_dock_positions = self.get_open_dock_positions(cx);
 3943        if !open_dock_positions.is_empty() {
 3944            self.last_open_dock_positions = open_dock_positions;
 3945        }
 3946    }
 3947
 3948    /// Toggles all docks between open and closed states.
 3949    ///
 3950    /// If any docks are open, closes all and remembers their positions. If all
 3951    /// docks are closed, restores the last remembered dock configuration.
 3952    fn toggle_all_docks(
 3953        &mut self,
 3954        _: &ToggleAllDocks,
 3955        window: &mut Window,
 3956        cx: &mut Context<Self>,
 3957    ) {
 3958        let open_dock_positions = self.get_open_dock_positions(cx);
 3959
 3960        if !open_dock_positions.is_empty() {
 3961            self.close_all_docks(window, cx);
 3962        } else if !self.last_open_dock_positions.is_empty() {
 3963            self.restore_last_open_docks(window, cx);
 3964        }
 3965    }
 3966
 3967    /// Reopens docks from the most recently remembered configuration.
 3968    ///
 3969    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3970    /// and clears the stored positions.
 3971    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3972        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3973
 3974        for position in positions_to_open {
 3975            let dock = self.dock_at_position(position);
 3976            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3977        }
 3978
 3979        cx.focus_self(window);
 3980        cx.notify();
 3981        self.serialize_workspace(window, cx);
 3982    }
 3983
 3984    /// Transfer focus to the panel of the given type.
 3985    pub fn focus_panel<T: Panel>(
 3986        &mut self,
 3987        window: &mut Window,
 3988        cx: &mut Context<Self>,
 3989    ) -> Option<Entity<T>> {
 3990        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3991        panel.to_any().downcast().ok()
 3992    }
 3993
 3994    /// Focus the panel of the given type if it isn't already focused. If it is
 3995    /// already focused, then transfer focus back to the workspace center.
 3996    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3997    /// panel when transferring focus back to the center.
 3998    pub fn toggle_panel_focus<T: Panel>(
 3999        &mut self,
 4000        window: &mut Window,
 4001        cx: &mut Context<Self>,
 4002    ) -> bool {
 4003        let mut did_focus_panel = false;
 4004        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4005            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4006            did_focus_panel
 4007        });
 4008
 4009        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4010            self.close_panel::<T>(window, cx);
 4011        }
 4012
 4013        telemetry::event!(
 4014            "Panel Button Clicked",
 4015            name = T::persistent_name(),
 4016            toggle_state = did_focus_panel
 4017        );
 4018
 4019        did_focus_panel
 4020    }
 4021
 4022    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4023        if let Some(item) = self.active_item(cx) {
 4024            item.item_focus_handle(cx).focus(window, cx);
 4025        } else {
 4026            log::error!("Could not find a focus target when switching focus to the center panes",);
 4027        }
 4028    }
 4029
 4030    pub fn activate_panel_for_proto_id(
 4031        &mut self,
 4032        panel_id: PanelId,
 4033        window: &mut Window,
 4034        cx: &mut Context<Self>,
 4035    ) -> Option<Arc<dyn PanelHandle>> {
 4036        let mut panel = None;
 4037        for dock in self.all_docks() {
 4038            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4039                panel = dock.update(cx, |dock, cx| {
 4040                    dock.activate_panel(panel_index, window, cx);
 4041                    dock.set_open(true, window, cx);
 4042                    dock.active_panel().cloned()
 4043                });
 4044                break;
 4045            }
 4046        }
 4047
 4048        if panel.is_some() {
 4049            cx.notify();
 4050            self.serialize_workspace(window, cx);
 4051        }
 4052
 4053        panel
 4054    }
 4055
 4056    /// Focus or unfocus the given panel type, depending on the given callback.
 4057    fn focus_or_unfocus_panel<T: Panel>(
 4058        &mut self,
 4059        window: &mut Window,
 4060        cx: &mut Context<Self>,
 4061        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4062    ) -> Option<Arc<dyn PanelHandle>> {
 4063        let mut result_panel = None;
 4064        let mut serialize = false;
 4065        for dock in self.all_docks() {
 4066            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4067                let mut focus_center = false;
 4068                let panel = dock.update(cx, |dock, cx| {
 4069                    dock.activate_panel(panel_index, window, cx);
 4070
 4071                    let panel = dock.active_panel().cloned();
 4072                    if let Some(panel) = panel.as_ref() {
 4073                        if should_focus(&**panel, window, cx) {
 4074                            dock.set_open(true, window, cx);
 4075                            panel.panel_focus_handle(cx).focus(window, cx);
 4076                        } else {
 4077                            focus_center = true;
 4078                        }
 4079                    }
 4080                    panel
 4081                });
 4082
 4083                if focus_center {
 4084                    self.active_pane
 4085                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4086                }
 4087
 4088                result_panel = panel;
 4089                serialize = true;
 4090                break;
 4091            }
 4092        }
 4093
 4094        if serialize {
 4095            self.serialize_workspace(window, cx);
 4096        }
 4097
 4098        cx.notify();
 4099        result_panel
 4100    }
 4101
 4102    /// Open the panel of the given type
 4103    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4104        for dock in self.all_docks() {
 4105            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4106                dock.update(cx, |dock, cx| {
 4107                    dock.activate_panel(panel_index, window, cx);
 4108                    dock.set_open(true, window, cx);
 4109                });
 4110            }
 4111        }
 4112    }
 4113
 4114    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4115        for dock in self.all_docks().iter() {
 4116            dock.update(cx, |dock, cx| {
 4117                if dock.panel::<T>().is_some() {
 4118                    dock.set_open(false, window, cx)
 4119                }
 4120            })
 4121        }
 4122    }
 4123
 4124    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4125        self.all_docks()
 4126            .iter()
 4127            .find_map(|dock| dock.read(cx).panel::<T>())
 4128    }
 4129
 4130    fn dismiss_zoomed_items_to_reveal(
 4131        &mut self,
 4132        dock_to_reveal: Option<DockPosition>,
 4133        window: &mut Window,
 4134        cx: &mut Context<Self>,
 4135    ) {
 4136        // If a center pane is zoomed, unzoom it.
 4137        for pane in &self.panes {
 4138            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4139                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4140            }
 4141        }
 4142
 4143        // If another dock is zoomed, hide it.
 4144        let mut focus_center = false;
 4145        for dock in self.all_docks() {
 4146            dock.update(cx, |dock, cx| {
 4147                if Some(dock.position()) != dock_to_reveal
 4148                    && let Some(panel) = dock.active_panel()
 4149                    && panel.is_zoomed(window, cx)
 4150                {
 4151                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4152                    dock.set_open(false, window, cx);
 4153                }
 4154            });
 4155        }
 4156
 4157        if focus_center {
 4158            self.active_pane
 4159                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4160        }
 4161
 4162        if self.zoomed_position != dock_to_reveal {
 4163            self.zoomed = None;
 4164            self.zoomed_position = None;
 4165            cx.emit(Event::ZoomChanged);
 4166        }
 4167
 4168        cx.notify();
 4169    }
 4170
 4171    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4172        let pane = cx.new(|cx| {
 4173            let mut pane = Pane::new(
 4174                self.weak_handle(),
 4175                self.project.clone(),
 4176                self.pane_history_timestamp.clone(),
 4177                None,
 4178                NewFile.boxed_clone(),
 4179                true,
 4180                window,
 4181                cx,
 4182            );
 4183            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4184            pane
 4185        });
 4186        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4187            .detach();
 4188        self.panes.push(pane.clone());
 4189
 4190        window.focus(&pane.focus_handle(cx), cx);
 4191
 4192        cx.emit(Event::PaneAdded(pane.clone()));
 4193        pane
 4194    }
 4195
 4196    pub fn add_item_to_center(
 4197        &mut self,
 4198        item: Box<dyn ItemHandle>,
 4199        window: &mut Window,
 4200        cx: &mut Context<Self>,
 4201    ) -> bool {
 4202        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4203            if let Some(center_pane) = center_pane.upgrade() {
 4204                center_pane.update(cx, |pane, cx| {
 4205                    pane.add_item(item, true, true, None, window, cx)
 4206                });
 4207                true
 4208            } else {
 4209                false
 4210            }
 4211        } else {
 4212            false
 4213        }
 4214    }
 4215
 4216    pub fn add_item_to_active_pane(
 4217        &mut self,
 4218        item: Box<dyn ItemHandle>,
 4219        destination_index: Option<usize>,
 4220        focus_item: bool,
 4221        window: &mut Window,
 4222        cx: &mut App,
 4223    ) {
 4224        self.add_item(
 4225            self.active_pane.clone(),
 4226            item,
 4227            destination_index,
 4228            false,
 4229            focus_item,
 4230            window,
 4231            cx,
 4232        )
 4233    }
 4234
 4235    pub fn add_item(
 4236        &mut self,
 4237        pane: Entity<Pane>,
 4238        item: Box<dyn ItemHandle>,
 4239        destination_index: Option<usize>,
 4240        activate_pane: bool,
 4241        focus_item: bool,
 4242        window: &mut Window,
 4243        cx: &mut App,
 4244    ) {
 4245        pane.update(cx, |pane, cx| {
 4246            pane.add_item(
 4247                item,
 4248                activate_pane,
 4249                focus_item,
 4250                destination_index,
 4251                window,
 4252                cx,
 4253            )
 4254        });
 4255    }
 4256
 4257    pub fn split_item(
 4258        &mut self,
 4259        split_direction: SplitDirection,
 4260        item: Box<dyn ItemHandle>,
 4261        window: &mut Window,
 4262        cx: &mut Context<Self>,
 4263    ) {
 4264        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4265        self.add_item(new_pane, item, None, true, true, window, cx);
 4266    }
 4267
 4268    pub fn open_abs_path(
 4269        &mut self,
 4270        abs_path: PathBuf,
 4271        options: OpenOptions,
 4272        window: &mut Window,
 4273        cx: &mut Context<Self>,
 4274    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4275        cx.spawn_in(window, async move |workspace, cx| {
 4276            let open_paths_task_result = workspace
 4277                .update_in(cx, |workspace, window, cx| {
 4278                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4279                })
 4280                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4281                .await;
 4282            anyhow::ensure!(
 4283                open_paths_task_result.len() == 1,
 4284                "open abs path {abs_path:?} task returned incorrect number of results"
 4285            );
 4286            match open_paths_task_result
 4287                .into_iter()
 4288                .next()
 4289                .expect("ensured single task result")
 4290            {
 4291                Some(open_result) => {
 4292                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4293                }
 4294                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4295            }
 4296        })
 4297    }
 4298
 4299    pub fn split_abs_path(
 4300        &mut self,
 4301        abs_path: PathBuf,
 4302        visible: bool,
 4303        window: &mut Window,
 4304        cx: &mut Context<Self>,
 4305    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4306        let project_path_task =
 4307            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4308        cx.spawn_in(window, async move |this, cx| {
 4309            let (_, path) = project_path_task.await?;
 4310            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4311                .await
 4312        })
 4313    }
 4314
 4315    pub fn open_path(
 4316        &mut self,
 4317        path: impl Into<ProjectPath>,
 4318        pane: Option<WeakEntity<Pane>>,
 4319        focus_item: bool,
 4320        window: &mut Window,
 4321        cx: &mut App,
 4322    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4323        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4324    }
 4325
 4326    pub fn open_path_preview(
 4327        &mut self,
 4328        path: impl Into<ProjectPath>,
 4329        pane: Option<WeakEntity<Pane>>,
 4330        focus_item: bool,
 4331        allow_preview: bool,
 4332        activate: bool,
 4333        window: &mut Window,
 4334        cx: &mut App,
 4335    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4336        let pane = pane.unwrap_or_else(|| {
 4337            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4338                self.panes
 4339                    .first()
 4340                    .expect("There must be an active pane")
 4341                    .downgrade()
 4342            })
 4343        });
 4344
 4345        let project_path = path.into();
 4346        let task = self.load_path(project_path.clone(), window, cx);
 4347        window.spawn(cx, async move |cx| {
 4348            let (project_entry_id, build_item) = task.await?;
 4349
 4350            pane.update_in(cx, |pane, window, cx| {
 4351                pane.open_item(
 4352                    project_entry_id,
 4353                    project_path,
 4354                    focus_item,
 4355                    allow_preview,
 4356                    activate,
 4357                    None,
 4358                    window,
 4359                    cx,
 4360                    build_item,
 4361                )
 4362            })
 4363        })
 4364    }
 4365
 4366    pub fn split_path(
 4367        &mut self,
 4368        path: impl Into<ProjectPath>,
 4369        window: &mut Window,
 4370        cx: &mut Context<Self>,
 4371    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4372        self.split_path_preview(path, false, None, window, cx)
 4373    }
 4374
 4375    pub fn split_path_preview(
 4376        &mut self,
 4377        path: impl Into<ProjectPath>,
 4378        allow_preview: bool,
 4379        split_direction: Option<SplitDirection>,
 4380        window: &mut Window,
 4381        cx: &mut Context<Self>,
 4382    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4383        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4384            self.panes
 4385                .first()
 4386                .expect("There must be an active pane")
 4387                .downgrade()
 4388        });
 4389
 4390        if let Member::Pane(center_pane) = &self.center.root
 4391            && center_pane.read(cx).items_len() == 0
 4392        {
 4393            return self.open_path(path, Some(pane), true, window, cx);
 4394        }
 4395
 4396        let project_path = path.into();
 4397        let task = self.load_path(project_path.clone(), window, cx);
 4398        cx.spawn_in(window, async move |this, cx| {
 4399            let (project_entry_id, build_item) = task.await?;
 4400            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4401                let pane = pane.upgrade()?;
 4402                let new_pane = this.split_pane(
 4403                    pane,
 4404                    split_direction.unwrap_or(SplitDirection::Right),
 4405                    window,
 4406                    cx,
 4407                );
 4408                new_pane.update(cx, |new_pane, cx| {
 4409                    Some(new_pane.open_item(
 4410                        project_entry_id,
 4411                        project_path,
 4412                        true,
 4413                        allow_preview,
 4414                        true,
 4415                        None,
 4416                        window,
 4417                        cx,
 4418                        build_item,
 4419                    ))
 4420                })
 4421            })
 4422            .map(|option| option.context("pane was dropped"))?
 4423        })
 4424    }
 4425
 4426    fn load_path(
 4427        &mut self,
 4428        path: ProjectPath,
 4429        window: &mut Window,
 4430        cx: &mut App,
 4431    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4432        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4433        registry.open_path(self.project(), &path, window, cx)
 4434    }
 4435
 4436    pub fn find_project_item<T>(
 4437        &self,
 4438        pane: &Entity<Pane>,
 4439        project_item: &Entity<T::Item>,
 4440        cx: &App,
 4441    ) -> Option<Entity<T>>
 4442    where
 4443        T: ProjectItem,
 4444    {
 4445        use project::ProjectItem as _;
 4446        let project_item = project_item.read(cx);
 4447        let entry_id = project_item.entry_id(cx);
 4448        let project_path = project_item.project_path(cx);
 4449
 4450        let mut item = None;
 4451        if let Some(entry_id) = entry_id {
 4452            item = pane.read(cx).item_for_entry(entry_id, cx);
 4453        }
 4454        if item.is_none()
 4455            && let Some(project_path) = project_path
 4456        {
 4457            item = pane.read(cx).item_for_path(project_path, cx);
 4458        }
 4459
 4460        item.and_then(|item| item.downcast::<T>())
 4461    }
 4462
 4463    pub fn is_project_item_open<T>(
 4464        &self,
 4465        pane: &Entity<Pane>,
 4466        project_item: &Entity<T::Item>,
 4467        cx: &App,
 4468    ) -> bool
 4469    where
 4470        T: ProjectItem,
 4471    {
 4472        self.find_project_item::<T>(pane, project_item, cx)
 4473            .is_some()
 4474    }
 4475
 4476    pub fn open_project_item<T>(
 4477        &mut self,
 4478        pane: Entity<Pane>,
 4479        project_item: Entity<T::Item>,
 4480        activate_pane: bool,
 4481        focus_item: bool,
 4482        keep_old_preview: bool,
 4483        allow_new_preview: bool,
 4484        window: &mut Window,
 4485        cx: &mut Context<Self>,
 4486    ) -> Entity<T>
 4487    where
 4488        T: ProjectItem,
 4489    {
 4490        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4491
 4492        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4493            if !keep_old_preview
 4494                && let Some(old_id) = old_item_id
 4495                && old_id != item.item_id()
 4496            {
 4497                // switching to a different item, so unpreview old active item
 4498                pane.update(cx, |pane, _| {
 4499                    pane.unpreview_item_if_preview(old_id);
 4500                });
 4501            }
 4502
 4503            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4504            if !allow_new_preview {
 4505                pane.update(cx, |pane, _| {
 4506                    pane.unpreview_item_if_preview(item.item_id());
 4507                });
 4508            }
 4509            return item;
 4510        }
 4511
 4512        let item = pane.update(cx, |pane, cx| {
 4513            cx.new(|cx| {
 4514                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4515            })
 4516        });
 4517        let mut destination_index = None;
 4518        pane.update(cx, |pane, cx| {
 4519            if !keep_old_preview && let Some(old_id) = old_item_id {
 4520                pane.unpreview_item_if_preview(old_id);
 4521            }
 4522            if allow_new_preview {
 4523                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4524            }
 4525        });
 4526
 4527        self.add_item(
 4528            pane,
 4529            Box::new(item.clone()),
 4530            destination_index,
 4531            activate_pane,
 4532            focus_item,
 4533            window,
 4534            cx,
 4535        );
 4536        item
 4537    }
 4538
 4539    pub fn open_shared_screen(
 4540        &mut self,
 4541        peer_id: PeerId,
 4542        window: &mut Window,
 4543        cx: &mut Context<Self>,
 4544    ) {
 4545        if let Some(shared_screen) =
 4546            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4547        {
 4548            self.active_pane.update(cx, |pane, cx| {
 4549                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4550            });
 4551        }
 4552    }
 4553
 4554    pub fn activate_item(
 4555        &mut self,
 4556        item: &dyn ItemHandle,
 4557        activate_pane: bool,
 4558        focus_item: bool,
 4559        window: &mut Window,
 4560        cx: &mut App,
 4561    ) -> bool {
 4562        let result = self.panes.iter().find_map(|pane| {
 4563            pane.read(cx)
 4564                .index_for_item(item)
 4565                .map(|ix| (pane.clone(), ix))
 4566        });
 4567        if let Some((pane, ix)) = result {
 4568            pane.update(cx, |pane, cx| {
 4569                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4570            });
 4571            true
 4572        } else {
 4573            false
 4574        }
 4575    }
 4576
 4577    fn activate_pane_at_index(
 4578        &mut self,
 4579        action: &ActivatePane,
 4580        window: &mut Window,
 4581        cx: &mut Context<Self>,
 4582    ) {
 4583        let panes = self.center.panes();
 4584        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4585            window.focus(&pane.focus_handle(cx), cx);
 4586        } else {
 4587            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4588                .detach();
 4589        }
 4590    }
 4591
 4592    fn move_item_to_pane_at_index(
 4593        &mut self,
 4594        action: &MoveItemToPane,
 4595        window: &mut Window,
 4596        cx: &mut Context<Self>,
 4597    ) {
 4598        let panes = self.center.panes();
 4599        let destination = match panes.get(action.destination) {
 4600            Some(&destination) => destination.clone(),
 4601            None => {
 4602                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4603                    return;
 4604                }
 4605                let direction = SplitDirection::Right;
 4606                let split_off_pane = self
 4607                    .find_pane_in_direction(direction, cx)
 4608                    .unwrap_or_else(|| self.active_pane.clone());
 4609                let new_pane = self.add_pane(window, cx);
 4610                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4611                new_pane
 4612            }
 4613        };
 4614
 4615        if action.clone {
 4616            if self
 4617                .active_pane
 4618                .read(cx)
 4619                .active_item()
 4620                .is_some_and(|item| item.can_split(cx))
 4621            {
 4622                clone_active_item(
 4623                    self.database_id(),
 4624                    &self.active_pane,
 4625                    &destination,
 4626                    action.focus,
 4627                    window,
 4628                    cx,
 4629                );
 4630                return;
 4631            }
 4632        }
 4633        move_active_item(
 4634            &self.active_pane,
 4635            &destination,
 4636            action.focus,
 4637            true,
 4638            window,
 4639            cx,
 4640        )
 4641    }
 4642
 4643    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4644        let panes = self.center.panes();
 4645        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4646            let next_ix = (ix + 1) % panes.len();
 4647            let next_pane = panes[next_ix].clone();
 4648            window.focus(&next_pane.focus_handle(cx), cx);
 4649        }
 4650    }
 4651
 4652    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4653        let panes = self.center.panes();
 4654        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4655            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4656            let prev_pane = panes[prev_ix].clone();
 4657            window.focus(&prev_pane.focus_handle(cx), cx);
 4658        }
 4659    }
 4660
 4661    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4662        let last_pane = self.center.last_pane();
 4663        window.focus(&last_pane.focus_handle(cx), cx);
 4664    }
 4665
 4666    pub fn activate_pane_in_direction(
 4667        &mut self,
 4668        direction: SplitDirection,
 4669        window: &mut Window,
 4670        cx: &mut App,
 4671    ) {
 4672        use ActivateInDirectionTarget as Target;
 4673        enum Origin {
 4674            Sidebar,
 4675            LeftDock,
 4676            RightDock,
 4677            BottomDock,
 4678            Center,
 4679        }
 4680
 4681        let origin: Origin = if self
 4682            .sidebar_focus_handle
 4683            .as_ref()
 4684            .is_some_and(|h| h.contains_focused(window, cx))
 4685        {
 4686            Origin::Sidebar
 4687        } else {
 4688            [
 4689                (&self.left_dock, Origin::LeftDock),
 4690                (&self.right_dock, Origin::RightDock),
 4691                (&self.bottom_dock, Origin::BottomDock),
 4692            ]
 4693            .into_iter()
 4694            .find_map(|(dock, origin)| {
 4695                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4696                    Some(origin)
 4697                } else {
 4698                    None
 4699                }
 4700            })
 4701            .unwrap_or(Origin::Center)
 4702        };
 4703
 4704        let get_last_active_pane = || {
 4705            let pane = self
 4706                .last_active_center_pane
 4707                .clone()
 4708                .unwrap_or_else(|| {
 4709                    self.panes
 4710                        .first()
 4711                        .expect("There must be an active pane")
 4712                        .downgrade()
 4713                })
 4714                .upgrade()?;
 4715            (pane.read(cx).items_len() != 0).then_some(pane)
 4716        };
 4717
 4718        let try_dock =
 4719            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4720
 4721        let sidebar_target = self
 4722            .sidebar_focus_handle
 4723            .as_ref()
 4724            .map(|h| Target::Sidebar(h.clone()));
 4725
 4726        let target = match (origin, direction) {
 4727            // From the sidebar, only Right navigates into the workspace.
 4728            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4729                .or_else(|| get_last_active_pane().map(Target::Pane))
 4730                .or_else(|| try_dock(&self.bottom_dock))
 4731                .or_else(|| try_dock(&self.right_dock)),
 4732
 4733            (Origin::Sidebar, _) => None,
 4734
 4735            // We're in the center, so we first try to go to a different pane,
 4736            // otherwise try to go to a dock.
 4737            (Origin::Center, direction) => {
 4738                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4739                    Some(Target::Pane(pane))
 4740                } else {
 4741                    match direction {
 4742                        SplitDirection::Up => None,
 4743                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4744                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4745                        SplitDirection::Right => try_dock(&self.right_dock),
 4746                    }
 4747                }
 4748            }
 4749
 4750            (Origin::LeftDock, SplitDirection::Right) => {
 4751                if let Some(last_active_pane) = get_last_active_pane() {
 4752                    Some(Target::Pane(last_active_pane))
 4753                } else {
 4754                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4755                }
 4756            }
 4757
 4758            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4759
 4760            (Origin::LeftDock, SplitDirection::Down)
 4761            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4762
 4763            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4764            (Origin::BottomDock, SplitDirection::Left) => {
 4765                try_dock(&self.left_dock).or(sidebar_target)
 4766            }
 4767            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4768
 4769            (Origin::RightDock, SplitDirection::Left) => {
 4770                if let Some(last_active_pane) = get_last_active_pane() {
 4771                    Some(Target::Pane(last_active_pane))
 4772                } else {
 4773                    try_dock(&self.bottom_dock)
 4774                        .or_else(|| try_dock(&self.left_dock))
 4775                        .or(sidebar_target)
 4776                }
 4777            }
 4778
 4779            _ => None,
 4780        };
 4781
 4782        match target {
 4783            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4784                let pane = pane.read(cx);
 4785                if let Some(item) = pane.active_item() {
 4786                    item.item_focus_handle(cx).focus(window, cx);
 4787                } else {
 4788                    log::error!(
 4789                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4790                    );
 4791                }
 4792            }
 4793            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4794                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4795                window.defer(cx, move |window, cx| {
 4796                    let dock = dock.read(cx);
 4797                    if let Some(panel) = dock.active_panel() {
 4798                        panel.panel_focus_handle(cx).focus(window, cx);
 4799                    } else {
 4800                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4801                    }
 4802                })
 4803            }
 4804            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4805                focus_handle.focus(window, cx);
 4806            }
 4807            None => {}
 4808        }
 4809    }
 4810
 4811    pub fn move_item_to_pane_in_direction(
 4812        &mut self,
 4813        action: &MoveItemToPaneInDirection,
 4814        window: &mut Window,
 4815        cx: &mut Context<Self>,
 4816    ) {
 4817        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4818            Some(destination) => destination,
 4819            None => {
 4820                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4821                    return;
 4822                }
 4823                let new_pane = self.add_pane(window, cx);
 4824                self.center
 4825                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4826                new_pane
 4827            }
 4828        };
 4829
 4830        if action.clone {
 4831            if self
 4832                .active_pane
 4833                .read(cx)
 4834                .active_item()
 4835                .is_some_and(|item| item.can_split(cx))
 4836            {
 4837                clone_active_item(
 4838                    self.database_id(),
 4839                    &self.active_pane,
 4840                    &destination,
 4841                    action.focus,
 4842                    window,
 4843                    cx,
 4844                );
 4845                return;
 4846            }
 4847        }
 4848        move_active_item(
 4849            &self.active_pane,
 4850            &destination,
 4851            action.focus,
 4852            true,
 4853            window,
 4854            cx,
 4855        );
 4856    }
 4857
 4858    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4859        self.center.bounding_box_for_pane(pane)
 4860    }
 4861
 4862    pub fn find_pane_in_direction(
 4863        &mut self,
 4864        direction: SplitDirection,
 4865        cx: &App,
 4866    ) -> Option<Entity<Pane>> {
 4867        self.center
 4868            .find_pane_in_direction(&self.active_pane, direction, cx)
 4869            .cloned()
 4870    }
 4871
 4872    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4873        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4874            self.center.swap(&self.active_pane, &to, cx);
 4875            cx.notify();
 4876        }
 4877    }
 4878
 4879    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4880        if self
 4881            .center
 4882            .move_to_border(&self.active_pane, direction, cx)
 4883            .unwrap()
 4884        {
 4885            cx.notify();
 4886        }
 4887    }
 4888
 4889    pub fn resize_pane(
 4890        &mut self,
 4891        axis: gpui::Axis,
 4892        amount: Pixels,
 4893        window: &mut Window,
 4894        cx: &mut Context<Self>,
 4895    ) {
 4896        let docks = self.all_docks();
 4897        let active_dock = docks
 4898            .into_iter()
 4899            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4900
 4901        if let Some(dock_entity) = active_dock {
 4902            let dock = dock_entity.read(cx);
 4903            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 4904                return;
 4905            };
 4906            match dock.position() {
 4907                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4908                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4909                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4910            }
 4911        } else {
 4912            self.center
 4913                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4914        }
 4915        cx.notify();
 4916    }
 4917
 4918    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4919        self.center.reset_pane_sizes(cx);
 4920        cx.notify();
 4921    }
 4922
 4923    fn handle_pane_focused(
 4924        &mut self,
 4925        pane: Entity<Pane>,
 4926        window: &mut Window,
 4927        cx: &mut Context<Self>,
 4928    ) {
 4929        // This is explicitly hoisted out of the following check for pane identity as
 4930        // terminal panel panes are not registered as a center panes.
 4931        self.status_bar.update(cx, |status_bar, cx| {
 4932            status_bar.set_active_pane(&pane, window, cx);
 4933        });
 4934        if self.active_pane != pane {
 4935            self.set_active_pane(&pane, window, cx);
 4936        }
 4937
 4938        if self.last_active_center_pane.is_none() {
 4939            self.last_active_center_pane = Some(pane.downgrade());
 4940        }
 4941
 4942        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4943        // This prevents the dock from closing when focus events fire during window activation.
 4944        // We also preserve any dock whose active panel itself has focus — this covers
 4945        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4946        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4947            let dock_read = dock.read(cx);
 4948            if let Some(panel) = dock_read.active_panel() {
 4949                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4950                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4951                {
 4952                    return Some(dock_read.position());
 4953                }
 4954            }
 4955            None
 4956        });
 4957
 4958        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4959        if pane.read(cx).is_zoomed() {
 4960            self.zoomed = Some(pane.downgrade().into());
 4961        } else {
 4962            self.zoomed = None;
 4963        }
 4964        self.zoomed_position = None;
 4965        cx.emit(Event::ZoomChanged);
 4966        self.update_active_view_for_followers(window, cx);
 4967        pane.update(cx, |pane, _| {
 4968            pane.track_alternate_file_items();
 4969        });
 4970
 4971        cx.notify();
 4972    }
 4973
 4974    fn set_active_pane(
 4975        &mut self,
 4976        pane: &Entity<Pane>,
 4977        window: &mut Window,
 4978        cx: &mut Context<Self>,
 4979    ) {
 4980        self.active_pane = pane.clone();
 4981        self.active_item_path_changed(true, window, cx);
 4982        self.last_active_center_pane = Some(pane.downgrade());
 4983    }
 4984
 4985    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4986        self.update_active_view_for_followers(window, cx);
 4987    }
 4988
 4989    fn handle_pane_event(
 4990        &mut self,
 4991        pane: &Entity<Pane>,
 4992        event: &pane::Event,
 4993        window: &mut Window,
 4994        cx: &mut Context<Self>,
 4995    ) {
 4996        let mut serialize_workspace = true;
 4997        match event {
 4998            pane::Event::AddItem { item } => {
 4999                item.added_to_pane(self, pane.clone(), window, cx);
 5000                cx.emit(Event::ItemAdded {
 5001                    item: item.boxed_clone(),
 5002                });
 5003            }
 5004            pane::Event::Split { direction, mode } => {
 5005                match mode {
 5006                    SplitMode::ClonePane => {
 5007                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5008                            .detach();
 5009                    }
 5010                    SplitMode::EmptyPane => {
 5011                        self.split_pane(pane.clone(), *direction, window, cx);
 5012                    }
 5013                    SplitMode::MovePane => {
 5014                        self.split_and_move(pane.clone(), *direction, window, cx);
 5015                    }
 5016                };
 5017            }
 5018            pane::Event::JoinIntoNext => {
 5019                self.join_pane_into_next(pane.clone(), window, cx);
 5020            }
 5021            pane::Event::JoinAll => {
 5022                self.join_all_panes(window, cx);
 5023            }
 5024            pane::Event::Remove { focus_on_pane } => {
 5025                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5026            }
 5027            pane::Event::ActivateItem {
 5028                local,
 5029                focus_changed,
 5030            } => {
 5031                window.invalidate_character_coordinates();
 5032
 5033                pane.update(cx, |pane, _| {
 5034                    pane.track_alternate_file_items();
 5035                });
 5036                if *local {
 5037                    self.unfollow_in_pane(pane, window, cx);
 5038                }
 5039                serialize_workspace = *focus_changed || pane != self.active_pane();
 5040                if pane == self.active_pane() {
 5041                    self.active_item_path_changed(*focus_changed, window, cx);
 5042                    self.update_active_view_for_followers(window, cx);
 5043                } else if *local {
 5044                    self.set_active_pane(pane, window, cx);
 5045                }
 5046            }
 5047            pane::Event::UserSavedItem { item, save_intent } => {
 5048                cx.emit(Event::UserSavedItem {
 5049                    pane: pane.downgrade(),
 5050                    item: item.boxed_clone(),
 5051                    save_intent: *save_intent,
 5052                });
 5053                serialize_workspace = false;
 5054            }
 5055            pane::Event::ChangeItemTitle => {
 5056                if *pane == self.active_pane {
 5057                    self.active_item_path_changed(false, window, cx);
 5058                }
 5059                serialize_workspace = false;
 5060            }
 5061            pane::Event::RemovedItem { item } => {
 5062                cx.emit(Event::ActiveItemChanged);
 5063                self.update_window_edited(window, cx);
 5064                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5065                    && entry.get().entity_id() == pane.entity_id()
 5066                {
 5067                    entry.remove();
 5068                }
 5069                cx.emit(Event::ItemRemoved {
 5070                    item_id: item.item_id(),
 5071                });
 5072            }
 5073            pane::Event::Focus => {
 5074                window.invalidate_character_coordinates();
 5075                self.handle_pane_focused(pane.clone(), window, cx);
 5076            }
 5077            pane::Event::ZoomIn => {
 5078                if *pane == self.active_pane {
 5079                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5080                    if pane.read(cx).has_focus(window, cx) {
 5081                        self.zoomed = Some(pane.downgrade().into());
 5082                        self.zoomed_position = None;
 5083                        cx.emit(Event::ZoomChanged);
 5084                    }
 5085                    cx.notify();
 5086                }
 5087            }
 5088            pane::Event::ZoomOut => {
 5089                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5090                if self.zoomed_position.is_none() {
 5091                    self.zoomed = None;
 5092                    cx.emit(Event::ZoomChanged);
 5093                }
 5094                cx.notify();
 5095            }
 5096            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5097        }
 5098
 5099        if serialize_workspace {
 5100            self.serialize_workspace(window, cx);
 5101        }
 5102    }
 5103
 5104    pub fn unfollow_in_pane(
 5105        &mut self,
 5106        pane: &Entity<Pane>,
 5107        window: &mut Window,
 5108        cx: &mut Context<Workspace>,
 5109    ) -> Option<CollaboratorId> {
 5110        let leader_id = self.leader_for_pane(pane)?;
 5111        self.unfollow(leader_id, window, cx);
 5112        Some(leader_id)
 5113    }
 5114
 5115    pub fn split_pane(
 5116        &mut self,
 5117        pane_to_split: Entity<Pane>,
 5118        split_direction: SplitDirection,
 5119        window: &mut Window,
 5120        cx: &mut Context<Self>,
 5121    ) -> Entity<Pane> {
 5122        let new_pane = self.add_pane(window, cx);
 5123        self.center
 5124            .split(&pane_to_split, &new_pane, split_direction, cx);
 5125        cx.notify();
 5126        new_pane
 5127    }
 5128
 5129    pub fn split_and_move(
 5130        &mut self,
 5131        pane: Entity<Pane>,
 5132        direction: SplitDirection,
 5133        window: &mut Window,
 5134        cx: &mut Context<Self>,
 5135    ) {
 5136        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5137            return;
 5138        };
 5139        let new_pane = self.add_pane(window, cx);
 5140        new_pane.update(cx, |pane, cx| {
 5141            pane.add_item(item, true, true, None, window, cx)
 5142        });
 5143        self.center.split(&pane, &new_pane, direction, cx);
 5144        cx.notify();
 5145    }
 5146
 5147    pub fn split_and_clone(
 5148        &mut self,
 5149        pane: Entity<Pane>,
 5150        direction: SplitDirection,
 5151        window: &mut Window,
 5152        cx: &mut Context<Self>,
 5153    ) -> Task<Option<Entity<Pane>>> {
 5154        let Some(item) = pane.read(cx).active_item() else {
 5155            return Task::ready(None);
 5156        };
 5157        if !item.can_split(cx) {
 5158            return Task::ready(None);
 5159        }
 5160        let task = item.clone_on_split(self.database_id(), window, cx);
 5161        cx.spawn_in(window, async move |this, cx| {
 5162            if let Some(clone) = task.await {
 5163                this.update_in(cx, |this, window, cx| {
 5164                    let new_pane = this.add_pane(window, cx);
 5165                    let nav_history = pane.read(cx).fork_nav_history();
 5166                    new_pane.update(cx, |pane, cx| {
 5167                        pane.set_nav_history(nav_history, cx);
 5168                        pane.add_item(clone, true, true, None, window, cx)
 5169                    });
 5170                    this.center.split(&pane, &new_pane, direction, cx);
 5171                    cx.notify();
 5172                    new_pane
 5173                })
 5174                .ok()
 5175            } else {
 5176                None
 5177            }
 5178        })
 5179    }
 5180
 5181    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5182        let active_item = self.active_pane.read(cx).active_item();
 5183        for pane in &self.panes {
 5184            join_pane_into_active(&self.active_pane, pane, window, cx);
 5185        }
 5186        if let Some(active_item) = active_item {
 5187            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5188        }
 5189        cx.notify();
 5190    }
 5191
 5192    pub fn join_pane_into_next(
 5193        &mut self,
 5194        pane: Entity<Pane>,
 5195        window: &mut Window,
 5196        cx: &mut Context<Self>,
 5197    ) {
 5198        let next_pane = self
 5199            .find_pane_in_direction(SplitDirection::Right, cx)
 5200            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5201            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5202            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5203        let Some(next_pane) = next_pane else {
 5204            return;
 5205        };
 5206        move_all_items(&pane, &next_pane, window, cx);
 5207        cx.notify();
 5208    }
 5209
 5210    fn remove_pane(
 5211        &mut self,
 5212        pane: Entity<Pane>,
 5213        focus_on: Option<Entity<Pane>>,
 5214        window: &mut Window,
 5215        cx: &mut Context<Self>,
 5216    ) {
 5217        if self.center.remove(&pane, cx).unwrap() {
 5218            self.force_remove_pane(&pane, &focus_on, window, cx);
 5219            self.unfollow_in_pane(&pane, window, cx);
 5220            self.last_leaders_by_pane.remove(&pane.downgrade());
 5221            for removed_item in pane.read(cx).items() {
 5222                self.panes_by_item.remove(&removed_item.item_id());
 5223            }
 5224
 5225            cx.notify();
 5226        } else {
 5227            self.active_item_path_changed(true, window, cx);
 5228        }
 5229        cx.emit(Event::PaneRemoved);
 5230    }
 5231
 5232    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5233        &mut self.panes
 5234    }
 5235
 5236    pub fn panes(&self) -> &[Entity<Pane>] {
 5237        &self.panes
 5238    }
 5239
 5240    pub fn active_pane(&self) -> &Entity<Pane> {
 5241        &self.active_pane
 5242    }
 5243
 5244    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5245        for dock in self.all_docks() {
 5246            if dock.focus_handle(cx).contains_focused(window, cx)
 5247                && let Some(pane) = dock
 5248                    .read(cx)
 5249                    .active_panel()
 5250                    .and_then(|panel| panel.pane(cx))
 5251            {
 5252                return pane;
 5253            }
 5254        }
 5255        self.active_pane().clone()
 5256    }
 5257
 5258    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5259        self.find_pane_in_direction(SplitDirection::Right, cx)
 5260            .unwrap_or_else(|| {
 5261                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5262            })
 5263    }
 5264
 5265    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5266        self.pane_for_item_id(handle.item_id())
 5267    }
 5268
 5269    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5270        let weak_pane = self.panes_by_item.get(&item_id)?;
 5271        weak_pane.upgrade()
 5272    }
 5273
 5274    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5275        self.panes
 5276            .iter()
 5277            .find(|pane| pane.entity_id() == entity_id)
 5278            .cloned()
 5279    }
 5280
 5281    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5282        self.follower_states.retain(|leader_id, state| {
 5283            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5284                for item in state.items_by_leader_view_id.values() {
 5285                    item.view.set_leader_id(None, window, cx);
 5286                }
 5287                false
 5288            } else {
 5289                true
 5290            }
 5291        });
 5292        cx.notify();
 5293    }
 5294
 5295    pub fn start_following(
 5296        &mut self,
 5297        leader_id: impl Into<CollaboratorId>,
 5298        window: &mut Window,
 5299        cx: &mut Context<Self>,
 5300    ) -> Option<Task<Result<()>>> {
 5301        let leader_id = leader_id.into();
 5302        let pane = self.active_pane().clone();
 5303
 5304        self.last_leaders_by_pane
 5305            .insert(pane.downgrade(), leader_id);
 5306        self.unfollow(leader_id, window, cx);
 5307        self.unfollow_in_pane(&pane, window, cx);
 5308        self.follower_states.insert(
 5309            leader_id,
 5310            FollowerState {
 5311                center_pane: pane.clone(),
 5312                dock_pane: None,
 5313                active_view_id: None,
 5314                items_by_leader_view_id: Default::default(),
 5315            },
 5316        );
 5317        cx.notify();
 5318
 5319        match leader_id {
 5320            CollaboratorId::PeerId(leader_peer_id) => {
 5321                let room_id = self.active_call()?.room_id(cx)?;
 5322                let project_id = self.project.read(cx).remote_id();
 5323                let request = self.app_state.client.request(proto::Follow {
 5324                    room_id,
 5325                    project_id,
 5326                    leader_id: Some(leader_peer_id),
 5327                });
 5328
 5329                Some(cx.spawn_in(window, async move |this, cx| {
 5330                    let response = request.await?;
 5331                    this.update(cx, |this, _| {
 5332                        let state = this
 5333                            .follower_states
 5334                            .get_mut(&leader_id)
 5335                            .context("following interrupted")?;
 5336                        state.active_view_id = response
 5337                            .active_view
 5338                            .as_ref()
 5339                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5340                        anyhow::Ok(())
 5341                    })??;
 5342                    if let Some(view) = response.active_view {
 5343                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5344                    }
 5345                    this.update_in(cx, |this, window, cx| {
 5346                        this.leader_updated(leader_id, window, cx)
 5347                    })?;
 5348                    Ok(())
 5349                }))
 5350            }
 5351            CollaboratorId::Agent => {
 5352                self.leader_updated(leader_id, window, cx)?;
 5353                Some(Task::ready(Ok(())))
 5354            }
 5355        }
 5356    }
 5357
 5358    pub fn follow_next_collaborator(
 5359        &mut self,
 5360        _: &FollowNextCollaborator,
 5361        window: &mut Window,
 5362        cx: &mut Context<Self>,
 5363    ) {
 5364        let collaborators = self.project.read(cx).collaborators();
 5365        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5366            let mut collaborators = collaborators.keys().copied();
 5367            for peer_id in collaborators.by_ref() {
 5368                if CollaboratorId::PeerId(peer_id) == leader_id {
 5369                    break;
 5370                }
 5371            }
 5372            collaborators.next().map(CollaboratorId::PeerId)
 5373        } else if let Some(last_leader_id) =
 5374            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5375        {
 5376            match last_leader_id {
 5377                CollaboratorId::PeerId(peer_id) => {
 5378                    if collaborators.contains_key(peer_id) {
 5379                        Some(*last_leader_id)
 5380                    } else {
 5381                        None
 5382                    }
 5383                }
 5384                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5385            }
 5386        } else {
 5387            None
 5388        };
 5389
 5390        let pane = self.active_pane.clone();
 5391        let Some(leader_id) = next_leader_id.or_else(|| {
 5392            Some(CollaboratorId::PeerId(
 5393                collaborators.keys().copied().next()?,
 5394            ))
 5395        }) else {
 5396            return;
 5397        };
 5398        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5399            return;
 5400        }
 5401        if let Some(task) = self.start_following(leader_id, window, cx) {
 5402            task.detach_and_log_err(cx)
 5403        }
 5404    }
 5405
 5406    pub fn follow(
 5407        &mut self,
 5408        leader_id: impl Into<CollaboratorId>,
 5409        window: &mut Window,
 5410        cx: &mut Context<Self>,
 5411    ) {
 5412        let leader_id = leader_id.into();
 5413
 5414        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5415            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5416                return;
 5417            };
 5418            let Some(remote_participant) =
 5419                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5420            else {
 5421                return;
 5422            };
 5423
 5424            let project = self.project.read(cx);
 5425
 5426            let other_project_id = match remote_participant.location {
 5427                ParticipantLocation::External => None,
 5428                ParticipantLocation::UnsharedProject => None,
 5429                ParticipantLocation::SharedProject { project_id } => {
 5430                    if Some(project_id) == project.remote_id() {
 5431                        None
 5432                    } else {
 5433                        Some(project_id)
 5434                    }
 5435                }
 5436            };
 5437
 5438            // if they are active in another project, follow there.
 5439            if let Some(project_id) = other_project_id {
 5440                let app_state = self.app_state.clone();
 5441                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5442                    .detach_and_log_err(cx);
 5443            }
 5444        }
 5445
 5446        // if you're already following, find the right pane and focus it.
 5447        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5448            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5449
 5450            return;
 5451        }
 5452
 5453        // Otherwise, follow.
 5454        if let Some(task) = self.start_following(leader_id, window, cx) {
 5455            task.detach_and_log_err(cx)
 5456        }
 5457    }
 5458
 5459    pub fn unfollow(
 5460        &mut self,
 5461        leader_id: impl Into<CollaboratorId>,
 5462        window: &mut Window,
 5463        cx: &mut Context<Self>,
 5464    ) -> Option<()> {
 5465        cx.notify();
 5466
 5467        let leader_id = leader_id.into();
 5468        let state = self.follower_states.remove(&leader_id)?;
 5469        for (_, item) in state.items_by_leader_view_id {
 5470            item.view.set_leader_id(None, window, cx);
 5471        }
 5472
 5473        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5474            let project_id = self.project.read(cx).remote_id();
 5475            let room_id = self.active_call()?.room_id(cx)?;
 5476            self.app_state
 5477                .client
 5478                .send(proto::Unfollow {
 5479                    room_id,
 5480                    project_id,
 5481                    leader_id: Some(leader_peer_id),
 5482                })
 5483                .log_err();
 5484        }
 5485
 5486        Some(())
 5487    }
 5488
 5489    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5490        self.follower_states.contains_key(&id.into())
 5491    }
 5492
 5493    fn active_item_path_changed(
 5494        &mut self,
 5495        focus_changed: bool,
 5496        window: &mut Window,
 5497        cx: &mut Context<Self>,
 5498    ) {
 5499        cx.emit(Event::ActiveItemChanged);
 5500        let active_entry = self.active_project_path(cx);
 5501        self.project.update(cx, |project, cx| {
 5502            project.set_active_path(active_entry.clone(), cx)
 5503        });
 5504
 5505        if focus_changed && let Some(project_path) = &active_entry {
 5506            let git_store_entity = self.project.read(cx).git_store().clone();
 5507            git_store_entity.update(cx, |git_store, cx| {
 5508                git_store.set_active_repo_for_path(project_path, cx);
 5509            });
 5510        }
 5511
 5512        self.update_window_title(window, cx);
 5513    }
 5514
 5515    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5516        let project = self.project().read(cx);
 5517        let mut title = String::new();
 5518
 5519        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5520            let name = {
 5521                let settings_location = SettingsLocation {
 5522                    worktree_id: worktree.read(cx).id(),
 5523                    path: RelPath::empty(),
 5524                };
 5525
 5526                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5527                match &settings.project_name {
 5528                    Some(name) => name.as_str(),
 5529                    None => worktree.read(cx).root_name_str(),
 5530                }
 5531            };
 5532            if i > 0 {
 5533                title.push_str(", ");
 5534            }
 5535            title.push_str(name);
 5536        }
 5537
 5538        if title.is_empty() {
 5539            title = "empty project".to_string();
 5540        }
 5541
 5542        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5543            let filename = path.path.file_name().or_else(|| {
 5544                Some(
 5545                    project
 5546                        .worktree_for_id(path.worktree_id, cx)?
 5547                        .read(cx)
 5548                        .root_name_str(),
 5549                )
 5550            });
 5551
 5552            if let Some(filename) = filename {
 5553                title.push_str("");
 5554                title.push_str(filename.as_ref());
 5555            }
 5556        }
 5557
 5558        if project.is_via_collab() {
 5559            title.push_str("");
 5560        } else if project.is_shared() {
 5561            title.push_str("");
 5562        }
 5563
 5564        if let Some(last_title) = self.last_window_title.as_ref()
 5565            && &title == last_title
 5566        {
 5567            return;
 5568        }
 5569        window.set_window_title(&title);
 5570        SystemWindowTabController::update_tab_title(
 5571            cx,
 5572            window.window_handle().window_id(),
 5573            SharedString::from(&title),
 5574        );
 5575        self.last_window_title = Some(title);
 5576    }
 5577
 5578    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5579        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5580        if is_edited != self.window_edited {
 5581            self.window_edited = is_edited;
 5582            window.set_window_edited(self.window_edited)
 5583        }
 5584    }
 5585
 5586    fn update_item_dirty_state(
 5587        &mut self,
 5588        item: &dyn ItemHandle,
 5589        window: &mut Window,
 5590        cx: &mut App,
 5591    ) {
 5592        let is_dirty = item.is_dirty(cx);
 5593        let item_id = item.item_id();
 5594        let was_dirty = self.dirty_items.contains_key(&item_id);
 5595        if is_dirty == was_dirty {
 5596            return;
 5597        }
 5598        if was_dirty {
 5599            self.dirty_items.remove(&item_id);
 5600            self.update_window_edited(window, cx);
 5601            return;
 5602        }
 5603
 5604        let workspace = self.weak_handle();
 5605        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5606            return;
 5607        };
 5608        let on_release_callback = Box::new(move |cx: &mut App| {
 5609            window_handle
 5610                .update(cx, |_, window, cx| {
 5611                    workspace
 5612                        .update(cx, |workspace, cx| {
 5613                            workspace.dirty_items.remove(&item_id);
 5614                            workspace.update_window_edited(window, cx)
 5615                        })
 5616                        .ok();
 5617                })
 5618                .ok();
 5619        });
 5620
 5621        let s = item.on_release(cx, on_release_callback);
 5622        self.dirty_items.insert(item_id, s);
 5623        self.update_window_edited(window, cx);
 5624    }
 5625
 5626    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5627        if self.notifications.is_empty() {
 5628            None
 5629        } else {
 5630            Some(
 5631                div()
 5632                    .absolute()
 5633                    .right_3()
 5634                    .bottom_3()
 5635                    .w_112()
 5636                    .h_full()
 5637                    .flex()
 5638                    .flex_col()
 5639                    .justify_end()
 5640                    .gap_2()
 5641                    .children(
 5642                        self.notifications
 5643                            .iter()
 5644                            .map(|(_, notification)| notification.clone().into_any()),
 5645                    ),
 5646            )
 5647        }
 5648    }
 5649
 5650    // RPC handlers
 5651
 5652    fn active_view_for_follower(
 5653        &self,
 5654        follower_project_id: Option<u64>,
 5655        window: &mut Window,
 5656        cx: &mut Context<Self>,
 5657    ) -> Option<proto::View> {
 5658        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5659        let item = item?;
 5660        let leader_id = self
 5661            .pane_for(&*item)
 5662            .and_then(|pane| self.leader_for_pane(&pane));
 5663        let leader_peer_id = match leader_id {
 5664            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5665            Some(CollaboratorId::Agent) | None => None,
 5666        };
 5667
 5668        let item_handle = item.to_followable_item_handle(cx)?;
 5669        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5670        let variant = item_handle.to_state_proto(window, cx)?;
 5671
 5672        if item_handle.is_project_item(window, cx)
 5673            && (follower_project_id.is_none()
 5674                || follower_project_id != self.project.read(cx).remote_id())
 5675        {
 5676            return None;
 5677        }
 5678
 5679        Some(proto::View {
 5680            id: id.to_proto(),
 5681            leader_id: leader_peer_id,
 5682            variant: Some(variant),
 5683            panel_id: panel_id.map(|id| id as i32),
 5684        })
 5685    }
 5686
 5687    fn handle_follow(
 5688        &mut self,
 5689        follower_project_id: Option<u64>,
 5690        window: &mut Window,
 5691        cx: &mut Context<Self>,
 5692    ) -> proto::FollowResponse {
 5693        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5694
 5695        cx.notify();
 5696        proto::FollowResponse {
 5697            views: active_view.iter().cloned().collect(),
 5698            active_view,
 5699        }
 5700    }
 5701
 5702    fn handle_update_followers(
 5703        &mut self,
 5704        leader_id: PeerId,
 5705        message: proto::UpdateFollowers,
 5706        _window: &mut Window,
 5707        _cx: &mut Context<Self>,
 5708    ) {
 5709        self.leader_updates_tx
 5710            .unbounded_send((leader_id, message))
 5711            .ok();
 5712    }
 5713
 5714    async fn process_leader_update(
 5715        this: &WeakEntity<Self>,
 5716        leader_id: PeerId,
 5717        update: proto::UpdateFollowers,
 5718        cx: &mut AsyncWindowContext,
 5719    ) -> Result<()> {
 5720        match update.variant.context("invalid update")? {
 5721            proto::update_followers::Variant::CreateView(view) => {
 5722                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5723                let should_add_view = this.update(cx, |this, _| {
 5724                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5725                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5726                    } else {
 5727                        anyhow::Ok(false)
 5728                    }
 5729                })??;
 5730
 5731                if should_add_view {
 5732                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5733                }
 5734            }
 5735            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5736                let should_add_view = this.update(cx, |this, _| {
 5737                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5738                        state.active_view_id = update_active_view
 5739                            .view
 5740                            .as_ref()
 5741                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5742
 5743                        if state.active_view_id.is_some_and(|view_id| {
 5744                            !state.items_by_leader_view_id.contains_key(&view_id)
 5745                        }) {
 5746                            anyhow::Ok(true)
 5747                        } else {
 5748                            anyhow::Ok(false)
 5749                        }
 5750                    } else {
 5751                        anyhow::Ok(false)
 5752                    }
 5753                })??;
 5754
 5755                if should_add_view && let Some(view) = update_active_view.view {
 5756                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5757                }
 5758            }
 5759            proto::update_followers::Variant::UpdateView(update_view) => {
 5760                let variant = update_view.variant.context("missing update view variant")?;
 5761                let id = update_view.id.context("missing update view id")?;
 5762                let mut tasks = Vec::new();
 5763                this.update_in(cx, |this, window, cx| {
 5764                    let project = this.project.clone();
 5765                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5766                        let view_id = ViewId::from_proto(id.clone())?;
 5767                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5768                            tasks.push(item.view.apply_update_proto(
 5769                                &project,
 5770                                variant.clone(),
 5771                                window,
 5772                                cx,
 5773                            ));
 5774                        }
 5775                    }
 5776                    anyhow::Ok(())
 5777                })??;
 5778                try_join_all(tasks).await.log_err();
 5779            }
 5780        }
 5781        this.update_in(cx, |this, window, cx| {
 5782            this.leader_updated(leader_id, window, cx)
 5783        })?;
 5784        Ok(())
 5785    }
 5786
 5787    async fn add_view_from_leader(
 5788        this: WeakEntity<Self>,
 5789        leader_id: PeerId,
 5790        view: &proto::View,
 5791        cx: &mut AsyncWindowContext,
 5792    ) -> Result<()> {
 5793        let this = this.upgrade().context("workspace dropped")?;
 5794
 5795        let Some(id) = view.id.clone() else {
 5796            anyhow::bail!("no id for view");
 5797        };
 5798        let id = ViewId::from_proto(id)?;
 5799        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5800
 5801        let pane = this.update(cx, |this, _cx| {
 5802            let state = this
 5803                .follower_states
 5804                .get(&leader_id.into())
 5805                .context("stopped following")?;
 5806            anyhow::Ok(state.pane().clone())
 5807        })?;
 5808        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5809            let client = this.read(cx).client().clone();
 5810            pane.items().find_map(|item| {
 5811                let item = item.to_followable_item_handle(cx)?;
 5812                if item.remote_id(&client, window, cx) == Some(id) {
 5813                    Some(item)
 5814                } else {
 5815                    None
 5816                }
 5817            })
 5818        })?;
 5819        let item = if let Some(existing_item) = existing_item {
 5820            existing_item
 5821        } else {
 5822            let variant = view.variant.clone();
 5823            anyhow::ensure!(variant.is_some(), "missing view variant");
 5824
 5825            let task = cx.update(|window, cx| {
 5826                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5827            })?;
 5828
 5829            let Some(task) = task else {
 5830                anyhow::bail!(
 5831                    "failed to construct view from leader (maybe from a different version of zed?)"
 5832                );
 5833            };
 5834
 5835            let mut new_item = task.await?;
 5836            pane.update_in(cx, |pane, window, cx| {
 5837                let mut item_to_remove = None;
 5838                for (ix, item) in pane.items().enumerate() {
 5839                    if let Some(item) = item.to_followable_item_handle(cx) {
 5840                        match new_item.dedup(item.as_ref(), window, cx) {
 5841                            Some(item::Dedup::KeepExisting) => {
 5842                                new_item =
 5843                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5844                                break;
 5845                            }
 5846                            Some(item::Dedup::ReplaceExisting) => {
 5847                                item_to_remove = Some((ix, item.item_id()));
 5848                                break;
 5849                            }
 5850                            None => {}
 5851                        }
 5852                    }
 5853                }
 5854
 5855                if let Some((ix, id)) = item_to_remove {
 5856                    pane.remove_item(id, false, false, window, cx);
 5857                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5858                }
 5859            })?;
 5860
 5861            new_item
 5862        };
 5863
 5864        this.update_in(cx, |this, window, cx| {
 5865            let state = this.follower_states.get_mut(&leader_id.into())?;
 5866            item.set_leader_id(Some(leader_id.into()), window, cx);
 5867            state.items_by_leader_view_id.insert(
 5868                id,
 5869                FollowerView {
 5870                    view: item,
 5871                    location: panel_id,
 5872                },
 5873            );
 5874
 5875            Some(())
 5876        })
 5877        .context("no follower state")?;
 5878
 5879        Ok(())
 5880    }
 5881
 5882    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5883        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5884            return;
 5885        };
 5886
 5887        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5888            let buffer_entity_id = agent_location.buffer.entity_id();
 5889            let view_id = ViewId {
 5890                creator: CollaboratorId::Agent,
 5891                id: buffer_entity_id.as_u64(),
 5892            };
 5893            follower_state.active_view_id = Some(view_id);
 5894
 5895            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5896                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5897                hash_map::Entry::Vacant(entry) => {
 5898                    let existing_view =
 5899                        follower_state
 5900                            .center_pane
 5901                            .read(cx)
 5902                            .items()
 5903                            .find_map(|item| {
 5904                                let item = item.to_followable_item_handle(cx)?;
 5905                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5906                                    && item.project_item_model_ids(cx).as_slice()
 5907                                        == [buffer_entity_id]
 5908                                {
 5909                                    Some(item)
 5910                                } else {
 5911                                    None
 5912                                }
 5913                            });
 5914                    let view = existing_view.or_else(|| {
 5915                        agent_location.buffer.upgrade().and_then(|buffer| {
 5916                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5917                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5918                            })?
 5919                            .to_followable_item_handle(cx)
 5920                        })
 5921                    });
 5922
 5923                    view.map(|view| {
 5924                        entry.insert(FollowerView {
 5925                            view,
 5926                            location: None,
 5927                        })
 5928                    })
 5929                }
 5930            };
 5931
 5932            if let Some(item) = item {
 5933                item.view
 5934                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5935                item.view
 5936                    .update_agent_location(agent_location.position, window, cx);
 5937            }
 5938        } else {
 5939            follower_state.active_view_id = None;
 5940        }
 5941
 5942        self.leader_updated(CollaboratorId::Agent, window, cx);
 5943    }
 5944
 5945    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5946        let mut is_project_item = true;
 5947        let mut update = proto::UpdateActiveView::default();
 5948        if window.is_window_active() {
 5949            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5950
 5951            if let Some(item) = active_item
 5952                && item.item_focus_handle(cx).contains_focused(window, cx)
 5953            {
 5954                let leader_id = self
 5955                    .pane_for(&*item)
 5956                    .and_then(|pane| self.leader_for_pane(&pane));
 5957                let leader_peer_id = match leader_id {
 5958                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5959                    Some(CollaboratorId::Agent) | None => None,
 5960                };
 5961
 5962                if let Some(item) = item.to_followable_item_handle(cx) {
 5963                    let id = item
 5964                        .remote_id(&self.app_state.client, window, cx)
 5965                        .map(|id| id.to_proto());
 5966
 5967                    if let Some(id) = id
 5968                        && let Some(variant) = item.to_state_proto(window, cx)
 5969                    {
 5970                        let view = Some(proto::View {
 5971                            id,
 5972                            leader_id: leader_peer_id,
 5973                            variant: Some(variant),
 5974                            panel_id: panel_id.map(|id| id as i32),
 5975                        });
 5976
 5977                        is_project_item = item.is_project_item(window, cx);
 5978                        update = proto::UpdateActiveView { view };
 5979                    };
 5980                }
 5981            }
 5982        }
 5983
 5984        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5985        if active_view_id != self.last_active_view_id.as_ref() {
 5986            self.last_active_view_id = active_view_id.cloned();
 5987            self.update_followers(
 5988                is_project_item,
 5989                proto::update_followers::Variant::UpdateActiveView(update),
 5990                window,
 5991                cx,
 5992            );
 5993        }
 5994    }
 5995
 5996    fn active_item_for_followers(
 5997        &self,
 5998        window: &mut Window,
 5999        cx: &mut App,
 6000    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6001        let mut active_item = None;
 6002        let mut panel_id = None;
 6003        for dock in self.all_docks() {
 6004            if dock.focus_handle(cx).contains_focused(window, cx)
 6005                && let Some(panel) = dock.read(cx).active_panel()
 6006                && let Some(pane) = panel.pane(cx)
 6007                && let Some(item) = pane.read(cx).active_item()
 6008            {
 6009                active_item = Some(item);
 6010                panel_id = panel.remote_id();
 6011                break;
 6012            }
 6013        }
 6014
 6015        if active_item.is_none() {
 6016            active_item = self.active_pane().read(cx).active_item();
 6017        }
 6018        (active_item, panel_id)
 6019    }
 6020
 6021    fn update_followers(
 6022        &self,
 6023        project_only: bool,
 6024        update: proto::update_followers::Variant,
 6025        _: &mut Window,
 6026        cx: &mut App,
 6027    ) -> Option<()> {
 6028        // If this update only applies to for followers in the current project,
 6029        // then skip it unless this project is shared. If it applies to all
 6030        // followers, regardless of project, then set `project_id` to none,
 6031        // indicating that it goes to all followers.
 6032        let project_id = if project_only {
 6033            Some(self.project.read(cx).remote_id()?)
 6034        } else {
 6035            None
 6036        };
 6037        self.app_state().workspace_store.update(cx, |store, cx| {
 6038            store.update_followers(project_id, update, cx)
 6039        })
 6040    }
 6041
 6042    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6043        self.follower_states.iter().find_map(|(leader_id, state)| {
 6044            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6045                Some(*leader_id)
 6046            } else {
 6047                None
 6048            }
 6049        })
 6050    }
 6051
 6052    fn leader_updated(
 6053        &mut self,
 6054        leader_id: impl Into<CollaboratorId>,
 6055        window: &mut Window,
 6056        cx: &mut Context<Self>,
 6057    ) -> Option<Box<dyn ItemHandle>> {
 6058        cx.notify();
 6059
 6060        let leader_id = leader_id.into();
 6061        let (panel_id, item) = match leader_id {
 6062            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6063            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6064        };
 6065
 6066        let state = self.follower_states.get(&leader_id)?;
 6067        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6068        let pane;
 6069        if let Some(panel_id) = panel_id {
 6070            pane = self
 6071                .activate_panel_for_proto_id(panel_id, window, cx)?
 6072                .pane(cx)?;
 6073            let state = self.follower_states.get_mut(&leader_id)?;
 6074            state.dock_pane = Some(pane.clone());
 6075        } else {
 6076            pane = state.center_pane.clone();
 6077            let state = self.follower_states.get_mut(&leader_id)?;
 6078            if let Some(dock_pane) = state.dock_pane.take() {
 6079                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6080            }
 6081        }
 6082
 6083        pane.update(cx, |pane, cx| {
 6084            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6085            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6086                pane.activate_item(index, false, false, window, cx);
 6087            } else {
 6088                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6089            }
 6090
 6091            if focus_active_item {
 6092                pane.focus_active_item(window, cx)
 6093            }
 6094        });
 6095
 6096        Some(item)
 6097    }
 6098
 6099    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6100        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6101        let active_view_id = state.active_view_id?;
 6102        Some(
 6103            state
 6104                .items_by_leader_view_id
 6105                .get(&active_view_id)?
 6106                .view
 6107                .boxed_clone(),
 6108        )
 6109    }
 6110
 6111    fn active_item_for_peer(
 6112        &self,
 6113        peer_id: PeerId,
 6114        window: &mut Window,
 6115        cx: &mut Context<Self>,
 6116    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6117        let call = self.active_call()?;
 6118        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6119        let leader_in_this_app;
 6120        let leader_in_this_project;
 6121        match participant.location {
 6122            ParticipantLocation::SharedProject { project_id } => {
 6123                leader_in_this_app = true;
 6124                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6125            }
 6126            ParticipantLocation::UnsharedProject => {
 6127                leader_in_this_app = true;
 6128                leader_in_this_project = false;
 6129            }
 6130            ParticipantLocation::External => {
 6131                leader_in_this_app = false;
 6132                leader_in_this_project = false;
 6133            }
 6134        };
 6135        let state = self.follower_states.get(&peer_id.into())?;
 6136        let mut item_to_activate = None;
 6137        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6138            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6139                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6140            {
 6141                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6142            }
 6143        } else if let Some(shared_screen) =
 6144            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6145        {
 6146            item_to_activate = Some((None, Box::new(shared_screen)));
 6147        }
 6148        item_to_activate
 6149    }
 6150
 6151    fn shared_screen_for_peer(
 6152        &self,
 6153        peer_id: PeerId,
 6154        pane: &Entity<Pane>,
 6155        window: &mut Window,
 6156        cx: &mut App,
 6157    ) -> Option<Entity<SharedScreen>> {
 6158        self.active_call()?
 6159            .create_shared_screen(peer_id, pane, window, cx)
 6160    }
 6161
 6162    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6163        if window.is_window_active() {
 6164            self.update_active_view_for_followers(window, cx);
 6165
 6166            if let Some(database_id) = self.database_id {
 6167                let db = WorkspaceDb::global(cx);
 6168                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6169                    .detach();
 6170            }
 6171        } else {
 6172            for pane in &self.panes {
 6173                pane.update(cx, |pane, cx| {
 6174                    if let Some(item) = pane.active_item() {
 6175                        item.workspace_deactivated(window, cx);
 6176                    }
 6177                    for item in pane.items() {
 6178                        if matches!(
 6179                            item.workspace_settings(cx).autosave,
 6180                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6181                        ) {
 6182                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6183                                .detach_and_log_err(cx);
 6184                        }
 6185                    }
 6186                });
 6187            }
 6188        }
 6189    }
 6190
 6191    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6192        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6193    }
 6194
 6195    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6196        self.active_call.as_ref().map(|(call, _)| call.clone())
 6197    }
 6198
 6199    fn on_active_call_event(
 6200        &mut self,
 6201        event: &ActiveCallEvent,
 6202        window: &mut Window,
 6203        cx: &mut Context<Self>,
 6204    ) {
 6205        match event {
 6206            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6207            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6208                self.leader_updated(participant_id, window, cx);
 6209            }
 6210        }
 6211    }
 6212
 6213    pub fn database_id(&self) -> Option<WorkspaceId> {
 6214        self.database_id
 6215    }
 6216
 6217    #[cfg(any(test, feature = "test-support"))]
 6218    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6219        self.database_id = Some(id);
 6220    }
 6221
 6222    pub fn session_id(&self) -> Option<String> {
 6223        self.session_id.clone()
 6224    }
 6225
 6226    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6227        let Some(display) = window.display(cx) else {
 6228            return Task::ready(());
 6229        };
 6230        let Ok(display_uuid) = display.uuid() else {
 6231            return Task::ready(());
 6232        };
 6233
 6234        let window_bounds = window.inner_window_bounds();
 6235        let database_id = self.database_id;
 6236        let has_paths = !self.root_paths(cx).is_empty();
 6237        let db = WorkspaceDb::global(cx);
 6238        let kvp = db::kvp::KeyValueStore::global(cx);
 6239
 6240        cx.background_executor().spawn(async move {
 6241            if !has_paths {
 6242                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6243                    .await
 6244                    .log_err();
 6245            }
 6246            if let Some(database_id) = database_id {
 6247                db.set_window_open_status(
 6248                    database_id,
 6249                    SerializedWindowBounds(window_bounds),
 6250                    display_uuid,
 6251                )
 6252                .await
 6253                .log_err();
 6254            } else {
 6255                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6256                    .await
 6257                    .log_err();
 6258            }
 6259        })
 6260    }
 6261
 6262    /// Bypass the 200ms serialization throttle and write workspace state to
 6263    /// the DB immediately. Returns a task the caller can await to ensure the
 6264    /// write completes. Used by the quit handler so the most recent state
 6265    /// isn't lost to a pending throttle timer when the process exits.
 6266    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6267        self._schedule_serialize_workspace.take();
 6268        self._serialize_workspace_task.take();
 6269        self.bounds_save_task_queued.take();
 6270
 6271        let bounds_task = self.save_window_bounds(window, cx);
 6272        let serialize_task = self.serialize_workspace_internal(window, cx);
 6273        cx.spawn(async move |_| {
 6274            bounds_task.await;
 6275            serialize_task.await;
 6276        })
 6277    }
 6278
 6279    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6280        let project = self.project().read(cx);
 6281        project
 6282            .visible_worktrees(cx)
 6283            .map(|worktree| worktree.read(cx).abs_path())
 6284            .collect::<Vec<_>>()
 6285    }
 6286
 6287    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6288        match member {
 6289            Member::Axis(PaneAxis { members, .. }) => {
 6290                for child in members.iter() {
 6291                    self.remove_panes(child.clone(), window, cx)
 6292                }
 6293            }
 6294            Member::Pane(pane) => {
 6295                self.force_remove_pane(&pane, &None, window, cx);
 6296            }
 6297        }
 6298    }
 6299
 6300    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6301        self.session_id.take();
 6302        self.serialize_workspace_internal(window, cx)
 6303    }
 6304
 6305    fn force_remove_pane(
 6306        &mut self,
 6307        pane: &Entity<Pane>,
 6308        focus_on: &Option<Entity<Pane>>,
 6309        window: &mut Window,
 6310        cx: &mut Context<Workspace>,
 6311    ) {
 6312        self.panes.retain(|p| p != pane);
 6313        if let Some(focus_on) = focus_on {
 6314            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6315        } else if self.active_pane() == pane {
 6316            self.panes
 6317                .last()
 6318                .unwrap()
 6319                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6320        }
 6321        if self.last_active_center_pane == Some(pane.downgrade()) {
 6322            self.last_active_center_pane = None;
 6323        }
 6324        cx.notify();
 6325    }
 6326
 6327    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6328        if self._schedule_serialize_workspace.is_none() {
 6329            self._schedule_serialize_workspace =
 6330                Some(cx.spawn_in(window, async move |this, cx| {
 6331                    cx.background_executor()
 6332                        .timer(SERIALIZATION_THROTTLE_TIME)
 6333                        .await;
 6334                    this.update_in(cx, |this, window, cx| {
 6335                        this._serialize_workspace_task =
 6336                            Some(this.serialize_workspace_internal(window, cx));
 6337                        this._schedule_serialize_workspace.take();
 6338                    })
 6339                    .log_err();
 6340                }));
 6341        }
 6342    }
 6343
 6344    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6345        let Some(database_id) = self.database_id() else {
 6346            return Task::ready(());
 6347        };
 6348
 6349        fn serialize_pane_handle(
 6350            pane_handle: &Entity<Pane>,
 6351            window: &mut Window,
 6352            cx: &mut App,
 6353        ) -> SerializedPane {
 6354            let (items, active, pinned_count) = {
 6355                let pane = pane_handle.read(cx);
 6356                let active_item_id = pane.active_item().map(|item| item.item_id());
 6357                (
 6358                    pane.items()
 6359                        .filter_map(|handle| {
 6360                            let handle = handle.to_serializable_item_handle(cx)?;
 6361
 6362                            Some(SerializedItem {
 6363                                kind: Arc::from(handle.serialized_item_kind()),
 6364                                item_id: handle.item_id().as_u64(),
 6365                                active: Some(handle.item_id()) == active_item_id,
 6366                                preview: pane.is_active_preview_item(handle.item_id()),
 6367                            })
 6368                        })
 6369                        .collect::<Vec<_>>(),
 6370                    pane.has_focus(window, cx),
 6371                    pane.pinned_count(),
 6372                )
 6373            };
 6374
 6375            SerializedPane::new(items, active, pinned_count)
 6376        }
 6377
 6378        fn build_serialized_pane_group(
 6379            pane_group: &Member,
 6380            window: &mut Window,
 6381            cx: &mut App,
 6382        ) -> SerializedPaneGroup {
 6383            match pane_group {
 6384                Member::Axis(PaneAxis {
 6385                    axis,
 6386                    members,
 6387                    flexes,
 6388                    bounding_boxes: _,
 6389                }) => SerializedPaneGroup::Group {
 6390                    axis: SerializedAxis(*axis),
 6391                    children: members
 6392                        .iter()
 6393                        .map(|member| build_serialized_pane_group(member, window, cx))
 6394                        .collect::<Vec<_>>(),
 6395                    flexes: Some(flexes.lock().clone()),
 6396                },
 6397                Member::Pane(pane_handle) => {
 6398                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6399                }
 6400            }
 6401        }
 6402
 6403        fn build_serialized_docks(
 6404            this: &Workspace,
 6405            window: &mut Window,
 6406            cx: &mut App,
 6407        ) -> DockStructure {
 6408            this.capture_dock_state(window, cx)
 6409        }
 6410
 6411        match self.workspace_location(cx) {
 6412            WorkspaceLocation::Location(location, paths) => {
 6413                let breakpoints = self.project.update(cx, |project, cx| {
 6414                    project
 6415                        .breakpoint_store()
 6416                        .read(cx)
 6417                        .all_source_breakpoints(cx)
 6418                });
 6419                let user_toolchains = self
 6420                    .project
 6421                    .read(cx)
 6422                    .user_toolchains(cx)
 6423                    .unwrap_or_default();
 6424
 6425                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6426                let docks = build_serialized_docks(self, window, cx);
 6427                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6428
 6429                let serialized_workspace = SerializedWorkspace {
 6430                    id: database_id,
 6431                    location,
 6432                    paths,
 6433                    center_group,
 6434                    window_bounds,
 6435                    display: Default::default(),
 6436                    docks,
 6437                    centered_layout: self.centered_layout,
 6438                    session_id: self.session_id.clone(),
 6439                    breakpoints,
 6440                    window_id: Some(window.window_handle().window_id().as_u64()),
 6441                    user_toolchains,
 6442                };
 6443
 6444                let db = WorkspaceDb::global(cx);
 6445                window.spawn(cx, async move |_| {
 6446                    db.save_workspace(serialized_workspace).await;
 6447                })
 6448            }
 6449            WorkspaceLocation::DetachFromSession => {
 6450                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6451                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6452                // Save dock state for empty local workspaces
 6453                let docks = build_serialized_docks(self, window, cx);
 6454                let db = WorkspaceDb::global(cx);
 6455                let kvp = db::kvp::KeyValueStore::global(cx);
 6456                window.spawn(cx, async move |_| {
 6457                    db.set_window_open_status(
 6458                        database_id,
 6459                        window_bounds,
 6460                        display.unwrap_or_default(),
 6461                    )
 6462                    .await
 6463                    .log_err();
 6464                    db.set_session_id(database_id, None).await.log_err();
 6465                    persistence::write_default_dock_state(&kvp, docks)
 6466                        .await
 6467                        .log_err();
 6468                })
 6469            }
 6470            WorkspaceLocation::None => {
 6471                // Save dock state for empty non-local workspaces
 6472                let docks = build_serialized_docks(self, window, cx);
 6473                let kvp = db::kvp::KeyValueStore::global(cx);
 6474                window.spawn(cx, async move |_| {
 6475                    persistence::write_default_dock_state(&kvp, docks)
 6476                        .await
 6477                        .log_err();
 6478                })
 6479            }
 6480        }
 6481    }
 6482
 6483    fn has_any_items_open(&self, cx: &App) -> bool {
 6484        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6485    }
 6486
 6487    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6488        let paths = PathList::new(&self.root_paths(cx));
 6489        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6490            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6491        } else if self.project.read(cx).is_local() {
 6492            if !paths.is_empty() || self.has_any_items_open(cx) {
 6493                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6494            } else {
 6495                WorkspaceLocation::DetachFromSession
 6496            }
 6497        } else {
 6498            WorkspaceLocation::None
 6499        }
 6500    }
 6501
 6502    fn update_history(&self, cx: &mut App) {
 6503        let Some(id) = self.database_id() else {
 6504            return;
 6505        };
 6506        if !self.project.read(cx).is_local() {
 6507            return;
 6508        }
 6509        if let Some(manager) = HistoryManager::global(cx) {
 6510            let paths = PathList::new(&self.root_paths(cx));
 6511            manager.update(cx, |this, cx| {
 6512                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6513            });
 6514        }
 6515    }
 6516
 6517    async fn serialize_items(
 6518        this: &WeakEntity<Self>,
 6519        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6520        cx: &mut AsyncWindowContext,
 6521    ) -> Result<()> {
 6522        const CHUNK_SIZE: usize = 200;
 6523
 6524        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6525
 6526        while let Some(items_received) = serializable_items.next().await {
 6527            let unique_items =
 6528                items_received
 6529                    .into_iter()
 6530                    .fold(HashMap::default(), |mut acc, item| {
 6531                        acc.entry(item.item_id()).or_insert(item);
 6532                        acc
 6533                    });
 6534
 6535            // We use into_iter() here so that the references to the items are moved into
 6536            // the tasks and not kept alive while we're sleeping.
 6537            for (_, item) in unique_items.into_iter() {
 6538                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6539                    item.serialize(workspace, false, window, cx)
 6540                }) {
 6541                    cx.background_spawn(async move { task.await.log_err() })
 6542                        .detach();
 6543                }
 6544            }
 6545
 6546            cx.background_executor()
 6547                .timer(SERIALIZATION_THROTTLE_TIME)
 6548                .await;
 6549        }
 6550
 6551        Ok(())
 6552    }
 6553
 6554    pub(crate) fn enqueue_item_serialization(
 6555        &mut self,
 6556        item: Box<dyn SerializableItemHandle>,
 6557    ) -> Result<()> {
 6558        self.serializable_items_tx
 6559            .unbounded_send(item)
 6560            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6561    }
 6562
 6563    pub(crate) fn load_workspace(
 6564        serialized_workspace: SerializedWorkspace,
 6565        paths_to_open: Vec<Option<ProjectPath>>,
 6566        window: &mut Window,
 6567        cx: &mut Context<Workspace>,
 6568    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6569        cx.spawn_in(window, async move |workspace, cx| {
 6570            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6571
 6572            let mut center_group = None;
 6573            let mut center_items = None;
 6574
 6575            // Traverse the splits tree and add to things
 6576            if let Some((group, active_pane, items)) = serialized_workspace
 6577                .center_group
 6578                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6579                .await
 6580            {
 6581                center_items = Some(items);
 6582                center_group = Some((group, active_pane))
 6583            }
 6584
 6585            let mut items_by_project_path = HashMap::default();
 6586            let mut item_ids_by_kind = HashMap::default();
 6587            let mut all_deserialized_items = Vec::default();
 6588            cx.update(|_, cx| {
 6589                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6590                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6591                        item_ids_by_kind
 6592                            .entry(serializable_item_handle.serialized_item_kind())
 6593                            .or_insert(Vec::new())
 6594                            .push(item.item_id().as_u64() as ItemId);
 6595                    }
 6596
 6597                    if let Some(project_path) = item.project_path(cx) {
 6598                        items_by_project_path.insert(project_path, item.clone());
 6599                    }
 6600                    all_deserialized_items.push(item);
 6601                }
 6602            })?;
 6603
 6604            let opened_items = paths_to_open
 6605                .into_iter()
 6606                .map(|path_to_open| {
 6607                    path_to_open
 6608                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6609                })
 6610                .collect::<Vec<_>>();
 6611
 6612            // Remove old panes from workspace panes list
 6613            workspace.update_in(cx, |workspace, window, cx| {
 6614                if let Some((center_group, active_pane)) = center_group {
 6615                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6616
 6617                    // Swap workspace center group
 6618                    workspace.center = PaneGroup::with_root(center_group);
 6619                    workspace.center.set_is_center(true);
 6620                    workspace.center.mark_positions(cx);
 6621
 6622                    if let Some(active_pane) = active_pane {
 6623                        workspace.set_active_pane(&active_pane, window, cx);
 6624                        cx.focus_self(window);
 6625                    } else {
 6626                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6627                    }
 6628                }
 6629
 6630                let docks = serialized_workspace.docks;
 6631
 6632                for (dock, serialized_dock) in [
 6633                    (&mut workspace.right_dock, docks.right),
 6634                    (&mut workspace.left_dock, docks.left),
 6635                    (&mut workspace.bottom_dock, docks.bottom),
 6636                ]
 6637                .iter_mut()
 6638                {
 6639                    dock.update(cx, |dock, cx| {
 6640                        dock.serialized_dock = Some(serialized_dock.clone());
 6641                        dock.restore_state(window, cx);
 6642                    });
 6643                }
 6644
 6645                cx.notify();
 6646            })?;
 6647
 6648            let _ = project
 6649                .update(cx, |project, cx| {
 6650                    project
 6651                        .breakpoint_store()
 6652                        .update(cx, |breakpoint_store, cx| {
 6653                            breakpoint_store
 6654                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6655                        })
 6656                })
 6657                .await;
 6658
 6659            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6660            // after loading the items, we might have different items and in order to avoid
 6661            // the database filling up, we delete items that haven't been loaded now.
 6662            //
 6663            // The items that have been loaded, have been saved after they've been added to the workspace.
 6664            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6665                item_ids_by_kind
 6666                    .into_iter()
 6667                    .map(|(item_kind, loaded_items)| {
 6668                        SerializableItemRegistry::cleanup(
 6669                            item_kind,
 6670                            serialized_workspace.id,
 6671                            loaded_items,
 6672                            window,
 6673                            cx,
 6674                        )
 6675                        .log_err()
 6676                    })
 6677                    .collect::<Vec<_>>()
 6678            })?;
 6679
 6680            futures::future::join_all(clean_up_tasks).await;
 6681
 6682            workspace
 6683                .update_in(cx, |workspace, window, cx| {
 6684                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6685                    workspace.serialize_workspace_internal(window, cx).detach();
 6686
 6687                    // Ensure that we mark the window as edited if we did load dirty items
 6688                    workspace.update_window_edited(window, cx);
 6689                })
 6690                .ok();
 6691
 6692            Ok(opened_items)
 6693        })
 6694    }
 6695
 6696    pub fn key_context(&self, cx: &App) -> KeyContext {
 6697        let mut context = KeyContext::new_with_defaults();
 6698        context.add("Workspace");
 6699        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6700        if let Some(status) = self
 6701            .debugger_provider
 6702            .as_ref()
 6703            .and_then(|provider| provider.active_thread_state(cx))
 6704        {
 6705            match status {
 6706                ThreadStatus::Running | ThreadStatus::Stepping => {
 6707                    context.add("debugger_running");
 6708                }
 6709                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6710                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6711            }
 6712        }
 6713
 6714        if self.left_dock.read(cx).is_open() {
 6715            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6716                context.set("left_dock", active_panel.panel_key());
 6717            }
 6718        }
 6719
 6720        if self.right_dock.read(cx).is_open() {
 6721            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6722                context.set("right_dock", active_panel.panel_key());
 6723            }
 6724        }
 6725
 6726        if self.bottom_dock.read(cx).is_open() {
 6727            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6728                context.set("bottom_dock", active_panel.panel_key());
 6729            }
 6730        }
 6731
 6732        context
 6733    }
 6734
 6735    /// Multiworkspace uses this to add workspace action handling to itself
 6736    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6737        self.add_workspace_actions_listeners(div, window, cx)
 6738            .on_action(cx.listener(
 6739                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6740                    for action in &action_sequence.0 {
 6741                        window.dispatch_action(action.boxed_clone(), cx);
 6742                    }
 6743                },
 6744            ))
 6745            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6746            .on_action(cx.listener(Self::close_all_items_and_panes))
 6747            .on_action(cx.listener(Self::close_item_in_all_panes))
 6748            .on_action(cx.listener(Self::save_all))
 6749            .on_action(cx.listener(Self::send_keystrokes))
 6750            .on_action(cx.listener(Self::add_folder_to_project))
 6751            .on_action(cx.listener(Self::follow_next_collaborator))
 6752            .on_action(cx.listener(Self::activate_pane_at_index))
 6753            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6754            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6755            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6756            .on_action(cx.listener(Self::toggle_theme_mode))
 6757            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6758                let pane = workspace.active_pane().clone();
 6759                workspace.unfollow_in_pane(&pane, window, cx);
 6760            }))
 6761            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6762                workspace
 6763                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6764                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6765            }))
 6766            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6767                workspace
 6768                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6769                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6770            }))
 6771            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6772                workspace
 6773                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6774                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6775            }))
 6776            .on_action(
 6777                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6778                    workspace.activate_previous_pane(window, cx)
 6779                }),
 6780            )
 6781            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6782                workspace.activate_next_pane(window, cx)
 6783            }))
 6784            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6785                workspace.activate_last_pane(window, cx)
 6786            }))
 6787            .on_action(
 6788                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6789                    workspace.activate_next_window(cx)
 6790                }),
 6791            )
 6792            .on_action(
 6793                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6794                    workspace.activate_previous_window(cx)
 6795                }),
 6796            )
 6797            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6798                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6799            }))
 6800            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6801                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6802            }))
 6803            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6804                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6805            }))
 6806            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6807                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6808            }))
 6809            .on_action(cx.listener(
 6810                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6811                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6812                },
 6813            ))
 6814            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6815                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6816            }))
 6817            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6818                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6819            }))
 6820            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6821                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6822            }))
 6823            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6824                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6825            }))
 6826            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6827                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6828                    SplitDirection::Down,
 6829                    SplitDirection::Up,
 6830                    SplitDirection::Right,
 6831                    SplitDirection::Left,
 6832                ];
 6833                for dir in DIRECTION_PRIORITY {
 6834                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6835                        workspace.swap_pane_in_direction(dir, cx);
 6836                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6837                        break;
 6838                    }
 6839                }
 6840            }))
 6841            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6842                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6843            }))
 6844            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6845                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6846            }))
 6847            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6848                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6849            }))
 6850            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6851                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6852            }))
 6853            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6854                this.toggle_dock(DockPosition::Left, window, cx);
 6855            }))
 6856            .on_action(cx.listener(
 6857                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6858                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6859                },
 6860            ))
 6861            .on_action(cx.listener(
 6862                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6863                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6864                },
 6865            ))
 6866            .on_action(cx.listener(
 6867                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6868                    if !workspace.close_active_dock(window, cx) {
 6869                        cx.propagate();
 6870                    }
 6871                },
 6872            ))
 6873            .on_action(
 6874                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6875                    workspace.close_all_docks(window, cx);
 6876                }),
 6877            )
 6878            .on_action(cx.listener(Self::toggle_all_docks))
 6879            .on_action(cx.listener(
 6880                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6881                    workspace.clear_all_notifications(cx);
 6882                },
 6883            ))
 6884            .on_action(cx.listener(
 6885                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6886                    workspace.clear_navigation_history(window, cx);
 6887                },
 6888            ))
 6889            .on_action(cx.listener(
 6890                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6891                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6892                        workspace.suppress_notification(&notification_id, cx);
 6893                    }
 6894                },
 6895            ))
 6896            .on_action(cx.listener(
 6897                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6898                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6899                },
 6900            ))
 6901            .on_action(
 6902                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6903                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6904                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6905                            trusted_worktrees.clear_trusted_paths()
 6906                        });
 6907                        let db = WorkspaceDb::global(cx);
 6908                        cx.spawn(async move |_, cx| {
 6909                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6910                                cx.update(|cx| reload(cx));
 6911                            }
 6912                        })
 6913                        .detach();
 6914                    }
 6915                }),
 6916            )
 6917            .on_action(cx.listener(
 6918                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6919                    workspace.reopen_closed_item(window, cx).detach();
 6920                },
 6921            ))
 6922            .on_action(cx.listener(
 6923                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6924                    for dock in workspace.all_docks() {
 6925                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6926                            let panel = dock.read(cx).active_panel().cloned();
 6927                            if let Some(panel) = panel {
 6928                                dock.update(cx, |dock, cx| {
 6929                                    dock.set_panel_size_state(
 6930                                        panel.as_ref(),
 6931                                        dock::PanelSizeState::default(),
 6932                                        cx,
 6933                                    );
 6934                                });
 6935                            }
 6936                            return;
 6937                        }
 6938                    }
 6939                },
 6940            ))
 6941            .on_action(cx.listener(
 6942                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 6943                    for dock in workspace.all_docks() {
 6944                        let panel = dock.read(cx).visible_panel().cloned();
 6945                        if let Some(panel) = panel {
 6946                            dock.update(cx, |dock, cx| {
 6947                                dock.set_panel_size_state(
 6948                                    panel.as_ref(),
 6949                                    dock::PanelSizeState::default(),
 6950                                    cx,
 6951                                );
 6952                            });
 6953                        }
 6954                    }
 6955                },
 6956            ))
 6957            .on_action(cx.listener(
 6958                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6959                    adjust_active_dock_size_by_px(
 6960                        px_with_ui_font_fallback(act.px, cx),
 6961                        workspace,
 6962                        window,
 6963                        cx,
 6964                    );
 6965                },
 6966            ))
 6967            .on_action(cx.listener(
 6968                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6969                    adjust_active_dock_size_by_px(
 6970                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6971                        workspace,
 6972                        window,
 6973                        cx,
 6974                    );
 6975                },
 6976            ))
 6977            .on_action(cx.listener(
 6978                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6979                    adjust_open_docks_size_by_px(
 6980                        px_with_ui_font_fallback(act.px, cx),
 6981                        workspace,
 6982                        window,
 6983                        cx,
 6984                    );
 6985                },
 6986            ))
 6987            .on_action(cx.listener(
 6988                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6989                    adjust_open_docks_size_by_px(
 6990                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6991                        workspace,
 6992                        window,
 6993                        cx,
 6994                    );
 6995                },
 6996            ))
 6997            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6998            .on_action(cx.listener(
 6999                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 7000                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7001                        let dock = active_dock.read(cx);
 7002                        if let Some(active_panel) = dock.active_panel() {
 7003                            if active_panel.pane(cx).is_none() {
 7004                                let mut recent_pane: Option<Entity<Pane>> = None;
 7005                                let mut recent_timestamp = 0;
 7006                                for pane_handle in workspace.panes() {
 7007                                    let pane = pane_handle.read(cx);
 7008                                    for entry in pane.activation_history() {
 7009                                        if entry.timestamp > recent_timestamp {
 7010                                            recent_timestamp = entry.timestamp;
 7011                                            recent_pane = Some(pane_handle.clone());
 7012                                        }
 7013                                    }
 7014                                }
 7015
 7016                                if let Some(pane) = recent_pane {
 7017                                    pane.update(cx, |pane, cx| {
 7018                                        let current_index = pane.active_item_index();
 7019                                        let items_len = pane.items_len();
 7020                                        if items_len > 0 {
 7021                                            let next_index = if current_index + 1 < items_len {
 7022                                                current_index + 1
 7023                                            } else {
 7024                                                0
 7025                                            };
 7026                                            pane.activate_item(
 7027                                                next_index, false, false, window, cx,
 7028                                            );
 7029                                        }
 7030                                    });
 7031                                    return;
 7032                                }
 7033                            }
 7034                        }
 7035                    }
 7036                    cx.propagate();
 7037                },
 7038            ))
 7039            .on_action(cx.listener(
 7040                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 7041                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7042                        let dock = active_dock.read(cx);
 7043                        if let Some(active_panel) = dock.active_panel() {
 7044                            if active_panel.pane(cx).is_none() {
 7045                                let mut recent_pane: Option<Entity<Pane>> = None;
 7046                                let mut recent_timestamp = 0;
 7047                                for pane_handle in workspace.panes() {
 7048                                    let pane = pane_handle.read(cx);
 7049                                    for entry in pane.activation_history() {
 7050                                        if entry.timestamp > recent_timestamp {
 7051                                            recent_timestamp = entry.timestamp;
 7052                                            recent_pane = Some(pane_handle.clone());
 7053                                        }
 7054                                    }
 7055                                }
 7056
 7057                                if let Some(pane) = recent_pane {
 7058                                    pane.update(cx, |pane, cx| {
 7059                                        let current_index = pane.active_item_index();
 7060                                        let items_len = pane.items_len();
 7061                                        if items_len > 0 {
 7062                                            let prev_index = if current_index > 0 {
 7063                                                current_index - 1
 7064                                            } else {
 7065                                                items_len.saturating_sub(1)
 7066                                            };
 7067                                            pane.activate_item(
 7068                                                prev_index, false, false, window, cx,
 7069                                            );
 7070                                        }
 7071                                    });
 7072                                    return;
 7073                                }
 7074                            }
 7075                        }
 7076                    }
 7077                    cx.propagate();
 7078                },
 7079            ))
 7080            .on_action(cx.listener(
 7081                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7082                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7083                        let dock = active_dock.read(cx);
 7084                        if let Some(active_panel) = dock.active_panel() {
 7085                            if active_panel.pane(cx).is_none() {
 7086                                let active_pane = workspace.active_pane().clone();
 7087                                active_pane.update(cx, |pane, cx| {
 7088                                    pane.close_active_item(action, window, cx)
 7089                                        .detach_and_log_err(cx);
 7090                                });
 7091                                return;
 7092                            }
 7093                        }
 7094                    }
 7095                    cx.propagate();
 7096                },
 7097            ))
 7098            .on_action(
 7099                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7100                    let pane = workspace.active_pane().clone();
 7101                    if let Some(item) = pane.read(cx).active_item() {
 7102                        item.toggle_read_only(window, cx);
 7103                    }
 7104                }),
 7105            )
 7106            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7107                workspace.focus_center_pane(window, cx);
 7108            }))
 7109            .on_action(cx.listener(Workspace::cancel))
 7110    }
 7111
 7112    #[cfg(any(test, feature = "test-support"))]
 7113    pub fn set_random_database_id(&mut self) {
 7114        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7115    }
 7116
 7117    #[cfg(any(test, feature = "test-support"))]
 7118    pub(crate) fn test_new(
 7119        project: Entity<Project>,
 7120        window: &mut Window,
 7121        cx: &mut Context<Self>,
 7122    ) -> Self {
 7123        use node_runtime::NodeRuntime;
 7124        use session::Session;
 7125
 7126        let client = project.read(cx).client();
 7127        let user_store = project.read(cx).user_store();
 7128        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7129        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7130        window.activate_window();
 7131        let app_state = Arc::new(AppState {
 7132            languages: project.read(cx).languages().clone(),
 7133            workspace_store,
 7134            client,
 7135            user_store,
 7136            fs: project.read(cx).fs().clone(),
 7137            build_window_options: |_, _| Default::default(),
 7138            node_runtime: NodeRuntime::unavailable(),
 7139            session,
 7140        });
 7141        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7142        workspace
 7143            .active_pane
 7144            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7145        workspace
 7146    }
 7147
 7148    pub fn register_action<A: Action>(
 7149        &mut self,
 7150        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7151    ) -> &mut Self {
 7152        let callback = Arc::new(callback);
 7153
 7154        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7155            let callback = callback.clone();
 7156            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7157                (callback)(workspace, event, window, cx)
 7158            }))
 7159        }));
 7160        self
 7161    }
 7162    pub fn register_action_renderer(
 7163        &mut self,
 7164        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7165    ) -> &mut Self {
 7166        self.workspace_actions.push(Box::new(callback));
 7167        self
 7168    }
 7169
 7170    fn add_workspace_actions_listeners(
 7171        &self,
 7172        mut div: Div,
 7173        window: &mut Window,
 7174        cx: &mut Context<Self>,
 7175    ) -> Div {
 7176        for action in self.workspace_actions.iter() {
 7177            div = (action)(div, self, window, cx)
 7178        }
 7179        div
 7180    }
 7181
 7182    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7183        self.modal_layer.read(cx).has_active_modal()
 7184    }
 7185
 7186    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7187        self.modal_layer
 7188            .read(cx)
 7189            .is_active_modal_command_palette(cx)
 7190    }
 7191
 7192    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7193        self.modal_layer.read(cx).active_modal()
 7194    }
 7195
 7196    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7197    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7198    /// If no modal is active, the new modal will be shown.
 7199    ///
 7200    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7201    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7202    /// will not be shown.
 7203    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7204    where
 7205        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7206    {
 7207        self.modal_layer.update(cx, |modal_layer, cx| {
 7208            modal_layer.toggle_modal(window, cx, build)
 7209        })
 7210    }
 7211
 7212    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7213        self.modal_layer
 7214            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7215    }
 7216
 7217    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7218        self.toast_layer
 7219            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7220    }
 7221
 7222    pub fn toggle_centered_layout(
 7223        &mut self,
 7224        _: &ToggleCenteredLayout,
 7225        _: &mut Window,
 7226        cx: &mut Context<Self>,
 7227    ) {
 7228        self.centered_layout = !self.centered_layout;
 7229        if let Some(database_id) = self.database_id() {
 7230            let db = WorkspaceDb::global(cx);
 7231            let centered_layout = self.centered_layout;
 7232            cx.background_spawn(async move {
 7233                db.set_centered_layout(database_id, centered_layout).await
 7234            })
 7235            .detach_and_log_err(cx);
 7236        }
 7237        cx.notify();
 7238    }
 7239
 7240    fn adjust_padding(padding: Option<f32>) -> f32 {
 7241        padding
 7242            .unwrap_or(CenteredPaddingSettings::default().0)
 7243            .clamp(
 7244                CenteredPaddingSettings::MIN_PADDING,
 7245                CenteredPaddingSettings::MAX_PADDING,
 7246            )
 7247    }
 7248
 7249    fn render_dock(
 7250        &self,
 7251        position: DockPosition,
 7252        dock: &Entity<Dock>,
 7253        window: &mut Window,
 7254        cx: &mut App,
 7255    ) -> Option<Div> {
 7256        if self.zoomed_position == Some(position) {
 7257            return None;
 7258        }
 7259
 7260        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7261            let pane = panel.pane(cx)?;
 7262            let follower_states = &self.follower_states;
 7263            leader_border_for_pane(follower_states, &pane, window, cx)
 7264        });
 7265
 7266        let mut container = div()
 7267            .flex()
 7268            .overflow_hidden()
 7269            .flex_none()
 7270            .child(dock.clone())
 7271            .children(leader_border);
 7272
 7273        // Apply sizing only when the dock is open. When closed the dock is still
 7274        // included in the element tree so its focus handle remains mounted — without
 7275        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7276        let dock = dock.read(cx);
 7277        if let Some(panel) = dock.visible_panel() {
 7278            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7279            if position.axis() == Axis::Horizontal {
 7280                if let Some(ratio) = size_state
 7281                    .and_then(|state| state.flexible_size_ratio)
 7282                    .or_else(|| self.default_flexible_dock_ratio(position))
 7283                    && panel.supports_flexible_size(window, cx)
 7284                {
 7285                    let ratio = ratio.clamp(0.001, 0.999);
 7286                    let grow = ratio / (1.0 - ratio);
 7287                    let style = container.style();
 7288                    style.flex_grow = Some(grow);
 7289                    style.flex_shrink = Some(1.0);
 7290                    style.flex_basis = Some(relative(0.).into());
 7291                } else {
 7292                    let size = size_state
 7293                        .and_then(|state| state.size)
 7294                        .unwrap_or_else(|| panel.default_size(window, cx));
 7295                    container = container.w(size);
 7296                }
 7297            } else {
 7298                let size = size_state
 7299                    .and_then(|state| state.size)
 7300                    .unwrap_or_else(|| panel.default_size(window, cx));
 7301                container = container.h(size);
 7302            }
 7303        }
 7304
 7305        Some(container)
 7306    }
 7307
 7308    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7309        window
 7310            .root::<MultiWorkspace>()
 7311            .flatten()
 7312            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7313    }
 7314
 7315    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7316        self.zoomed.as_ref()
 7317    }
 7318
 7319    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7320        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7321            return;
 7322        };
 7323        let windows = cx.windows();
 7324        let next_window =
 7325            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7326                || {
 7327                    windows
 7328                        .iter()
 7329                        .cycle()
 7330                        .skip_while(|window| window.window_id() != current_window_id)
 7331                        .nth(1)
 7332                },
 7333            );
 7334
 7335        if let Some(window) = next_window {
 7336            window
 7337                .update(cx, |_, window, _| window.activate_window())
 7338                .ok();
 7339        }
 7340    }
 7341
 7342    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7343        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7344            return;
 7345        };
 7346        let windows = cx.windows();
 7347        let prev_window =
 7348            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7349                || {
 7350                    windows
 7351                        .iter()
 7352                        .rev()
 7353                        .cycle()
 7354                        .skip_while(|window| window.window_id() != current_window_id)
 7355                        .nth(1)
 7356                },
 7357            );
 7358
 7359        if let Some(window) = prev_window {
 7360            window
 7361                .update(cx, |_, window, _| window.activate_window())
 7362                .ok();
 7363        }
 7364    }
 7365
 7366    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7367        if cx.stop_active_drag(window) {
 7368        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7369            dismiss_app_notification(&notification_id, cx);
 7370        } else {
 7371            cx.propagate();
 7372        }
 7373    }
 7374
 7375    fn resize_dock(
 7376        &mut self,
 7377        dock_pos: DockPosition,
 7378        new_size: Pixels,
 7379        window: &mut Window,
 7380        cx: &mut Context<Self>,
 7381    ) {
 7382        match dock_pos {
 7383            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7384            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7385            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7386        }
 7387    }
 7388
 7389    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7390        let workspace_width = self.bounds.size.width;
 7391        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7392
 7393        self.right_dock.read_with(cx, |right_dock, cx| {
 7394            let right_dock_size = right_dock
 7395                .stored_active_panel_size(window, cx)
 7396                .unwrap_or(Pixels::ZERO);
 7397            if right_dock_size + size > workspace_width {
 7398                size = workspace_width - right_dock_size
 7399            }
 7400        });
 7401
 7402        let ratio = self.flexible_dock_ratio_for_size(DockPosition::Left, size, window, cx);
 7403        self.left_dock.update(cx, |left_dock, cx| {
 7404            if WorkspaceSettings::get_global(cx)
 7405                .resize_all_panels_in_dock
 7406                .contains(&DockPosition::Left)
 7407            {
 7408                left_dock.resize_all_panels(Some(size), ratio, window, cx);
 7409            } else {
 7410                left_dock.resize_active_panel(Some(size), ratio, window, cx);
 7411            }
 7412        });
 7413    }
 7414
 7415    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7416        let workspace_width = self.bounds.size.width;
 7417        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7418        self.left_dock.read_with(cx, |left_dock, cx| {
 7419            let left_dock_size = left_dock
 7420                .stored_active_panel_size(window, cx)
 7421                .unwrap_or(Pixels::ZERO);
 7422            if left_dock_size + size > workspace_width {
 7423                size = workspace_width - left_dock_size
 7424            }
 7425        });
 7426        let ratio = self.flexible_dock_ratio_for_size(DockPosition::Right, size, window, cx);
 7427        self.right_dock.update(cx, |right_dock, cx| {
 7428            if WorkspaceSettings::get_global(cx)
 7429                .resize_all_panels_in_dock
 7430                .contains(&DockPosition::Right)
 7431            {
 7432                right_dock.resize_all_panels(Some(size), ratio, window, cx);
 7433            } else {
 7434                right_dock.resize_active_panel(Some(size), ratio, window, cx);
 7435            }
 7436        });
 7437    }
 7438
 7439    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7440        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7441        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7442            if WorkspaceSettings::get_global(cx)
 7443                .resize_all_panels_in_dock
 7444                .contains(&DockPosition::Bottom)
 7445            {
 7446                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7447            } else {
 7448                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7449            }
 7450        });
 7451    }
 7452
 7453    fn toggle_edit_predictions_all_files(
 7454        &mut self,
 7455        _: &ToggleEditPrediction,
 7456        _window: &mut Window,
 7457        cx: &mut Context<Self>,
 7458    ) {
 7459        let fs = self.project().read(cx).fs().clone();
 7460        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7461        update_settings_file(fs, cx, move |file, _| {
 7462            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7463        });
 7464    }
 7465
 7466    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7467        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7468        let next_mode = match current_mode {
 7469            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7470                theme_settings::ThemeAppearanceMode::Dark
 7471            }
 7472            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7473                theme_settings::ThemeAppearanceMode::Light
 7474            }
 7475            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7476                match cx.theme().appearance() {
 7477                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7478                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7479                }
 7480            }
 7481        };
 7482
 7483        let fs = self.project().read(cx).fs().clone();
 7484        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7485            theme_settings::set_mode(settings, next_mode);
 7486        });
 7487    }
 7488
 7489    pub fn show_worktree_trust_security_modal(
 7490        &mut self,
 7491        toggle: bool,
 7492        window: &mut Window,
 7493        cx: &mut Context<Self>,
 7494    ) {
 7495        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7496            if toggle {
 7497                security_modal.update(cx, |security_modal, cx| {
 7498                    security_modal.dismiss(cx);
 7499                })
 7500            } else {
 7501                security_modal.update(cx, |security_modal, cx| {
 7502                    security_modal.refresh_restricted_paths(cx);
 7503                });
 7504            }
 7505        } else {
 7506            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7507                .map(|trusted_worktrees| {
 7508                    trusted_worktrees
 7509                        .read(cx)
 7510                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7511                })
 7512                .unwrap_or(false);
 7513            if has_restricted_worktrees {
 7514                let project = self.project().read(cx);
 7515                let remote_host = project
 7516                    .remote_connection_options(cx)
 7517                    .map(RemoteHostLocation::from);
 7518                let worktree_store = project.worktree_store().downgrade();
 7519                self.toggle_modal(window, cx, |_, cx| {
 7520                    SecurityModal::new(worktree_store, remote_host, cx)
 7521                });
 7522            }
 7523        }
 7524    }
 7525}
 7526
 7527pub trait AnyActiveCall {
 7528    fn entity(&self) -> AnyEntity;
 7529    fn is_in_room(&self, _: &App) -> bool;
 7530    fn room_id(&self, _: &App) -> Option<u64>;
 7531    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7532    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7533    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7534    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7535    fn is_sharing_project(&self, _: &App) -> bool;
 7536    fn has_remote_participants(&self, _: &App) -> bool;
 7537    fn local_participant_is_guest(&self, _: &App) -> bool;
 7538    fn client(&self, _: &App) -> Arc<Client>;
 7539    fn share_on_join(&self, _: &App) -> bool;
 7540    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7541    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7542    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7543    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7544    fn join_project(
 7545        &self,
 7546        _: u64,
 7547        _: Arc<LanguageRegistry>,
 7548        _: Arc<dyn Fs>,
 7549        _: &mut App,
 7550    ) -> Task<Result<Entity<Project>>>;
 7551    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7552    fn subscribe(
 7553        &self,
 7554        _: &mut Window,
 7555        _: &mut Context<Workspace>,
 7556        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7557    ) -> Subscription;
 7558    fn create_shared_screen(
 7559        &self,
 7560        _: PeerId,
 7561        _: &Entity<Pane>,
 7562        _: &mut Window,
 7563        _: &mut App,
 7564    ) -> Option<Entity<SharedScreen>>;
 7565}
 7566
 7567#[derive(Clone)]
 7568pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7569impl Global for GlobalAnyActiveCall {}
 7570
 7571impl GlobalAnyActiveCall {
 7572    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7573        cx.try_global()
 7574    }
 7575
 7576    pub(crate) fn global(cx: &App) -> &Self {
 7577        cx.global()
 7578    }
 7579}
 7580
 7581pub fn merge_conflict_notification_id() -> NotificationId {
 7582    struct MergeConflictNotification;
 7583    NotificationId::unique::<MergeConflictNotification>()
 7584}
 7585
 7586/// Workspace-local view of a remote participant's location.
 7587#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7588pub enum ParticipantLocation {
 7589    SharedProject { project_id: u64 },
 7590    UnsharedProject,
 7591    External,
 7592}
 7593
 7594impl ParticipantLocation {
 7595    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7596        match location
 7597            .and_then(|l| l.variant)
 7598            .context("participant location was not provided")?
 7599        {
 7600            proto::participant_location::Variant::SharedProject(project) => {
 7601                Ok(Self::SharedProject {
 7602                    project_id: project.id,
 7603                })
 7604            }
 7605            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7606            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7607        }
 7608    }
 7609}
 7610/// Workspace-local view of a remote collaborator's state.
 7611/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7612#[derive(Clone)]
 7613pub struct RemoteCollaborator {
 7614    pub user: Arc<User>,
 7615    pub peer_id: PeerId,
 7616    pub location: ParticipantLocation,
 7617    pub participant_index: ParticipantIndex,
 7618}
 7619
 7620pub enum ActiveCallEvent {
 7621    ParticipantLocationChanged { participant_id: PeerId },
 7622    RemoteVideoTracksChanged { participant_id: PeerId },
 7623}
 7624
 7625fn leader_border_for_pane(
 7626    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7627    pane: &Entity<Pane>,
 7628    _: &Window,
 7629    cx: &App,
 7630) -> Option<Div> {
 7631    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7632        if state.pane() == pane {
 7633            Some((*leader_id, state))
 7634        } else {
 7635            None
 7636        }
 7637    })?;
 7638
 7639    let mut leader_color = match leader_id {
 7640        CollaboratorId::PeerId(leader_peer_id) => {
 7641            let leader = GlobalAnyActiveCall::try_global(cx)?
 7642                .0
 7643                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7644
 7645            cx.theme()
 7646                .players()
 7647                .color_for_participant(leader.participant_index.0)
 7648                .cursor
 7649        }
 7650        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7651    };
 7652    leader_color.fade_out(0.3);
 7653    Some(
 7654        div()
 7655            .absolute()
 7656            .size_full()
 7657            .left_0()
 7658            .top_0()
 7659            .border_2()
 7660            .border_color(leader_color),
 7661    )
 7662}
 7663
 7664fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7665    ZED_WINDOW_POSITION
 7666        .zip(*ZED_WINDOW_SIZE)
 7667        .map(|(position, size)| Bounds {
 7668            origin: position,
 7669            size,
 7670        })
 7671}
 7672
 7673fn open_items(
 7674    serialized_workspace: Option<SerializedWorkspace>,
 7675    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7676    window: &mut Window,
 7677    cx: &mut Context<Workspace>,
 7678) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7679    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7680        Workspace::load_workspace(
 7681            serialized_workspace,
 7682            project_paths_to_open
 7683                .iter()
 7684                .map(|(_, project_path)| project_path)
 7685                .cloned()
 7686                .collect(),
 7687            window,
 7688            cx,
 7689        )
 7690    });
 7691
 7692    cx.spawn_in(window, async move |workspace, cx| {
 7693        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7694
 7695        if let Some(restored_items) = restored_items {
 7696            let restored_items = restored_items.await?;
 7697
 7698            let restored_project_paths = restored_items
 7699                .iter()
 7700                .filter_map(|item| {
 7701                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7702                        .ok()
 7703                        .flatten()
 7704                })
 7705                .collect::<HashSet<_>>();
 7706
 7707            for restored_item in restored_items {
 7708                opened_items.push(restored_item.map(Ok));
 7709            }
 7710
 7711            project_paths_to_open
 7712                .iter_mut()
 7713                .for_each(|(_, project_path)| {
 7714                    if let Some(project_path_to_open) = project_path
 7715                        && restored_project_paths.contains(project_path_to_open)
 7716                    {
 7717                        *project_path = None;
 7718                    }
 7719                });
 7720        } else {
 7721            for _ in 0..project_paths_to_open.len() {
 7722                opened_items.push(None);
 7723            }
 7724        }
 7725        assert!(opened_items.len() == project_paths_to_open.len());
 7726
 7727        let tasks =
 7728            project_paths_to_open
 7729                .into_iter()
 7730                .enumerate()
 7731                .map(|(ix, (abs_path, project_path))| {
 7732                    let workspace = workspace.clone();
 7733                    cx.spawn(async move |cx| {
 7734                        let file_project_path = project_path?;
 7735                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7736                            workspace.project().update(cx, |project, cx| {
 7737                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7738                            })
 7739                        });
 7740
 7741                        // We only want to open file paths here. If one of the items
 7742                        // here is a directory, it was already opened further above
 7743                        // with a `find_or_create_worktree`.
 7744                        if let Ok(task) = abs_path_task
 7745                            && task.await.is_none_or(|p| p.is_file())
 7746                        {
 7747                            return Some((
 7748                                ix,
 7749                                workspace
 7750                                    .update_in(cx, |workspace, window, cx| {
 7751                                        workspace.open_path(
 7752                                            file_project_path,
 7753                                            None,
 7754                                            true,
 7755                                            window,
 7756                                            cx,
 7757                                        )
 7758                                    })
 7759                                    .log_err()?
 7760                                    .await,
 7761                            ));
 7762                        }
 7763                        None
 7764                    })
 7765                });
 7766
 7767        let tasks = tasks.collect::<Vec<_>>();
 7768
 7769        let tasks = futures::future::join_all(tasks);
 7770        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7771            opened_items[ix] = Some(path_open_result);
 7772        }
 7773
 7774        Ok(opened_items)
 7775    })
 7776}
 7777
 7778#[derive(Clone)]
 7779enum ActivateInDirectionTarget {
 7780    Pane(Entity<Pane>),
 7781    Dock(Entity<Dock>),
 7782    Sidebar(FocusHandle),
 7783}
 7784
 7785fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7786    window
 7787        .update(cx, |multi_workspace, _, cx| {
 7788            let workspace = multi_workspace.workspace().clone();
 7789            workspace.update(cx, |workspace, cx| {
 7790                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7791                    struct DatabaseFailedNotification;
 7792
 7793                    workspace.show_notification(
 7794                        NotificationId::unique::<DatabaseFailedNotification>(),
 7795                        cx,
 7796                        |cx| {
 7797                            cx.new(|cx| {
 7798                                MessageNotification::new("Failed to load the database file.", cx)
 7799                                    .primary_message("File an Issue")
 7800                                    .primary_icon(IconName::Plus)
 7801                                    .primary_on_click(|window, cx| {
 7802                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7803                                    })
 7804                            })
 7805                        },
 7806                    );
 7807                }
 7808            });
 7809        })
 7810        .log_err();
 7811}
 7812
 7813fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7814    if val == 0 {
 7815        ThemeSettings::get_global(cx).ui_font_size(cx)
 7816    } else {
 7817        px(val as f32)
 7818    }
 7819}
 7820
 7821fn adjust_active_dock_size_by_px(
 7822    px: Pixels,
 7823    workspace: &mut Workspace,
 7824    window: &mut Window,
 7825    cx: &mut Context<Workspace>,
 7826) {
 7827    let Some(active_dock) = workspace
 7828        .all_docks()
 7829        .into_iter()
 7830        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7831    else {
 7832        return;
 7833    };
 7834    let dock = active_dock.read(cx);
 7835    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7836        return;
 7837    };
 7838    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7839}
 7840
 7841fn adjust_open_docks_size_by_px(
 7842    px: Pixels,
 7843    workspace: &mut Workspace,
 7844    window: &mut Window,
 7845    cx: &mut Context<Workspace>,
 7846) {
 7847    let docks = workspace
 7848        .all_docks()
 7849        .into_iter()
 7850        .filter_map(|dock_entity| {
 7851            let dock = dock_entity.read(cx);
 7852            if dock.is_open() {
 7853                let dock_pos = dock.position();
 7854                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7855                Some((dock_pos, panel_size + px))
 7856            } else {
 7857                None
 7858            }
 7859        })
 7860        .collect::<Vec<_>>();
 7861
 7862    for (position, new_size) in docks {
 7863        workspace.resize_dock(position, new_size, window, cx);
 7864    }
 7865}
 7866
 7867impl Focusable for Workspace {
 7868    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7869        self.active_pane.focus_handle(cx)
 7870    }
 7871}
 7872
 7873#[derive(Clone)]
 7874struct DraggedDock(DockPosition);
 7875
 7876impl Render for DraggedDock {
 7877    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7878        gpui::Empty
 7879    }
 7880}
 7881
 7882impl Render for Workspace {
 7883    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7884        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7885        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7886            log::info!("Rendered first frame");
 7887        }
 7888
 7889        let centered_layout = self.centered_layout
 7890            && self.center.panes().len() == 1
 7891            && self.active_item(cx).is_some();
 7892        let render_padding = |size| {
 7893            (size > 0.0).then(|| {
 7894                div()
 7895                    .h_full()
 7896                    .w(relative(size))
 7897                    .bg(cx.theme().colors().editor_background)
 7898                    .border_color(cx.theme().colors().pane_group_border)
 7899            })
 7900        };
 7901        let paddings = if centered_layout {
 7902            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7903            (
 7904                render_padding(Self::adjust_padding(
 7905                    settings.left_padding.map(|padding| padding.0),
 7906                )),
 7907                render_padding(Self::adjust_padding(
 7908                    settings.right_padding.map(|padding| padding.0),
 7909                )),
 7910            )
 7911        } else {
 7912            (None, None)
 7913        };
 7914        let ui_font = theme_settings::setup_ui_font(window, cx);
 7915
 7916        let theme = cx.theme().clone();
 7917        let colors = theme.colors();
 7918        let notification_entities = self
 7919            .notifications
 7920            .iter()
 7921            .map(|(_, notification)| notification.entity_id())
 7922            .collect::<Vec<_>>();
 7923        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7924
 7925        div()
 7926            .relative()
 7927            .size_full()
 7928            .flex()
 7929            .flex_col()
 7930            .font(ui_font)
 7931            .gap_0()
 7932                .justify_start()
 7933                .items_start()
 7934                .text_color(colors.text)
 7935                .overflow_hidden()
 7936                .children(self.titlebar_item.clone())
 7937                .on_modifiers_changed(move |_, _, cx| {
 7938                    for &id in &notification_entities {
 7939                        cx.notify(id);
 7940                    }
 7941                })
 7942                .child(
 7943                    div()
 7944                        .size_full()
 7945                        .relative()
 7946                        .flex_1()
 7947                        .flex()
 7948                        .flex_col()
 7949                        .child(
 7950                            div()
 7951                                .id("workspace")
 7952                                .bg(colors.background)
 7953                                .relative()
 7954                                .flex_1()
 7955                                .w_full()
 7956                                .flex()
 7957                                .flex_col()
 7958                                .overflow_hidden()
 7959                                .border_t_1()
 7960                                .border_b_1()
 7961                                .border_color(colors.border)
 7962                                .child({
 7963                                    let this = cx.entity();
 7964                                    canvas(
 7965                                        move |bounds, window, cx| {
 7966                                            this.update(cx, |this, cx| {
 7967                                                let bounds_changed = this.bounds != bounds;
 7968                                                this.bounds = bounds;
 7969
 7970                                                if bounds_changed {
 7971                                                    this.left_dock.update(cx, |dock, cx| {
 7972                                                        dock.clamp_panel_size(
 7973                                                            bounds.size.width,
 7974                                                            window,
 7975                                                            cx,
 7976                                                        )
 7977                                                    });
 7978
 7979                                                    this.right_dock.update(cx, |dock, cx| {
 7980                                                        dock.clamp_panel_size(
 7981                                                            bounds.size.width,
 7982                                                            window,
 7983                                                            cx,
 7984                                                        )
 7985                                                    });
 7986
 7987                                                    this.bottom_dock.update(cx, |dock, cx| {
 7988                                                        dock.clamp_panel_size(
 7989                                                            bounds.size.height,
 7990                                                            window,
 7991                                                            cx,
 7992                                                        )
 7993                                                    });
 7994                                                }
 7995                                            })
 7996                                        },
 7997                                        |_, _, _, _| {},
 7998                                    )
 7999                                    .absolute()
 8000                                    .size_full()
 8001                                })
 8002                                .when(self.zoomed.is_none(), |this| {
 8003                                    this.on_drag_move(cx.listener(
 8004                                        move |workspace,
 8005                                              e: &DragMoveEvent<DraggedDock>,
 8006                                              window,
 8007                                              cx| {
 8008                                            if workspace.previous_dock_drag_coordinates
 8009                                                != Some(e.event.position)
 8010                                            {
 8011                                                workspace.previous_dock_drag_coordinates =
 8012                                                    Some(e.event.position);
 8013
 8014                                                match e.drag(cx).0 {
 8015                                                    DockPosition::Left => {
 8016                                                        workspace.resize_left_dock(
 8017                                                            e.event.position.x
 8018                                                                - workspace.bounds.left(),
 8019                                                            window,
 8020                                                            cx,
 8021                                                        );
 8022                                                    }
 8023                                                    DockPosition::Right => {
 8024                                                        workspace.resize_right_dock(
 8025                                                            workspace.bounds.right()
 8026                                                                - e.event.position.x,
 8027                                                            window,
 8028                                                            cx,
 8029                                                        );
 8030                                                    }
 8031                                                    DockPosition::Bottom => {
 8032                                                        workspace.resize_bottom_dock(
 8033                                                            workspace.bounds.bottom()
 8034                                                                - e.event.position.y,
 8035                                                            window,
 8036                                                            cx,
 8037                                                        );
 8038                                                    }
 8039                                                };
 8040                                                workspace.serialize_workspace(window, cx);
 8041                                            }
 8042                                        },
 8043                                    ))
 8044
 8045                                })
 8046                                .child({
 8047                                    match bottom_dock_layout {
 8048                                        BottomDockLayout::Full => div()
 8049                                            .flex()
 8050                                            .flex_col()
 8051                                            .h_full()
 8052                                            .child(
 8053                                                div()
 8054                                                    .flex()
 8055                                                    .flex_row()
 8056                                                    .flex_1()
 8057                                                    .overflow_hidden()
 8058                                                    .children(self.render_dock(
 8059                                                        DockPosition::Left,
 8060                                                        &self.left_dock,
 8061                                                        window,
 8062                                                        cx,
 8063                                                    ))
 8064
 8065                                                    .child(
 8066                                                        div()
 8067                                                            .flex()
 8068                                                            .flex_col()
 8069                                                            .flex_1()
 8070                                                            .overflow_hidden()
 8071                                                            .child(
 8072                                                                h_flex()
 8073                                                                    .flex_1()
 8074                                                                    .when_some(
 8075                                                                        paddings.0,
 8076                                                                        |this, p| {
 8077                                                                            this.child(
 8078                                                                                p.border_r_1(),
 8079                                                                            )
 8080                                                                        },
 8081                                                                    )
 8082                                                                    .child(self.center.render(
 8083                                                                        self.zoomed.as_ref(),
 8084                                                                        &PaneRenderContext {
 8085                                                                            follower_states:
 8086                                                                                &self.follower_states,
 8087                                                                            active_call: self.active_call(),
 8088                                                                            active_pane: &self.active_pane,
 8089                                                                            app_state: &self.app_state,
 8090                                                                            project: &self.project,
 8091                                                                            workspace: &self.weak_self,
 8092                                                                        },
 8093                                                                        window,
 8094                                                                        cx,
 8095                                                                    ))
 8096                                                                    .when_some(
 8097                                                                        paddings.1,
 8098                                                                        |this, p| {
 8099                                                                            this.child(
 8100                                                                                p.border_l_1(),
 8101                                                                            )
 8102                                                                        },
 8103                                                                    ),
 8104                                                            ),
 8105                                                    )
 8106
 8107                                                    .children(self.render_dock(
 8108                                                        DockPosition::Right,
 8109                                                        &self.right_dock,
 8110                                                        window,
 8111                                                        cx,
 8112                                                    )),
 8113                                            )
 8114                                            .child(div().w_full().children(self.render_dock(
 8115                                                DockPosition::Bottom,
 8116                                                &self.bottom_dock,
 8117                                                window,
 8118                                                cx
 8119                                            ))),
 8120
 8121                                        BottomDockLayout::LeftAligned => div()
 8122                                            .flex()
 8123                                            .flex_row()
 8124                                            .h_full()
 8125                                            .child(
 8126                                                div()
 8127                                                    .flex()
 8128                                                    .flex_col()
 8129                                                    .flex_1()
 8130                                                    .h_full()
 8131                                                    .child(
 8132                                                        div()
 8133                                                            .flex()
 8134                                                            .flex_row()
 8135                                                            .flex_1()
 8136                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8137
 8138                                                            .child(
 8139                                                                div()
 8140                                                                    .flex()
 8141                                                                    .flex_col()
 8142                                                                    .flex_1()
 8143                                                                    .overflow_hidden()
 8144                                                                    .child(
 8145                                                                        h_flex()
 8146                                                                            .flex_1()
 8147                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8148                                                                            .child(self.center.render(
 8149                                                                                self.zoomed.as_ref(),
 8150                                                                                &PaneRenderContext {
 8151                                                                                    follower_states:
 8152                                                                                        &self.follower_states,
 8153                                                                                    active_call: self.active_call(),
 8154                                                                                    active_pane: &self.active_pane,
 8155                                                                                    app_state: &self.app_state,
 8156                                                                                    project: &self.project,
 8157                                                                                    workspace: &self.weak_self,
 8158                                                                                },
 8159                                                                                window,
 8160                                                                                cx,
 8161                                                                            ))
 8162                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8163                                                                    )
 8164                                                            )
 8165
 8166                                                    )
 8167                                                    .child(
 8168                                                        div()
 8169                                                            .w_full()
 8170                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8171                                                    ),
 8172                                            )
 8173                                            .children(self.render_dock(
 8174                                                DockPosition::Right,
 8175                                                &self.right_dock,
 8176                                                window,
 8177                                                cx,
 8178                                            )),
 8179                                        BottomDockLayout::RightAligned => div()
 8180                                            .flex()
 8181                                            .flex_row()
 8182                                            .h_full()
 8183                                            .children(self.render_dock(
 8184                                                DockPosition::Left,
 8185                                                &self.left_dock,
 8186                                                window,
 8187                                                cx,
 8188                                            ))
 8189
 8190                                            .child(
 8191                                                div()
 8192                                                    .flex()
 8193                                                    .flex_col()
 8194                                                    .flex_1()
 8195                                                    .h_full()
 8196                                                    .child(
 8197                                                        div()
 8198                                                            .flex()
 8199                                                            .flex_row()
 8200                                                            .flex_1()
 8201                                                            .child(
 8202                                                                div()
 8203                                                                    .flex()
 8204                                                                    .flex_col()
 8205                                                                    .flex_1()
 8206                                                                    .overflow_hidden()
 8207                                                                    .child(
 8208                                                                        h_flex()
 8209                                                                            .flex_1()
 8210                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8211                                                                            .child(self.center.render(
 8212                                                                                self.zoomed.as_ref(),
 8213                                                                                &PaneRenderContext {
 8214                                                                                    follower_states:
 8215                                                                                        &self.follower_states,
 8216                                                                                    active_call: self.active_call(),
 8217                                                                                    active_pane: &self.active_pane,
 8218                                                                                    app_state: &self.app_state,
 8219                                                                                    project: &self.project,
 8220                                                                                    workspace: &self.weak_self,
 8221                                                                                },
 8222                                                                                window,
 8223                                                                                cx,
 8224                                                                            ))
 8225                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8226                                                                    )
 8227                                                            )
 8228
 8229                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8230                                                    )
 8231                                                    .child(
 8232                                                        div()
 8233                                                            .w_full()
 8234                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8235                                                    ),
 8236                                            ),
 8237                                        BottomDockLayout::Contained => div()
 8238                                            .flex()
 8239                                            .flex_row()
 8240                                            .h_full()
 8241                                            .children(self.render_dock(
 8242                                                DockPosition::Left,
 8243                                                &self.left_dock,
 8244                                                window,
 8245                                                cx,
 8246                                            ))
 8247
 8248                                            .child(
 8249                                                div()
 8250                                                    .flex()
 8251                                                    .flex_col()
 8252                                                    .flex_1()
 8253                                                    .overflow_hidden()
 8254                                                    .child(
 8255                                                        h_flex()
 8256                                                            .flex_1()
 8257                                                            .when_some(paddings.0, |this, p| {
 8258                                                                this.child(p.border_r_1())
 8259                                                            })
 8260                                                            .child(self.center.render(
 8261                                                                self.zoomed.as_ref(),
 8262                                                                &PaneRenderContext {
 8263                                                                    follower_states:
 8264                                                                        &self.follower_states,
 8265                                                                    active_call: self.active_call(),
 8266                                                                    active_pane: &self.active_pane,
 8267                                                                    app_state: &self.app_state,
 8268                                                                    project: &self.project,
 8269                                                                    workspace: &self.weak_self,
 8270                                                                },
 8271                                                                window,
 8272                                                                cx,
 8273                                                            ))
 8274                                                            .when_some(paddings.1, |this, p| {
 8275                                                                this.child(p.border_l_1())
 8276                                                            }),
 8277                                                    )
 8278                                                    .children(self.render_dock(
 8279                                                        DockPosition::Bottom,
 8280                                                        &self.bottom_dock,
 8281                                                        window,
 8282                                                        cx,
 8283                                                    )),
 8284                                            )
 8285
 8286                                            .children(self.render_dock(
 8287                                                DockPosition::Right,
 8288                                                &self.right_dock,
 8289                                                window,
 8290                                                cx,
 8291                                            )),
 8292                                    }
 8293                                })
 8294                                .children(self.zoomed.as_ref().and_then(|view| {
 8295                                    let zoomed_view = view.upgrade()?;
 8296                                    let div = div()
 8297                                        .occlude()
 8298                                        .absolute()
 8299                                        .overflow_hidden()
 8300                                        .border_color(colors.border)
 8301                                        .bg(colors.background)
 8302                                        .child(zoomed_view)
 8303                                        .inset_0()
 8304                                        .shadow_lg();
 8305
 8306                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8307                                       return Some(div);
 8308                                    }
 8309
 8310                                    Some(match self.zoomed_position {
 8311                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8312                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8313                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8314                                        None => {
 8315                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8316                                        }
 8317                                    })
 8318                                }))
 8319                                .children(self.render_notifications(window, cx)),
 8320                        )
 8321                        .when(self.status_bar_visible(cx), |parent| {
 8322                            parent.child(self.status_bar.clone())
 8323                        })
 8324                        .child(self.toast_layer.clone()),
 8325                )
 8326    }
 8327}
 8328
 8329impl WorkspaceStore {
 8330    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8331        Self {
 8332            workspaces: Default::default(),
 8333            _subscriptions: vec![
 8334                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8335                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8336            ],
 8337            client,
 8338        }
 8339    }
 8340
 8341    pub fn update_followers(
 8342        &self,
 8343        project_id: Option<u64>,
 8344        update: proto::update_followers::Variant,
 8345        cx: &App,
 8346    ) -> Option<()> {
 8347        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8348        let room_id = active_call.0.room_id(cx)?;
 8349        self.client
 8350            .send(proto::UpdateFollowers {
 8351                room_id,
 8352                project_id,
 8353                variant: Some(update),
 8354            })
 8355            .log_err()
 8356    }
 8357
 8358    pub async fn handle_follow(
 8359        this: Entity<Self>,
 8360        envelope: TypedEnvelope<proto::Follow>,
 8361        mut cx: AsyncApp,
 8362    ) -> Result<proto::FollowResponse> {
 8363        this.update(&mut cx, |this, cx| {
 8364            let follower = Follower {
 8365                project_id: envelope.payload.project_id,
 8366                peer_id: envelope.original_sender_id()?,
 8367            };
 8368
 8369            let mut response = proto::FollowResponse::default();
 8370
 8371            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8372                let Some(workspace) = weak_workspace.upgrade() else {
 8373                    return false;
 8374                };
 8375                window_handle
 8376                    .update(cx, |_, window, cx| {
 8377                        workspace.update(cx, |workspace, cx| {
 8378                            let handler_response =
 8379                                workspace.handle_follow(follower.project_id, window, cx);
 8380                            if let Some(active_view) = handler_response.active_view
 8381                                && workspace.project.read(cx).remote_id() == follower.project_id
 8382                            {
 8383                                response.active_view = Some(active_view)
 8384                            }
 8385                        });
 8386                    })
 8387                    .is_ok()
 8388            });
 8389
 8390            Ok(response)
 8391        })
 8392    }
 8393
 8394    async fn handle_update_followers(
 8395        this: Entity<Self>,
 8396        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8397        mut cx: AsyncApp,
 8398    ) -> Result<()> {
 8399        let leader_id = envelope.original_sender_id()?;
 8400        let update = envelope.payload;
 8401
 8402        this.update(&mut cx, |this, cx| {
 8403            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8404                let Some(workspace) = weak_workspace.upgrade() else {
 8405                    return false;
 8406                };
 8407                window_handle
 8408                    .update(cx, |_, window, cx| {
 8409                        workspace.update(cx, |workspace, cx| {
 8410                            let project_id = workspace.project.read(cx).remote_id();
 8411                            if update.project_id != project_id && update.project_id.is_some() {
 8412                                return;
 8413                            }
 8414                            workspace.handle_update_followers(
 8415                                leader_id,
 8416                                update.clone(),
 8417                                window,
 8418                                cx,
 8419                            );
 8420                        });
 8421                    })
 8422                    .is_ok()
 8423            });
 8424            Ok(())
 8425        })
 8426    }
 8427
 8428    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8429        self.workspaces.iter().map(|(_, weak)| weak)
 8430    }
 8431
 8432    pub fn workspaces_with_windows(
 8433        &self,
 8434    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8435        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8436    }
 8437}
 8438
 8439impl ViewId {
 8440    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8441        Ok(Self {
 8442            creator: message
 8443                .creator
 8444                .map(CollaboratorId::PeerId)
 8445                .context("creator is missing")?,
 8446            id: message.id,
 8447        })
 8448    }
 8449
 8450    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8451        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8452            Some(proto::ViewId {
 8453                creator: Some(peer_id),
 8454                id: self.id,
 8455            })
 8456        } else {
 8457            None
 8458        }
 8459    }
 8460}
 8461
 8462impl FollowerState {
 8463    fn pane(&self) -> &Entity<Pane> {
 8464        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8465    }
 8466}
 8467
 8468pub trait WorkspaceHandle {
 8469    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8470}
 8471
 8472impl WorkspaceHandle for Entity<Workspace> {
 8473    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8474        self.read(cx)
 8475            .worktrees(cx)
 8476            .flat_map(|worktree| {
 8477                let worktree_id = worktree.read(cx).id();
 8478                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8479                    worktree_id,
 8480                    path: f.path.clone(),
 8481                })
 8482            })
 8483            .collect::<Vec<_>>()
 8484    }
 8485}
 8486
 8487pub async fn last_opened_workspace_location(
 8488    db: &WorkspaceDb,
 8489    fs: &dyn fs::Fs,
 8490) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8491    db.last_workspace(fs)
 8492        .await
 8493        .log_err()
 8494        .flatten()
 8495        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8496}
 8497
 8498pub async fn last_session_workspace_locations(
 8499    db: &WorkspaceDb,
 8500    last_session_id: &str,
 8501    last_session_window_stack: Option<Vec<WindowId>>,
 8502    fs: &dyn fs::Fs,
 8503) -> Option<Vec<SessionWorkspace>> {
 8504    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8505        .await
 8506        .log_err()
 8507}
 8508
 8509pub struct MultiWorkspaceRestoreResult {
 8510    pub window_handle: WindowHandle<MultiWorkspace>,
 8511    pub errors: Vec<anyhow::Error>,
 8512}
 8513
 8514pub async fn restore_multiworkspace(
 8515    multi_workspace: SerializedMultiWorkspace,
 8516    app_state: Arc<AppState>,
 8517    cx: &mut AsyncApp,
 8518) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8519    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8520    let mut group_iter = workspaces.into_iter();
 8521    let first = group_iter
 8522        .next()
 8523        .context("window group must not be empty")?;
 8524
 8525    let window_handle = if first.paths.is_empty() {
 8526        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8527            .await?
 8528    } else {
 8529        let OpenResult { window, .. } = cx
 8530            .update(|cx| {
 8531                Workspace::new_local(
 8532                    first.paths.paths().to_vec(),
 8533                    app_state.clone(),
 8534                    None,
 8535                    None,
 8536                    None,
 8537                    true,
 8538                    cx,
 8539                )
 8540            })
 8541            .await?;
 8542        window
 8543    };
 8544
 8545    let mut errors = Vec::new();
 8546
 8547    for session_workspace in group_iter {
 8548        let error = if session_workspace.paths.is_empty() {
 8549            cx.update(|cx| {
 8550                open_workspace_by_id(
 8551                    session_workspace.workspace_id,
 8552                    app_state.clone(),
 8553                    Some(window_handle),
 8554                    cx,
 8555                )
 8556            })
 8557            .await
 8558            .err()
 8559        } else {
 8560            cx.update(|cx| {
 8561                Workspace::new_local(
 8562                    session_workspace.paths.paths().to_vec(),
 8563                    app_state.clone(),
 8564                    Some(window_handle),
 8565                    None,
 8566                    None,
 8567                    false,
 8568                    cx,
 8569                )
 8570            })
 8571            .await
 8572            .err()
 8573        };
 8574
 8575        if let Some(error) = error {
 8576            errors.push(error);
 8577        }
 8578    }
 8579
 8580    if let Some(target_id) = state.active_workspace_id {
 8581        window_handle
 8582            .update(cx, |multi_workspace, window, cx| {
 8583                let target_index = multi_workspace
 8584                    .workspaces()
 8585                    .iter()
 8586                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8587                if let Some(index) = target_index {
 8588                    multi_workspace.activate_index(index, window, cx);
 8589                } else if !multi_workspace.workspaces().is_empty() {
 8590                    multi_workspace.activate_index(0, window, cx);
 8591                }
 8592            })
 8593            .ok();
 8594    } else {
 8595        window_handle
 8596            .update(cx, |multi_workspace, window, cx| {
 8597                if !multi_workspace.workspaces().is_empty() {
 8598                    multi_workspace.activate_index(0, window, cx);
 8599                }
 8600            })
 8601            .ok();
 8602    }
 8603
 8604    if state.sidebar_open {
 8605        window_handle
 8606            .update(cx, |multi_workspace, _, cx| {
 8607                multi_workspace.open_sidebar(cx);
 8608            })
 8609            .ok();
 8610    }
 8611
 8612    window_handle
 8613        .update(cx, |_, window, _cx| {
 8614            window.activate_window();
 8615        })
 8616        .ok();
 8617
 8618    Ok(MultiWorkspaceRestoreResult {
 8619        window_handle,
 8620        errors,
 8621    })
 8622}
 8623
 8624actions!(
 8625    collab,
 8626    [
 8627        /// Opens the channel notes for the current call.
 8628        ///
 8629        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8630        /// channel in the collab panel.
 8631        ///
 8632        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8633        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8634        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8635        OpenChannelNotes,
 8636        /// Mutes your microphone.
 8637        Mute,
 8638        /// Deafens yourself (mute both microphone and speakers).
 8639        Deafen,
 8640        /// Leaves the current call.
 8641        LeaveCall,
 8642        /// Shares the current project with collaborators.
 8643        ShareProject,
 8644        /// Shares your screen with collaborators.
 8645        ScreenShare,
 8646        /// Copies the current room name and session id for debugging purposes.
 8647        CopyRoomId,
 8648    ]
 8649);
 8650
 8651/// Opens the channel notes for a specific channel by its ID.
 8652#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8653#[action(namespace = collab)]
 8654#[serde(deny_unknown_fields)]
 8655pub struct OpenChannelNotesById {
 8656    pub channel_id: u64,
 8657}
 8658
 8659actions!(
 8660    zed,
 8661    [
 8662        /// Opens the Zed log file.
 8663        OpenLog,
 8664        /// Reveals the Zed log file in the system file manager.
 8665        RevealLogInFileManager
 8666    ]
 8667);
 8668
 8669async fn join_channel_internal(
 8670    channel_id: ChannelId,
 8671    app_state: &Arc<AppState>,
 8672    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8673    requesting_workspace: Option<WeakEntity<Workspace>>,
 8674    active_call: &dyn AnyActiveCall,
 8675    cx: &mut AsyncApp,
 8676) -> Result<bool> {
 8677    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8678        if !active_call.is_in_room(cx) {
 8679            return (false, false);
 8680        }
 8681
 8682        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8683        let should_prompt = active_call.is_sharing_project(cx)
 8684            && active_call.has_remote_participants(cx)
 8685            && !already_in_channel;
 8686        (should_prompt, already_in_channel)
 8687    });
 8688
 8689    if already_in_channel {
 8690        let task = cx.update(|cx| {
 8691            if let Some((project, host)) = active_call.most_active_project(cx) {
 8692                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8693            } else {
 8694                None
 8695            }
 8696        });
 8697        if let Some(task) = task {
 8698            task.await?;
 8699        }
 8700        return anyhow::Ok(true);
 8701    }
 8702
 8703    if should_prompt {
 8704        if let Some(multi_workspace) = requesting_window {
 8705            let answer = multi_workspace
 8706                .update(cx, |_, window, cx| {
 8707                    window.prompt(
 8708                        PromptLevel::Warning,
 8709                        "Do you want to switch channels?",
 8710                        Some("Leaving this call will unshare your current project."),
 8711                        &["Yes, Join Channel", "Cancel"],
 8712                        cx,
 8713                    )
 8714                })?
 8715                .await;
 8716
 8717            if answer == Ok(1) {
 8718                return Ok(false);
 8719            }
 8720        } else {
 8721            return Ok(false);
 8722        }
 8723    }
 8724
 8725    let client = cx.update(|cx| active_call.client(cx));
 8726
 8727    let mut client_status = client.status();
 8728
 8729    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8730    'outer: loop {
 8731        let Some(status) = client_status.recv().await else {
 8732            anyhow::bail!("error connecting");
 8733        };
 8734
 8735        match status {
 8736            Status::Connecting
 8737            | Status::Authenticating
 8738            | Status::Authenticated
 8739            | Status::Reconnecting
 8740            | Status::Reauthenticating
 8741            | Status::Reauthenticated => continue,
 8742            Status::Connected { .. } => break 'outer,
 8743            Status::SignedOut | Status::AuthenticationError => {
 8744                return Err(ErrorCode::SignedOut.into());
 8745            }
 8746            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8747            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8748                return Err(ErrorCode::Disconnected.into());
 8749            }
 8750        }
 8751    }
 8752
 8753    let joined = cx
 8754        .update(|cx| active_call.join_channel(channel_id, cx))
 8755        .await?;
 8756
 8757    if !joined {
 8758        return anyhow::Ok(true);
 8759    }
 8760
 8761    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8762
 8763    let task = cx.update(|cx| {
 8764        if let Some((project, host)) = active_call.most_active_project(cx) {
 8765            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8766        }
 8767
 8768        // If you are the first to join a channel, see if you should share your project.
 8769        if !active_call.has_remote_participants(cx)
 8770            && !active_call.local_participant_is_guest(cx)
 8771            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8772        {
 8773            let project = workspace.update(cx, |workspace, cx| {
 8774                let project = workspace.project.read(cx);
 8775
 8776                if !active_call.share_on_join(cx) {
 8777                    return None;
 8778                }
 8779
 8780                if (project.is_local() || project.is_via_remote_server())
 8781                    && project.visible_worktrees(cx).any(|tree| {
 8782                        tree.read(cx)
 8783                            .root_entry()
 8784                            .is_some_and(|entry| entry.is_dir())
 8785                    })
 8786                {
 8787                    Some(workspace.project.clone())
 8788                } else {
 8789                    None
 8790                }
 8791            });
 8792            if let Some(project) = project {
 8793                let share_task = active_call.share_project(project, cx);
 8794                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8795                    share_task.await?;
 8796                    Ok(())
 8797                }));
 8798            }
 8799        }
 8800
 8801        None
 8802    });
 8803    if let Some(task) = task {
 8804        task.await?;
 8805        return anyhow::Ok(true);
 8806    }
 8807    anyhow::Ok(false)
 8808}
 8809
 8810pub fn join_channel(
 8811    channel_id: ChannelId,
 8812    app_state: Arc<AppState>,
 8813    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8814    requesting_workspace: Option<WeakEntity<Workspace>>,
 8815    cx: &mut App,
 8816) -> Task<Result<()>> {
 8817    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8818    cx.spawn(async move |cx| {
 8819        let result = join_channel_internal(
 8820            channel_id,
 8821            &app_state,
 8822            requesting_window,
 8823            requesting_workspace,
 8824            &*active_call.0,
 8825            cx,
 8826        )
 8827        .await;
 8828
 8829        // join channel succeeded, and opened a window
 8830        if matches!(result, Ok(true)) {
 8831            return anyhow::Ok(());
 8832        }
 8833
 8834        // find an existing workspace to focus and show call controls
 8835        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8836        if active_window.is_none() {
 8837            // no open workspaces, make one to show the error in (blergh)
 8838            let OpenResult {
 8839                window: window_handle,
 8840                ..
 8841            } = cx
 8842                .update(|cx| {
 8843                    Workspace::new_local(
 8844                        vec![],
 8845                        app_state.clone(),
 8846                        requesting_window,
 8847                        None,
 8848                        None,
 8849                        true,
 8850                        cx,
 8851                    )
 8852                })
 8853                .await?;
 8854
 8855            window_handle
 8856                .update(cx, |_, window, _cx| {
 8857                    window.activate_window();
 8858                })
 8859                .ok();
 8860
 8861            if result.is_ok() {
 8862                cx.update(|cx| {
 8863                    cx.dispatch_action(&OpenChannelNotes);
 8864                });
 8865            }
 8866
 8867            active_window = Some(window_handle);
 8868        }
 8869
 8870        if let Err(err) = result {
 8871            log::error!("failed to join channel: {}", err);
 8872            if let Some(active_window) = active_window {
 8873                active_window
 8874                    .update(cx, |_, window, cx| {
 8875                        let detail: SharedString = match err.error_code() {
 8876                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8877                            ErrorCode::UpgradeRequired => concat!(
 8878                                "Your are running an unsupported version of Zed. ",
 8879                                "Please update to continue."
 8880                            )
 8881                            .into(),
 8882                            ErrorCode::NoSuchChannel => concat!(
 8883                                "No matching channel was found. ",
 8884                                "Please check the link and try again."
 8885                            )
 8886                            .into(),
 8887                            ErrorCode::Forbidden => concat!(
 8888                                "This channel is private, and you do not have access. ",
 8889                                "Please ask someone to add you and try again."
 8890                            )
 8891                            .into(),
 8892                            ErrorCode::Disconnected => {
 8893                                "Please check your internet connection and try again.".into()
 8894                            }
 8895                            _ => format!("{}\n\nPlease try again.", err).into(),
 8896                        };
 8897                        window.prompt(
 8898                            PromptLevel::Critical,
 8899                            "Failed to join channel",
 8900                            Some(&detail),
 8901                            &["Ok"],
 8902                            cx,
 8903                        )
 8904                    })?
 8905                    .await
 8906                    .ok();
 8907            }
 8908        }
 8909
 8910        // return ok, we showed the error to the user.
 8911        anyhow::Ok(())
 8912    })
 8913}
 8914
 8915pub async fn get_any_active_multi_workspace(
 8916    app_state: Arc<AppState>,
 8917    mut cx: AsyncApp,
 8918) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8919    // find an existing workspace to focus and show call controls
 8920    let active_window = activate_any_workspace_window(&mut cx);
 8921    if active_window.is_none() {
 8922        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8923            .await?;
 8924    }
 8925    activate_any_workspace_window(&mut cx).context("could not open zed")
 8926}
 8927
 8928fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8929    cx.update(|cx| {
 8930        if let Some(workspace_window) = cx
 8931            .active_window()
 8932            .and_then(|window| window.downcast::<MultiWorkspace>())
 8933        {
 8934            return Some(workspace_window);
 8935        }
 8936
 8937        for window in cx.windows() {
 8938            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8939                workspace_window
 8940                    .update(cx, |_, window, _| window.activate_window())
 8941                    .ok();
 8942                return Some(workspace_window);
 8943            }
 8944        }
 8945        None
 8946    })
 8947}
 8948
 8949pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8950    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8951}
 8952
 8953pub fn workspace_windows_for_location(
 8954    serialized_location: &SerializedWorkspaceLocation,
 8955    cx: &App,
 8956) -> Vec<WindowHandle<MultiWorkspace>> {
 8957    cx.windows()
 8958        .into_iter()
 8959        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8960        .filter(|multi_workspace| {
 8961            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8962                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8963                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8964                }
 8965                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8966                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8967                    a.distro_name == b.distro_name
 8968                }
 8969                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8970                    a.container_id == b.container_id
 8971                }
 8972                #[cfg(any(test, feature = "test-support"))]
 8973                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8974                    a.id == b.id
 8975                }
 8976                _ => false,
 8977            };
 8978
 8979            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8980                multi_workspace.workspaces().iter().any(|workspace| {
 8981                    match workspace.read(cx).workspace_location(cx) {
 8982                        WorkspaceLocation::Location(location, _) => {
 8983                            match (&location, serialized_location) {
 8984                                (
 8985                                    SerializedWorkspaceLocation::Local,
 8986                                    SerializedWorkspaceLocation::Local,
 8987                                ) => true,
 8988                                (
 8989                                    SerializedWorkspaceLocation::Remote(a),
 8990                                    SerializedWorkspaceLocation::Remote(b),
 8991                                ) => same_host(a, b),
 8992                                _ => false,
 8993                            }
 8994                        }
 8995                        _ => false,
 8996                    }
 8997                })
 8998            })
 8999        })
 9000        .collect()
 9001}
 9002
 9003pub async fn find_existing_workspace(
 9004    abs_paths: &[PathBuf],
 9005    open_options: &OpenOptions,
 9006    location: &SerializedWorkspaceLocation,
 9007    cx: &mut AsyncApp,
 9008) -> (
 9009    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9010    OpenVisible,
 9011) {
 9012    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9013    let mut open_visible = OpenVisible::All;
 9014    let mut best_match = None;
 9015
 9016    if open_options.open_new_workspace != Some(true) {
 9017        cx.update(|cx| {
 9018            for window in workspace_windows_for_location(location, cx) {
 9019                if let Ok(multi_workspace) = window.read(cx) {
 9020                    for workspace in multi_workspace.workspaces() {
 9021                        let project = workspace.read(cx).project.read(cx);
 9022                        let m = project.visibility_for_paths(
 9023                            abs_paths,
 9024                            open_options.open_new_workspace == None,
 9025                            cx,
 9026                        );
 9027                        if m > best_match {
 9028                            existing = Some((window, workspace.clone()));
 9029                            best_match = m;
 9030                        } else if best_match.is_none()
 9031                            && open_options.open_new_workspace == Some(false)
 9032                        {
 9033                            existing = Some((window, workspace.clone()))
 9034                        }
 9035                    }
 9036                }
 9037            }
 9038        });
 9039
 9040        let all_paths_are_files = existing
 9041            .as_ref()
 9042            .and_then(|(_, target_workspace)| {
 9043                cx.update(|cx| {
 9044                    let workspace = target_workspace.read(cx);
 9045                    let project = workspace.project.read(cx);
 9046                    let path_style = workspace.path_style(cx);
 9047                    Some(!abs_paths.iter().any(|path| {
 9048                        let path = util::paths::SanitizedPath::new(path);
 9049                        project.worktrees(cx).any(|worktree| {
 9050                            let worktree = worktree.read(cx);
 9051                            let abs_path = worktree.abs_path();
 9052                            path_style
 9053                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9054                                .and_then(|rel| worktree.entry_for_path(&rel))
 9055                                .is_some_and(|e| e.is_dir())
 9056                        })
 9057                    }))
 9058                })
 9059            })
 9060            .unwrap_or(false);
 9061
 9062        if open_options.open_new_workspace.is_none()
 9063            && existing.is_some()
 9064            && open_options.wait
 9065            && all_paths_are_files
 9066        {
 9067            cx.update(|cx| {
 9068                let windows = workspace_windows_for_location(location, cx);
 9069                let window = cx
 9070                    .active_window()
 9071                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9072                    .filter(|window| windows.contains(window))
 9073                    .or_else(|| windows.into_iter().next());
 9074                if let Some(window) = window {
 9075                    if let Ok(multi_workspace) = window.read(cx) {
 9076                        let active_workspace = multi_workspace.workspace().clone();
 9077                        existing = Some((window, active_workspace));
 9078                        open_visible = OpenVisible::None;
 9079                    }
 9080                }
 9081            });
 9082        }
 9083    }
 9084    (existing, open_visible)
 9085}
 9086
 9087#[derive(Default, Clone)]
 9088pub struct OpenOptions {
 9089    pub visible: Option<OpenVisible>,
 9090    pub focus: Option<bool>,
 9091    pub open_new_workspace: Option<bool>,
 9092    pub wait: bool,
 9093    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 9094    pub env: Option<HashMap<String, String>>,
 9095}
 9096
 9097/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9098/// or [`Workspace::open_workspace_for_paths`].
 9099pub struct OpenResult {
 9100    pub window: WindowHandle<MultiWorkspace>,
 9101    pub workspace: Entity<Workspace>,
 9102    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9103}
 9104
 9105/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9106pub fn open_workspace_by_id(
 9107    workspace_id: WorkspaceId,
 9108    app_state: Arc<AppState>,
 9109    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9110    cx: &mut App,
 9111) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9112    let project_handle = Project::local(
 9113        app_state.client.clone(),
 9114        app_state.node_runtime.clone(),
 9115        app_state.user_store.clone(),
 9116        app_state.languages.clone(),
 9117        app_state.fs.clone(),
 9118        None,
 9119        project::LocalProjectFlags {
 9120            init_worktree_trust: true,
 9121            ..project::LocalProjectFlags::default()
 9122        },
 9123        cx,
 9124    );
 9125
 9126    let db = WorkspaceDb::global(cx);
 9127    let kvp = db::kvp::KeyValueStore::global(cx);
 9128    cx.spawn(async move |cx| {
 9129        let serialized_workspace = db
 9130            .workspace_for_id(workspace_id)
 9131            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9132
 9133        let centered_layout = serialized_workspace.centered_layout;
 9134
 9135        let (window, workspace) = if let Some(window) = requesting_window {
 9136            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9137                let workspace = cx.new(|cx| {
 9138                    let mut workspace = Workspace::new(
 9139                        Some(workspace_id),
 9140                        project_handle.clone(),
 9141                        app_state.clone(),
 9142                        window,
 9143                        cx,
 9144                    );
 9145                    workspace.centered_layout = centered_layout;
 9146                    workspace
 9147                });
 9148                multi_workspace.add_workspace(workspace.clone(), cx);
 9149                workspace
 9150            })?;
 9151            (window, workspace)
 9152        } else {
 9153            let window_bounds_override = window_bounds_env_override();
 9154
 9155            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9156                (Some(WindowBounds::Windowed(bounds)), None)
 9157            } else if let Some(display) = serialized_workspace.display
 9158                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9159            {
 9160                (Some(bounds.0), Some(display))
 9161            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9162                (Some(bounds), Some(display))
 9163            } else {
 9164                (None, None)
 9165            };
 9166
 9167            let options = cx.update(|cx| {
 9168                let mut options = (app_state.build_window_options)(display, cx);
 9169                options.window_bounds = window_bounds;
 9170                options
 9171            });
 9172
 9173            let window = cx.open_window(options, {
 9174                let app_state = app_state.clone();
 9175                let project_handle = project_handle.clone();
 9176                move |window, cx| {
 9177                    let workspace = cx.new(|cx| {
 9178                        let mut workspace = Workspace::new(
 9179                            Some(workspace_id),
 9180                            project_handle,
 9181                            app_state,
 9182                            window,
 9183                            cx,
 9184                        );
 9185                        workspace.centered_layout = centered_layout;
 9186                        workspace
 9187                    });
 9188                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9189                }
 9190            })?;
 9191
 9192            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9193                multi_workspace.workspace().clone()
 9194            })?;
 9195
 9196            (window, workspace)
 9197        };
 9198
 9199        notify_if_database_failed(window, cx);
 9200
 9201        // Restore items from the serialized workspace
 9202        window
 9203            .update(cx, |_, window, cx| {
 9204                workspace.update(cx, |_workspace, cx| {
 9205                    open_items(Some(serialized_workspace), vec![], window, cx)
 9206                })
 9207            })?
 9208            .await?;
 9209
 9210        window.update(cx, |_, window, cx| {
 9211            workspace.update(cx, |workspace, cx| {
 9212                workspace.serialize_workspace(window, cx);
 9213            });
 9214        })?;
 9215
 9216        Ok(window)
 9217    })
 9218}
 9219
 9220#[allow(clippy::type_complexity)]
 9221pub fn open_paths(
 9222    abs_paths: &[PathBuf],
 9223    app_state: Arc<AppState>,
 9224    open_options: OpenOptions,
 9225    cx: &mut App,
 9226) -> Task<anyhow::Result<OpenResult>> {
 9227    let abs_paths = abs_paths.to_vec();
 9228    #[cfg(target_os = "windows")]
 9229    let wsl_path = abs_paths
 9230        .iter()
 9231        .find_map(|p| util::paths::WslPath::from_path(p));
 9232
 9233    cx.spawn(async move |cx| {
 9234        let (mut existing, mut open_visible) = find_existing_workspace(
 9235            &abs_paths,
 9236            &open_options,
 9237            &SerializedWorkspaceLocation::Local,
 9238            cx,
 9239        )
 9240        .await;
 9241
 9242        // Fallback: if no workspace contains the paths and all paths are files,
 9243        // prefer an existing local workspace window (active window first).
 9244        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9245            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9246            let all_metadatas = futures::future::join_all(all_paths)
 9247                .await
 9248                .into_iter()
 9249                .filter_map(|result| result.ok().flatten())
 9250                .collect::<Vec<_>>();
 9251
 9252            if all_metadatas.iter().all(|file| !file.is_dir) {
 9253                cx.update(|cx| {
 9254                    let windows = workspace_windows_for_location(
 9255                        &SerializedWorkspaceLocation::Local,
 9256                        cx,
 9257                    );
 9258                    let window = cx
 9259                        .active_window()
 9260                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9261                        .filter(|window| windows.contains(window))
 9262                        .or_else(|| windows.into_iter().next());
 9263                    if let Some(window) = window {
 9264                        if let Ok(multi_workspace) = window.read(cx) {
 9265                            let active_workspace = multi_workspace.workspace().clone();
 9266                            existing = Some((window, active_workspace));
 9267                            open_visible = OpenVisible::None;
 9268                        }
 9269                    }
 9270                });
 9271            }
 9272        }
 9273
 9274        let result = if let Some((existing, target_workspace)) = existing {
 9275            let open_task = existing
 9276                .update(cx, |multi_workspace, window, cx| {
 9277                    window.activate_window();
 9278                    multi_workspace.activate(target_workspace.clone(), cx);
 9279                    target_workspace.update(cx, |workspace, cx| {
 9280                        workspace.open_paths(
 9281                            abs_paths,
 9282                            OpenOptions {
 9283                                visible: Some(open_visible),
 9284                                ..Default::default()
 9285                            },
 9286                            None,
 9287                            window,
 9288                            cx,
 9289                        )
 9290                    })
 9291                })?
 9292                .await;
 9293
 9294            _ = existing.update(cx, |multi_workspace, _, cx| {
 9295                let workspace = multi_workspace.workspace().clone();
 9296                workspace.update(cx, |workspace, cx| {
 9297                    for item in open_task.iter().flatten() {
 9298                        if let Err(e) = item {
 9299                            workspace.show_error(&e, cx);
 9300                        }
 9301                    }
 9302                });
 9303            });
 9304
 9305            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9306        } else {
 9307            let result = cx
 9308                .update(move |cx| {
 9309                    Workspace::new_local(
 9310                        abs_paths,
 9311                        app_state.clone(),
 9312                        open_options.replace_window,
 9313                        open_options.env,
 9314                        None,
 9315                        true,
 9316                        cx,
 9317                    )
 9318                })
 9319                .await;
 9320
 9321            if let Ok(ref result) = result {
 9322                result.window
 9323                    .update(cx, |_, window, _cx| {
 9324                        window.activate_window();
 9325                    })
 9326                    .log_err();
 9327            }
 9328
 9329            result
 9330        };
 9331
 9332        #[cfg(target_os = "windows")]
 9333        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9334            && let Ok(ref result) = result
 9335        {
 9336            result.window
 9337                .update(cx, move |multi_workspace, _window, cx| {
 9338                    struct OpenInWsl;
 9339                    let workspace = multi_workspace.workspace().clone();
 9340                    workspace.update(cx, |workspace, cx| {
 9341                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9342                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9343                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9344                            cx.new(move |cx| {
 9345                                MessageNotification::new(msg, cx)
 9346                                    .primary_message("Open in WSL")
 9347                                    .primary_icon(IconName::FolderOpen)
 9348                                    .primary_on_click(move |window, cx| {
 9349                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9350                                                distro: remote::WslConnectionOptions {
 9351                                                        distro_name: distro.clone(),
 9352                                                    user: None,
 9353                                                },
 9354                                                paths: vec![path.clone().into()],
 9355                                            }), cx)
 9356                                    })
 9357                            })
 9358                        });
 9359                    });
 9360                })
 9361                .unwrap();
 9362        };
 9363        result
 9364    })
 9365}
 9366
 9367pub fn open_new(
 9368    open_options: OpenOptions,
 9369    app_state: Arc<AppState>,
 9370    cx: &mut App,
 9371    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9372) -> Task<anyhow::Result<()>> {
 9373    let task = Workspace::new_local(
 9374        Vec::new(),
 9375        app_state,
 9376        open_options.replace_window,
 9377        open_options.env,
 9378        Some(Box::new(init)),
 9379        true,
 9380        cx,
 9381    );
 9382    cx.spawn(async move |cx| {
 9383        let OpenResult { window, .. } = task.await?;
 9384        window
 9385            .update(cx, |_, window, _cx| {
 9386                window.activate_window();
 9387            })
 9388            .ok();
 9389        Ok(())
 9390    })
 9391}
 9392
 9393pub fn create_and_open_local_file(
 9394    path: &'static Path,
 9395    window: &mut Window,
 9396    cx: &mut Context<Workspace>,
 9397    default_content: impl 'static + Send + FnOnce() -> Rope,
 9398) -> Task<Result<Box<dyn ItemHandle>>> {
 9399    cx.spawn_in(window, async move |workspace, cx| {
 9400        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9401        if !fs.is_file(path).await {
 9402            fs.create_file(path, Default::default()).await?;
 9403            fs.save(path, &default_content(), Default::default())
 9404                .await?;
 9405        }
 9406
 9407        workspace
 9408            .update_in(cx, |workspace, window, cx| {
 9409                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9410                    let path = workspace
 9411                        .project
 9412                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9413                    cx.spawn_in(window, async move |workspace, cx| {
 9414                        let path = path.await?;
 9415
 9416                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9417
 9418                        let mut items = workspace
 9419                            .update_in(cx, |workspace, window, cx| {
 9420                                workspace.open_paths(
 9421                                    vec![path.to_path_buf()],
 9422                                    OpenOptions {
 9423                                        visible: Some(OpenVisible::None),
 9424                                        ..Default::default()
 9425                                    },
 9426                                    None,
 9427                                    window,
 9428                                    cx,
 9429                                )
 9430                            })?
 9431                            .await;
 9432                        let item = items.pop().flatten();
 9433                        item.with_context(|| format!("path {path:?} is not a file"))?
 9434                    })
 9435                })
 9436            })?
 9437            .await?
 9438            .await
 9439    })
 9440}
 9441
 9442pub fn open_remote_project_with_new_connection(
 9443    window: WindowHandle<MultiWorkspace>,
 9444    remote_connection: Arc<dyn RemoteConnection>,
 9445    cancel_rx: oneshot::Receiver<()>,
 9446    delegate: Arc<dyn RemoteClientDelegate>,
 9447    app_state: Arc<AppState>,
 9448    paths: Vec<PathBuf>,
 9449    cx: &mut App,
 9450) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9451    cx.spawn(async move |cx| {
 9452        let (workspace_id, serialized_workspace) =
 9453            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9454                .await?;
 9455
 9456        let session = match cx
 9457            .update(|cx| {
 9458                remote::RemoteClient::new(
 9459                    ConnectionIdentifier::Workspace(workspace_id.0),
 9460                    remote_connection,
 9461                    cancel_rx,
 9462                    delegate,
 9463                    cx,
 9464                )
 9465            })
 9466            .await?
 9467        {
 9468            Some(result) => result,
 9469            None => return Ok(Vec::new()),
 9470        };
 9471
 9472        let project = cx.update(|cx| {
 9473            project::Project::remote(
 9474                session,
 9475                app_state.client.clone(),
 9476                app_state.node_runtime.clone(),
 9477                app_state.user_store.clone(),
 9478                app_state.languages.clone(),
 9479                app_state.fs.clone(),
 9480                true,
 9481                cx,
 9482            )
 9483        });
 9484
 9485        open_remote_project_inner(
 9486            project,
 9487            paths,
 9488            workspace_id,
 9489            serialized_workspace,
 9490            app_state,
 9491            window,
 9492            cx,
 9493        )
 9494        .await
 9495    })
 9496}
 9497
 9498pub fn open_remote_project_with_existing_connection(
 9499    connection_options: RemoteConnectionOptions,
 9500    project: Entity<Project>,
 9501    paths: Vec<PathBuf>,
 9502    app_state: Arc<AppState>,
 9503    window: WindowHandle<MultiWorkspace>,
 9504    cx: &mut AsyncApp,
 9505) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9506    cx.spawn(async move |cx| {
 9507        let (workspace_id, serialized_workspace) =
 9508            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9509
 9510        open_remote_project_inner(
 9511            project,
 9512            paths,
 9513            workspace_id,
 9514            serialized_workspace,
 9515            app_state,
 9516            window,
 9517            cx,
 9518        )
 9519        .await
 9520    })
 9521}
 9522
 9523async fn open_remote_project_inner(
 9524    project: Entity<Project>,
 9525    paths: Vec<PathBuf>,
 9526    workspace_id: WorkspaceId,
 9527    serialized_workspace: Option<SerializedWorkspace>,
 9528    app_state: Arc<AppState>,
 9529    window: WindowHandle<MultiWorkspace>,
 9530    cx: &mut AsyncApp,
 9531) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9532    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9533    let toolchains = db.toolchains(workspace_id).await?;
 9534    for (toolchain, worktree_path, path) in toolchains {
 9535        project
 9536            .update(cx, |this, cx| {
 9537                let Some(worktree_id) =
 9538                    this.find_worktree(&worktree_path, cx)
 9539                        .and_then(|(worktree, rel_path)| {
 9540                            if rel_path.is_empty() {
 9541                                Some(worktree.read(cx).id())
 9542                            } else {
 9543                                None
 9544                            }
 9545                        })
 9546                else {
 9547                    return Task::ready(None);
 9548                };
 9549
 9550                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9551            })
 9552            .await;
 9553    }
 9554    let mut project_paths_to_open = vec![];
 9555    let mut project_path_errors = vec![];
 9556
 9557    for path in paths {
 9558        let result = cx
 9559            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9560            .await;
 9561        match result {
 9562            Ok((_, project_path)) => {
 9563                project_paths_to_open.push((path.clone(), Some(project_path)));
 9564            }
 9565            Err(error) => {
 9566                project_path_errors.push(error);
 9567            }
 9568        };
 9569    }
 9570
 9571    if project_paths_to_open.is_empty() {
 9572        return Err(project_path_errors.pop().context("no paths given")?);
 9573    }
 9574
 9575    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9576        telemetry::event!("SSH Project Opened");
 9577
 9578        let new_workspace = cx.new(|cx| {
 9579            let mut workspace =
 9580                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9581            workspace.update_history(cx);
 9582
 9583            if let Some(ref serialized) = serialized_workspace {
 9584                workspace.centered_layout = serialized.centered_layout;
 9585            }
 9586
 9587            workspace
 9588        });
 9589
 9590        multi_workspace.activate(new_workspace.clone(), cx);
 9591        new_workspace
 9592    })?;
 9593
 9594    let items = window
 9595        .update(cx, |_, window, cx| {
 9596            window.activate_window();
 9597            workspace.update(cx, |_workspace, cx| {
 9598                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9599            })
 9600        })?
 9601        .await?;
 9602
 9603    workspace.update(cx, |workspace, cx| {
 9604        for error in project_path_errors {
 9605            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9606                if let Some(path) = error.error_tag("path") {
 9607                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9608                }
 9609            } else {
 9610                workspace.show_error(&error, cx)
 9611            }
 9612        }
 9613    });
 9614
 9615    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9616}
 9617
 9618fn deserialize_remote_project(
 9619    connection_options: RemoteConnectionOptions,
 9620    paths: Vec<PathBuf>,
 9621    cx: &AsyncApp,
 9622) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9623    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9624    cx.background_spawn(async move {
 9625        let remote_connection_id = db
 9626            .get_or_create_remote_connection(connection_options)
 9627            .await?;
 9628
 9629        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9630
 9631        let workspace_id = if let Some(workspace_id) =
 9632            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9633        {
 9634            workspace_id
 9635        } else {
 9636            db.next_id().await?
 9637        };
 9638
 9639        Ok((workspace_id, serialized_workspace))
 9640    })
 9641}
 9642
 9643pub fn join_in_room_project(
 9644    project_id: u64,
 9645    follow_user_id: u64,
 9646    app_state: Arc<AppState>,
 9647    cx: &mut App,
 9648) -> Task<Result<()>> {
 9649    let windows = cx.windows();
 9650    cx.spawn(async move |cx| {
 9651        let existing_window_and_workspace: Option<(
 9652            WindowHandle<MultiWorkspace>,
 9653            Entity<Workspace>,
 9654        )> = windows.into_iter().find_map(|window_handle| {
 9655            window_handle
 9656                .downcast::<MultiWorkspace>()
 9657                .and_then(|window_handle| {
 9658                    window_handle
 9659                        .update(cx, |multi_workspace, _window, cx| {
 9660                            for workspace in multi_workspace.workspaces() {
 9661                                if workspace.read(cx).project().read(cx).remote_id()
 9662                                    == Some(project_id)
 9663                                {
 9664                                    return Some((window_handle, workspace.clone()));
 9665                                }
 9666                            }
 9667                            None
 9668                        })
 9669                        .unwrap_or(None)
 9670                })
 9671        });
 9672
 9673        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9674            existing_window_and_workspace
 9675        {
 9676            existing_window
 9677                .update(cx, |multi_workspace, _, cx| {
 9678                    multi_workspace.activate(target_workspace, cx);
 9679                })
 9680                .ok();
 9681            existing_window
 9682        } else {
 9683            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9684            let project = cx
 9685                .update(|cx| {
 9686                    active_call.0.join_project(
 9687                        project_id,
 9688                        app_state.languages.clone(),
 9689                        app_state.fs.clone(),
 9690                        cx,
 9691                    )
 9692                })
 9693                .await?;
 9694
 9695            let window_bounds_override = window_bounds_env_override();
 9696            cx.update(|cx| {
 9697                let mut options = (app_state.build_window_options)(None, cx);
 9698                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9699                cx.open_window(options, |window, cx| {
 9700                    let workspace = cx.new(|cx| {
 9701                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9702                    });
 9703                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9704                })
 9705            })?
 9706        };
 9707
 9708        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9709            cx.activate(true);
 9710            window.activate_window();
 9711
 9712            // We set the active workspace above, so this is the correct workspace.
 9713            let workspace = multi_workspace.workspace().clone();
 9714            workspace.update(cx, |workspace, cx| {
 9715                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9716                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9717                    .or_else(|| {
 9718                        // If we couldn't follow the given user, follow the host instead.
 9719                        let collaborator = workspace
 9720                            .project()
 9721                            .read(cx)
 9722                            .collaborators()
 9723                            .values()
 9724                            .find(|collaborator| collaborator.is_host)?;
 9725                        Some(collaborator.peer_id)
 9726                    });
 9727
 9728                if let Some(follow_peer_id) = follow_peer_id {
 9729                    workspace.follow(follow_peer_id, window, cx);
 9730                }
 9731            });
 9732        })?;
 9733
 9734        anyhow::Ok(())
 9735    })
 9736}
 9737
 9738pub fn reload(cx: &mut App) {
 9739    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9740    let mut workspace_windows = cx
 9741        .windows()
 9742        .into_iter()
 9743        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9744        .collect::<Vec<_>>();
 9745
 9746    // If multiple windows have unsaved changes, and need a save prompt,
 9747    // prompt in the active window before switching to a different window.
 9748    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9749
 9750    let mut prompt = None;
 9751    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9752        prompt = window
 9753            .update(cx, |_, window, cx| {
 9754                window.prompt(
 9755                    PromptLevel::Info,
 9756                    "Are you sure you want to restart?",
 9757                    None,
 9758                    &["Restart", "Cancel"],
 9759                    cx,
 9760                )
 9761            })
 9762            .ok();
 9763    }
 9764
 9765    cx.spawn(async move |cx| {
 9766        if let Some(prompt) = prompt {
 9767            let answer = prompt.await?;
 9768            if answer != 0 {
 9769                return anyhow::Ok(());
 9770            }
 9771        }
 9772
 9773        // If the user cancels any save prompt, then keep the app open.
 9774        for window in workspace_windows {
 9775            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9776                let workspace = multi_workspace.workspace().clone();
 9777                workspace.update(cx, |workspace, cx| {
 9778                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9779                })
 9780            }) && !should_close.await?
 9781            {
 9782                return anyhow::Ok(());
 9783            }
 9784        }
 9785        cx.update(|cx| cx.restart());
 9786        anyhow::Ok(())
 9787    })
 9788    .detach_and_log_err(cx);
 9789}
 9790
 9791fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9792    let mut parts = value.split(',');
 9793    let x: usize = parts.next()?.parse().ok()?;
 9794    let y: usize = parts.next()?.parse().ok()?;
 9795    Some(point(px(x as f32), px(y as f32)))
 9796}
 9797
 9798fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9799    let mut parts = value.split(',');
 9800    let width: usize = parts.next()?.parse().ok()?;
 9801    let height: usize = parts.next()?.parse().ok()?;
 9802    Some(size(px(width as f32), px(height as f32)))
 9803}
 9804
 9805/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9806/// appropriate.
 9807///
 9808/// The `border_radius_tiling` parameter allows overriding which corners get
 9809/// rounded, independently of the actual window tiling state. This is used
 9810/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9811/// we want square corners on the left (so the sidebar appears flush with the
 9812/// window edge) but we still need the shadow padding for proper visual
 9813/// appearance. Unlike actual window tiling, this only affects border radius -
 9814/// not padding or shadows.
 9815pub fn client_side_decorations(
 9816    element: impl IntoElement,
 9817    window: &mut Window,
 9818    cx: &mut App,
 9819    border_radius_tiling: Tiling,
 9820) -> Stateful<Div> {
 9821    const BORDER_SIZE: Pixels = px(1.0);
 9822    let decorations = window.window_decorations();
 9823    let tiling = match decorations {
 9824        Decorations::Server => Tiling::default(),
 9825        Decorations::Client { tiling } => tiling,
 9826    };
 9827
 9828    match decorations {
 9829        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9830        Decorations::Server => window.set_client_inset(px(0.0)),
 9831    }
 9832
 9833    struct GlobalResizeEdge(ResizeEdge);
 9834    impl Global for GlobalResizeEdge {}
 9835
 9836    div()
 9837        .id("window-backdrop")
 9838        .bg(transparent_black())
 9839        .map(|div| match decorations {
 9840            Decorations::Server => div,
 9841            Decorations::Client { .. } => div
 9842                .when(
 9843                    !(tiling.top
 9844                        || tiling.right
 9845                        || border_radius_tiling.top
 9846                        || border_radius_tiling.right),
 9847                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9848                )
 9849                .when(
 9850                    !(tiling.top
 9851                        || tiling.left
 9852                        || border_radius_tiling.top
 9853                        || border_radius_tiling.left),
 9854                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9855                )
 9856                .when(
 9857                    !(tiling.bottom
 9858                        || tiling.right
 9859                        || border_radius_tiling.bottom
 9860                        || border_radius_tiling.right),
 9861                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9862                )
 9863                .when(
 9864                    !(tiling.bottom
 9865                        || tiling.left
 9866                        || border_radius_tiling.bottom
 9867                        || border_radius_tiling.left),
 9868                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9869                )
 9870                .when(!tiling.top, |div| {
 9871                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9872                })
 9873                .when(!tiling.bottom, |div| {
 9874                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9875                })
 9876                .when(!tiling.left, |div| {
 9877                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9878                })
 9879                .when(!tiling.right, |div| {
 9880                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9881                })
 9882                .on_mouse_move(move |e, window, cx| {
 9883                    let size = window.window_bounds().get_bounds().size;
 9884                    let pos = e.position;
 9885
 9886                    let new_edge =
 9887                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9888
 9889                    let edge = cx.try_global::<GlobalResizeEdge>();
 9890                    if new_edge != edge.map(|edge| edge.0) {
 9891                        window
 9892                            .window_handle()
 9893                            .update(cx, |workspace, _, cx| {
 9894                                cx.notify(workspace.entity_id());
 9895                            })
 9896                            .ok();
 9897                    }
 9898                })
 9899                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9900                    let size = window.window_bounds().get_bounds().size;
 9901                    let pos = e.position;
 9902
 9903                    let edge = match resize_edge(
 9904                        pos,
 9905                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9906                        size,
 9907                        tiling,
 9908                    ) {
 9909                        Some(value) => value,
 9910                        None => return,
 9911                    };
 9912
 9913                    window.start_window_resize(edge);
 9914                }),
 9915        })
 9916        .size_full()
 9917        .child(
 9918            div()
 9919                .cursor(CursorStyle::Arrow)
 9920                .map(|div| match decorations {
 9921                    Decorations::Server => div,
 9922                    Decorations::Client { .. } => div
 9923                        .border_color(cx.theme().colors().border)
 9924                        .when(
 9925                            !(tiling.top
 9926                                || tiling.right
 9927                                || border_radius_tiling.top
 9928                                || border_radius_tiling.right),
 9929                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9930                        )
 9931                        .when(
 9932                            !(tiling.top
 9933                                || tiling.left
 9934                                || border_radius_tiling.top
 9935                                || border_radius_tiling.left),
 9936                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9937                        )
 9938                        .when(
 9939                            !(tiling.bottom
 9940                                || tiling.right
 9941                                || border_radius_tiling.bottom
 9942                                || border_radius_tiling.right),
 9943                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9944                        )
 9945                        .when(
 9946                            !(tiling.bottom
 9947                                || tiling.left
 9948                                || border_radius_tiling.bottom
 9949                                || border_radius_tiling.left),
 9950                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9951                        )
 9952                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9953                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9954                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9955                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9956                        .when(!tiling.is_tiled(), |div| {
 9957                            div.shadow(vec![gpui::BoxShadow {
 9958                                color: Hsla {
 9959                                    h: 0.,
 9960                                    s: 0.,
 9961                                    l: 0.,
 9962                                    a: 0.4,
 9963                                },
 9964                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9965                                spread_radius: px(0.),
 9966                                offset: point(px(0.0), px(0.0)),
 9967                            }])
 9968                        }),
 9969                })
 9970                .on_mouse_move(|_e, _, cx| {
 9971                    cx.stop_propagation();
 9972                })
 9973                .size_full()
 9974                .child(element),
 9975        )
 9976        .map(|div| match decorations {
 9977            Decorations::Server => div,
 9978            Decorations::Client { tiling, .. } => div.child(
 9979                canvas(
 9980                    |_bounds, window, _| {
 9981                        window.insert_hitbox(
 9982                            Bounds::new(
 9983                                point(px(0.0), px(0.0)),
 9984                                window.window_bounds().get_bounds().size,
 9985                            ),
 9986                            HitboxBehavior::Normal,
 9987                        )
 9988                    },
 9989                    move |_bounds, hitbox, window, cx| {
 9990                        let mouse = window.mouse_position();
 9991                        let size = window.window_bounds().get_bounds().size;
 9992                        let Some(edge) =
 9993                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9994                        else {
 9995                            return;
 9996                        };
 9997                        cx.set_global(GlobalResizeEdge(edge));
 9998                        window.set_cursor_style(
 9999                            match edge {
10000                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10001                                ResizeEdge::Left | ResizeEdge::Right => {
10002                                    CursorStyle::ResizeLeftRight
10003                                }
10004                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10005                                    CursorStyle::ResizeUpLeftDownRight
10006                                }
10007                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10008                                    CursorStyle::ResizeUpRightDownLeft
10009                                }
10010                            },
10011                            &hitbox,
10012                        );
10013                    },
10014                )
10015                .size_full()
10016                .absolute(),
10017            ),
10018        })
10019}
10020
10021fn resize_edge(
10022    pos: Point<Pixels>,
10023    shadow_size: Pixels,
10024    window_size: Size<Pixels>,
10025    tiling: Tiling,
10026) -> Option<ResizeEdge> {
10027    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10028    if bounds.contains(&pos) {
10029        return None;
10030    }
10031
10032    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10033    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10034    if !tiling.top && top_left_bounds.contains(&pos) {
10035        return Some(ResizeEdge::TopLeft);
10036    }
10037
10038    let top_right_bounds = Bounds::new(
10039        Point::new(window_size.width - corner_size.width, px(0.)),
10040        corner_size,
10041    );
10042    if !tiling.top && top_right_bounds.contains(&pos) {
10043        return Some(ResizeEdge::TopRight);
10044    }
10045
10046    let bottom_left_bounds = Bounds::new(
10047        Point::new(px(0.), window_size.height - corner_size.height),
10048        corner_size,
10049    );
10050    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10051        return Some(ResizeEdge::BottomLeft);
10052    }
10053
10054    let bottom_right_bounds = Bounds::new(
10055        Point::new(
10056            window_size.width - corner_size.width,
10057            window_size.height - corner_size.height,
10058        ),
10059        corner_size,
10060    );
10061    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10062        return Some(ResizeEdge::BottomRight);
10063    }
10064
10065    if !tiling.top && pos.y < shadow_size {
10066        Some(ResizeEdge::Top)
10067    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10068        Some(ResizeEdge::Bottom)
10069    } else if !tiling.left && pos.x < shadow_size {
10070        Some(ResizeEdge::Left)
10071    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10072        Some(ResizeEdge::Right)
10073    } else {
10074        None
10075    }
10076}
10077
10078fn join_pane_into_active(
10079    active_pane: &Entity<Pane>,
10080    pane: &Entity<Pane>,
10081    window: &mut Window,
10082    cx: &mut App,
10083) {
10084    if pane == active_pane {
10085    } else if pane.read(cx).items_len() == 0 {
10086        pane.update(cx, |_, cx| {
10087            cx.emit(pane::Event::Remove {
10088                focus_on_pane: None,
10089            });
10090        })
10091    } else {
10092        move_all_items(pane, active_pane, window, cx);
10093    }
10094}
10095
10096fn move_all_items(
10097    from_pane: &Entity<Pane>,
10098    to_pane: &Entity<Pane>,
10099    window: &mut Window,
10100    cx: &mut App,
10101) {
10102    let destination_is_different = from_pane != to_pane;
10103    let mut moved_items = 0;
10104    for (item_ix, item_handle) in from_pane
10105        .read(cx)
10106        .items()
10107        .enumerate()
10108        .map(|(ix, item)| (ix, item.clone()))
10109        .collect::<Vec<_>>()
10110    {
10111        let ix = item_ix - moved_items;
10112        if destination_is_different {
10113            // Close item from previous pane
10114            from_pane.update(cx, |source, cx| {
10115                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10116            });
10117            moved_items += 1;
10118        }
10119
10120        // This automatically removes duplicate items in the pane
10121        to_pane.update(cx, |destination, cx| {
10122            destination.add_item(item_handle, true, true, None, window, cx);
10123            window.focus(&destination.focus_handle(cx), cx)
10124        });
10125    }
10126}
10127
10128pub fn move_item(
10129    source: &Entity<Pane>,
10130    destination: &Entity<Pane>,
10131    item_id_to_move: EntityId,
10132    destination_index: usize,
10133    activate: bool,
10134    window: &mut Window,
10135    cx: &mut App,
10136) {
10137    let Some((item_ix, item_handle)) = source
10138        .read(cx)
10139        .items()
10140        .enumerate()
10141        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10142        .map(|(ix, item)| (ix, item.clone()))
10143    else {
10144        // Tab was closed during drag
10145        return;
10146    };
10147
10148    if source != destination {
10149        // Close item from previous pane
10150        source.update(cx, |source, cx| {
10151            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10152        });
10153    }
10154
10155    // This automatically removes duplicate items in the pane
10156    destination.update(cx, |destination, cx| {
10157        destination.add_item_inner(
10158            item_handle,
10159            activate,
10160            activate,
10161            activate,
10162            Some(destination_index),
10163            window,
10164            cx,
10165        );
10166        if activate {
10167            window.focus(&destination.focus_handle(cx), cx)
10168        }
10169    });
10170}
10171
10172pub fn move_active_item(
10173    source: &Entity<Pane>,
10174    destination: &Entity<Pane>,
10175    focus_destination: bool,
10176    close_if_empty: bool,
10177    window: &mut Window,
10178    cx: &mut App,
10179) {
10180    if source == destination {
10181        return;
10182    }
10183    let Some(active_item) = source.read(cx).active_item() else {
10184        return;
10185    };
10186    source.update(cx, |source_pane, cx| {
10187        let item_id = active_item.item_id();
10188        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10189        destination.update(cx, |target_pane, cx| {
10190            target_pane.add_item(
10191                active_item,
10192                focus_destination,
10193                focus_destination,
10194                Some(target_pane.items_len()),
10195                window,
10196                cx,
10197            );
10198        });
10199    });
10200}
10201
10202pub fn clone_active_item(
10203    workspace_id: Option<WorkspaceId>,
10204    source: &Entity<Pane>,
10205    destination: &Entity<Pane>,
10206    focus_destination: bool,
10207    window: &mut Window,
10208    cx: &mut App,
10209) {
10210    if source == destination {
10211        return;
10212    }
10213    let Some(active_item) = source.read(cx).active_item() else {
10214        return;
10215    };
10216    if !active_item.can_split(cx) {
10217        return;
10218    }
10219    let destination = destination.downgrade();
10220    let task = active_item.clone_on_split(workspace_id, window, cx);
10221    window
10222        .spawn(cx, async move |cx| {
10223            let Some(clone) = task.await else {
10224                return;
10225            };
10226            destination
10227                .update_in(cx, |target_pane, window, cx| {
10228                    target_pane.add_item(
10229                        clone,
10230                        focus_destination,
10231                        focus_destination,
10232                        Some(target_pane.items_len()),
10233                        window,
10234                        cx,
10235                    );
10236                })
10237                .log_err();
10238        })
10239        .detach();
10240}
10241
10242#[derive(Debug)]
10243pub struct WorkspacePosition {
10244    pub window_bounds: Option<WindowBounds>,
10245    pub display: Option<Uuid>,
10246    pub centered_layout: bool,
10247}
10248
10249pub fn remote_workspace_position_from_db(
10250    connection_options: RemoteConnectionOptions,
10251    paths_to_open: &[PathBuf],
10252    cx: &App,
10253) -> Task<Result<WorkspacePosition>> {
10254    let paths = paths_to_open.to_vec();
10255    let db = WorkspaceDb::global(cx);
10256    let kvp = db::kvp::KeyValueStore::global(cx);
10257
10258    cx.background_spawn(async move {
10259        let remote_connection_id = db
10260            .get_or_create_remote_connection(connection_options)
10261            .await
10262            .context("fetching serialized ssh project")?;
10263        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10264
10265        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10266            (Some(WindowBounds::Windowed(bounds)), None)
10267        } else {
10268            let restorable_bounds = serialized_workspace
10269                .as_ref()
10270                .and_then(|workspace| {
10271                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10272                })
10273                .or_else(|| persistence::read_default_window_bounds(&kvp));
10274
10275            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10276                (Some(serialized_bounds), Some(serialized_display))
10277            } else {
10278                (None, None)
10279            }
10280        };
10281
10282        let centered_layout = serialized_workspace
10283            .as_ref()
10284            .map(|w| w.centered_layout)
10285            .unwrap_or(false);
10286
10287        Ok(WorkspacePosition {
10288            window_bounds,
10289            display,
10290            centered_layout,
10291        })
10292    })
10293}
10294
10295pub fn with_active_or_new_workspace(
10296    cx: &mut App,
10297    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10298) {
10299    match cx
10300        .active_window()
10301        .and_then(|w| w.downcast::<MultiWorkspace>())
10302    {
10303        Some(multi_workspace) => {
10304            cx.defer(move |cx| {
10305                multi_workspace
10306                    .update(cx, |multi_workspace, window, cx| {
10307                        let workspace = multi_workspace.workspace().clone();
10308                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10309                    })
10310                    .log_err();
10311            });
10312        }
10313        None => {
10314            let app_state = AppState::global(cx);
10315            open_new(
10316                OpenOptions::default(),
10317                app_state,
10318                cx,
10319                move |workspace, window, cx| f(workspace, window, cx),
10320            )
10321            .detach_and_log_err(cx);
10322        }
10323    }
10324}
10325
10326/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10327/// key. This migration path only runs once per panel per workspace.
10328fn load_legacy_panel_size(
10329    panel_key: &str,
10330    dock_position: DockPosition,
10331    workspace: &Workspace,
10332    cx: &mut App,
10333) -> Option<Pixels> {
10334    #[derive(Deserialize)]
10335    struct LegacyPanelState {
10336        #[serde(default)]
10337        width: Option<Pixels>,
10338        #[serde(default)]
10339        height: Option<Pixels>,
10340    }
10341
10342    let workspace_id = workspace
10343        .database_id()
10344        .map(|id| i64::from(id).to_string())
10345        .or_else(|| workspace.session_id())?;
10346
10347    let legacy_key = match panel_key {
10348        "ProjectPanel" => {
10349            format!("{}-{:?}", "ProjectPanel", workspace_id)
10350        }
10351        "OutlinePanel" => {
10352            format!("{}-{:?}", "OutlinePanel", workspace_id)
10353        }
10354        "GitPanel" => {
10355            format!("{}-{:?}", "GitPanel", workspace_id)
10356        }
10357        "TerminalPanel" => {
10358            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10359        }
10360        _ => return None,
10361    };
10362
10363    let kvp = db::kvp::KeyValueStore::global(cx);
10364    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10365    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10366    let size = match dock_position {
10367        DockPosition::Bottom => state.height,
10368        DockPosition::Left | DockPosition::Right => state.width,
10369    }?;
10370
10371    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10372        .detach_and_log_err(cx);
10373
10374    Some(size)
10375}
10376
10377#[cfg(test)]
10378mod tests {
10379    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10380
10381    use super::*;
10382    use crate::{
10383        dock::{PanelEvent, test::TestPanel},
10384        item::{
10385            ItemBufferKind, ItemEvent,
10386            test::{TestItem, TestProjectItem},
10387        },
10388    };
10389    use fs::FakeFs;
10390    use gpui::{
10391        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10392        UpdateGlobal, VisualTestContext, px,
10393    };
10394    use project::{Project, ProjectEntryId};
10395    use serde_json::json;
10396    use settings::SettingsStore;
10397    use util::path;
10398    use util::rel_path::rel_path;
10399
10400    #[gpui::test]
10401    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10402        init_test(cx);
10403
10404        let fs = FakeFs::new(cx.executor());
10405        let project = Project::test(fs, [], cx).await;
10406        let (workspace, cx) =
10407            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10408
10409        // Adding an item with no ambiguity renders the tab without detail.
10410        let item1 = cx.new(|cx| {
10411            let mut item = TestItem::new(cx);
10412            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10413            item
10414        });
10415        workspace.update_in(cx, |workspace, window, cx| {
10416            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10417        });
10418        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10419
10420        // Adding an item that creates ambiguity increases the level of detail on
10421        // both tabs.
10422        let item2 = cx.new_window_entity(|_window, cx| {
10423            let mut item = TestItem::new(cx);
10424            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10425            item
10426        });
10427        workspace.update_in(cx, |workspace, window, cx| {
10428            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10429        });
10430        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10431        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10432
10433        // Adding an item that creates ambiguity increases the level of detail only
10434        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10435        // we stop at the highest detail available.
10436        let item3 = cx.new(|cx| {
10437            let mut item = TestItem::new(cx);
10438            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10439            item
10440        });
10441        workspace.update_in(cx, |workspace, window, cx| {
10442            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10443        });
10444        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10445        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10446        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10447    }
10448
10449    #[gpui::test]
10450    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10451        init_test(cx);
10452
10453        let fs = FakeFs::new(cx.executor());
10454        fs.insert_tree(
10455            "/root1",
10456            json!({
10457                "one.txt": "",
10458                "two.txt": "",
10459            }),
10460        )
10461        .await;
10462        fs.insert_tree(
10463            "/root2",
10464            json!({
10465                "three.txt": "",
10466            }),
10467        )
10468        .await;
10469
10470        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10471        let (workspace, cx) =
10472            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10473        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10474        let worktree_id = project.update(cx, |project, cx| {
10475            project.worktrees(cx).next().unwrap().read(cx).id()
10476        });
10477
10478        let item1 = cx.new(|cx| {
10479            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10480        });
10481        let item2 = cx.new(|cx| {
10482            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10483        });
10484
10485        // Add an item to an empty pane
10486        workspace.update_in(cx, |workspace, window, cx| {
10487            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10488        });
10489        project.update(cx, |project, cx| {
10490            assert_eq!(
10491                project.active_entry(),
10492                project
10493                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10494                    .map(|e| e.id)
10495            );
10496        });
10497        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10498
10499        // Add a second item to a non-empty pane
10500        workspace.update_in(cx, |workspace, window, cx| {
10501            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10502        });
10503        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10504        project.update(cx, |project, cx| {
10505            assert_eq!(
10506                project.active_entry(),
10507                project
10508                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10509                    .map(|e| e.id)
10510            );
10511        });
10512
10513        // Close the active item
10514        pane.update_in(cx, |pane, window, cx| {
10515            pane.close_active_item(&Default::default(), window, cx)
10516        })
10517        .await
10518        .unwrap();
10519        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10520        project.update(cx, |project, cx| {
10521            assert_eq!(
10522                project.active_entry(),
10523                project
10524                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10525                    .map(|e| e.id)
10526            );
10527        });
10528
10529        // Add a project folder
10530        project
10531            .update(cx, |project, cx| {
10532                project.find_or_create_worktree("root2", true, cx)
10533            })
10534            .await
10535            .unwrap();
10536        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10537
10538        // Remove a project folder
10539        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10540        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10541    }
10542
10543    #[gpui::test]
10544    async fn test_close_window(cx: &mut TestAppContext) {
10545        init_test(cx);
10546
10547        let fs = FakeFs::new(cx.executor());
10548        fs.insert_tree("/root", json!({ "one": "" })).await;
10549
10550        let project = Project::test(fs, ["root".as_ref()], cx).await;
10551        let (workspace, cx) =
10552            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10553
10554        // When there are no dirty items, there's nothing to do.
10555        let item1 = cx.new(TestItem::new);
10556        workspace.update_in(cx, |w, window, cx| {
10557            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10558        });
10559        let task = workspace.update_in(cx, |w, window, cx| {
10560            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10561        });
10562        assert!(task.await.unwrap());
10563
10564        // When there are dirty untitled items, prompt to save each one. If the user
10565        // cancels any prompt, then abort.
10566        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10567        let item3 = cx.new(|cx| {
10568            TestItem::new(cx)
10569                .with_dirty(true)
10570                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10571        });
10572        workspace.update_in(cx, |w, window, cx| {
10573            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10574            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10575        });
10576        let task = workspace.update_in(cx, |w, window, cx| {
10577            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10578        });
10579        cx.executor().run_until_parked();
10580        cx.simulate_prompt_answer("Cancel"); // cancel save all
10581        cx.executor().run_until_parked();
10582        assert!(!cx.has_pending_prompt());
10583        assert!(!task.await.unwrap());
10584    }
10585
10586    #[gpui::test]
10587    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10588        init_test(cx);
10589
10590        let fs = FakeFs::new(cx.executor());
10591        fs.insert_tree("/root", json!({ "one": "" })).await;
10592
10593        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10594        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10595        let multi_workspace_handle =
10596            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10597        cx.run_until_parked();
10598
10599        let workspace_a = multi_workspace_handle
10600            .read_with(cx, |mw, _| mw.workspace().clone())
10601            .unwrap();
10602
10603        let workspace_b = multi_workspace_handle
10604            .update(cx, |mw, window, cx| {
10605                mw.test_add_workspace(project_b, window, cx)
10606            })
10607            .unwrap();
10608
10609        // Activate workspace A
10610        multi_workspace_handle
10611            .update(cx, |mw, window, cx| {
10612                mw.activate_index(0, window, cx);
10613            })
10614            .unwrap();
10615
10616        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10617
10618        // Workspace A has a clean item
10619        let item_a = cx.new(TestItem::new);
10620        workspace_a.update_in(cx, |w, window, cx| {
10621            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10622        });
10623
10624        // Workspace B has a dirty item
10625        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10626        workspace_b.update_in(cx, |w, window, cx| {
10627            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10628        });
10629
10630        // Verify workspace A is active
10631        multi_workspace_handle
10632            .read_with(cx, |mw, _| {
10633                assert_eq!(mw.active_workspace_index(), 0);
10634            })
10635            .unwrap();
10636
10637        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10638        multi_workspace_handle
10639            .update(cx, |mw, window, cx| {
10640                mw.close_window(&CloseWindow, window, cx);
10641            })
10642            .unwrap();
10643        cx.run_until_parked();
10644
10645        // Workspace B should now be active since it has dirty items that need attention
10646        multi_workspace_handle
10647            .read_with(cx, |mw, _| {
10648                assert_eq!(
10649                    mw.active_workspace_index(),
10650                    1,
10651                    "workspace B should be activated when it prompts"
10652                );
10653            })
10654            .unwrap();
10655
10656        // User cancels the save prompt from workspace B
10657        cx.simulate_prompt_answer("Cancel");
10658        cx.run_until_parked();
10659
10660        // Window should still exist because workspace B's close was cancelled
10661        assert!(
10662            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10663            "window should still exist after cancelling one workspace's close"
10664        );
10665    }
10666
10667    #[gpui::test]
10668    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10669        init_test(cx);
10670
10671        // Register TestItem as a serializable item
10672        cx.update(|cx| {
10673            register_serializable_item::<TestItem>(cx);
10674        });
10675
10676        let fs = FakeFs::new(cx.executor());
10677        fs.insert_tree("/root", json!({ "one": "" })).await;
10678
10679        let project = Project::test(fs, ["root".as_ref()], cx).await;
10680        let (workspace, cx) =
10681            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10682
10683        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10684        let item1 = cx.new(|cx| {
10685            TestItem::new(cx)
10686                .with_dirty(true)
10687                .with_serialize(|| Some(Task::ready(Ok(()))))
10688        });
10689        let item2 = cx.new(|cx| {
10690            TestItem::new(cx)
10691                .with_dirty(true)
10692                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10693                .with_serialize(|| Some(Task::ready(Ok(()))))
10694        });
10695        workspace.update_in(cx, |w, window, cx| {
10696            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10697            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10698        });
10699        let task = workspace.update_in(cx, |w, window, cx| {
10700            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10701        });
10702        assert!(task.await.unwrap());
10703    }
10704
10705    #[gpui::test]
10706    async fn test_close_pane_items(cx: &mut TestAppContext) {
10707        init_test(cx);
10708
10709        let fs = FakeFs::new(cx.executor());
10710
10711        let project = Project::test(fs, None, cx).await;
10712        let (workspace, cx) =
10713            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10714
10715        let item1 = cx.new(|cx| {
10716            TestItem::new(cx)
10717                .with_dirty(true)
10718                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10719        });
10720        let item2 = cx.new(|cx| {
10721            TestItem::new(cx)
10722                .with_dirty(true)
10723                .with_conflict(true)
10724                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10725        });
10726        let item3 = cx.new(|cx| {
10727            TestItem::new(cx)
10728                .with_dirty(true)
10729                .with_conflict(true)
10730                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10731        });
10732        let item4 = cx.new(|cx| {
10733            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10734                let project_item = TestProjectItem::new_untitled(cx);
10735                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10736                project_item
10737            }])
10738        });
10739        let pane = workspace.update_in(cx, |workspace, window, cx| {
10740            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10741            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10742            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10743            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10744            workspace.active_pane().clone()
10745        });
10746
10747        let close_items = pane.update_in(cx, |pane, window, cx| {
10748            pane.activate_item(1, true, true, window, cx);
10749            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10750            let item1_id = item1.item_id();
10751            let item3_id = item3.item_id();
10752            let item4_id = item4.item_id();
10753            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10754                [item1_id, item3_id, item4_id].contains(&id)
10755            })
10756        });
10757        cx.executor().run_until_parked();
10758
10759        assert!(cx.has_pending_prompt());
10760        cx.simulate_prompt_answer("Save all");
10761
10762        cx.executor().run_until_parked();
10763
10764        // Item 1 is saved. There's a prompt to save item 3.
10765        pane.update(cx, |pane, cx| {
10766            assert_eq!(item1.read(cx).save_count, 1);
10767            assert_eq!(item1.read(cx).save_as_count, 0);
10768            assert_eq!(item1.read(cx).reload_count, 0);
10769            assert_eq!(pane.items_len(), 3);
10770            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10771        });
10772        assert!(cx.has_pending_prompt());
10773
10774        // Cancel saving item 3.
10775        cx.simulate_prompt_answer("Discard");
10776        cx.executor().run_until_parked();
10777
10778        // Item 3 is reloaded. There's a prompt to save item 4.
10779        pane.update(cx, |pane, cx| {
10780            assert_eq!(item3.read(cx).save_count, 0);
10781            assert_eq!(item3.read(cx).save_as_count, 0);
10782            assert_eq!(item3.read(cx).reload_count, 1);
10783            assert_eq!(pane.items_len(), 2);
10784            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10785        });
10786
10787        // There's a prompt for a path for item 4.
10788        cx.simulate_new_path_selection(|_| Some(Default::default()));
10789        close_items.await.unwrap();
10790
10791        // The requested items are closed.
10792        pane.update(cx, |pane, cx| {
10793            assert_eq!(item4.read(cx).save_count, 0);
10794            assert_eq!(item4.read(cx).save_as_count, 1);
10795            assert_eq!(item4.read(cx).reload_count, 0);
10796            assert_eq!(pane.items_len(), 1);
10797            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10798        });
10799    }
10800
10801    #[gpui::test]
10802    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10803        init_test(cx);
10804
10805        let fs = FakeFs::new(cx.executor());
10806        let project = Project::test(fs, [], cx).await;
10807        let (workspace, cx) =
10808            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10809
10810        // Create several workspace items with single project entries, and two
10811        // workspace items with multiple project entries.
10812        let single_entry_items = (0..=4)
10813            .map(|project_entry_id| {
10814                cx.new(|cx| {
10815                    TestItem::new(cx)
10816                        .with_dirty(true)
10817                        .with_project_items(&[dirty_project_item(
10818                            project_entry_id,
10819                            &format!("{project_entry_id}.txt"),
10820                            cx,
10821                        )])
10822                })
10823            })
10824            .collect::<Vec<_>>();
10825        let item_2_3 = cx.new(|cx| {
10826            TestItem::new(cx)
10827                .with_dirty(true)
10828                .with_buffer_kind(ItemBufferKind::Multibuffer)
10829                .with_project_items(&[
10830                    single_entry_items[2].read(cx).project_items[0].clone(),
10831                    single_entry_items[3].read(cx).project_items[0].clone(),
10832                ])
10833        });
10834        let item_3_4 = cx.new(|cx| {
10835            TestItem::new(cx)
10836                .with_dirty(true)
10837                .with_buffer_kind(ItemBufferKind::Multibuffer)
10838                .with_project_items(&[
10839                    single_entry_items[3].read(cx).project_items[0].clone(),
10840                    single_entry_items[4].read(cx).project_items[0].clone(),
10841                ])
10842        });
10843
10844        // Create two panes that contain the following project entries:
10845        //   left pane:
10846        //     multi-entry items:   (2, 3)
10847        //     single-entry items:  0, 2, 3, 4
10848        //   right pane:
10849        //     single-entry items:  4, 1
10850        //     multi-entry items:   (3, 4)
10851        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10852            let left_pane = workspace.active_pane().clone();
10853            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10854            workspace.add_item_to_active_pane(
10855                single_entry_items[0].boxed_clone(),
10856                None,
10857                true,
10858                window,
10859                cx,
10860            );
10861            workspace.add_item_to_active_pane(
10862                single_entry_items[2].boxed_clone(),
10863                None,
10864                true,
10865                window,
10866                cx,
10867            );
10868            workspace.add_item_to_active_pane(
10869                single_entry_items[3].boxed_clone(),
10870                None,
10871                true,
10872                window,
10873                cx,
10874            );
10875            workspace.add_item_to_active_pane(
10876                single_entry_items[4].boxed_clone(),
10877                None,
10878                true,
10879                window,
10880                cx,
10881            );
10882
10883            let right_pane =
10884                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10885
10886            let boxed_clone = single_entry_items[1].boxed_clone();
10887            let right_pane = window.spawn(cx, async move |cx| {
10888                right_pane.await.inspect(|right_pane| {
10889                    right_pane
10890                        .update_in(cx, |pane, window, cx| {
10891                            pane.add_item(boxed_clone, true, true, None, window, cx);
10892                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10893                        })
10894                        .unwrap();
10895                })
10896            });
10897
10898            (left_pane, right_pane)
10899        });
10900        let right_pane = right_pane.await.unwrap();
10901        cx.focus(&right_pane);
10902
10903        let close = right_pane.update_in(cx, |pane, window, cx| {
10904            pane.close_all_items(&CloseAllItems::default(), window, cx)
10905                .unwrap()
10906        });
10907        cx.executor().run_until_parked();
10908
10909        let msg = cx.pending_prompt().unwrap().0;
10910        assert!(msg.contains("1.txt"));
10911        assert!(!msg.contains("2.txt"));
10912        assert!(!msg.contains("3.txt"));
10913        assert!(!msg.contains("4.txt"));
10914
10915        // With best-effort close, cancelling item 1 keeps it open but items 4
10916        // and (3,4) still close since their entries exist in left pane.
10917        cx.simulate_prompt_answer("Cancel");
10918        close.await;
10919
10920        right_pane.read_with(cx, |pane, _| {
10921            assert_eq!(pane.items_len(), 1);
10922        });
10923
10924        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10925        left_pane
10926            .update_in(cx, |left_pane, window, cx| {
10927                left_pane.close_item_by_id(
10928                    single_entry_items[3].entity_id(),
10929                    SaveIntent::Skip,
10930                    window,
10931                    cx,
10932                )
10933            })
10934            .await
10935            .unwrap();
10936
10937        let close = left_pane.update_in(cx, |pane, window, cx| {
10938            pane.close_all_items(&CloseAllItems::default(), window, cx)
10939                .unwrap()
10940        });
10941        cx.executor().run_until_parked();
10942
10943        let details = cx.pending_prompt().unwrap().1;
10944        assert!(details.contains("0.txt"));
10945        assert!(details.contains("3.txt"));
10946        assert!(details.contains("4.txt"));
10947        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10948        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10949        // assert!(!details.contains("2.txt"));
10950
10951        cx.simulate_prompt_answer("Save all");
10952        cx.executor().run_until_parked();
10953        close.await;
10954
10955        left_pane.read_with(cx, |pane, _| {
10956            assert_eq!(pane.items_len(), 0);
10957        });
10958    }
10959
10960    #[gpui::test]
10961    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10962        init_test(cx);
10963
10964        let fs = FakeFs::new(cx.executor());
10965        let project = Project::test(fs, [], cx).await;
10966        let (workspace, cx) =
10967            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10968        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10969
10970        let item = cx.new(|cx| {
10971            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10972        });
10973        let item_id = item.entity_id();
10974        workspace.update_in(cx, |workspace, window, cx| {
10975            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10976        });
10977
10978        // Autosave on window change.
10979        item.update(cx, |item, cx| {
10980            SettingsStore::update_global(cx, |settings, cx| {
10981                settings.update_user_settings(cx, |settings| {
10982                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10983                })
10984            });
10985            item.is_dirty = true;
10986        });
10987
10988        // Deactivating the window saves the file.
10989        cx.deactivate_window();
10990        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10991
10992        // Re-activating the window doesn't save the file.
10993        cx.update(|window, _| window.activate_window());
10994        cx.executor().run_until_parked();
10995        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10996
10997        // Autosave on focus change.
10998        item.update_in(cx, |item, window, cx| {
10999            cx.focus_self(window);
11000            SettingsStore::update_global(cx, |settings, cx| {
11001                settings.update_user_settings(cx, |settings| {
11002                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11003                })
11004            });
11005            item.is_dirty = true;
11006        });
11007        // Blurring the item saves the file.
11008        item.update_in(cx, |_, window, _| window.blur());
11009        cx.executor().run_until_parked();
11010        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11011
11012        // Deactivating the window still saves the file.
11013        item.update_in(cx, |item, window, cx| {
11014            cx.focus_self(window);
11015            item.is_dirty = true;
11016        });
11017        cx.deactivate_window();
11018        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11019
11020        // Autosave after delay.
11021        item.update(cx, |item, cx| {
11022            SettingsStore::update_global(cx, |settings, cx| {
11023                settings.update_user_settings(cx, |settings| {
11024                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11025                        milliseconds: 500.into(),
11026                    });
11027                })
11028            });
11029            item.is_dirty = true;
11030            cx.emit(ItemEvent::Edit);
11031        });
11032
11033        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11034        cx.executor().advance_clock(Duration::from_millis(250));
11035        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11036
11037        // After delay expires, the file is saved.
11038        cx.executor().advance_clock(Duration::from_millis(250));
11039        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11040
11041        // Autosave after delay, should save earlier than delay if tab is closed
11042        item.update(cx, |item, cx| {
11043            item.is_dirty = true;
11044            cx.emit(ItemEvent::Edit);
11045        });
11046        cx.executor().advance_clock(Duration::from_millis(250));
11047        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11048
11049        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11050        pane.update_in(cx, |pane, window, cx| {
11051            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11052        })
11053        .await
11054        .unwrap();
11055        assert!(!cx.has_pending_prompt());
11056        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11057
11058        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11059        workspace.update_in(cx, |workspace, window, cx| {
11060            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11061        });
11062        item.update_in(cx, |item, _window, cx| {
11063            item.is_dirty = true;
11064            for project_item in &mut item.project_items {
11065                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11066            }
11067        });
11068        cx.run_until_parked();
11069        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11070
11071        // Autosave on focus change, ensuring closing the tab counts as such.
11072        item.update(cx, |item, cx| {
11073            SettingsStore::update_global(cx, |settings, cx| {
11074                settings.update_user_settings(cx, |settings| {
11075                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11076                })
11077            });
11078            item.is_dirty = true;
11079            for project_item in &mut item.project_items {
11080                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11081            }
11082        });
11083
11084        pane.update_in(cx, |pane, window, cx| {
11085            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11086        })
11087        .await
11088        .unwrap();
11089        assert!(!cx.has_pending_prompt());
11090        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11091
11092        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11093        workspace.update_in(cx, |workspace, window, cx| {
11094            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11095        });
11096        item.update_in(cx, |item, window, cx| {
11097            item.project_items[0].update(cx, |item, _| {
11098                item.entry_id = None;
11099            });
11100            item.is_dirty = true;
11101            window.blur();
11102        });
11103        cx.run_until_parked();
11104        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11105
11106        // Ensure autosave is prevented for deleted files also when closing the buffer.
11107        let _close_items = pane.update_in(cx, |pane, window, cx| {
11108            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11109        });
11110        cx.run_until_parked();
11111        assert!(cx.has_pending_prompt());
11112        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11113    }
11114
11115    #[gpui::test]
11116    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11117        init_test(cx);
11118
11119        let fs = FakeFs::new(cx.executor());
11120        let project = Project::test(fs, [], cx).await;
11121        let (workspace, cx) =
11122            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11123
11124        // Create a multibuffer-like item with two child focus handles,
11125        // simulating individual buffer editors within a multibuffer.
11126        let item = cx.new(|cx| {
11127            TestItem::new(cx)
11128                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11129                .with_child_focus_handles(2, cx)
11130        });
11131        workspace.update_in(cx, |workspace, window, cx| {
11132            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11133        });
11134
11135        // Set autosave to OnFocusChange and focus the first child handle,
11136        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11137        item.update_in(cx, |item, window, cx| {
11138            SettingsStore::update_global(cx, |settings, cx| {
11139                settings.update_user_settings(cx, |settings| {
11140                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11141                })
11142            });
11143            item.is_dirty = true;
11144            window.focus(&item.child_focus_handles[0], cx);
11145        });
11146        cx.executor().run_until_parked();
11147        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11148
11149        // Moving focus from one child to another within the same item should
11150        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11151        item.update_in(cx, |item, window, cx| {
11152            window.focus(&item.child_focus_handles[1], cx);
11153        });
11154        cx.executor().run_until_parked();
11155        item.read_with(cx, |item, _| {
11156            assert_eq!(
11157                item.save_count, 0,
11158                "Switching focus between children within the same item should not autosave"
11159            );
11160        });
11161
11162        // Blurring the item saves the file. This is the core regression scenario:
11163        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11164        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11165        // the leaf is always a child focus handle, so `on_blur` never detected
11166        // focus leaving the item.
11167        item.update_in(cx, |_, window, _| window.blur());
11168        cx.executor().run_until_parked();
11169        item.read_with(cx, |item, _| {
11170            assert_eq!(
11171                item.save_count, 1,
11172                "Blurring should trigger autosave when focus was on a child of the item"
11173            );
11174        });
11175
11176        // Deactivating the window should also trigger autosave when a child of
11177        // the multibuffer item currently owns focus.
11178        item.update_in(cx, |item, window, cx| {
11179            item.is_dirty = true;
11180            window.focus(&item.child_focus_handles[0], cx);
11181        });
11182        cx.executor().run_until_parked();
11183        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11184
11185        cx.deactivate_window();
11186        item.read_with(cx, |item, _| {
11187            assert_eq!(
11188                item.save_count, 2,
11189                "Deactivating window should trigger autosave when focus was on a child"
11190            );
11191        });
11192    }
11193
11194    #[gpui::test]
11195    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11196        init_test(cx);
11197
11198        let fs = FakeFs::new(cx.executor());
11199
11200        let project = Project::test(fs, [], cx).await;
11201        let (workspace, cx) =
11202            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11203
11204        let item = cx.new(|cx| {
11205            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11206        });
11207        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11208        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11209        let toolbar_notify_count = Rc::new(RefCell::new(0));
11210
11211        workspace.update_in(cx, |workspace, window, cx| {
11212            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11213            let toolbar_notification_count = toolbar_notify_count.clone();
11214            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11215                *toolbar_notification_count.borrow_mut() += 1
11216            })
11217            .detach();
11218        });
11219
11220        pane.read_with(cx, |pane, _| {
11221            assert!(!pane.can_navigate_backward());
11222            assert!(!pane.can_navigate_forward());
11223        });
11224
11225        item.update_in(cx, |item, _, cx| {
11226            item.set_state("one".to_string(), cx);
11227        });
11228
11229        // Toolbar must be notified to re-render the navigation buttons
11230        assert_eq!(*toolbar_notify_count.borrow(), 1);
11231
11232        pane.read_with(cx, |pane, _| {
11233            assert!(pane.can_navigate_backward());
11234            assert!(!pane.can_navigate_forward());
11235        });
11236
11237        workspace
11238            .update_in(cx, |workspace, window, cx| {
11239                workspace.go_back(pane.downgrade(), window, cx)
11240            })
11241            .await
11242            .unwrap();
11243
11244        assert_eq!(*toolbar_notify_count.borrow(), 2);
11245        pane.read_with(cx, |pane, _| {
11246            assert!(!pane.can_navigate_backward());
11247            assert!(pane.can_navigate_forward());
11248        });
11249    }
11250
11251    /// Tests that the navigation history deduplicates entries for the same item.
11252    ///
11253    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11254    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11255    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11256    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11257    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11258    ///
11259    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11260    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11261    #[gpui::test]
11262    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11263        init_test(cx);
11264
11265        let fs = FakeFs::new(cx.executor());
11266        let project = Project::test(fs, [], cx).await;
11267        let (workspace, cx) =
11268            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11269
11270        let item_a = cx.new(|cx| {
11271            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11272        });
11273        let item_b = cx.new(|cx| {
11274            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11275        });
11276        let item_c = cx.new(|cx| {
11277            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11278        });
11279
11280        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11281
11282        workspace.update_in(cx, |workspace, window, cx| {
11283            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11284            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11285            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11286        });
11287
11288        workspace.update_in(cx, |workspace, window, cx| {
11289            workspace.activate_item(&item_a, false, false, window, cx);
11290        });
11291        cx.run_until_parked();
11292
11293        workspace.update_in(cx, |workspace, window, cx| {
11294            workspace.activate_item(&item_b, false, false, window, cx);
11295        });
11296        cx.run_until_parked();
11297
11298        workspace.update_in(cx, |workspace, window, cx| {
11299            workspace.activate_item(&item_a, false, false, window, cx);
11300        });
11301        cx.run_until_parked();
11302
11303        workspace.update_in(cx, |workspace, window, cx| {
11304            workspace.activate_item(&item_b, false, false, window, cx);
11305        });
11306        cx.run_until_parked();
11307
11308        workspace.update_in(cx, |workspace, window, cx| {
11309            workspace.activate_item(&item_a, false, false, window, cx);
11310        });
11311        cx.run_until_parked();
11312
11313        workspace.update_in(cx, |workspace, window, cx| {
11314            workspace.activate_item(&item_b, false, false, window, cx);
11315        });
11316        cx.run_until_parked();
11317
11318        workspace.update_in(cx, |workspace, window, cx| {
11319            workspace.activate_item(&item_c, false, false, window, cx);
11320        });
11321        cx.run_until_parked();
11322
11323        let backward_count = pane.read_with(cx, |pane, cx| {
11324            let mut count = 0;
11325            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11326                count += 1;
11327            });
11328            count
11329        });
11330        assert!(
11331            backward_count <= 4,
11332            "Should have at most 4 entries, got {}",
11333            backward_count
11334        );
11335
11336        workspace
11337            .update_in(cx, |workspace, window, cx| {
11338                workspace.go_back(pane.downgrade(), window, cx)
11339            })
11340            .await
11341            .unwrap();
11342
11343        let active_item = workspace.read_with(cx, |workspace, cx| {
11344            workspace.active_item(cx).unwrap().item_id()
11345        });
11346        assert_eq!(
11347            active_item,
11348            item_b.entity_id(),
11349            "After first go_back, should be at item B"
11350        );
11351
11352        workspace
11353            .update_in(cx, |workspace, window, cx| {
11354                workspace.go_back(pane.downgrade(), window, cx)
11355            })
11356            .await
11357            .unwrap();
11358
11359        let active_item = workspace.read_with(cx, |workspace, cx| {
11360            workspace.active_item(cx).unwrap().item_id()
11361        });
11362        assert_eq!(
11363            active_item,
11364            item_a.entity_id(),
11365            "After second go_back, should be at item A"
11366        );
11367
11368        pane.read_with(cx, |pane, _| {
11369            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11370        });
11371    }
11372
11373    #[gpui::test]
11374    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11375        init_test(cx);
11376        let fs = FakeFs::new(cx.executor());
11377        let project = Project::test(fs, [], cx).await;
11378        let (multi_workspace, cx) =
11379            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11380        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11381
11382        workspace.update_in(cx, |workspace, window, cx| {
11383            let first_item = cx.new(|cx| {
11384                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11385            });
11386            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11387            workspace.split_pane(
11388                workspace.active_pane().clone(),
11389                SplitDirection::Right,
11390                window,
11391                cx,
11392            );
11393            workspace.split_pane(
11394                workspace.active_pane().clone(),
11395                SplitDirection::Right,
11396                window,
11397                cx,
11398            );
11399        });
11400
11401        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11402            let panes = workspace.center.panes();
11403            assert!(panes.len() >= 2);
11404            (
11405                panes.first().expect("at least one pane").entity_id(),
11406                panes.last().expect("at least one pane").entity_id(),
11407            )
11408        });
11409
11410        workspace.update_in(cx, |workspace, window, cx| {
11411            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11412        });
11413        workspace.update(cx, |workspace, _| {
11414            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11415            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11416        });
11417
11418        cx.dispatch_action(ActivateLastPane);
11419
11420        workspace.update(cx, |workspace, _| {
11421            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11422        });
11423    }
11424
11425    #[gpui::test]
11426    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11427        init_test(cx);
11428        let fs = FakeFs::new(cx.executor());
11429
11430        let project = Project::test(fs, [], cx).await;
11431        let (workspace, cx) =
11432            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11433
11434        let panel = workspace.update_in(cx, |workspace, window, cx| {
11435            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11436            workspace.add_panel(panel.clone(), window, cx);
11437
11438            workspace
11439                .right_dock()
11440                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11441
11442            panel
11443        });
11444
11445        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11446        pane.update_in(cx, |pane, window, cx| {
11447            let item = cx.new(TestItem::new);
11448            pane.add_item(Box::new(item), true, true, None, window, cx);
11449        });
11450
11451        // Transfer focus from center to panel
11452        workspace.update_in(cx, |workspace, window, cx| {
11453            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11454        });
11455
11456        workspace.update_in(cx, |workspace, window, cx| {
11457            assert!(workspace.right_dock().read(cx).is_open());
11458            assert!(!panel.is_zoomed(window, cx));
11459            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11460        });
11461
11462        // Transfer focus from panel to center
11463        workspace.update_in(cx, |workspace, window, cx| {
11464            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11465        });
11466
11467        workspace.update_in(cx, |workspace, window, cx| {
11468            assert!(workspace.right_dock().read(cx).is_open());
11469            assert!(!panel.is_zoomed(window, cx));
11470            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11471            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11472        });
11473
11474        // Close the dock
11475        workspace.update_in(cx, |workspace, window, cx| {
11476            workspace.toggle_dock(DockPosition::Right, window, cx);
11477        });
11478
11479        workspace.update_in(cx, |workspace, window, cx| {
11480            assert!(!workspace.right_dock().read(cx).is_open());
11481            assert!(!panel.is_zoomed(window, cx));
11482            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11483            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11484        });
11485
11486        // Open the dock
11487        workspace.update_in(cx, |workspace, window, cx| {
11488            workspace.toggle_dock(DockPosition::Right, window, cx);
11489        });
11490
11491        workspace.update_in(cx, |workspace, window, cx| {
11492            assert!(workspace.right_dock().read(cx).is_open());
11493            assert!(!panel.is_zoomed(window, cx));
11494            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11495        });
11496
11497        // Focus and zoom panel
11498        panel.update_in(cx, |panel, window, cx| {
11499            cx.focus_self(window);
11500            panel.set_zoomed(true, window, cx)
11501        });
11502
11503        workspace.update_in(cx, |workspace, window, cx| {
11504            assert!(workspace.right_dock().read(cx).is_open());
11505            assert!(panel.is_zoomed(window, cx));
11506            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11507        });
11508
11509        // Transfer focus to the center closes the dock
11510        workspace.update_in(cx, |workspace, window, cx| {
11511            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11512        });
11513
11514        workspace.update_in(cx, |workspace, window, cx| {
11515            assert!(!workspace.right_dock().read(cx).is_open());
11516            assert!(panel.is_zoomed(window, cx));
11517            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11518        });
11519
11520        // Transferring focus back to the panel keeps it zoomed
11521        workspace.update_in(cx, |workspace, window, cx| {
11522            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11523        });
11524
11525        workspace.update_in(cx, |workspace, window, cx| {
11526            assert!(workspace.right_dock().read(cx).is_open());
11527            assert!(panel.is_zoomed(window, cx));
11528            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11529        });
11530
11531        // Close the dock while it is zoomed
11532        workspace.update_in(cx, |workspace, window, cx| {
11533            workspace.toggle_dock(DockPosition::Right, window, cx)
11534        });
11535
11536        workspace.update_in(cx, |workspace, window, cx| {
11537            assert!(!workspace.right_dock().read(cx).is_open());
11538            assert!(panel.is_zoomed(window, cx));
11539            assert!(workspace.zoomed.is_none());
11540            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11541        });
11542
11543        // Opening the dock, when it's zoomed, retains focus
11544        workspace.update_in(cx, |workspace, window, cx| {
11545            workspace.toggle_dock(DockPosition::Right, window, cx)
11546        });
11547
11548        workspace.update_in(cx, |workspace, window, cx| {
11549            assert!(workspace.right_dock().read(cx).is_open());
11550            assert!(panel.is_zoomed(window, cx));
11551            assert!(workspace.zoomed.is_some());
11552            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11553        });
11554
11555        // Unzoom and close the panel, zoom the active pane.
11556        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11557        workspace.update_in(cx, |workspace, window, cx| {
11558            workspace.toggle_dock(DockPosition::Right, window, cx)
11559        });
11560        pane.update_in(cx, |pane, window, cx| {
11561            pane.toggle_zoom(&Default::default(), window, cx)
11562        });
11563
11564        // Opening a dock unzooms the pane.
11565        workspace.update_in(cx, |workspace, window, cx| {
11566            workspace.toggle_dock(DockPosition::Right, window, cx)
11567        });
11568        workspace.update_in(cx, |workspace, window, cx| {
11569            let pane = pane.read(cx);
11570            assert!(!pane.is_zoomed());
11571            assert!(!pane.focus_handle(cx).is_focused(window));
11572            assert!(workspace.right_dock().read(cx).is_open());
11573            assert!(workspace.zoomed.is_none());
11574        });
11575    }
11576
11577    #[gpui::test]
11578    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11579        init_test(cx);
11580        let fs = FakeFs::new(cx.executor());
11581
11582        let project = Project::test(fs, [], cx).await;
11583        let (workspace, cx) =
11584            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11585
11586        let panel = workspace.update_in(cx, |workspace, window, cx| {
11587            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11588            workspace.add_panel(panel.clone(), window, cx);
11589            panel
11590        });
11591
11592        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11593        pane.update_in(cx, |pane, window, cx| {
11594            let item = cx.new(TestItem::new);
11595            pane.add_item(Box::new(item), true, true, None, window, cx);
11596        });
11597
11598        // Enable close_panel_on_toggle
11599        cx.update_global(|store: &mut SettingsStore, cx| {
11600            store.update_user_settings(cx, |settings| {
11601                settings.workspace.close_panel_on_toggle = Some(true);
11602            });
11603        });
11604
11605        // Panel starts closed. Toggling should open and focus it.
11606        workspace.update_in(cx, |workspace, window, cx| {
11607            assert!(!workspace.right_dock().read(cx).is_open());
11608            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11609        });
11610
11611        workspace.update_in(cx, |workspace, window, cx| {
11612            assert!(
11613                workspace.right_dock().read(cx).is_open(),
11614                "Dock should be open after toggling from center"
11615            );
11616            assert!(
11617                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11618                "Panel should be focused after toggling from center"
11619            );
11620        });
11621
11622        // Panel is open and focused. Toggling should close the panel and
11623        // return focus to the center.
11624        workspace.update_in(cx, |workspace, window, cx| {
11625            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11626        });
11627
11628        workspace.update_in(cx, |workspace, window, cx| {
11629            assert!(
11630                !workspace.right_dock().read(cx).is_open(),
11631                "Dock should be closed after toggling from focused panel"
11632            );
11633            assert!(
11634                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11635                "Panel should not be focused after toggling from focused panel"
11636            );
11637        });
11638
11639        // Open the dock and focus something else so the panel is open but not
11640        // focused. Toggling should focus the panel (not close it).
11641        workspace.update_in(cx, |workspace, window, cx| {
11642            workspace
11643                .right_dock()
11644                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11645            window.focus(&pane.read(cx).focus_handle(cx), cx);
11646        });
11647
11648        workspace.update_in(cx, |workspace, window, cx| {
11649            assert!(workspace.right_dock().read(cx).is_open());
11650            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11651            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11652        });
11653
11654        workspace.update_in(cx, |workspace, window, cx| {
11655            assert!(
11656                workspace.right_dock().read(cx).is_open(),
11657                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11658            );
11659            assert!(
11660                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11661                "Panel should be focused after toggling an open-but-unfocused panel"
11662            );
11663        });
11664
11665        // Now disable the setting and verify the original behavior: toggling
11666        // from a focused panel moves focus to center but leaves the dock open.
11667        cx.update_global(|store: &mut SettingsStore, cx| {
11668            store.update_user_settings(cx, |settings| {
11669                settings.workspace.close_panel_on_toggle = Some(false);
11670            });
11671        });
11672
11673        workspace.update_in(cx, |workspace, window, cx| {
11674            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11675        });
11676
11677        workspace.update_in(cx, |workspace, window, cx| {
11678            assert!(
11679                workspace.right_dock().read(cx).is_open(),
11680                "Dock should remain open when setting is disabled"
11681            );
11682            assert!(
11683                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11684                "Panel should not be focused after toggling with setting disabled"
11685            );
11686        });
11687    }
11688
11689    #[gpui::test]
11690    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11691        init_test(cx);
11692        let fs = FakeFs::new(cx.executor());
11693
11694        let project = Project::test(fs, [], cx).await;
11695        let (workspace, cx) =
11696            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11697
11698        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11699            workspace.active_pane().clone()
11700        });
11701
11702        // Add an item to the pane so it can be zoomed
11703        workspace.update_in(cx, |workspace, window, cx| {
11704            let item = cx.new(TestItem::new);
11705            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11706        });
11707
11708        // Initially not zoomed
11709        workspace.update_in(cx, |workspace, _window, cx| {
11710            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11711            assert!(
11712                workspace.zoomed.is_none(),
11713                "Workspace should track no zoomed pane"
11714            );
11715            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11716        });
11717
11718        // Zoom In
11719        pane.update_in(cx, |pane, window, cx| {
11720            pane.zoom_in(&crate::ZoomIn, window, cx);
11721        });
11722
11723        workspace.update_in(cx, |workspace, window, cx| {
11724            assert!(
11725                pane.read(cx).is_zoomed(),
11726                "Pane should be zoomed after ZoomIn"
11727            );
11728            assert!(
11729                workspace.zoomed.is_some(),
11730                "Workspace should track the zoomed pane"
11731            );
11732            assert!(
11733                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11734                "ZoomIn should focus the pane"
11735            );
11736        });
11737
11738        // Zoom In again is a no-op
11739        pane.update_in(cx, |pane, window, cx| {
11740            pane.zoom_in(&crate::ZoomIn, window, cx);
11741        });
11742
11743        workspace.update_in(cx, |workspace, window, cx| {
11744            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11745            assert!(
11746                workspace.zoomed.is_some(),
11747                "Workspace still tracks zoomed pane"
11748            );
11749            assert!(
11750                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11751                "Pane remains focused after repeated ZoomIn"
11752            );
11753        });
11754
11755        // Zoom Out
11756        pane.update_in(cx, |pane, window, cx| {
11757            pane.zoom_out(&crate::ZoomOut, window, cx);
11758        });
11759
11760        workspace.update_in(cx, |workspace, _window, cx| {
11761            assert!(
11762                !pane.read(cx).is_zoomed(),
11763                "Pane should unzoom after ZoomOut"
11764            );
11765            assert!(
11766                workspace.zoomed.is_none(),
11767                "Workspace clears zoom tracking after ZoomOut"
11768            );
11769        });
11770
11771        // Zoom Out again is a no-op
11772        pane.update_in(cx, |pane, window, cx| {
11773            pane.zoom_out(&crate::ZoomOut, window, cx);
11774        });
11775
11776        workspace.update_in(cx, |workspace, _window, cx| {
11777            assert!(
11778                !pane.read(cx).is_zoomed(),
11779                "Second ZoomOut keeps pane unzoomed"
11780            );
11781            assert!(
11782                workspace.zoomed.is_none(),
11783                "Workspace remains without zoomed pane"
11784            );
11785        });
11786    }
11787
11788    #[gpui::test]
11789    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11790        init_test(cx);
11791        let fs = FakeFs::new(cx.executor());
11792
11793        let project = Project::test(fs, [], cx).await;
11794        let (workspace, cx) =
11795            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11796        workspace.update_in(cx, |workspace, window, cx| {
11797            // Open two docks
11798            let left_dock = workspace.dock_at_position(DockPosition::Left);
11799            let right_dock = workspace.dock_at_position(DockPosition::Right);
11800
11801            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11802            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11803
11804            assert!(left_dock.read(cx).is_open());
11805            assert!(right_dock.read(cx).is_open());
11806        });
11807
11808        workspace.update_in(cx, |workspace, window, cx| {
11809            // Toggle all docks - should close both
11810            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11811
11812            let left_dock = workspace.dock_at_position(DockPosition::Left);
11813            let right_dock = workspace.dock_at_position(DockPosition::Right);
11814            assert!(!left_dock.read(cx).is_open());
11815            assert!(!right_dock.read(cx).is_open());
11816        });
11817
11818        workspace.update_in(cx, |workspace, window, cx| {
11819            // Toggle again - should reopen both
11820            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11821
11822            let left_dock = workspace.dock_at_position(DockPosition::Left);
11823            let right_dock = workspace.dock_at_position(DockPosition::Right);
11824            assert!(left_dock.read(cx).is_open());
11825            assert!(right_dock.read(cx).is_open());
11826        });
11827    }
11828
11829    #[gpui::test]
11830    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11831        init_test(cx);
11832        let fs = FakeFs::new(cx.executor());
11833
11834        let project = Project::test(fs, [], cx).await;
11835        let (workspace, cx) =
11836            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11837        workspace.update_in(cx, |workspace, window, cx| {
11838            // Open two docks
11839            let left_dock = workspace.dock_at_position(DockPosition::Left);
11840            let right_dock = workspace.dock_at_position(DockPosition::Right);
11841
11842            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11843            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11844
11845            assert!(left_dock.read(cx).is_open());
11846            assert!(right_dock.read(cx).is_open());
11847        });
11848
11849        workspace.update_in(cx, |workspace, window, cx| {
11850            // Close them manually
11851            workspace.toggle_dock(DockPosition::Left, window, cx);
11852            workspace.toggle_dock(DockPosition::Right, window, cx);
11853
11854            let left_dock = workspace.dock_at_position(DockPosition::Left);
11855            let right_dock = workspace.dock_at_position(DockPosition::Right);
11856            assert!(!left_dock.read(cx).is_open());
11857            assert!(!right_dock.read(cx).is_open());
11858        });
11859
11860        workspace.update_in(cx, |workspace, window, cx| {
11861            // Toggle all docks - only last closed (right dock) should reopen
11862            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11863
11864            let left_dock = workspace.dock_at_position(DockPosition::Left);
11865            let right_dock = workspace.dock_at_position(DockPosition::Right);
11866            assert!(!left_dock.read(cx).is_open());
11867            assert!(right_dock.read(cx).is_open());
11868        });
11869    }
11870
11871    #[gpui::test]
11872    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11873        init_test(cx);
11874        let fs = FakeFs::new(cx.executor());
11875        let project = Project::test(fs, [], cx).await;
11876        let (multi_workspace, cx) =
11877            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11878        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11879
11880        // Open two docks (left and right) with one panel each
11881        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11882            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11883            workspace.add_panel(left_panel.clone(), window, cx);
11884
11885            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11886            workspace.add_panel(right_panel.clone(), window, cx);
11887
11888            workspace.toggle_dock(DockPosition::Left, window, cx);
11889            workspace.toggle_dock(DockPosition::Right, window, cx);
11890
11891            // Verify initial state
11892            assert!(
11893                workspace.left_dock().read(cx).is_open(),
11894                "Left dock should be open"
11895            );
11896            assert_eq!(
11897                workspace
11898                    .left_dock()
11899                    .read(cx)
11900                    .visible_panel()
11901                    .unwrap()
11902                    .panel_id(),
11903                left_panel.panel_id(),
11904                "Left panel should be visible in left dock"
11905            );
11906            assert!(
11907                workspace.right_dock().read(cx).is_open(),
11908                "Right dock should be open"
11909            );
11910            assert_eq!(
11911                workspace
11912                    .right_dock()
11913                    .read(cx)
11914                    .visible_panel()
11915                    .unwrap()
11916                    .panel_id(),
11917                right_panel.panel_id(),
11918                "Right panel should be visible in right dock"
11919            );
11920            assert!(
11921                !workspace.bottom_dock().read(cx).is_open(),
11922                "Bottom dock should be closed"
11923            );
11924
11925            (left_panel, right_panel)
11926        });
11927
11928        // Focus the left panel and move it to the next position (bottom dock)
11929        workspace.update_in(cx, |workspace, window, cx| {
11930            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11931            assert!(
11932                left_panel.read(cx).focus_handle(cx).is_focused(window),
11933                "Left panel should be focused"
11934            );
11935        });
11936
11937        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11938
11939        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11940        workspace.update(cx, |workspace, cx| {
11941            assert!(
11942                !workspace.left_dock().read(cx).is_open(),
11943                "Left dock should be closed"
11944            );
11945            assert!(
11946                workspace.bottom_dock().read(cx).is_open(),
11947                "Bottom dock should now be open"
11948            );
11949            assert_eq!(
11950                left_panel.read(cx).position,
11951                DockPosition::Bottom,
11952                "Left panel should now be in the bottom dock"
11953            );
11954            assert_eq!(
11955                workspace
11956                    .bottom_dock()
11957                    .read(cx)
11958                    .visible_panel()
11959                    .unwrap()
11960                    .panel_id(),
11961                left_panel.panel_id(),
11962                "Left panel should be the visible panel in the bottom dock"
11963            );
11964        });
11965
11966        // Toggle all docks off
11967        workspace.update_in(cx, |workspace, window, cx| {
11968            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11969            assert!(
11970                !workspace.left_dock().read(cx).is_open(),
11971                "Left dock should be closed"
11972            );
11973            assert!(
11974                !workspace.right_dock().read(cx).is_open(),
11975                "Right dock should be closed"
11976            );
11977            assert!(
11978                !workspace.bottom_dock().read(cx).is_open(),
11979                "Bottom dock should be closed"
11980            );
11981        });
11982
11983        // Toggle all docks back on and verify positions are restored
11984        workspace.update_in(cx, |workspace, window, cx| {
11985            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11986            assert!(
11987                !workspace.left_dock().read(cx).is_open(),
11988                "Left dock should remain closed"
11989            );
11990            assert!(
11991                workspace.right_dock().read(cx).is_open(),
11992                "Right dock should remain open"
11993            );
11994            assert!(
11995                workspace.bottom_dock().read(cx).is_open(),
11996                "Bottom dock should remain open"
11997            );
11998            assert_eq!(
11999                left_panel.read(cx).position,
12000                DockPosition::Bottom,
12001                "Left panel should remain in the bottom dock"
12002            );
12003            assert_eq!(
12004                right_panel.read(cx).position,
12005                DockPosition::Right,
12006                "Right panel should remain in the right dock"
12007            );
12008            assert_eq!(
12009                workspace
12010                    .bottom_dock()
12011                    .read(cx)
12012                    .visible_panel()
12013                    .unwrap()
12014                    .panel_id(),
12015                left_panel.panel_id(),
12016                "Left panel should be the visible panel in the right dock"
12017            );
12018        });
12019    }
12020
12021    #[gpui::test]
12022    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12023        init_test(cx);
12024
12025        let fs = FakeFs::new(cx.executor());
12026
12027        let project = Project::test(fs, None, cx).await;
12028        let (workspace, cx) =
12029            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12030
12031        // Let's arrange the panes like this:
12032        //
12033        // +-----------------------+
12034        // |         top           |
12035        // +------+--------+-------+
12036        // | left | center | right |
12037        // +------+--------+-------+
12038        // |        bottom         |
12039        // +-----------------------+
12040
12041        let top_item = cx.new(|cx| {
12042            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12043        });
12044        let bottom_item = cx.new(|cx| {
12045            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12046        });
12047        let left_item = cx.new(|cx| {
12048            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12049        });
12050        let right_item = cx.new(|cx| {
12051            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12052        });
12053        let center_item = cx.new(|cx| {
12054            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12055        });
12056
12057        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12058            let top_pane_id = workspace.active_pane().entity_id();
12059            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12060            workspace.split_pane(
12061                workspace.active_pane().clone(),
12062                SplitDirection::Down,
12063                window,
12064                cx,
12065            );
12066            top_pane_id
12067        });
12068        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12069            let bottom_pane_id = workspace.active_pane().entity_id();
12070            workspace.add_item_to_active_pane(
12071                Box::new(bottom_item.clone()),
12072                None,
12073                false,
12074                window,
12075                cx,
12076            );
12077            workspace.split_pane(
12078                workspace.active_pane().clone(),
12079                SplitDirection::Up,
12080                window,
12081                cx,
12082            );
12083            bottom_pane_id
12084        });
12085        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12086            let left_pane_id = workspace.active_pane().entity_id();
12087            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12088            workspace.split_pane(
12089                workspace.active_pane().clone(),
12090                SplitDirection::Right,
12091                window,
12092                cx,
12093            );
12094            left_pane_id
12095        });
12096        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12097            let right_pane_id = workspace.active_pane().entity_id();
12098            workspace.add_item_to_active_pane(
12099                Box::new(right_item.clone()),
12100                None,
12101                false,
12102                window,
12103                cx,
12104            );
12105            workspace.split_pane(
12106                workspace.active_pane().clone(),
12107                SplitDirection::Left,
12108                window,
12109                cx,
12110            );
12111            right_pane_id
12112        });
12113        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12114            let center_pane_id = workspace.active_pane().entity_id();
12115            workspace.add_item_to_active_pane(
12116                Box::new(center_item.clone()),
12117                None,
12118                false,
12119                window,
12120                cx,
12121            );
12122            center_pane_id
12123        });
12124        cx.executor().run_until_parked();
12125
12126        workspace.update_in(cx, |workspace, window, cx| {
12127            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12128
12129            // Join into next from center pane into right
12130            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12131        });
12132
12133        workspace.update_in(cx, |workspace, window, cx| {
12134            let active_pane = workspace.active_pane();
12135            assert_eq!(right_pane_id, active_pane.entity_id());
12136            assert_eq!(2, active_pane.read(cx).items_len());
12137            let item_ids_in_pane =
12138                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12139            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12140            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12141
12142            // Join into next from right pane into bottom
12143            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12144        });
12145
12146        workspace.update_in(cx, |workspace, window, cx| {
12147            let active_pane = workspace.active_pane();
12148            assert_eq!(bottom_pane_id, active_pane.entity_id());
12149            assert_eq!(3, active_pane.read(cx).items_len());
12150            let item_ids_in_pane =
12151                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12152            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12153            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12154            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12155
12156            // Join into next from bottom pane into left
12157            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12158        });
12159
12160        workspace.update_in(cx, |workspace, window, cx| {
12161            let active_pane = workspace.active_pane();
12162            assert_eq!(left_pane_id, active_pane.entity_id());
12163            assert_eq!(4, active_pane.read(cx).items_len());
12164            let item_ids_in_pane =
12165                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12166            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12167            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12168            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12169            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12170
12171            // Join into next from left pane into top
12172            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12173        });
12174
12175        workspace.update_in(cx, |workspace, window, cx| {
12176            let active_pane = workspace.active_pane();
12177            assert_eq!(top_pane_id, active_pane.entity_id());
12178            assert_eq!(5, active_pane.read(cx).items_len());
12179            let item_ids_in_pane =
12180                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12181            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12182            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12183            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12184            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12185            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12186
12187            // Single pane left: no-op
12188            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12189        });
12190
12191        workspace.update(cx, |workspace, _cx| {
12192            let active_pane = workspace.active_pane();
12193            assert_eq!(top_pane_id, active_pane.entity_id());
12194        });
12195    }
12196
12197    fn add_an_item_to_active_pane(
12198        cx: &mut VisualTestContext,
12199        workspace: &Entity<Workspace>,
12200        item_id: u64,
12201    ) -> Entity<TestItem> {
12202        let item = cx.new(|cx| {
12203            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12204                item_id,
12205                "item{item_id}.txt",
12206                cx,
12207            )])
12208        });
12209        workspace.update_in(cx, |workspace, window, cx| {
12210            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12211        });
12212        item
12213    }
12214
12215    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12216        workspace.update_in(cx, |workspace, window, cx| {
12217            workspace.split_pane(
12218                workspace.active_pane().clone(),
12219                SplitDirection::Right,
12220                window,
12221                cx,
12222            )
12223        })
12224    }
12225
12226    #[gpui::test]
12227    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12228        init_test(cx);
12229        let fs = FakeFs::new(cx.executor());
12230        let project = Project::test(fs, None, cx).await;
12231        let (workspace, cx) =
12232            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12233
12234        add_an_item_to_active_pane(cx, &workspace, 1);
12235        split_pane(cx, &workspace);
12236        add_an_item_to_active_pane(cx, &workspace, 2);
12237        split_pane(cx, &workspace); // empty pane
12238        split_pane(cx, &workspace);
12239        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12240
12241        cx.executor().run_until_parked();
12242
12243        workspace.update(cx, |workspace, cx| {
12244            let num_panes = workspace.panes().len();
12245            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12246            let active_item = workspace
12247                .active_pane()
12248                .read(cx)
12249                .active_item()
12250                .expect("item is in focus");
12251
12252            assert_eq!(num_panes, 4);
12253            assert_eq!(num_items_in_current_pane, 1);
12254            assert_eq!(active_item.item_id(), last_item.item_id());
12255        });
12256
12257        workspace.update_in(cx, |workspace, window, cx| {
12258            workspace.join_all_panes(window, cx);
12259        });
12260
12261        workspace.update(cx, |workspace, cx| {
12262            let num_panes = workspace.panes().len();
12263            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12264            let active_item = workspace
12265                .active_pane()
12266                .read(cx)
12267                .active_item()
12268                .expect("item is in focus");
12269
12270            assert_eq!(num_panes, 1);
12271            assert_eq!(num_items_in_current_pane, 3);
12272            assert_eq!(active_item.item_id(), last_item.item_id());
12273        });
12274    }
12275
12276    #[gpui::test]
12277    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12278        init_test(cx);
12279        let fs = FakeFs::new(cx.executor());
12280
12281        let project = Project::test(fs, [], cx).await;
12282        let (multi_workspace, cx) =
12283            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12284        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12285
12286        workspace.update(cx, |workspace, _cx| {
12287            workspace.bounds.size.width = px(800.);
12288        });
12289
12290        workspace.update_in(cx, |workspace, window, cx| {
12291            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12292            workspace.add_panel(panel, window, cx);
12293            workspace.toggle_dock(DockPosition::Right, window, cx);
12294        });
12295
12296        let (panel, resized_width, ratio_basis_width) =
12297            workspace.update_in(cx, |workspace, window, cx| {
12298                let item = cx.new(|cx| {
12299                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12300                });
12301                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12302
12303                let dock = workspace.right_dock().read(cx);
12304                let workspace_width = workspace.bounds.size.width;
12305                let initial_width = workspace
12306                    .dock_size(&dock, window, cx)
12307                    .expect("flexible dock should have an initial width");
12308
12309                assert_eq!(initial_width, workspace_width / 2.);
12310
12311                workspace.resize_right_dock(px(300.), window, cx);
12312
12313                let dock = workspace.right_dock().read(cx);
12314                let resized_width = workspace
12315                    .dock_size(&dock, window, cx)
12316                    .expect("flexible dock should keep its resized width");
12317
12318                assert_eq!(resized_width, px(300.));
12319
12320                let panel = workspace
12321                    .right_dock()
12322                    .read(cx)
12323                    .visible_panel()
12324                    .expect("flexible dock should have a visible panel")
12325                    .panel_id();
12326
12327                (panel, resized_width, workspace_width)
12328            });
12329
12330        workspace.update_in(cx, |workspace, window, cx| {
12331            workspace.toggle_dock(DockPosition::Right, window, cx);
12332            workspace.toggle_dock(DockPosition::Right, window, cx);
12333
12334            let dock = workspace.right_dock().read(cx);
12335            let reopened_width = workspace
12336                .dock_size(&dock, window, cx)
12337                .expect("flexible dock should restore when reopened");
12338
12339            assert_eq!(reopened_width, resized_width);
12340
12341            let right_dock = workspace.right_dock().read(cx);
12342            let flexible_panel = right_dock
12343                .visible_panel()
12344                .expect("flexible dock should still have a visible panel");
12345            assert_eq!(flexible_panel.panel_id(), panel);
12346            assert_eq!(
12347                right_dock
12348                    .stored_panel_size_state(flexible_panel.as_ref())
12349                    .and_then(|size_state| size_state.flexible_size_ratio),
12350                Some(resized_width.to_f64() as f32 / workspace.bounds.size.width.to_f64() as f32)
12351            );
12352        });
12353
12354        workspace.update_in(cx, |workspace, window, cx| {
12355            workspace.split_pane(
12356                workspace.active_pane().clone(),
12357                SplitDirection::Right,
12358                window,
12359                cx,
12360            );
12361
12362            let dock = workspace.right_dock().read(cx);
12363            let split_width = workspace
12364                .dock_size(&dock, window, cx)
12365                .expect("flexible dock should keep its user-resized proportion");
12366
12367            assert_eq!(split_width, px(300.));
12368
12369            workspace.bounds.size.width = px(1600.);
12370
12371            let dock = workspace.right_dock().read(cx);
12372            let resized_window_width = workspace
12373                .dock_size(&dock, window, cx)
12374                .expect("flexible dock should preserve proportional size on window resize");
12375
12376            assert_eq!(
12377                resized_window_width,
12378                workspace.bounds.size.width
12379                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12380            );
12381        });
12382    }
12383
12384    #[gpui::test]
12385    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12386        init_test(cx);
12387        let fs = FakeFs::new(cx.executor());
12388
12389        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12390        {
12391            let project = Project::test(fs.clone(), [], cx).await;
12392            let (multi_workspace, cx) =
12393                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12394            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12395
12396            workspace.update(cx, |workspace, _cx| {
12397                workspace.set_random_database_id();
12398                workspace.bounds.size.width = px(800.);
12399            });
12400
12401            let panel = workspace.update_in(cx, |workspace, window, cx| {
12402                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12403                workspace.add_panel(panel.clone(), window, cx);
12404                workspace.toggle_dock(DockPosition::Left, window, cx);
12405                panel
12406            });
12407
12408            workspace.update_in(cx, |workspace, window, cx| {
12409                workspace.resize_left_dock(px(350.), window, cx);
12410            });
12411
12412            cx.run_until_parked();
12413
12414            let persisted = workspace.read_with(cx, |workspace, cx| {
12415                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12416            });
12417            assert_eq!(
12418                persisted.and_then(|s| s.size),
12419                Some(px(350.)),
12420                "fixed-width panel size should be persisted to KVP"
12421            );
12422
12423            // Remove the panel and re-add a fresh instance with the same key.
12424            // The new instance should have its size state restored from KVP.
12425            workspace.update_in(cx, |workspace, window, cx| {
12426                workspace.remove_panel(&panel, window, cx);
12427            });
12428
12429            workspace.update_in(cx, |workspace, window, cx| {
12430                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12431                workspace.add_panel(new_panel, window, cx);
12432
12433                let left_dock = workspace.left_dock().read(cx);
12434                let size_state = left_dock
12435                    .panel::<TestPanel>()
12436                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12437                assert_eq!(
12438                    size_state.and_then(|s| s.size),
12439                    Some(px(350.)),
12440                    "re-added fixed-width panel should restore persisted size from KVP"
12441                );
12442            });
12443        }
12444
12445        // Flexible panel: both pixel size and ratio are persisted and restored.
12446        {
12447            let project = Project::test(fs.clone(), [], cx).await;
12448            let (multi_workspace, cx) =
12449                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12450            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12451
12452            workspace.update(cx, |workspace, _cx| {
12453                workspace.set_random_database_id();
12454                workspace.bounds.size.width = px(800.);
12455            });
12456
12457            let panel = workspace.update_in(cx, |workspace, window, cx| {
12458                let item = cx.new(|cx| {
12459                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12460                });
12461                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12462
12463                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12464                workspace.add_panel(panel.clone(), window, cx);
12465                workspace.toggle_dock(DockPosition::Right, window, cx);
12466                panel
12467            });
12468
12469            workspace.update_in(cx, |workspace, window, cx| {
12470                workspace.resize_right_dock(px(300.), window, cx);
12471            });
12472
12473            cx.run_until_parked();
12474
12475            let persisted = workspace
12476                .read_with(cx, |workspace, cx| {
12477                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12478                })
12479                .expect("flexible panel state should be persisted to KVP");
12480            assert_eq!(
12481                persisted.size, None,
12482                "flexible panel should not persist a redundant pixel size"
12483            );
12484            let original_ratio = persisted
12485                .flexible_size_ratio
12486                .expect("flexible panel ratio should be persisted");
12487
12488            // Remove the panel and re-add: both size and ratio should be restored.
12489            workspace.update_in(cx, |workspace, window, cx| {
12490                workspace.remove_panel(&panel, window, cx);
12491            });
12492
12493            workspace.update_in(cx, |workspace, window, cx| {
12494                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12495                workspace.add_panel(new_panel, window, cx);
12496
12497                let right_dock = workspace.right_dock().read(cx);
12498                let size_state = right_dock
12499                    .panel::<TestPanel>()
12500                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12501                    .expect("re-added flexible panel should have restored size state from KVP");
12502                assert_eq!(
12503                    size_state.size, None,
12504                    "re-added flexible panel should not have a persisted pixel size"
12505                );
12506                assert_eq!(
12507                    size_state.flexible_size_ratio,
12508                    Some(original_ratio),
12509                    "re-added flexible panel should restore persisted ratio"
12510                );
12511            });
12512        }
12513    }
12514
12515    #[gpui::test]
12516    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12517        init_test(cx);
12518        let fs = FakeFs::new(cx.executor());
12519
12520        let project = Project::test(fs, [], cx).await;
12521        let (multi_workspace, cx) =
12522            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12523        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12524
12525        workspace.update(cx, |workspace, _cx| {
12526            workspace.bounds.size.width = px(900.);
12527        });
12528
12529        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12530        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12531        // and the center pane each take half the workspace width.
12532        workspace.update_in(cx, |workspace, window, cx| {
12533            let item = cx.new(|cx| {
12534                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12535            });
12536            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12537
12538            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12539            workspace.add_panel(panel, window, cx);
12540            workspace.toggle_dock(DockPosition::Left, window, cx);
12541
12542            let left_dock = workspace.left_dock().read(cx);
12543            let left_width = workspace
12544                .dock_size(&left_dock, window, cx)
12545                .expect("left dock should have an active panel");
12546
12547            assert_eq!(
12548                left_width,
12549                workspace.bounds.size.width / 2.,
12550                "flexible left panel should split evenly with the center pane"
12551            );
12552        });
12553
12554        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12555        // change horizontal width fractions, so the flexible panel stays at the same
12556        // width as each half of the split.
12557        workspace.update_in(cx, |workspace, window, cx| {
12558            workspace.split_pane(
12559                workspace.active_pane().clone(),
12560                SplitDirection::Down,
12561                window,
12562                cx,
12563            );
12564
12565            let left_dock = workspace.left_dock().read(cx);
12566            let left_width = workspace
12567                .dock_size(&left_dock, window, cx)
12568                .expect("left dock should still have an active panel after vertical split");
12569
12570            assert_eq!(
12571                left_width,
12572                workspace.bounds.size.width / 2.,
12573                "flexible left panel width should match each vertically-split pane"
12574            );
12575        });
12576
12577        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12578        // size reduces the available width, so the flexible left panel and the center
12579        // panes all shrink proportionally to accommodate it.
12580        workspace.update_in(cx, |workspace, window, cx| {
12581            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12582            workspace.add_panel(panel, window, cx);
12583            workspace.toggle_dock(DockPosition::Right, window, cx);
12584
12585            let right_dock = workspace.right_dock().read(cx);
12586            let right_width = workspace
12587                .dock_size(&right_dock, window, cx)
12588                .expect("right dock should have an active panel");
12589
12590            let left_dock = workspace.left_dock().read(cx);
12591            let left_width = workspace
12592                .dock_size(&left_dock, window, cx)
12593                .expect("left dock should still have an active panel");
12594
12595            let available_width = workspace.bounds.size.width - right_width;
12596            assert_eq!(
12597                left_width,
12598                available_width / 2.,
12599                "flexible left panel should shrink proportionally as the right dock takes space"
12600            );
12601        });
12602    }
12603
12604    struct TestModal(FocusHandle);
12605
12606    impl TestModal {
12607        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12608            Self(cx.focus_handle())
12609        }
12610    }
12611
12612    impl EventEmitter<DismissEvent> for TestModal {}
12613
12614    impl Focusable for TestModal {
12615        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12616            self.0.clone()
12617        }
12618    }
12619
12620    impl ModalView for TestModal {}
12621
12622    impl Render for TestModal {
12623        fn render(
12624            &mut self,
12625            _window: &mut Window,
12626            _cx: &mut Context<TestModal>,
12627        ) -> impl IntoElement {
12628            div().track_focus(&self.0)
12629        }
12630    }
12631
12632    #[gpui::test]
12633    async fn test_panels(cx: &mut gpui::TestAppContext) {
12634        init_test(cx);
12635        let fs = FakeFs::new(cx.executor());
12636
12637        let project = Project::test(fs, [], cx).await;
12638        let (multi_workspace, cx) =
12639            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12640        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12641
12642        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12643            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12644            workspace.add_panel(panel_1.clone(), window, cx);
12645            workspace.toggle_dock(DockPosition::Left, window, cx);
12646            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12647            workspace.add_panel(panel_2.clone(), window, cx);
12648            workspace.toggle_dock(DockPosition::Right, window, cx);
12649
12650            let left_dock = workspace.left_dock();
12651            assert_eq!(
12652                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12653                panel_1.panel_id()
12654            );
12655            assert_eq!(
12656                workspace.dock_size(&left_dock.read(cx), window, cx),
12657                Some(px(300.))
12658            );
12659
12660            workspace.resize_left_dock(px(1337.), window, cx);
12661            assert_eq!(
12662                workspace
12663                    .right_dock()
12664                    .read(cx)
12665                    .visible_panel()
12666                    .unwrap()
12667                    .panel_id(),
12668                panel_2.panel_id(),
12669            );
12670
12671            (panel_1, panel_2)
12672        });
12673
12674        // Move panel_1 to the right
12675        panel_1.update_in(cx, |panel_1, window, cx| {
12676            panel_1.set_position(DockPosition::Right, window, cx)
12677        });
12678
12679        workspace.update_in(cx, |workspace, window, cx| {
12680            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12681            // Since it was the only panel on the left, the left dock should now be closed.
12682            assert!(!workspace.left_dock().read(cx).is_open());
12683            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12684            let right_dock = workspace.right_dock();
12685            assert_eq!(
12686                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12687                panel_1.panel_id()
12688            );
12689            assert_eq!(
12690                right_dock
12691                    .read(cx)
12692                    .active_panel_size()
12693                    .unwrap()
12694                    .size
12695                    .unwrap(),
12696                px(1337.)
12697            );
12698
12699            // Now we move panel_2 to the left
12700            panel_2.set_position(DockPosition::Left, window, cx);
12701        });
12702
12703        workspace.update(cx, |workspace, cx| {
12704            // Since panel_2 was not visible on the right, we don't open the left dock.
12705            assert!(!workspace.left_dock().read(cx).is_open());
12706            // And the right dock is unaffected in its displaying of panel_1
12707            assert!(workspace.right_dock().read(cx).is_open());
12708            assert_eq!(
12709                workspace
12710                    .right_dock()
12711                    .read(cx)
12712                    .visible_panel()
12713                    .unwrap()
12714                    .panel_id(),
12715                panel_1.panel_id(),
12716            );
12717        });
12718
12719        // Move panel_1 back to the left
12720        panel_1.update_in(cx, |panel_1, window, cx| {
12721            panel_1.set_position(DockPosition::Left, window, cx)
12722        });
12723
12724        workspace.update_in(cx, |workspace, window, cx| {
12725            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12726            let left_dock = workspace.left_dock();
12727            assert!(left_dock.read(cx).is_open());
12728            assert_eq!(
12729                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12730                panel_1.panel_id()
12731            );
12732            assert_eq!(
12733                workspace.dock_size(&left_dock.read(cx), window, cx),
12734                Some(px(1337.))
12735            );
12736            // And the right dock should be closed as it no longer has any panels.
12737            assert!(!workspace.right_dock().read(cx).is_open());
12738
12739            // Now we move panel_1 to the bottom
12740            panel_1.set_position(DockPosition::Bottom, window, cx);
12741        });
12742
12743        workspace.update_in(cx, |workspace, window, cx| {
12744            // Since panel_1 was visible on the left, we close the left dock.
12745            assert!(!workspace.left_dock().read(cx).is_open());
12746            // The bottom dock is sized based on the panel's default size,
12747            // since the panel orientation changed from vertical to horizontal.
12748            let bottom_dock = workspace.bottom_dock();
12749            assert_eq!(
12750                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12751                Some(px(300.))
12752            );
12753            // Close bottom dock and move panel_1 back to the left.
12754            bottom_dock.update(cx, |bottom_dock, cx| {
12755                bottom_dock.set_open(false, window, cx)
12756            });
12757            panel_1.set_position(DockPosition::Left, window, cx);
12758        });
12759
12760        // Emit activated event on panel 1
12761        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12762
12763        // Now the left dock is open and panel_1 is active and focused.
12764        workspace.update_in(cx, |workspace, window, cx| {
12765            let left_dock = workspace.left_dock();
12766            assert!(left_dock.read(cx).is_open());
12767            assert_eq!(
12768                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12769                panel_1.panel_id(),
12770            );
12771            assert!(panel_1.focus_handle(cx).is_focused(window));
12772        });
12773
12774        // Emit closed event on panel 2, which is not active
12775        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12776
12777        // Wo don't close the left dock, because panel_2 wasn't the active panel
12778        workspace.update(cx, |workspace, cx| {
12779            let left_dock = workspace.left_dock();
12780            assert!(left_dock.read(cx).is_open());
12781            assert_eq!(
12782                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12783                panel_1.panel_id(),
12784            );
12785        });
12786
12787        // Emitting a ZoomIn event shows the panel as zoomed.
12788        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12789        workspace.read_with(cx, |workspace, _| {
12790            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12791            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12792        });
12793
12794        // Move panel to another dock while it is zoomed
12795        panel_1.update_in(cx, |panel, window, cx| {
12796            panel.set_position(DockPosition::Right, window, cx)
12797        });
12798        workspace.read_with(cx, |workspace, _| {
12799            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12800
12801            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12802        });
12803
12804        // This is a helper for getting a:
12805        // - valid focus on an element,
12806        // - that isn't a part of the panes and panels system of the Workspace,
12807        // - and doesn't trigger the 'on_focus_lost' API.
12808        let focus_other_view = {
12809            let workspace = workspace.clone();
12810            move |cx: &mut VisualTestContext| {
12811                workspace.update_in(cx, |workspace, window, cx| {
12812                    if workspace.active_modal::<TestModal>(cx).is_some() {
12813                        workspace.toggle_modal(window, cx, TestModal::new);
12814                        workspace.toggle_modal(window, cx, TestModal::new);
12815                    } else {
12816                        workspace.toggle_modal(window, cx, TestModal::new);
12817                    }
12818                })
12819            }
12820        };
12821
12822        // If focus is transferred to another view that's not a panel or another pane, we still show
12823        // the panel as zoomed.
12824        focus_other_view(cx);
12825        workspace.read_with(cx, |workspace, _| {
12826            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12827            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12828        });
12829
12830        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12831        workspace.update_in(cx, |_workspace, window, cx| {
12832            cx.focus_self(window);
12833        });
12834        workspace.read_with(cx, |workspace, _| {
12835            assert_eq!(workspace.zoomed, None);
12836            assert_eq!(workspace.zoomed_position, None);
12837        });
12838
12839        // If focus is transferred again to another view that's not a panel or a pane, we won't
12840        // show the panel as zoomed because it wasn't zoomed before.
12841        focus_other_view(cx);
12842        workspace.read_with(cx, |workspace, _| {
12843            assert_eq!(workspace.zoomed, None);
12844            assert_eq!(workspace.zoomed_position, None);
12845        });
12846
12847        // When the panel is activated, it is zoomed again.
12848        cx.dispatch_action(ToggleRightDock);
12849        workspace.read_with(cx, |workspace, _| {
12850            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12851            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12852        });
12853
12854        // Emitting a ZoomOut event unzooms the panel.
12855        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12856        workspace.read_with(cx, |workspace, _| {
12857            assert_eq!(workspace.zoomed, None);
12858            assert_eq!(workspace.zoomed_position, None);
12859        });
12860
12861        // Emit closed event on panel 1, which is active
12862        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12863
12864        // Now the left dock is closed, because panel_1 was the active panel
12865        workspace.update(cx, |workspace, cx| {
12866            let right_dock = workspace.right_dock();
12867            assert!(!right_dock.read(cx).is_open());
12868        });
12869    }
12870
12871    #[gpui::test]
12872    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12873        init_test(cx);
12874
12875        let fs = FakeFs::new(cx.background_executor.clone());
12876        let project = Project::test(fs, [], cx).await;
12877        let (workspace, cx) =
12878            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12879        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12880
12881        let dirty_regular_buffer = cx.new(|cx| {
12882            TestItem::new(cx)
12883                .with_dirty(true)
12884                .with_label("1.txt")
12885                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12886        });
12887        let dirty_regular_buffer_2 = cx.new(|cx| {
12888            TestItem::new(cx)
12889                .with_dirty(true)
12890                .with_label("2.txt")
12891                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12892        });
12893        let dirty_multi_buffer_with_both = cx.new(|cx| {
12894            TestItem::new(cx)
12895                .with_dirty(true)
12896                .with_buffer_kind(ItemBufferKind::Multibuffer)
12897                .with_label("Fake Project Search")
12898                .with_project_items(&[
12899                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12900                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12901                ])
12902        });
12903        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12904        workspace.update_in(cx, |workspace, window, cx| {
12905            workspace.add_item(
12906                pane.clone(),
12907                Box::new(dirty_regular_buffer.clone()),
12908                None,
12909                false,
12910                false,
12911                window,
12912                cx,
12913            );
12914            workspace.add_item(
12915                pane.clone(),
12916                Box::new(dirty_regular_buffer_2.clone()),
12917                None,
12918                false,
12919                false,
12920                window,
12921                cx,
12922            );
12923            workspace.add_item(
12924                pane.clone(),
12925                Box::new(dirty_multi_buffer_with_both.clone()),
12926                None,
12927                false,
12928                false,
12929                window,
12930                cx,
12931            );
12932        });
12933
12934        pane.update_in(cx, |pane, window, cx| {
12935            pane.activate_item(2, true, true, window, cx);
12936            assert_eq!(
12937                pane.active_item().unwrap().item_id(),
12938                multi_buffer_with_both_files_id,
12939                "Should select the multi buffer in the pane"
12940            );
12941        });
12942        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12943            pane.close_other_items(
12944                &CloseOtherItems {
12945                    save_intent: Some(SaveIntent::Save),
12946                    close_pinned: true,
12947                },
12948                None,
12949                window,
12950                cx,
12951            )
12952        });
12953        cx.background_executor.run_until_parked();
12954        assert!(!cx.has_pending_prompt());
12955        close_all_but_multi_buffer_task
12956            .await
12957            .expect("Closing all buffers but the multi buffer failed");
12958        pane.update(cx, |pane, cx| {
12959            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12960            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12961            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12962            assert_eq!(pane.items_len(), 1);
12963            assert_eq!(
12964                pane.active_item().unwrap().item_id(),
12965                multi_buffer_with_both_files_id,
12966                "Should have only the multi buffer left in the pane"
12967            );
12968            assert!(
12969                dirty_multi_buffer_with_both.read(cx).is_dirty,
12970                "The multi buffer containing the unsaved buffer should still be dirty"
12971            );
12972        });
12973
12974        dirty_regular_buffer.update(cx, |buffer, cx| {
12975            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12976        });
12977
12978        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12979            pane.close_active_item(
12980                &CloseActiveItem {
12981                    save_intent: Some(SaveIntent::Close),
12982                    close_pinned: false,
12983                },
12984                window,
12985                cx,
12986            )
12987        });
12988        cx.background_executor.run_until_parked();
12989        assert!(
12990            cx.has_pending_prompt(),
12991            "Dirty multi buffer should prompt a save dialog"
12992        );
12993        cx.simulate_prompt_answer("Save");
12994        cx.background_executor.run_until_parked();
12995        close_multi_buffer_task
12996            .await
12997            .expect("Closing the multi buffer failed");
12998        pane.update(cx, |pane, cx| {
12999            assert_eq!(
13000                dirty_multi_buffer_with_both.read(cx).save_count,
13001                1,
13002                "Multi buffer item should get be saved"
13003            );
13004            // Test impl does not save inner items, so we do not assert them
13005            assert_eq!(
13006                pane.items_len(),
13007                0,
13008                "No more items should be left in the pane"
13009            );
13010            assert!(pane.active_item().is_none());
13011        });
13012    }
13013
13014    #[gpui::test]
13015    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13016        cx: &mut TestAppContext,
13017    ) {
13018        init_test(cx);
13019
13020        let fs = FakeFs::new(cx.background_executor.clone());
13021        let project = Project::test(fs, [], cx).await;
13022        let (workspace, cx) =
13023            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13024        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13025
13026        let dirty_regular_buffer = cx.new(|cx| {
13027            TestItem::new(cx)
13028                .with_dirty(true)
13029                .with_label("1.txt")
13030                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13031        });
13032        let dirty_regular_buffer_2 = cx.new(|cx| {
13033            TestItem::new(cx)
13034                .with_dirty(true)
13035                .with_label("2.txt")
13036                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13037        });
13038        let clear_regular_buffer = cx.new(|cx| {
13039            TestItem::new(cx)
13040                .with_label("3.txt")
13041                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13042        });
13043
13044        let dirty_multi_buffer_with_both = cx.new(|cx| {
13045            TestItem::new(cx)
13046                .with_dirty(true)
13047                .with_buffer_kind(ItemBufferKind::Multibuffer)
13048                .with_label("Fake Project Search")
13049                .with_project_items(&[
13050                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13051                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13052                    clear_regular_buffer.read(cx).project_items[0].clone(),
13053                ])
13054        });
13055        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13056        workspace.update_in(cx, |workspace, window, cx| {
13057            workspace.add_item(
13058                pane.clone(),
13059                Box::new(dirty_regular_buffer.clone()),
13060                None,
13061                false,
13062                false,
13063                window,
13064                cx,
13065            );
13066            workspace.add_item(
13067                pane.clone(),
13068                Box::new(dirty_multi_buffer_with_both.clone()),
13069                None,
13070                false,
13071                false,
13072                window,
13073                cx,
13074            );
13075        });
13076
13077        pane.update_in(cx, |pane, window, cx| {
13078            pane.activate_item(1, true, true, window, cx);
13079            assert_eq!(
13080                pane.active_item().unwrap().item_id(),
13081                multi_buffer_with_both_files_id,
13082                "Should select the multi buffer in the pane"
13083            );
13084        });
13085        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13086            pane.close_active_item(
13087                &CloseActiveItem {
13088                    save_intent: None,
13089                    close_pinned: false,
13090                },
13091                window,
13092                cx,
13093            )
13094        });
13095        cx.background_executor.run_until_parked();
13096        assert!(
13097            cx.has_pending_prompt(),
13098            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13099        );
13100    }
13101
13102    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13103    /// closed when they are deleted from disk.
13104    #[gpui::test]
13105    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13106        init_test(cx);
13107
13108        // Enable the close_on_disk_deletion setting
13109        cx.update_global(|store: &mut SettingsStore, cx| {
13110            store.update_user_settings(cx, |settings| {
13111                settings.workspace.close_on_file_delete = Some(true);
13112            });
13113        });
13114
13115        let fs = FakeFs::new(cx.background_executor.clone());
13116        let project = Project::test(fs, [], cx).await;
13117        let (workspace, cx) =
13118            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13119        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13120
13121        // Create a test item that simulates a file
13122        let item = cx.new(|cx| {
13123            TestItem::new(cx)
13124                .with_label("test.txt")
13125                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13126        });
13127
13128        // Add item to workspace
13129        workspace.update_in(cx, |workspace, window, cx| {
13130            workspace.add_item(
13131                pane.clone(),
13132                Box::new(item.clone()),
13133                None,
13134                false,
13135                false,
13136                window,
13137                cx,
13138            );
13139        });
13140
13141        // Verify the item is in the pane
13142        pane.read_with(cx, |pane, _| {
13143            assert_eq!(pane.items().count(), 1);
13144        });
13145
13146        // Simulate file deletion by setting the item's deleted state
13147        item.update(cx, |item, _| {
13148            item.set_has_deleted_file(true);
13149        });
13150
13151        // Emit UpdateTab event to trigger the close behavior
13152        cx.run_until_parked();
13153        item.update(cx, |_, cx| {
13154            cx.emit(ItemEvent::UpdateTab);
13155        });
13156
13157        // Allow the close operation to complete
13158        cx.run_until_parked();
13159
13160        // Verify the item was automatically closed
13161        pane.read_with(cx, |pane, _| {
13162            assert_eq!(
13163                pane.items().count(),
13164                0,
13165                "Item should be automatically closed when file is deleted"
13166            );
13167        });
13168    }
13169
13170    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13171    /// open with a strikethrough when they are deleted from disk.
13172    #[gpui::test]
13173    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13174        init_test(cx);
13175
13176        // Ensure close_on_disk_deletion is disabled (default)
13177        cx.update_global(|store: &mut SettingsStore, cx| {
13178            store.update_user_settings(cx, |settings| {
13179                settings.workspace.close_on_file_delete = Some(false);
13180            });
13181        });
13182
13183        let fs = FakeFs::new(cx.background_executor.clone());
13184        let project = Project::test(fs, [], cx).await;
13185        let (workspace, cx) =
13186            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13187        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13188
13189        // Create a test item that simulates a file
13190        let item = cx.new(|cx| {
13191            TestItem::new(cx)
13192                .with_label("test.txt")
13193                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13194        });
13195
13196        // Add item to workspace
13197        workspace.update_in(cx, |workspace, window, cx| {
13198            workspace.add_item(
13199                pane.clone(),
13200                Box::new(item.clone()),
13201                None,
13202                false,
13203                false,
13204                window,
13205                cx,
13206            );
13207        });
13208
13209        // Verify the item is in the pane
13210        pane.read_with(cx, |pane, _| {
13211            assert_eq!(pane.items().count(), 1);
13212        });
13213
13214        // Simulate file deletion
13215        item.update(cx, |item, _| {
13216            item.set_has_deleted_file(true);
13217        });
13218
13219        // Emit UpdateTab event
13220        cx.run_until_parked();
13221        item.update(cx, |_, cx| {
13222            cx.emit(ItemEvent::UpdateTab);
13223        });
13224
13225        // Allow any potential close operation to complete
13226        cx.run_until_parked();
13227
13228        // Verify the item remains open (with strikethrough)
13229        pane.read_with(cx, |pane, _| {
13230            assert_eq!(
13231                pane.items().count(),
13232                1,
13233                "Item should remain open when close_on_disk_deletion is disabled"
13234            );
13235        });
13236
13237        // Verify the item shows as deleted
13238        item.read_with(cx, |item, _| {
13239            assert!(
13240                item.has_deleted_file,
13241                "Item should be marked as having deleted file"
13242            );
13243        });
13244    }
13245
13246    /// Tests that dirty files are not automatically closed when deleted from disk,
13247    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13248    /// unsaved changes without being prompted.
13249    #[gpui::test]
13250    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13251        init_test(cx);
13252
13253        // Enable the close_on_file_delete setting
13254        cx.update_global(|store: &mut SettingsStore, cx| {
13255            store.update_user_settings(cx, |settings| {
13256                settings.workspace.close_on_file_delete = Some(true);
13257            });
13258        });
13259
13260        let fs = FakeFs::new(cx.background_executor.clone());
13261        let project = Project::test(fs, [], cx).await;
13262        let (workspace, cx) =
13263            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13264        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13265
13266        // Create a dirty test item
13267        let item = cx.new(|cx| {
13268            TestItem::new(cx)
13269                .with_dirty(true)
13270                .with_label("test.txt")
13271                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13272        });
13273
13274        // Add item to workspace
13275        workspace.update_in(cx, |workspace, window, cx| {
13276            workspace.add_item(
13277                pane.clone(),
13278                Box::new(item.clone()),
13279                None,
13280                false,
13281                false,
13282                window,
13283                cx,
13284            );
13285        });
13286
13287        // Simulate file deletion
13288        item.update(cx, |item, _| {
13289            item.set_has_deleted_file(true);
13290        });
13291
13292        // Emit UpdateTab event to trigger the close behavior
13293        cx.run_until_parked();
13294        item.update(cx, |_, cx| {
13295            cx.emit(ItemEvent::UpdateTab);
13296        });
13297
13298        // Allow any potential close operation to complete
13299        cx.run_until_parked();
13300
13301        // Verify the item remains open (dirty files are not auto-closed)
13302        pane.read_with(cx, |pane, _| {
13303            assert_eq!(
13304                pane.items().count(),
13305                1,
13306                "Dirty items should not be automatically closed even when file is deleted"
13307            );
13308        });
13309
13310        // Verify the item is marked as deleted and still dirty
13311        item.read_with(cx, |item, _| {
13312            assert!(
13313                item.has_deleted_file,
13314                "Item should be marked as having deleted file"
13315            );
13316            assert!(item.is_dirty, "Item should still be dirty");
13317        });
13318    }
13319
13320    /// Tests that navigation history is cleaned up when files are auto-closed
13321    /// due to deletion from disk.
13322    #[gpui::test]
13323    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13324        init_test(cx);
13325
13326        // Enable the close_on_file_delete setting
13327        cx.update_global(|store: &mut SettingsStore, cx| {
13328            store.update_user_settings(cx, |settings| {
13329                settings.workspace.close_on_file_delete = Some(true);
13330            });
13331        });
13332
13333        let fs = FakeFs::new(cx.background_executor.clone());
13334        let project = Project::test(fs, [], cx).await;
13335        let (workspace, cx) =
13336            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13337        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13338
13339        // Create test items
13340        let item1 = cx.new(|cx| {
13341            TestItem::new(cx)
13342                .with_label("test1.txt")
13343                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13344        });
13345        let item1_id = item1.item_id();
13346
13347        let item2 = cx.new(|cx| {
13348            TestItem::new(cx)
13349                .with_label("test2.txt")
13350                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13351        });
13352
13353        // Add items to workspace
13354        workspace.update_in(cx, |workspace, window, cx| {
13355            workspace.add_item(
13356                pane.clone(),
13357                Box::new(item1.clone()),
13358                None,
13359                false,
13360                false,
13361                window,
13362                cx,
13363            );
13364            workspace.add_item(
13365                pane.clone(),
13366                Box::new(item2.clone()),
13367                None,
13368                false,
13369                false,
13370                window,
13371                cx,
13372            );
13373        });
13374
13375        // Activate item1 to ensure it gets navigation entries
13376        pane.update_in(cx, |pane, window, cx| {
13377            pane.activate_item(0, true, true, window, cx);
13378        });
13379
13380        // Switch to item2 and back to create navigation history
13381        pane.update_in(cx, |pane, window, cx| {
13382            pane.activate_item(1, true, true, window, cx);
13383        });
13384        cx.run_until_parked();
13385
13386        pane.update_in(cx, |pane, window, cx| {
13387            pane.activate_item(0, true, true, window, cx);
13388        });
13389        cx.run_until_parked();
13390
13391        // Simulate file deletion for item1
13392        item1.update(cx, |item, _| {
13393            item.set_has_deleted_file(true);
13394        });
13395
13396        // Emit UpdateTab event to trigger the close behavior
13397        item1.update(cx, |_, cx| {
13398            cx.emit(ItemEvent::UpdateTab);
13399        });
13400        cx.run_until_parked();
13401
13402        // Verify item1 was closed
13403        pane.read_with(cx, |pane, _| {
13404            assert_eq!(
13405                pane.items().count(),
13406                1,
13407                "Should have 1 item remaining after auto-close"
13408            );
13409        });
13410
13411        // Check navigation history after close
13412        let has_item = pane.read_with(cx, |pane, cx| {
13413            let mut has_item = false;
13414            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13415                if entry.item.id() == item1_id {
13416                    has_item = true;
13417                }
13418            });
13419            has_item
13420        });
13421
13422        assert!(
13423            !has_item,
13424            "Navigation history should not contain closed item entries"
13425        );
13426    }
13427
13428    #[gpui::test]
13429    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13430        cx: &mut TestAppContext,
13431    ) {
13432        init_test(cx);
13433
13434        let fs = FakeFs::new(cx.background_executor.clone());
13435        let project = Project::test(fs, [], cx).await;
13436        let (workspace, cx) =
13437            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13438        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13439
13440        let dirty_regular_buffer = cx.new(|cx| {
13441            TestItem::new(cx)
13442                .with_dirty(true)
13443                .with_label("1.txt")
13444                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13445        });
13446        let dirty_regular_buffer_2 = cx.new(|cx| {
13447            TestItem::new(cx)
13448                .with_dirty(true)
13449                .with_label("2.txt")
13450                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13451        });
13452        let clear_regular_buffer = cx.new(|cx| {
13453            TestItem::new(cx)
13454                .with_label("3.txt")
13455                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13456        });
13457
13458        let dirty_multi_buffer = cx.new(|cx| {
13459            TestItem::new(cx)
13460                .with_dirty(true)
13461                .with_buffer_kind(ItemBufferKind::Multibuffer)
13462                .with_label("Fake Project Search")
13463                .with_project_items(&[
13464                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13465                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13466                    clear_regular_buffer.read(cx).project_items[0].clone(),
13467                ])
13468        });
13469        workspace.update_in(cx, |workspace, window, cx| {
13470            workspace.add_item(
13471                pane.clone(),
13472                Box::new(dirty_regular_buffer.clone()),
13473                None,
13474                false,
13475                false,
13476                window,
13477                cx,
13478            );
13479            workspace.add_item(
13480                pane.clone(),
13481                Box::new(dirty_regular_buffer_2.clone()),
13482                None,
13483                false,
13484                false,
13485                window,
13486                cx,
13487            );
13488            workspace.add_item(
13489                pane.clone(),
13490                Box::new(dirty_multi_buffer.clone()),
13491                None,
13492                false,
13493                false,
13494                window,
13495                cx,
13496            );
13497        });
13498
13499        pane.update_in(cx, |pane, window, cx| {
13500            pane.activate_item(2, true, true, window, cx);
13501            assert_eq!(
13502                pane.active_item().unwrap().item_id(),
13503                dirty_multi_buffer.item_id(),
13504                "Should select the multi buffer in the pane"
13505            );
13506        });
13507        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13508            pane.close_active_item(
13509                &CloseActiveItem {
13510                    save_intent: None,
13511                    close_pinned: false,
13512                },
13513                window,
13514                cx,
13515            )
13516        });
13517        cx.background_executor.run_until_parked();
13518        assert!(
13519            !cx.has_pending_prompt(),
13520            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13521        );
13522        close_multi_buffer_task
13523            .await
13524            .expect("Closing multi buffer failed");
13525        pane.update(cx, |pane, cx| {
13526            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13527            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13528            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13529            assert_eq!(
13530                pane.items()
13531                    .map(|item| item.item_id())
13532                    .sorted()
13533                    .collect::<Vec<_>>(),
13534                vec![
13535                    dirty_regular_buffer.item_id(),
13536                    dirty_regular_buffer_2.item_id(),
13537                ],
13538                "Should have no multi buffer left in the pane"
13539            );
13540            assert!(dirty_regular_buffer.read(cx).is_dirty);
13541            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13542        });
13543    }
13544
13545    #[gpui::test]
13546    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13547        init_test(cx);
13548        let fs = FakeFs::new(cx.executor());
13549        let project = Project::test(fs, [], cx).await;
13550        let (multi_workspace, cx) =
13551            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13552        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13553
13554        // Add a new panel to the right dock, opening the dock and setting the
13555        // focus to the new panel.
13556        let panel = workspace.update_in(cx, |workspace, window, cx| {
13557            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13558            workspace.add_panel(panel.clone(), window, cx);
13559
13560            workspace
13561                .right_dock()
13562                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13563
13564            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13565
13566            panel
13567        });
13568
13569        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13570        // panel to the next valid position which, in this case, is the left
13571        // dock.
13572        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13573        workspace.update(cx, |workspace, cx| {
13574            assert!(workspace.left_dock().read(cx).is_open());
13575            assert_eq!(panel.read(cx).position, DockPosition::Left);
13576        });
13577
13578        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13579        // panel to the next valid position which, in this case, is the bottom
13580        // dock.
13581        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13582        workspace.update(cx, |workspace, cx| {
13583            assert!(workspace.bottom_dock().read(cx).is_open());
13584            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13585        });
13586
13587        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13588        // around moving the panel to its initial position, the right dock.
13589        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13590        workspace.update(cx, |workspace, cx| {
13591            assert!(workspace.right_dock().read(cx).is_open());
13592            assert_eq!(panel.read(cx).position, DockPosition::Right);
13593        });
13594
13595        // Remove focus from the panel, ensuring that, if the panel is not
13596        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13597        // the panel's position, so the panel is still in the right dock.
13598        workspace.update_in(cx, |workspace, window, cx| {
13599            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13600        });
13601
13602        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13603        workspace.update(cx, |workspace, cx| {
13604            assert!(workspace.right_dock().read(cx).is_open());
13605            assert_eq!(panel.read(cx).position, DockPosition::Right);
13606        });
13607    }
13608
13609    #[gpui::test]
13610    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13611        init_test(cx);
13612
13613        let fs = FakeFs::new(cx.executor());
13614        let project = Project::test(fs, [], cx).await;
13615        let (workspace, cx) =
13616            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13617
13618        let item_1 = cx.new(|cx| {
13619            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13620        });
13621        workspace.update_in(cx, |workspace, window, cx| {
13622            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13623            workspace.move_item_to_pane_in_direction(
13624                &MoveItemToPaneInDirection {
13625                    direction: SplitDirection::Right,
13626                    focus: true,
13627                    clone: false,
13628                },
13629                window,
13630                cx,
13631            );
13632            workspace.move_item_to_pane_at_index(
13633                &MoveItemToPane {
13634                    destination: 3,
13635                    focus: true,
13636                    clone: false,
13637                },
13638                window,
13639                cx,
13640            );
13641
13642            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13643            assert_eq!(
13644                pane_items_paths(&workspace.active_pane, cx),
13645                vec!["first.txt".to_string()],
13646                "Single item was not moved anywhere"
13647            );
13648        });
13649
13650        let item_2 = cx.new(|cx| {
13651            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13652        });
13653        workspace.update_in(cx, |workspace, window, cx| {
13654            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13655            assert_eq!(
13656                pane_items_paths(&workspace.panes[0], cx),
13657                vec!["first.txt".to_string(), "second.txt".to_string()],
13658            );
13659            workspace.move_item_to_pane_in_direction(
13660                &MoveItemToPaneInDirection {
13661                    direction: SplitDirection::Right,
13662                    focus: true,
13663                    clone: false,
13664                },
13665                window,
13666                cx,
13667            );
13668
13669            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13670            assert_eq!(
13671                pane_items_paths(&workspace.panes[0], cx),
13672                vec!["first.txt".to_string()],
13673                "After moving, one item should be left in the original pane"
13674            );
13675            assert_eq!(
13676                pane_items_paths(&workspace.panes[1], cx),
13677                vec!["second.txt".to_string()],
13678                "New item should have been moved to the new pane"
13679            );
13680        });
13681
13682        let item_3 = cx.new(|cx| {
13683            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13684        });
13685        workspace.update_in(cx, |workspace, window, cx| {
13686            let original_pane = workspace.panes[0].clone();
13687            workspace.set_active_pane(&original_pane, window, cx);
13688            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13689            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13690            assert_eq!(
13691                pane_items_paths(&workspace.active_pane, cx),
13692                vec!["first.txt".to_string(), "third.txt".to_string()],
13693                "New pane should be ready to move one item out"
13694            );
13695
13696            workspace.move_item_to_pane_at_index(
13697                &MoveItemToPane {
13698                    destination: 3,
13699                    focus: true,
13700                    clone: false,
13701                },
13702                window,
13703                cx,
13704            );
13705            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13706            assert_eq!(
13707                pane_items_paths(&workspace.active_pane, cx),
13708                vec!["first.txt".to_string()],
13709                "After moving, one item should be left in the original pane"
13710            );
13711            assert_eq!(
13712                pane_items_paths(&workspace.panes[1], cx),
13713                vec!["second.txt".to_string()],
13714                "Previously created pane should be unchanged"
13715            );
13716            assert_eq!(
13717                pane_items_paths(&workspace.panes[2], cx),
13718                vec!["third.txt".to_string()],
13719                "New item should have been moved to the new pane"
13720            );
13721        });
13722    }
13723
13724    #[gpui::test]
13725    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13726        init_test(cx);
13727
13728        let fs = FakeFs::new(cx.executor());
13729        let project = Project::test(fs, [], cx).await;
13730        let (workspace, cx) =
13731            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13732
13733        let item_1 = cx.new(|cx| {
13734            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13735        });
13736        workspace.update_in(cx, |workspace, window, cx| {
13737            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13738            workspace.move_item_to_pane_in_direction(
13739                &MoveItemToPaneInDirection {
13740                    direction: SplitDirection::Right,
13741                    focus: true,
13742                    clone: true,
13743                },
13744                window,
13745                cx,
13746            );
13747        });
13748        cx.run_until_parked();
13749        workspace.update_in(cx, |workspace, window, cx| {
13750            workspace.move_item_to_pane_at_index(
13751                &MoveItemToPane {
13752                    destination: 3,
13753                    focus: true,
13754                    clone: true,
13755                },
13756                window,
13757                cx,
13758            );
13759        });
13760        cx.run_until_parked();
13761
13762        workspace.update(cx, |workspace, cx| {
13763            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13764            for pane in workspace.panes() {
13765                assert_eq!(
13766                    pane_items_paths(pane, cx),
13767                    vec!["first.txt".to_string()],
13768                    "Single item exists in all panes"
13769                );
13770            }
13771        });
13772
13773        // verify that the active pane has been updated after waiting for the
13774        // pane focus event to fire and resolve
13775        workspace.read_with(cx, |workspace, _app| {
13776            assert_eq!(
13777                workspace.active_pane(),
13778                &workspace.panes[2],
13779                "The third pane should be the active one: {:?}",
13780                workspace.panes
13781            );
13782        })
13783    }
13784
13785    #[gpui::test]
13786    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13787        init_test(cx);
13788
13789        let fs = FakeFs::new(cx.executor());
13790        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13791
13792        let project = Project::test(fs, ["root".as_ref()], cx).await;
13793        let (workspace, cx) =
13794            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13795
13796        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13797        // Add item to pane A with project path
13798        let item_a = cx.new(|cx| {
13799            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13800        });
13801        workspace.update_in(cx, |workspace, window, cx| {
13802            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13803        });
13804
13805        // Split to create pane B
13806        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13807            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13808        });
13809
13810        // Add item with SAME project path to pane B, and pin it
13811        let item_b = cx.new(|cx| {
13812            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13813        });
13814        pane_b.update_in(cx, |pane, window, cx| {
13815            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13816            pane.set_pinned_count(1);
13817        });
13818
13819        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13820        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13821
13822        // close_pinned: false should only close the unpinned copy
13823        workspace.update_in(cx, |workspace, window, cx| {
13824            workspace.close_item_in_all_panes(
13825                &CloseItemInAllPanes {
13826                    save_intent: Some(SaveIntent::Close),
13827                    close_pinned: false,
13828                },
13829                window,
13830                cx,
13831            )
13832        });
13833        cx.executor().run_until_parked();
13834
13835        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13836        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13837        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13838        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13839
13840        // Split again, seeing as closing the previous item also closed its
13841        // pane, so only pane remains, which does not allow us to properly test
13842        // that both items close when `close_pinned: true`.
13843        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13844            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13845        });
13846
13847        // Add an item with the same project path to pane C so that
13848        // close_item_in_all_panes can determine what to close across all panes
13849        // (it reads the active item from the active pane, and split_pane
13850        // creates an empty pane).
13851        let item_c = cx.new(|cx| {
13852            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13853        });
13854        pane_c.update_in(cx, |pane, window, cx| {
13855            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13856        });
13857
13858        // close_pinned: true should close the pinned copy too
13859        workspace.update_in(cx, |workspace, window, cx| {
13860            let panes_count = workspace.panes().len();
13861            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13862
13863            workspace.close_item_in_all_panes(
13864                &CloseItemInAllPanes {
13865                    save_intent: Some(SaveIntent::Close),
13866                    close_pinned: true,
13867                },
13868                window,
13869                cx,
13870            )
13871        });
13872        cx.executor().run_until_parked();
13873
13874        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13875        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13876        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13877        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13878    }
13879
13880    mod register_project_item_tests {
13881
13882        use super::*;
13883
13884        // View
13885        struct TestPngItemView {
13886            focus_handle: FocusHandle,
13887        }
13888        // Model
13889        struct TestPngItem {}
13890
13891        impl project::ProjectItem for TestPngItem {
13892            fn try_open(
13893                _project: &Entity<Project>,
13894                path: &ProjectPath,
13895                cx: &mut App,
13896            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13897                if path.path.extension().unwrap() == "png" {
13898                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13899                } else {
13900                    None
13901                }
13902            }
13903
13904            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13905                None
13906            }
13907
13908            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13909                None
13910            }
13911
13912            fn is_dirty(&self) -> bool {
13913                false
13914            }
13915        }
13916
13917        impl Item for TestPngItemView {
13918            type Event = ();
13919            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13920                "".into()
13921            }
13922        }
13923        impl EventEmitter<()> for TestPngItemView {}
13924        impl Focusable for TestPngItemView {
13925            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13926                self.focus_handle.clone()
13927            }
13928        }
13929
13930        impl Render for TestPngItemView {
13931            fn render(
13932                &mut self,
13933                _window: &mut Window,
13934                _cx: &mut Context<Self>,
13935            ) -> impl IntoElement {
13936                Empty
13937            }
13938        }
13939
13940        impl ProjectItem for TestPngItemView {
13941            type Item = TestPngItem;
13942
13943            fn for_project_item(
13944                _project: Entity<Project>,
13945                _pane: Option<&Pane>,
13946                _item: Entity<Self::Item>,
13947                _: &mut Window,
13948                cx: &mut Context<Self>,
13949            ) -> Self
13950            where
13951                Self: Sized,
13952            {
13953                Self {
13954                    focus_handle: cx.focus_handle(),
13955                }
13956            }
13957        }
13958
13959        // View
13960        struct TestIpynbItemView {
13961            focus_handle: FocusHandle,
13962        }
13963        // Model
13964        struct TestIpynbItem {}
13965
13966        impl project::ProjectItem for TestIpynbItem {
13967            fn try_open(
13968                _project: &Entity<Project>,
13969                path: &ProjectPath,
13970                cx: &mut App,
13971            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13972                if path.path.extension().unwrap() == "ipynb" {
13973                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13974                } else {
13975                    None
13976                }
13977            }
13978
13979            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13980                None
13981            }
13982
13983            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13984                None
13985            }
13986
13987            fn is_dirty(&self) -> bool {
13988                false
13989            }
13990        }
13991
13992        impl Item for TestIpynbItemView {
13993            type Event = ();
13994            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13995                "".into()
13996            }
13997        }
13998        impl EventEmitter<()> for TestIpynbItemView {}
13999        impl Focusable for TestIpynbItemView {
14000            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14001                self.focus_handle.clone()
14002            }
14003        }
14004
14005        impl Render for TestIpynbItemView {
14006            fn render(
14007                &mut self,
14008                _window: &mut Window,
14009                _cx: &mut Context<Self>,
14010            ) -> impl IntoElement {
14011                Empty
14012            }
14013        }
14014
14015        impl ProjectItem for TestIpynbItemView {
14016            type Item = TestIpynbItem;
14017
14018            fn for_project_item(
14019                _project: Entity<Project>,
14020                _pane: Option<&Pane>,
14021                _item: Entity<Self::Item>,
14022                _: &mut Window,
14023                cx: &mut Context<Self>,
14024            ) -> Self
14025            where
14026                Self: Sized,
14027            {
14028                Self {
14029                    focus_handle: cx.focus_handle(),
14030                }
14031            }
14032        }
14033
14034        struct TestAlternatePngItemView {
14035            focus_handle: FocusHandle,
14036        }
14037
14038        impl Item for TestAlternatePngItemView {
14039            type Event = ();
14040            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14041                "".into()
14042            }
14043        }
14044
14045        impl EventEmitter<()> for TestAlternatePngItemView {}
14046        impl Focusable for TestAlternatePngItemView {
14047            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14048                self.focus_handle.clone()
14049            }
14050        }
14051
14052        impl Render for TestAlternatePngItemView {
14053            fn render(
14054                &mut self,
14055                _window: &mut Window,
14056                _cx: &mut Context<Self>,
14057            ) -> impl IntoElement {
14058                Empty
14059            }
14060        }
14061
14062        impl ProjectItem for TestAlternatePngItemView {
14063            type Item = TestPngItem;
14064
14065            fn for_project_item(
14066                _project: Entity<Project>,
14067                _pane: Option<&Pane>,
14068                _item: Entity<Self::Item>,
14069                _: &mut Window,
14070                cx: &mut Context<Self>,
14071            ) -> Self
14072            where
14073                Self: Sized,
14074            {
14075                Self {
14076                    focus_handle: cx.focus_handle(),
14077                }
14078            }
14079        }
14080
14081        #[gpui::test]
14082        async fn test_register_project_item(cx: &mut TestAppContext) {
14083            init_test(cx);
14084
14085            cx.update(|cx| {
14086                register_project_item::<TestPngItemView>(cx);
14087                register_project_item::<TestIpynbItemView>(cx);
14088            });
14089
14090            let fs = FakeFs::new(cx.executor());
14091            fs.insert_tree(
14092                "/root1",
14093                json!({
14094                    "one.png": "BINARYDATAHERE",
14095                    "two.ipynb": "{ totally a notebook }",
14096                    "three.txt": "editing text, sure why not?"
14097                }),
14098            )
14099            .await;
14100
14101            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14102            let (workspace, cx) =
14103                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14104
14105            let worktree_id = project.update(cx, |project, cx| {
14106                project.worktrees(cx).next().unwrap().read(cx).id()
14107            });
14108
14109            let handle = workspace
14110                .update_in(cx, |workspace, window, cx| {
14111                    let project_path = (worktree_id, rel_path("one.png"));
14112                    workspace.open_path(project_path, None, true, window, cx)
14113                })
14114                .await
14115                .unwrap();
14116
14117            // Now we can check if the handle we got back errored or not
14118            assert_eq!(
14119                handle.to_any_view().entity_type(),
14120                TypeId::of::<TestPngItemView>()
14121            );
14122
14123            let handle = workspace
14124                .update_in(cx, |workspace, window, cx| {
14125                    let project_path = (worktree_id, rel_path("two.ipynb"));
14126                    workspace.open_path(project_path, None, true, window, cx)
14127                })
14128                .await
14129                .unwrap();
14130
14131            assert_eq!(
14132                handle.to_any_view().entity_type(),
14133                TypeId::of::<TestIpynbItemView>()
14134            );
14135
14136            let handle = workspace
14137                .update_in(cx, |workspace, window, cx| {
14138                    let project_path = (worktree_id, rel_path("three.txt"));
14139                    workspace.open_path(project_path, None, true, window, cx)
14140                })
14141                .await;
14142            assert!(handle.is_err());
14143        }
14144
14145        #[gpui::test]
14146        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14147            init_test(cx);
14148
14149            cx.update(|cx| {
14150                register_project_item::<TestPngItemView>(cx);
14151                register_project_item::<TestAlternatePngItemView>(cx);
14152            });
14153
14154            let fs = FakeFs::new(cx.executor());
14155            fs.insert_tree(
14156                "/root1",
14157                json!({
14158                    "one.png": "BINARYDATAHERE",
14159                    "two.ipynb": "{ totally a notebook }",
14160                    "three.txt": "editing text, sure why not?"
14161                }),
14162            )
14163            .await;
14164            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14165            let (workspace, cx) =
14166                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14167            let worktree_id = project.update(cx, |project, cx| {
14168                project.worktrees(cx).next().unwrap().read(cx).id()
14169            });
14170
14171            let handle = workspace
14172                .update_in(cx, |workspace, window, cx| {
14173                    let project_path = (worktree_id, rel_path("one.png"));
14174                    workspace.open_path(project_path, None, true, window, cx)
14175                })
14176                .await
14177                .unwrap();
14178
14179            // This _must_ be the second item registered
14180            assert_eq!(
14181                handle.to_any_view().entity_type(),
14182                TypeId::of::<TestAlternatePngItemView>()
14183            );
14184
14185            let handle = workspace
14186                .update_in(cx, |workspace, window, cx| {
14187                    let project_path = (worktree_id, rel_path("three.txt"));
14188                    workspace.open_path(project_path, None, true, window, cx)
14189                })
14190                .await;
14191            assert!(handle.is_err());
14192        }
14193    }
14194
14195    #[gpui::test]
14196    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14197        init_test(cx);
14198
14199        let fs = FakeFs::new(cx.executor());
14200        let project = Project::test(fs, [], cx).await;
14201        let (workspace, _cx) =
14202            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14203
14204        // Test with status bar shown (default)
14205        workspace.read_with(cx, |workspace, cx| {
14206            let visible = workspace.status_bar_visible(cx);
14207            assert!(visible, "Status bar should be visible by default");
14208        });
14209
14210        // Test with status bar hidden
14211        cx.update_global(|store: &mut SettingsStore, cx| {
14212            store.update_user_settings(cx, |settings| {
14213                settings.status_bar.get_or_insert_default().show = Some(false);
14214            });
14215        });
14216
14217        workspace.read_with(cx, |workspace, cx| {
14218            let visible = workspace.status_bar_visible(cx);
14219            assert!(!visible, "Status bar should be hidden when show is false");
14220        });
14221
14222        // Test with status bar shown explicitly
14223        cx.update_global(|store: &mut SettingsStore, cx| {
14224            store.update_user_settings(cx, |settings| {
14225                settings.status_bar.get_or_insert_default().show = Some(true);
14226            });
14227        });
14228
14229        workspace.read_with(cx, |workspace, cx| {
14230            let visible = workspace.status_bar_visible(cx);
14231            assert!(visible, "Status bar should be visible when show is true");
14232        });
14233    }
14234
14235    #[gpui::test]
14236    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14237        init_test(cx);
14238
14239        let fs = FakeFs::new(cx.executor());
14240        let project = Project::test(fs, [], cx).await;
14241        let (multi_workspace, cx) =
14242            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14243        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14244        let panel = workspace.update_in(cx, |workspace, window, cx| {
14245            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14246            workspace.add_panel(panel.clone(), window, cx);
14247
14248            workspace
14249                .right_dock()
14250                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14251
14252            panel
14253        });
14254
14255        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14256        let item_a = cx.new(TestItem::new);
14257        let item_b = cx.new(TestItem::new);
14258        let item_a_id = item_a.entity_id();
14259        let item_b_id = item_b.entity_id();
14260
14261        pane.update_in(cx, |pane, window, cx| {
14262            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14263            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14264        });
14265
14266        pane.read_with(cx, |pane, _| {
14267            assert_eq!(pane.items_len(), 2);
14268            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14269        });
14270
14271        workspace.update_in(cx, |workspace, window, cx| {
14272            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14273        });
14274
14275        workspace.update_in(cx, |_, window, cx| {
14276            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14277        });
14278
14279        // Assert that the `pane::CloseActiveItem` action is handled at the
14280        // workspace level when one of the dock panels is focused and, in that
14281        // case, the center pane's active item is closed but the focus is not
14282        // moved.
14283        cx.dispatch_action(pane::CloseActiveItem::default());
14284        cx.run_until_parked();
14285
14286        pane.read_with(cx, |pane, _| {
14287            assert_eq!(pane.items_len(), 1);
14288            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14289        });
14290
14291        workspace.update_in(cx, |workspace, window, cx| {
14292            assert!(workspace.right_dock().read(cx).is_open());
14293            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14294        });
14295    }
14296
14297    #[gpui::test]
14298    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14299        init_test(cx);
14300        let fs = FakeFs::new(cx.executor());
14301
14302        let project_a = Project::test(fs.clone(), [], cx).await;
14303        let project_b = Project::test(fs, [], cx).await;
14304
14305        let multi_workspace_handle =
14306            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14307        cx.run_until_parked();
14308
14309        let workspace_a = multi_workspace_handle
14310            .read_with(cx, |mw, _| mw.workspace().clone())
14311            .unwrap();
14312
14313        let _workspace_b = multi_workspace_handle
14314            .update(cx, |mw, window, cx| {
14315                mw.test_add_workspace(project_b, window, cx)
14316            })
14317            .unwrap();
14318
14319        // Switch to workspace A
14320        multi_workspace_handle
14321            .update(cx, |mw, window, cx| {
14322                mw.activate_index(0, window, cx);
14323            })
14324            .unwrap();
14325
14326        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14327
14328        // Add a panel to workspace A's right dock and open the dock
14329        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14330            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14331            workspace.add_panel(panel.clone(), window, cx);
14332            workspace
14333                .right_dock()
14334                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14335            panel
14336        });
14337
14338        // Focus the panel through the workspace (matching existing test pattern)
14339        workspace_a.update_in(cx, |workspace, window, cx| {
14340            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14341        });
14342
14343        // Zoom the panel
14344        panel.update_in(cx, |panel, window, cx| {
14345            panel.set_zoomed(true, window, cx);
14346        });
14347
14348        // Verify the panel is zoomed and the dock is open
14349        workspace_a.update_in(cx, |workspace, window, cx| {
14350            assert!(
14351                workspace.right_dock().read(cx).is_open(),
14352                "dock should be open before switch"
14353            );
14354            assert!(
14355                panel.is_zoomed(window, cx),
14356                "panel should be zoomed before switch"
14357            );
14358            assert!(
14359                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14360                "panel should be focused before switch"
14361            );
14362        });
14363
14364        // Switch to workspace B
14365        multi_workspace_handle
14366            .update(cx, |mw, window, cx| {
14367                mw.activate_index(1, window, cx);
14368            })
14369            .unwrap();
14370        cx.run_until_parked();
14371
14372        // Switch back to workspace A
14373        multi_workspace_handle
14374            .update(cx, |mw, window, cx| {
14375                mw.activate_index(0, window, cx);
14376            })
14377            .unwrap();
14378        cx.run_until_parked();
14379
14380        // Verify the panel is still zoomed and the dock is still open
14381        workspace_a.update_in(cx, |workspace, window, cx| {
14382            assert!(
14383                workspace.right_dock().read(cx).is_open(),
14384                "dock should still be open after switching back"
14385            );
14386            assert!(
14387                panel.is_zoomed(window, cx),
14388                "panel should still be zoomed after switching back"
14389            );
14390        });
14391    }
14392
14393    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14394        pane.read(cx)
14395            .items()
14396            .flat_map(|item| {
14397                item.project_paths(cx)
14398                    .into_iter()
14399                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14400            })
14401            .collect()
14402    }
14403
14404    pub fn init_test(cx: &mut TestAppContext) {
14405        cx.update(|cx| {
14406            let settings_store = SettingsStore::test(cx);
14407            cx.set_global(settings_store);
14408            cx.set_global(db::AppDatabase::test_new());
14409            theme_settings::init(theme::LoadThemes::JustBase, cx);
14410        });
14411    }
14412
14413    #[gpui::test]
14414    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14415        use settings::{ThemeName, ThemeSelection};
14416        use theme::SystemAppearance;
14417        use zed_actions::theme::ToggleMode;
14418
14419        init_test(cx);
14420
14421        let fs = FakeFs::new(cx.executor());
14422        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14423
14424        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14425            .await;
14426
14427        // Build a test project and workspace view so the test can invoke
14428        // the workspace action handler the same way the UI would.
14429        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14430        let (workspace, cx) =
14431            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14432
14433        // Seed the settings file with a plain static light theme so the
14434        // first toggle always starts from a known persisted state.
14435        workspace.update_in(cx, |_workspace, _window, cx| {
14436            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14437            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14438                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14439            });
14440        });
14441        cx.executor().advance_clock(Duration::from_millis(200));
14442        cx.run_until_parked();
14443
14444        // Confirm the initial persisted settings contain the static theme
14445        // we just wrote before any toggling happens.
14446        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14447        assert!(settings_text.contains(r#""theme": "One Light""#));
14448
14449        // Toggle once. This should migrate the persisted theme settings
14450        // into light/dark slots and enable system mode.
14451        workspace.update_in(cx, |workspace, window, cx| {
14452            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14453        });
14454        cx.executor().advance_clock(Duration::from_millis(200));
14455        cx.run_until_parked();
14456
14457        // 1. Static -> Dynamic
14458        // this assertion checks theme changed from static to dynamic.
14459        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14460        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14461        assert_eq!(
14462            parsed["theme"],
14463            serde_json::json!({
14464                "mode": "system",
14465                "light": "One Light",
14466                "dark": "One Dark"
14467            })
14468        );
14469
14470        // 2. Toggle again, suppose it will change the mode to light
14471        workspace.update_in(cx, |workspace, window, cx| {
14472            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14473        });
14474        cx.executor().advance_clock(Duration::from_millis(200));
14475        cx.run_until_parked();
14476
14477        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14478        assert!(settings_text.contains(r#""mode": "light""#));
14479    }
14480
14481    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14482        let item = TestProjectItem::new(id, path, cx);
14483        item.update(cx, |item, _| {
14484            item.is_dirty = true;
14485        });
14486        item
14487    }
14488
14489    #[gpui::test]
14490    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14491        cx: &mut gpui::TestAppContext,
14492    ) {
14493        init_test(cx);
14494        let fs = FakeFs::new(cx.executor());
14495
14496        let project = Project::test(fs, [], cx).await;
14497        let (workspace, cx) =
14498            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14499
14500        let panel = workspace.update_in(cx, |workspace, window, cx| {
14501            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14502            workspace.add_panel(panel.clone(), window, cx);
14503            workspace
14504                .right_dock()
14505                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14506            panel
14507        });
14508
14509        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14510        pane.update_in(cx, |pane, window, cx| {
14511            let item = cx.new(TestItem::new);
14512            pane.add_item(Box::new(item), true, true, None, window, cx);
14513        });
14514
14515        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14516        // mirrors the real-world flow and avoids side effects from directly
14517        // focusing the panel while the center pane is active.
14518        workspace.update_in(cx, |workspace, window, cx| {
14519            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14520        });
14521
14522        panel.update_in(cx, |panel, window, cx| {
14523            panel.set_zoomed(true, window, cx);
14524        });
14525
14526        workspace.update_in(cx, |workspace, window, cx| {
14527            assert!(workspace.right_dock().read(cx).is_open());
14528            assert!(panel.is_zoomed(window, cx));
14529            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14530        });
14531
14532        // Simulate a spurious pane::Event::Focus on the center pane while the
14533        // panel still has focus. This mirrors what happens during macOS window
14534        // activation: the center pane fires a focus event even though actual
14535        // focus remains on the dock panel.
14536        pane.update_in(cx, |_, _, cx| {
14537            cx.emit(pane::Event::Focus);
14538        });
14539
14540        // The dock must remain open because the panel had focus at the time the
14541        // event was processed. Before the fix, dock_to_preserve was None for
14542        // panels that don't implement pane(), causing the dock to close.
14543        workspace.update_in(cx, |workspace, window, cx| {
14544            assert!(
14545                workspace.right_dock().read(cx).is_open(),
14546                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14547            );
14548            assert!(panel.is_zoomed(window, cx));
14549        });
14550    }
14551
14552    #[gpui::test]
14553    async fn test_panels_stay_open_after_position_change_and_settings_update(
14554        cx: &mut gpui::TestAppContext,
14555    ) {
14556        init_test(cx);
14557        let fs = FakeFs::new(cx.executor());
14558        let project = Project::test(fs, [], cx).await;
14559        let (workspace, cx) =
14560            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14561
14562        // Add two panels to the left dock and open it.
14563        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14564            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14565            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14566            workspace.add_panel(panel_a.clone(), window, cx);
14567            workspace.add_panel(panel_b.clone(), window, cx);
14568            workspace.left_dock().update(cx, |dock, cx| {
14569                dock.set_open(true, window, cx);
14570                dock.activate_panel(0, window, cx);
14571            });
14572            (panel_a, panel_b)
14573        });
14574
14575        workspace.update_in(cx, |workspace, _, cx| {
14576            assert!(workspace.left_dock().read(cx).is_open());
14577        });
14578
14579        // Simulate a feature flag changing default dock positions: both panels
14580        // move from Left to Right.
14581        workspace.update_in(cx, |_workspace, _window, cx| {
14582            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14583            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14584            cx.update_global::<SettingsStore, _>(|_, _| {});
14585        });
14586
14587        // Both panels should now be in the right dock.
14588        workspace.update_in(cx, |workspace, _, cx| {
14589            let right_dock = workspace.right_dock().read(cx);
14590            assert_eq!(right_dock.panels_len(), 2);
14591        });
14592
14593        // Open the right dock and activate panel_b (simulating the user
14594        // opening the panel after it moved).
14595        workspace.update_in(cx, |workspace, window, cx| {
14596            workspace.right_dock().update(cx, |dock, cx| {
14597                dock.set_open(true, window, cx);
14598                dock.activate_panel(1, window, cx);
14599            });
14600        });
14601
14602        // Now trigger another SettingsStore change
14603        workspace.update_in(cx, |_workspace, _window, cx| {
14604            cx.update_global::<SettingsStore, _>(|_, _| {});
14605        });
14606
14607        workspace.update_in(cx, |workspace, _, cx| {
14608            assert!(
14609                workspace.right_dock().read(cx).is_open(),
14610                "Right dock should still be open after a settings change"
14611            );
14612            assert_eq!(
14613                workspace.right_dock().read(cx).panels_len(),
14614                2,
14615                "Both panels should still be in the right dock"
14616            );
14617        });
14618    }
14619}