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::{dock::PanelSizeState, 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    pub fn toggle_dock_panel_flexible_size(
 2205        &self,
 2206        dock: &Entity<Dock>,
 2207        panel: &dyn PanelHandle,
 2208        window: &mut Window,
 2209        cx: &mut App,
 2210    ) {
 2211        let position = dock.read(cx).position();
 2212        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2213        let current_flex =
 2214            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2215        dock.update(cx, |dock, cx| {
 2216            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2217        });
 2218    }
 2219
 2220    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2221        let panel = dock.active_panel()?;
 2222        let size_state = dock
 2223            .stored_panel_size_state(panel.as_ref())
 2224            .unwrap_or_default();
 2225        let position = dock.position();
 2226
 2227        let use_flex = panel.has_flexible_size(window, cx);
 2228
 2229        if position.axis() == Axis::Horizontal
 2230            && use_flex
 2231            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2232        {
 2233            let workspace_width = self.bounds.size.width;
 2234            if workspace_width <= Pixels::ZERO {
 2235                return None;
 2236            }
 2237            let flex = flex.max(0.001);
 2238            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2239            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2240                // Both docks are flex items sharing the full workspace width.
 2241                let total_flex = flex + 1.0 + opposite_flex;
 2242                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2243            } else {
 2244                // Opposite dock is fixed-width; flex items share (W - fixed).
 2245                let opposite_fixed = opposite
 2246                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2247                    .unwrap_or_default();
 2248                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2249                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2250            }
 2251        }
 2252
 2253        Some(
 2254            size_state
 2255                .size
 2256                .unwrap_or_else(|| panel.default_size(window, cx)),
 2257        )
 2258    }
 2259
 2260    pub fn dock_flex_for_size(
 2261        &self,
 2262        position: DockPosition,
 2263        size: Pixels,
 2264        window: &Window,
 2265        cx: &App,
 2266    ) -> Option<f32> {
 2267        if position.axis() != Axis::Horizontal {
 2268            return None;
 2269        }
 2270
 2271        let workspace_width = self.bounds.size.width;
 2272        if workspace_width <= Pixels::ZERO {
 2273            return None;
 2274        }
 2275
 2276        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2277        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2278            let size = size.clamp(px(0.), workspace_width - px(1.));
 2279            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2280        } else {
 2281            let opposite_width = opposite
 2282                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2283                .unwrap_or_default();
 2284            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2285            let remaining = (available - size).max(px(1.));
 2286            Some((size / remaining).max(0.0))
 2287        }
 2288    }
 2289
 2290    fn opposite_dock_panel_and_size_state(
 2291        &self,
 2292        position: DockPosition,
 2293        window: &Window,
 2294        cx: &App,
 2295    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2296        let opposite_position = match position {
 2297            DockPosition::Left => DockPosition::Right,
 2298            DockPosition::Right => DockPosition::Left,
 2299            DockPosition::Bottom => return None,
 2300        };
 2301
 2302        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2303        let panel = opposite_dock.visible_panel()?;
 2304        let mut size_state = opposite_dock
 2305            .stored_panel_size_state(panel.as_ref())
 2306            .unwrap_or_default();
 2307        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2308            size_state.flex = self.default_dock_flex(opposite_position);
 2309        }
 2310        Some((panel.clone(), size_state))
 2311    }
 2312
 2313    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2314        if position.axis() != Axis::Horizontal {
 2315            return None;
 2316        }
 2317
 2318        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2319        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2320    }
 2321
 2322    pub fn is_edited(&self) -> bool {
 2323        self.window_edited
 2324    }
 2325
 2326    pub fn add_panel<T: Panel>(
 2327        &mut self,
 2328        panel: Entity<T>,
 2329        window: &mut Window,
 2330        cx: &mut Context<Self>,
 2331    ) {
 2332        let focus_handle = panel.panel_focus_handle(cx);
 2333        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2334            .detach();
 2335
 2336        let dock_position = panel.position(window, cx);
 2337        let dock = self.dock_at_position(dock_position);
 2338        let any_panel = panel.to_any();
 2339        let persisted_size_state =
 2340            self.persisted_panel_size_state(T::panel_key(), cx)
 2341                .or_else(|| {
 2342                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2343                        let state = dock::PanelSizeState {
 2344                            size: Some(size),
 2345                            flex: None,
 2346                        };
 2347                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2348                        state
 2349                    })
 2350                });
 2351
 2352        dock.update(cx, |dock, cx| {
 2353            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2354            if let Some(size_state) = persisted_size_state {
 2355                dock.set_panel_size_state(&panel, size_state, cx);
 2356            }
 2357            index
 2358        });
 2359
 2360        cx.emit(Event::PanelAdded(any_panel));
 2361    }
 2362
 2363    pub fn remove_panel<T: Panel>(
 2364        &mut self,
 2365        panel: &Entity<T>,
 2366        window: &mut Window,
 2367        cx: &mut Context<Self>,
 2368    ) {
 2369        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2370            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2371        }
 2372    }
 2373
 2374    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2375        &self.status_bar
 2376    }
 2377
 2378    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2379        self.sidebar_focus_handle = handle;
 2380    }
 2381
 2382    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2383        StatusBarSettings::get_global(cx).show
 2384    }
 2385
 2386    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2387        self.multi_workspace.as_ref()
 2388    }
 2389
 2390    pub fn set_multi_workspace(
 2391        &mut self,
 2392        multi_workspace: WeakEntity<MultiWorkspace>,
 2393        cx: &mut App,
 2394    ) {
 2395        self.status_bar.update(cx, |status_bar, cx| {
 2396            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2397        });
 2398        self.multi_workspace = Some(multi_workspace);
 2399    }
 2400
 2401    pub fn app_state(&self) -> &Arc<AppState> {
 2402        &self.app_state
 2403    }
 2404
 2405    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2406        self._panels_task = Some(task);
 2407    }
 2408
 2409    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2410        self._panels_task.take()
 2411    }
 2412
 2413    pub fn user_store(&self) -> &Entity<UserStore> {
 2414        &self.app_state.user_store
 2415    }
 2416
 2417    pub fn project(&self) -> &Entity<Project> {
 2418        &self.project
 2419    }
 2420
 2421    pub fn path_style(&self, cx: &App) -> PathStyle {
 2422        self.project.read(cx).path_style(cx)
 2423    }
 2424
 2425    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2426        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2427
 2428        for pane_handle in &self.panes {
 2429            let pane = pane_handle.read(cx);
 2430
 2431            for entry in pane.activation_history() {
 2432                history.insert(
 2433                    entry.entity_id,
 2434                    history
 2435                        .get(&entry.entity_id)
 2436                        .cloned()
 2437                        .unwrap_or(0)
 2438                        .max(entry.timestamp),
 2439                );
 2440            }
 2441        }
 2442
 2443        history
 2444    }
 2445
 2446    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2447        let mut recent_item: Option<Entity<T>> = None;
 2448        let mut recent_timestamp = 0;
 2449        for pane_handle in &self.panes {
 2450            let pane = pane_handle.read(cx);
 2451            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2452                pane.items().map(|item| (item.item_id(), item)).collect();
 2453            for entry in pane.activation_history() {
 2454                if entry.timestamp > recent_timestamp
 2455                    && let Some(&item) = item_map.get(&entry.entity_id)
 2456                    && let Some(typed_item) = item.act_as::<T>(cx)
 2457                {
 2458                    recent_timestamp = entry.timestamp;
 2459                    recent_item = Some(typed_item);
 2460                }
 2461            }
 2462        }
 2463        recent_item
 2464    }
 2465
 2466    pub fn recent_navigation_history_iter(
 2467        &self,
 2468        cx: &App,
 2469    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2470        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2471        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2472
 2473        for pane in &self.panes {
 2474            let pane = pane.read(cx);
 2475
 2476            pane.nav_history()
 2477                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2478                    if let Some(fs_path) = &fs_path {
 2479                        abs_paths_opened
 2480                            .entry(fs_path.clone())
 2481                            .or_default()
 2482                            .insert(project_path.clone());
 2483                    }
 2484                    let timestamp = entry.timestamp;
 2485                    match history.entry(project_path) {
 2486                        hash_map::Entry::Occupied(mut entry) => {
 2487                            let (_, old_timestamp) = entry.get();
 2488                            if &timestamp > old_timestamp {
 2489                                entry.insert((fs_path, timestamp));
 2490                            }
 2491                        }
 2492                        hash_map::Entry::Vacant(entry) => {
 2493                            entry.insert((fs_path, timestamp));
 2494                        }
 2495                    }
 2496                });
 2497
 2498            if let Some(item) = pane.active_item()
 2499                && let Some(project_path) = item.project_path(cx)
 2500            {
 2501                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2502
 2503                if let Some(fs_path) = &fs_path {
 2504                    abs_paths_opened
 2505                        .entry(fs_path.clone())
 2506                        .or_default()
 2507                        .insert(project_path.clone());
 2508                }
 2509
 2510                history.insert(project_path, (fs_path, std::usize::MAX));
 2511            }
 2512        }
 2513
 2514        history
 2515            .into_iter()
 2516            .sorted_by_key(|(_, (_, order))| *order)
 2517            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2518            .rev()
 2519            .filter(move |(history_path, abs_path)| {
 2520                let latest_project_path_opened = abs_path
 2521                    .as_ref()
 2522                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2523                    .and_then(|project_paths| {
 2524                        project_paths
 2525                            .iter()
 2526                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2527                    });
 2528
 2529                latest_project_path_opened.is_none_or(|path| path == history_path)
 2530            })
 2531    }
 2532
 2533    pub fn recent_navigation_history(
 2534        &self,
 2535        limit: Option<usize>,
 2536        cx: &App,
 2537    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2538        self.recent_navigation_history_iter(cx)
 2539            .take(limit.unwrap_or(usize::MAX))
 2540            .collect()
 2541    }
 2542
 2543    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2544        for pane in &self.panes {
 2545            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2546        }
 2547    }
 2548
 2549    fn navigate_history(
 2550        &mut self,
 2551        pane: WeakEntity<Pane>,
 2552        mode: NavigationMode,
 2553        window: &mut Window,
 2554        cx: &mut Context<Workspace>,
 2555    ) -> Task<Result<()>> {
 2556        self.navigate_history_impl(
 2557            pane,
 2558            mode,
 2559            window,
 2560            &mut |history, cx| history.pop(mode, cx),
 2561            cx,
 2562        )
 2563    }
 2564
 2565    fn navigate_tag_history(
 2566        &mut self,
 2567        pane: WeakEntity<Pane>,
 2568        mode: TagNavigationMode,
 2569        window: &mut Window,
 2570        cx: &mut Context<Workspace>,
 2571    ) -> Task<Result<()>> {
 2572        self.navigate_history_impl(
 2573            pane,
 2574            NavigationMode::Normal,
 2575            window,
 2576            &mut |history, _cx| history.pop_tag(mode),
 2577            cx,
 2578        )
 2579    }
 2580
 2581    fn navigate_history_impl(
 2582        &mut self,
 2583        pane: WeakEntity<Pane>,
 2584        mode: NavigationMode,
 2585        window: &mut Window,
 2586        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2587        cx: &mut Context<Workspace>,
 2588    ) -> Task<Result<()>> {
 2589        let to_load = if let Some(pane) = pane.upgrade() {
 2590            pane.update(cx, |pane, cx| {
 2591                window.focus(&pane.focus_handle(cx), cx);
 2592                loop {
 2593                    // Retrieve the weak item handle from the history.
 2594                    let entry = cb(pane.nav_history_mut(), cx)?;
 2595
 2596                    // If the item is still present in this pane, then activate it.
 2597                    if let Some(index) = entry
 2598                        .item
 2599                        .upgrade()
 2600                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2601                    {
 2602                        let prev_active_item_index = pane.active_item_index();
 2603                        pane.nav_history_mut().set_mode(mode);
 2604                        pane.activate_item(index, true, true, window, cx);
 2605                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2606
 2607                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2608                        if let Some(data) = entry.data {
 2609                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2610                        }
 2611
 2612                        if navigated {
 2613                            break None;
 2614                        }
 2615                    } else {
 2616                        // If the item is no longer present in this pane, then retrieve its
 2617                        // path info in order to reopen it.
 2618                        break pane
 2619                            .nav_history()
 2620                            .path_for_item(entry.item.id())
 2621                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2622                    }
 2623                }
 2624            })
 2625        } else {
 2626            None
 2627        };
 2628
 2629        if let Some((project_path, abs_path, entry)) = to_load {
 2630            // If the item was no longer present, then load it again from its previous path, first try the local path
 2631            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2632
 2633            cx.spawn_in(window, async move  |workspace, cx| {
 2634                let open_by_project_path = open_by_project_path.await;
 2635                let mut navigated = false;
 2636                match open_by_project_path
 2637                    .with_context(|| format!("Navigating to {project_path:?}"))
 2638                {
 2639                    Ok((project_entry_id, build_item)) => {
 2640                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2641                            pane.nav_history_mut().set_mode(mode);
 2642                            pane.active_item().map(|p| p.item_id())
 2643                        })?;
 2644
 2645                        pane.update_in(cx, |pane, window, cx| {
 2646                            let item = pane.open_item(
 2647                                project_entry_id,
 2648                                project_path,
 2649                                true,
 2650                                entry.is_preview,
 2651                                true,
 2652                                None,
 2653                                window, cx,
 2654                                build_item,
 2655                            );
 2656                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2657                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2658                            if let Some(data) = entry.data {
 2659                                navigated |= item.navigate(data, window, cx);
 2660                            }
 2661                        })?;
 2662                    }
 2663                    Err(open_by_project_path_e) => {
 2664                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2665                        // and its worktree is now dropped
 2666                        if let Some(abs_path) = abs_path {
 2667                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2668                                pane.nav_history_mut().set_mode(mode);
 2669                                pane.active_item().map(|p| p.item_id())
 2670                            })?;
 2671                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2672                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2673                            })?;
 2674                            match open_by_abs_path
 2675                                .await
 2676                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2677                            {
 2678                                Ok(item) => {
 2679                                    pane.update_in(cx, |pane, window, cx| {
 2680                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2681                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2682                                        if let Some(data) = entry.data {
 2683                                            navigated |= item.navigate(data, window, cx);
 2684                                        }
 2685                                    })?;
 2686                                }
 2687                                Err(open_by_abs_path_e) => {
 2688                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2689                                }
 2690                            }
 2691                        }
 2692                    }
 2693                }
 2694
 2695                if !navigated {
 2696                    workspace
 2697                        .update_in(cx, |workspace, window, cx| {
 2698                            Self::navigate_history(workspace, pane, mode, window, cx)
 2699                        })?
 2700                        .await?;
 2701                }
 2702
 2703                Ok(())
 2704            })
 2705        } else {
 2706            Task::ready(Ok(()))
 2707        }
 2708    }
 2709
 2710    pub fn go_back(
 2711        &mut self,
 2712        pane: WeakEntity<Pane>,
 2713        window: &mut Window,
 2714        cx: &mut Context<Workspace>,
 2715    ) -> Task<Result<()>> {
 2716        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2717    }
 2718
 2719    pub fn go_forward(
 2720        &mut self,
 2721        pane: WeakEntity<Pane>,
 2722        window: &mut Window,
 2723        cx: &mut Context<Workspace>,
 2724    ) -> Task<Result<()>> {
 2725        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2726    }
 2727
 2728    pub fn reopen_closed_item(
 2729        &mut self,
 2730        window: &mut Window,
 2731        cx: &mut Context<Workspace>,
 2732    ) -> Task<Result<()>> {
 2733        self.navigate_history(
 2734            self.active_pane().downgrade(),
 2735            NavigationMode::ReopeningClosedItem,
 2736            window,
 2737            cx,
 2738        )
 2739    }
 2740
 2741    pub fn client(&self) -> &Arc<Client> {
 2742        &self.app_state.client
 2743    }
 2744
 2745    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2746        self.titlebar_item = Some(item);
 2747        cx.notify();
 2748    }
 2749
 2750    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2751        self.on_prompt_for_new_path = Some(prompt)
 2752    }
 2753
 2754    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2755        self.on_prompt_for_open_path = Some(prompt)
 2756    }
 2757
 2758    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2759        self.terminal_provider = Some(Box::new(provider));
 2760    }
 2761
 2762    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2763        self.debugger_provider = Some(Arc::new(provider));
 2764    }
 2765
 2766    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2767        self.debugger_provider.clone()
 2768    }
 2769
 2770    pub fn prompt_for_open_path(
 2771        &mut self,
 2772        path_prompt_options: PathPromptOptions,
 2773        lister: DirectoryLister,
 2774        window: &mut Window,
 2775        cx: &mut Context<Self>,
 2776    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2777        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2778            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2779            let rx = prompt(self, lister, window, cx);
 2780            self.on_prompt_for_open_path = Some(prompt);
 2781            rx
 2782        } else {
 2783            let (tx, rx) = oneshot::channel();
 2784            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2785
 2786            cx.spawn_in(window, async move |workspace, cx| {
 2787                let Ok(result) = abs_path.await else {
 2788                    return Ok(());
 2789                };
 2790
 2791                match result {
 2792                    Ok(result) => {
 2793                        tx.send(result).ok();
 2794                    }
 2795                    Err(err) => {
 2796                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2797                            workspace.show_portal_error(err.to_string(), cx);
 2798                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2799                            let rx = prompt(workspace, lister, window, cx);
 2800                            workspace.on_prompt_for_open_path = Some(prompt);
 2801                            rx
 2802                        })?;
 2803                        if let Ok(path) = rx.await {
 2804                            tx.send(path).ok();
 2805                        }
 2806                    }
 2807                };
 2808                anyhow::Ok(())
 2809            })
 2810            .detach();
 2811
 2812            rx
 2813        }
 2814    }
 2815
 2816    pub fn prompt_for_new_path(
 2817        &mut self,
 2818        lister: DirectoryLister,
 2819        suggested_name: Option<String>,
 2820        window: &mut Window,
 2821        cx: &mut Context<Self>,
 2822    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2823        if self.project.read(cx).is_via_collab()
 2824            || self.project.read(cx).is_via_remote_server()
 2825            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2826        {
 2827            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2828            let rx = prompt(self, lister, suggested_name, window, cx);
 2829            self.on_prompt_for_new_path = Some(prompt);
 2830            return rx;
 2831        }
 2832
 2833        let (tx, rx) = oneshot::channel();
 2834        cx.spawn_in(window, async move |workspace, cx| {
 2835            let abs_path = workspace.update(cx, |workspace, cx| {
 2836                let relative_to = workspace
 2837                    .most_recent_active_path(cx)
 2838                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2839                    .or_else(|| {
 2840                        let project = workspace.project.read(cx);
 2841                        project.visible_worktrees(cx).find_map(|worktree| {
 2842                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2843                        })
 2844                    })
 2845                    .or_else(std::env::home_dir)
 2846                    .unwrap_or_else(|| PathBuf::from(""));
 2847                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2848            })?;
 2849            let abs_path = match abs_path.await? {
 2850                Ok(path) => path,
 2851                Err(err) => {
 2852                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2853                        workspace.show_portal_error(err.to_string(), cx);
 2854
 2855                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2856                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2857                        workspace.on_prompt_for_new_path = Some(prompt);
 2858                        rx
 2859                    })?;
 2860                    if let Ok(path) = rx.await {
 2861                        tx.send(path).ok();
 2862                    }
 2863                    return anyhow::Ok(());
 2864                }
 2865            };
 2866
 2867            tx.send(abs_path.map(|path| vec![path])).ok();
 2868            anyhow::Ok(())
 2869        })
 2870        .detach();
 2871
 2872        rx
 2873    }
 2874
 2875    pub fn titlebar_item(&self) -> Option<AnyView> {
 2876        self.titlebar_item.clone()
 2877    }
 2878
 2879    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2880    /// When set, git-related operations should use this worktree instead of deriving
 2881    /// the active worktree from the focused file.
 2882    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2883        self.active_worktree_override
 2884    }
 2885
 2886    pub fn set_active_worktree_override(
 2887        &mut self,
 2888        worktree_id: Option<WorktreeId>,
 2889        cx: &mut Context<Self>,
 2890    ) {
 2891        self.active_worktree_override = worktree_id;
 2892        cx.notify();
 2893    }
 2894
 2895    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2896        self.active_worktree_override = None;
 2897        cx.notify();
 2898    }
 2899
 2900    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2901    ///
 2902    /// If the given workspace has a local project, then it will be passed
 2903    /// to the callback. Otherwise, a new empty window will be created.
 2904    pub fn with_local_workspace<T, F>(
 2905        &mut self,
 2906        window: &mut Window,
 2907        cx: &mut Context<Self>,
 2908        callback: F,
 2909    ) -> Task<Result<T>>
 2910    where
 2911        T: 'static,
 2912        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2913    {
 2914        if self.project.read(cx).is_local() {
 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    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2941    ///
 2942    /// If the given workspace has a local project, then it will be passed
 2943    /// to the callback. Otherwise, a new empty window will be created.
 2944    pub fn with_local_or_wsl_workspace<T, F>(
 2945        &mut self,
 2946        window: &mut Window,
 2947        cx: &mut Context<Self>,
 2948        callback: F,
 2949    ) -> Task<Result<T>>
 2950    where
 2951        T: 'static,
 2952        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2953    {
 2954        let project = self.project.read(cx);
 2955        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2956            Task::ready(Ok(callback(self, window, cx)))
 2957        } else {
 2958            let env = self.project.read(cx).cli_environment(cx);
 2959            let task = Self::new_local(
 2960                Vec::new(),
 2961                self.app_state.clone(),
 2962                None,
 2963                env,
 2964                None,
 2965                true,
 2966                cx,
 2967            );
 2968            cx.spawn_in(window, async move |_vh, cx| {
 2969                let OpenResult {
 2970                    window: multi_workspace_window,
 2971                    ..
 2972                } = task.await?;
 2973                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2974                    let workspace = multi_workspace.workspace().clone();
 2975                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2976                })
 2977            })
 2978        }
 2979    }
 2980
 2981    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2982        self.project.read(cx).worktrees(cx)
 2983    }
 2984
 2985    pub fn visible_worktrees<'a>(
 2986        &self,
 2987        cx: &'a App,
 2988    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2989        self.project.read(cx).visible_worktrees(cx)
 2990    }
 2991
 2992    #[cfg(any(test, feature = "test-support"))]
 2993    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2994        let futures = self
 2995            .worktrees(cx)
 2996            .filter_map(|worktree| worktree.read(cx).as_local())
 2997            .map(|worktree| worktree.scan_complete())
 2998            .collect::<Vec<_>>();
 2999        async move {
 3000            for future in futures {
 3001                future.await;
 3002            }
 3003        }
 3004    }
 3005
 3006    pub fn close_global(cx: &mut App) {
 3007        cx.defer(|cx| {
 3008            cx.windows().iter().find(|window| {
 3009                window
 3010                    .update(cx, |_, window, _| {
 3011                        if window.is_window_active() {
 3012                            //This can only get called when the window's project connection has been lost
 3013                            //so we don't need to prompt the user for anything and instead just close the window
 3014                            window.remove_window();
 3015                            true
 3016                        } else {
 3017                            false
 3018                        }
 3019                    })
 3020                    .unwrap_or(false)
 3021            });
 3022        });
 3023    }
 3024
 3025    pub fn move_focused_panel_to_next_position(
 3026        &mut self,
 3027        _: &MoveFocusedPanelToNextPosition,
 3028        window: &mut Window,
 3029        cx: &mut Context<Self>,
 3030    ) {
 3031        let docks = self.all_docks();
 3032        let active_dock = docks
 3033            .into_iter()
 3034            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3035
 3036        if let Some(dock) = active_dock {
 3037            dock.update(cx, |dock, cx| {
 3038                let active_panel = dock
 3039                    .active_panel()
 3040                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3041
 3042                if let Some(panel) = active_panel {
 3043                    panel.move_to_next_position(window, cx);
 3044                }
 3045            })
 3046        }
 3047    }
 3048
 3049    pub fn prepare_to_close(
 3050        &mut self,
 3051        close_intent: CloseIntent,
 3052        window: &mut Window,
 3053        cx: &mut Context<Self>,
 3054    ) -> Task<Result<bool>> {
 3055        let active_call = self.active_global_call();
 3056
 3057        cx.spawn_in(window, async move |this, cx| {
 3058            this.update(cx, |this, _| {
 3059                if close_intent == CloseIntent::CloseWindow {
 3060                    this.removing = true;
 3061                }
 3062            })?;
 3063
 3064            let workspace_count = cx.update(|_window, cx| {
 3065                cx.windows()
 3066                    .iter()
 3067                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3068                    .count()
 3069            })?;
 3070
 3071            #[cfg(target_os = "macos")]
 3072            let save_last_workspace = false;
 3073
 3074            // On Linux and Windows, closing the last window should restore the last workspace.
 3075            #[cfg(not(target_os = "macos"))]
 3076            let save_last_workspace = {
 3077                let remaining_workspaces = cx.update(|_window, cx| {
 3078                    cx.windows()
 3079                        .iter()
 3080                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3081                        .filter_map(|multi_workspace| {
 3082                            multi_workspace
 3083                                .update(cx, |multi_workspace, _, cx| {
 3084                                    multi_workspace.workspace().read(cx).removing
 3085                                })
 3086                                .ok()
 3087                        })
 3088                        .filter(|removing| !removing)
 3089                        .count()
 3090                })?;
 3091
 3092                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3093            };
 3094
 3095            if let Some(active_call) = active_call
 3096                && workspace_count == 1
 3097                && cx
 3098                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3099                    .unwrap_or(false)
 3100            {
 3101                if close_intent == CloseIntent::CloseWindow {
 3102                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3103                    let answer = cx.update(|window, cx| {
 3104                        window.prompt(
 3105                            PromptLevel::Warning,
 3106                            "Do you want to leave the current call?",
 3107                            None,
 3108                            &["Close window and hang up", "Cancel"],
 3109                            cx,
 3110                        )
 3111                    })?;
 3112
 3113                    if answer.await.log_err() == Some(1) {
 3114                        return anyhow::Ok(false);
 3115                    } else {
 3116                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3117                            task.await.log_err();
 3118                        }
 3119                    }
 3120                }
 3121                if close_intent == CloseIntent::ReplaceWindow {
 3122                    _ = cx.update(|_window, cx| {
 3123                        let multi_workspace = cx
 3124                            .windows()
 3125                            .iter()
 3126                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3127                            .next()
 3128                            .unwrap();
 3129                        let project = multi_workspace
 3130                            .read(cx)?
 3131                            .workspace()
 3132                            .read(cx)
 3133                            .project
 3134                            .clone();
 3135                        if project.read(cx).is_shared() {
 3136                            active_call.0.unshare_project(project, cx)?;
 3137                        }
 3138                        Ok::<_, anyhow::Error>(())
 3139                    });
 3140                }
 3141            }
 3142
 3143            let save_result = this
 3144                .update_in(cx, |this, window, cx| {
 3145                    this.save_all_internal(SaveIntent::Close, window, cx)
 3146                })?
 3147                .await;
 3148
 3149            // If we're not quitting, but closing, we remove the workspace from
 3150            // the current session.
 3151            if close_intent != CloseIntent::Quit
 3152                && !save_last_workspace
 3153                && save_result.as_ref().is_ok_and(|&res| res)
 3154            {
 3155                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3156                    .await;
 3157            }
 3158
 3159            save_result
 3160        })
 3161    }
 3162
 3163    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3164        self.save_all_internal(
 3165            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3166            window,
 3167            cx,
 3168        )
 3169        .detach_and_log_err(cx);
 3170    }
 3171
 3172    fn send_keystrokes(
 3173        &mut self,
 3174        action: &SendKeystrokes,
 3175        window: &mut Window,
 3176        cx: &mut Context<Self>,
 3177    ) {
 3178        let keystrokes: Vec<Keystroke> = action
 3179            .0
 3180            .split(' ')
 3181            .flat_map(|k| Keystroke::parse(k).log_err())
 3182            .map(|k| {
 3183                cx.keyboard_mapper()
 3184                    .map_key_equivalent(k, false)
 3185                    .inner()
 3186                    .clone()
 3187            })
 3188            .collect();
 3189        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3190    }
 3191
 3192    pub fn send_keystrokes_impl(
 3193        &mut self,
 3194        keystrokes: Vec<Keystroke>,
 3195        window: &mut Window,
 3196        cx: &mut Context<Self>,
 3197    ) -> Shared<Task<()>> {
 3198        let mut state = self.dispatching_keystrokes.borrow_mut();
 3199        if !state.dispatched.insert(keystrokes.clone()) {
 3200            cx.propagate();
 3201            return state.task.clone().unwrap();
 3202        }
 3203
 3204        state.queue.extend(keystrokes);
 3205
 3206        let keystrokes = self.dispatching_keystrokes.clone();
 3207        if state.task.is_none() {
 3208            state.task = Some(
 3209                window
 3210                    .spawn(cx, async move |cx| {
 3211                        // limit to 100 keystrokes to avoid infinite recursion.
 3212                        for _ in 0..100 {
 3213                            let keystroke = {
 3214                                let mut state = keystrokes.borrow_mut();
 3215                                let Some(keystroke) = state.queue.pop_front() else {
 3216                                    state.dispatched.clear();
 3217                                    state.task.take();
 3218                                    return;
 3219                                };
 3220                                keystroke
 3221                            };
 3222                            cx.update(|window, cx| {
 3223                                let focused = window.focused(cx);
 3224                                window.dispatch_keystroke(keystroke.clone(), cx);
 3225                                if window.focused(cx) != focused {
 3226                                    // dispatch_keystroke may cause the focus to change.
 3227                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3228                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3229                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3230                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3231                                    // )
 3232                                    window.draw(cx).clear();
 3233                                }
 3234                            })
 3235                            .ok();
 3236
 3237                            // Yield between synthetic keystrokes so deferred focus and
 3238                            // other effects can settle before dispatching the next key.
 3239                            yield_now().await;
 3240                        }
 3241
 3242                        *keystrokes.borrow_mut() = Default::default();
 3243                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3244                    })
 3245                    .shared(),
 3246            );
 3247        }
 3248        state.task.clone().unwrap()
 3249    }
 3250
 3251    fn save_all_internal(
 3252        &mut self,
 3253        mut save_intent: SaveIntent,
 3254        window: &mut Window,
 3255        cx: &mut Context<Self>,
 3256    ) -> Task<Result<bool>> {
 3257        if self.project.read(cx).is_disconnected(cx) {
 3258            return Task::ready(Ok(true));
 3259        }
 3260        let dirty_items = self
 3261            .panes
 3262            .iter()
 3263            .flat_map(|pane| {
 3264                pane.read(cx).items().filter_map(|item| {
 3265                    if item.is_dirty(cx) {
 3266                        item.tab_content_text(0, cx);
 3267                        Some((pane.downgrade(), item.boxed_clone()))
 3268                    } else {
 3269                        None
 3270                    }
 3271                })
 3272            })
 3273            .collect::<Vec<_>>();
 3274
 3275        let project = self.project.clone();
 3276        cx.spawn_in(window, async move |workspace, cx| {
 3277            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3278                let (serialize_tasks, remaining_dirty_items) =
 3279                    workspace.update_in(cx, |workspace, window, cx| {
 3280                        let mut remaining_dirty_items = Vec::new();
 3281                        let mut serialize_tasks = Vec::new();
 3282                        for (pane, item) in dirty_items {
 3283                            if let Some(task) = item
 3284                                .to_serializable_item_handle(cx)
 3285                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3286                            {
 3287                                serialize_tasks.push(task);
 3288                            } else {
 3289                                remaining_dirty_items.push((pane, item));
 3290                            }
 3291                        }
 3292                        (serialize_tasks, remaining_dirty_items)
 3293                    })?;
 3294
 3295                futures::future::try_join_all(serialize_tasks).await?;
 3296
 3297                if !remaining_dirty_items.is_empty() {
 3298                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3299                }
 3300
 3301                if remaining_dirty_items.len() > 1 {
 3302                    let answer = workspace.update_in(cx, |_, window, cx| {
 3303                        let detail = Pane::file_names_for_prompt(
 3304                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3305                            cx,
 3306                        );
 3307                        window.prompt(
 3308                            PromptLevel::Warning,
 3309                            "Do you want to save all changes in the following files?",
 3310                            Some(&detail),
 3311                            &["Save all", "Discard all", "Cancel"],
 3312                            cx,
 3313                        )
 3314                    })?;
 3315                    match answer.await.log_err() {
 3316                        Some(0) => save_intent = SaveIntent::SaveAll,
 3317                        Some(1) => save_intent = SaveIntent::Skip,
 3318                        Some(2) => return Ok(false),
 3319                        _ => {}
 3320                    }
 3321                }
 3322
 3323                remaining_dirty_items
 3324            } else {
 3325                dirty_items
 3326            };
 3327
 3328            for (pane, item) in dirty_items {
 3329                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3330                    (
 3331                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3332                        item.project_entry_ids(cx),
 3333                    )
 3334                })?;
 3335                if (singleton || !project_entry_ids.is_empty())
 3336                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3337                {
 3338                    return Ok(false);
 3339                }
 3340            }
 3341            Ok(true)
 3342        })
 3343    }
 3344
 3345    pub fn open_workspace_for_paths(
 3346        &mut self,
 3347        replace_current_window: bool,
 3348        paths: Vec<PathBuf>,
 3349        window: &mut Window,
 3350        cx: &mut Context<Self>,
 3351    ) -> Task<Result<Entity<Workspace>>> {
 3352        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3353        let is_remote = self.project.read(cx).is_via_collab();
 3354        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3355        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3356
 3357        let window_to_replace = if replace_current_window {
 3358            window_handle
 3359        } else if is_remote || has_worktree || has_dirty_items {
 3360            None
 3361        } else {
 3362            window_handle
 3363        };
 3364        let app_state = self.app_state.clone();
 3365
 3366        cx.spawn(async move |_, cx| {
 3367            let OpenResult { workspace, .. } = cx
 3368                .update(|cx| {
 3369                    open_paths(
 3370                        &paths,
 3371                        app_state,
 3372                        OpenOptions {
 3373                            replace_window: window_to_replace,
 3374                            ..Default::default()
 3375                        },
 3376                        cx,
 3377                    )
 3378                })
 3379                .await?;
 3380            Ok(workspace)
 3381        })
 3382    }
 3383
 3384    #[allow(clippy::type_complexity)]
 3385    pub fn open_paths(
 3386        &mut self,
 3387        mut abs_paths: Vec<PathBuf>,
 3388        options: OpenOptions,
 3389        pane: Option<WeakEntity<Pane>>,
 3390        window: &mut Window,
 3391        cx: &mut Context<Self>,
 3392    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3393        let fs = self.app_state.fs.clone();
 3394
 3395        let caller_ordered_abs_paths = abs_paths.clone();
 3396
 3397        // Sort the paths to ensure we add worktrees for parents before their children.
 3398        abs_paths.sort_unstable();
 3399        cx.spawn_in(window, async move |this, cx| {
 3400            let mut tasks = Vec::with_capacity(abs_paths.len());
 3401
 3402            for abs_path in &abs_paths {
 3403                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3404                    OpenVisible::All => Some(true),
 3405                    OpenVisible::None => Some(false),
 3406                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3407                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3408                        Some(None) => Some(true),
 3409                        None => None,
 3410                    },
 3411                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3412                        Some(Some(metadata)) => Some(metadata.is_dir),
 3413                        Some(None) => Some(false),
 3414                        None => None,
 3415                    },
 3416                };
 3417                let project_path = match visible {
 3418                    Some(visible) => match this
 3419                        .update(cx, |this, cx| {
 3420                            Workspace::project_path_for_path(
 3421                                this.project.clone(),
 3422                                abs_path,
 3423                                visible,
 3424                                cx,
 3425                            )
 3426                        })
 3427                        .log_err()
 3428                    {
 3429                        Some(project_path) => project_path.await.log_err(),
 3430                        None => None,
 3431                    },
 3432                    None => None,
 3433                };
 3434
 3435                let this = this.clone();
 3436                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3437                let fs = fs.clone();
 3438                let pane = pane.clone();
 3439                let task = cx.spawn(async move |cx| {
 3440                    let (_worktree, project_path) = project_path?;
 3441                    if fs.is_dir(&abs_path).await {
 3442                        // Opening a directory should not race to update the active entry.
 3443                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3444                        None
 3445                    } else {
 3446                        Some(
 3447                            this.update_in(cx, |this, window, cx| {
 3448                                this.open_path(
 3449                                    project_path,
 3450                                    pane,
 3451                                    options.focus.unwrap_or(true),
 3452                                    window,
 3453                                    cx,
 3454                                )
 3455                            })
 3456                            .ok()?
 3457                            .await,
 3458                        )
 3459                    }
 3460                });
 3461                tasks.push(task);
 3462            }
 3463
 3464            let results = futures::future::join_all(tasks).await;
 3465
 3466            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3467            let mut winner: Option<(PathBuf, bool)> = None;
 3468            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3469                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3470                    if !metadata.is_dir {
 3471                        winner = Some((abs_path, false));
 3472                        break;
 3473                    }
 3474                    if winner.is_none() {
 3475                        winner = Some((abs_path, true));
 3476                    }
 3477                } else if winner.is_none() {
 3478                    winner = Some((abs_path, false));
 3479                }
 3480            }
 3481
 3482            // Compute the winner entry id on the foreground thread and emit once, after all
 3483            // paths finish opening. This avoids races between concurrently-opening paths
 3484            // (directories in particular) and makes the resulting project panel selection
 3485            // deterministic.
 3486            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3487                'emit_winner: {
 3488                    let winner_abs_path: Arc<Path> =
 3489                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3490
 3491                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3492                        OpenVisible::All => true,
 3493                        OpenVisible::None => false,
 3494                        OpenVisible::OnlyFiles => !winner_is_dir,
 3495                        OpenVisible::OnlyDirectories => winner_is_dir,
 3496                    };
 3497
 3498                    let Some(worktree_task) = this
 3499                        .update(cx, |workspace, cx| {
 3500                            workspace.project.update(cx, |project, cx| {
 3501                                project.find_or_create_worktree(
 3502                                    winner_abs_path.as_ref(),
 3503                                    visible,
 3504                                    cx,
 3505                                )
 3506                            })
 3507                        })
 3508                        .ok()
 3509                    else {
 3510                        break 'emit_winner;
 3511                    };
 3512
 3513                    let Ok((worktree, _)) = worktree_task.await else {
 3514                        break 'emit_winner;
 3515                    };
 3516
 3517                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3518                        let worktree = worktree.read(cx);
 3519                        let worktree_abs_path = worktree.abs_path();
 3520                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3521                            worktree.root_entry()
 3522                        } else {
 3523                            winner_abs_path
 3524                                .strip_prefix(worktree_abs_path.as_ref())
 3525                                .ok()
 3526                                .and_then(|relative_path| {
 3527                                    let relative_path =
 3528                                        RelPath::new(relative_path, PathStyle::local())
 3529                                            .log_err()?;
 3530                                    worktree.entry_for_path(&relative_path)
 3531                                })
 3532                        }?;
 3533                        Some(entry.id)
 3534                    }) else {
 3535                        break 'emit_winner;
 3536                    };
 3537
 3538                    this.update(cx, |workspace, cx| {
 3539                        workspace.project.update(cx, |_, cx| {
 3540                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3541                        });
 3542                    })
 3543                    .ok();
 3544                }
 3545            }
 3546
 3547            results
 3548        })
 3549    }
 3550
 3551    pub fn open_resolved_path(
 3552        &mut self,
 3553        path: ResolvedPath,
 3554        window: &mut Window,
 3555        cx: &mut Context<Self>,
 3556    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3557        match path {
 3558            ResolvedPath::ProjectPath { project_path, .. } => {
 3559                self.open_path(project_path, None, true, window, cx)
 3560            }
 3561            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3562                PathBuf::from(path),
 3563                OpenOptions {
 3564                    visible: Some(OpenVisible::None),
 3565                    ..Default::default()
 3566                },
 3567                window,
 3568                cx,
 3569            ),
 3570        }
 3571    }
 3572
 3573    pub fn absolute_path_of_worktree(
 3574        &self,
 3575        worktree_id: WorktreeId,
 3576        cx: &mut Context<Self>,
 3577    ) -> Option<PathBuf> {
 3578        self.project
 3579            .read(cx)
 3580            .worktree_for_id(worktree_id, cx)
 3581            // TODO: use `abs_path` or `root_dir`
 3582            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3583    }
 3584
 3585    pub fn add_folder_to_project(
 3586        &mut self,
 3587        _: &AddFolderToProject,
 3588        window: &mut Window,
 3589        cx: &mut Context<Self>,
 3590    ) {
 3591        let project = self.project.read(cx);
 3592        if project.is_via_collab() {
 3593            self.show_error(
 3594                &anyhow!("You cannot add folders to someone else's project"),
 3595                cx,
 3596            );
 3597            return;
 3598        }
 3599        let paths = self.prompt_for_open_path(
 3600            PathPromptOptions {
 3601                files: false,
 3602                directories: true,
 3603                multiple: true,
 3604                prompt: None,
 3605            },
 3606            DirectoryLister::Project(self.project.clone()),
 3607            window,
 3608            cx,
 3609        );
 3610        cx.spawn_in(window, async move |this, cx| {
 3611            if let Some(paths) = paths.await.log_err().flatten() {
 3612                let results = this
 3613                    .update_in(cx, |this, window, cx| {
 3614                        this.open_paths(
 3615                            paths,
 3616                            OpenOptions {
 3617                                visible: Some(OpenVisible::All),
 3618                                ..Default::default()
 3619                            },
 3620                            None,
 3621                            window,
 3622                            cx,
 3623                        )
 3624                    })?
 3625                    .await;
 3626                for result in results.into_iter().flatten() {
 3627                    result.log_err();
 3628                }
 3629            }
 3630            anyhow::Ok(())
 3631        })
 3632        .detach_and_log_err(cx);
 3633    }
 3634
 3635    pub fn project_path_for_path(
 3636        project: Entity<Project>,
 3637        abs_path: &Path,
 3638        visible: bool,
 3639        cx: &mut App,
 3640    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3641        let entry = project.update(cx, |project, cx| {
 3642            project.find_or_create_worktree(abs_path, visible, cx)
 3643        });
 3644        cx.spawn(async move |cx| {
 3645            let (worktree, path) = entry.await?;
 3646            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3647            Ok((worktree, ProjectPath { worktree_id, path }))
 3648        })
 3649    }
 3650
 3651    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3652        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3653    }
 3654
 3655    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3656        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3657    }
 3658
 3659    pub fn items_of_type<'a, T: Item>(
 3660        &'a self,
 3661        cx: &'a App,
 3662    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3663        self.panes
 3664            .iter()
 3665            .flat_map(|pane| pane.read(cx).items_of_type())
 3666    }
 3667
 3668    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3669        self.active_pane().read(cx).active_item()
 3670    }
 3671
 3672    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3673        let item = self.active_item(cx)?;
 3674        item.to_any_view().downcast::<I>().ok()
 3675    }
 3676
 3677    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3678        self.active_item(cx).and_then(|item| item.project_path(cx))
 3679    }
 3680
 3681    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3682        self.recent_navigation_history_iter(cx)
 3683            .filter_map(|(path, abs_path)| {
 3684                let worktree = self
 3685                    .project
 3686                    .read(cx)
 3687                    .worktree_for_id(path.worktree_id, cx)?;
 3688                if worktree.read(cx).is_visible() {
 3689                    abs_path
 3690                } else {
 3691                    None
 3692                }
 3693            })
 3694            .next()
 3695    }
 3696
 3697    pub fn save_active_item(
 3698        &mut self,
 3699        save_intent: SaveIntent,
 3700        window: &mut Window,
 3701        cx: &mut App,
 3702    ) -> Task<Result<()>> {
 3703        let project = self.project.clone();
 3704        let pane = self.active_pane();
 3705        let item = pane.read(cx).active_item();
 3706        let pane = pane.downgrade();
 3707
 3708        window.spawn(cx, async move |cx| {
 3709            if let Some(item) = item {
 3710                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3711                    .await
 3712                    .map(|_| ())
 3713            } else {
 3714                Ok(())
 3715            }
 3716        })
 3717    }
 3718
 3719    pub fn close_inactive_items_and_panes(
 3720        &mut self,
 3721        action: &CloseInactiveTabsAndPanes,
 3722        window: &mut Window,
 3723        cx: &mut Context<Self>,
 3724    ) {
 3725        if let Some(task) = self.close_all_internal(
 3726            true,
 3727            action.save_intent.unwrap_or(SaveIntent::Close),
 3728            window,
 3729            cx,
 3730        ) {
 3731            task.detach_and_log_err(cx)
 3732        }
 3733    }
 3734
 3735    pub fn close_all_items_and_panes(
 3736        &mut self,
 3737        action: &CloseAllItemsAndPanes,
 3738        window: &mut Window,
 3739        cx: &mut Context<Self>,
 3740    ) {
 3741        if let Some(task) = self.close_all_internal(
 3742            false,
 3743            action.save_intent.unwrap_or(SaveIntent::Close),
 3744            window,
 3745            cx,
 3746        ) {
 3747            task.detach_and_log_err(cx)
 3748        }
 3749    }
 3750
 3751    /// Closes the active item across all panes.
 3752    pub fn close_item_in_all_panes(
 3753        &mut self,
 3754        action: &CloseItemInAllPanes,
 3755        window: &mut Window,
 3756        cx: &mut Context<Self>,
 3757    ) {
 3758        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3759            return;
 3760        };
 3761
 3762        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3763        let close_pinned = action.close_pinned;
 3764
 3765        if let Some(project_path) = active_item.project_path(cx) {
 3766            self.close_items_with_project_path(
 3767                &project_path,
 3768                save_intent,
 3769                close_pinned,
 3770                window,
 3771                cx,
 3772            );
 3773        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3774            let item_id = active_item.item_id();
 3775            self.active_pane().update(cx, |pane, cx| {
 3776                pane.close_item_by_id(item_id, save_intent, window, cx)
 3777                    .detach_and_log_err(cx);
 3778            });
 3779        }
 3780    }
 3781
 3782    /// Closes all items with the given project path across all panes.
 3783    pub fn close_items_with_project_path(
 3784        &mut self,
 3785        project_path: &ProjectPath,
 3786        save_intent: SaveIntent,
 3787        close_pinned: bool,
 3788        window: &mut Window,
 3789        cx: &mut Context<Self>,
 3790    ) {
 3791        let panes = self.panes().to_vec();
 3792        for pane in panes {
 3793            pane.update(cx, |pane, cx| {
 3794                pane.close_items_for_project_path(
 3795                    project_path,
 3796                    save_intent,
 3797                    close_pinned,
 3798                    window,
 3799                    cx,
 3800                )
 3801                .detach_and_log_err(cx);
 3802            });
 3803        }
 3804    }
 3805
 3806    fn close_all_internal(
 3807        &mut self,
 3808        retain_active_pane: bool,
 3809        save_intent: SaveIntent,
 3810        window: &mut Window,
 3811        cx: &mut Context<Self>,
 3812    ) -> Option<Task<Result<()>>> {
 3813        let current_pane = self.active_pane();
 3814
 3815        let mut tasks = Vec::new();
 3816
 3817        if retain_active_pane {
 3818            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3819                pane.close_other_items(
 3820                    &CloseOtherItems {
 3821                        save_intent: None,
 3822                        close_pinned: false,
 3823                    },
 3824                    None,
 3825                    window,
 3826                    cx,
 3827                )
 3828            });
 3829
 3830            tasks.push(current_pane_close);
 3831        }
 3832
 3833        for pane in self.panes() {
 3834            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3835                continue;
 3836            }
 3837
 3838            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3839                pane.close_all_items(
 3840                    &CloseAllItems {
 3841                        save_intent: Some(save_intent),
 3842                        close_pinned: false,
 3843                    },
 3844                    window,
 3845                    cx,
 3846                )
 3847            });
 3848
 3849            tasks.push(close_pane_items)
 3850        }
 3851
 3852        if tasks.is_empty() {
 3853            None
 3854        } else {
 3855            Some(cx.spawn_in(window, async move |_, _| {
 3856                for task in tasks {
 3857                    task.await?
 3858                }
 3859                Ok(())
 3860            }))
 3861        }
 3862    }
 3863
 3864    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3865        self.dock_at_position(position).read(cx).is_open()
 3866    }
 3867
 3868    pub fn toggle_dock(
 3869        &mut self,
 3870        dock_side: DockPosition,
 3871        window: &mut Window,
 3872        cx: &mut Context<Self>,
 3873    ) {
 3874        let mut focus_center = false;
 3875        let mut reveal_dock = false;
 3876
 3877        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3878        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3879
 3880        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3881            telemetry::event!(
 3882                "Panel Button Clicked",
 3883                name = panel.persistent_name(),
 3884                toggle_state = !was_visible
 3885            );
 3886        }
 3887        if was_visible {
 3888            self.save_open_dock_positions(cx);
 3889        }
 3890
 3891        let dock = self.dock_at_position(dock_side);
 3892        dock.update(cx, |dock, cx| {
 3893            dock.set_open(!was_visible, window, cx);
 3894
 3895            if dock.active_panel().is_none() {
 3896                let Some(panel_ix) = dock
 3897                    .first_enabled_panel_idx(cx)
 3898                    .log_with_level(log::Level::Info)
 3899                else {
 3900                    return;
 3901                };
 3902                dock.activate_panel(panel_ix, window, cx);
 3903            }
 3904
 3905            if let Some(active_panel) = dock.active_panel() {
 3906                if was_visible {
 3907                    if active_panel
 3908                        .panel_focus_handle(cx)
 3909                        .contains_focused(window, cx)
 3910                    {
 3911                        focus_center = true;
 3912                    }
 3913                } else {
 3914                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3915                    window.focus(focus_handle, cx);
 3916                    reveal_dock = true;
 3917                }
 3918            }
 3919        });
 3920
 3921        if reveal_dock {
 3922            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3923        }
 3924
 3925        if focus_center {
 3926            self.active_pane
 3927                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3928        }
 3929
 3930        cx.notify();
 3931        self.serialize_workspace(window, cx);
 3932    }
 3933
 3934    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3935        self.all_docks().into_iter().find(|&dock| {
 3936            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3937        })
 3938    }
 3939
 3940    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3941        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3942            self.save_open_dock_positions(cx);
 3943            dock.update(cx, |dock, cx| {
 3944                dock.set_open(false, window, cx);
 3945            });
 3946            return true;
 3947        }
 3948        false
 3949    }
 3950
 3951    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3952        self.save_open_dock_positions(cx);
 3953        for dock in self.all_docks() {
 3954            dock.update(cx, |dock, cx| {
 3955                dock.set_open(false, window, cx);
 3956            });
 3957        }
 3958
 3959        cx.focus_self(window);
 3960        cx.notify();
 3961        self.serialize_workspace(window, cx);
 3962    }
 3963
 3964    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3965        self.all_docks()
 3966            .into_iter()
 3967            .filter_map(|dock| {
 3968                let dock_ref = dock.read(cx);
 3969                if dock_ref.is_open() {
 3970                    Some(dock_ref.position())
 3971                } else {
 3972                    None
 3973                }
 3974            })
 3975            .collect()
 3976    }
 3977
 3978    /// Saves the positions of currently open docks.
 3979    ///
 3980    /// Updates `last_open_dock_positions` with positions of all currently open
 3981    /// docks, to later be restored by the 'Toggle All Docks' action.
 3982    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3983        let open_dock_positions = self.get_open_dock_positions(cx);
 3984        if !open_dock_positions.is_empty() {
 3985            self.last_open_dock_positions = open_dock_positions;
 3986        }
 3987    }
 3988
 3989    /// Toggles all docks between open and closed states.
 3990    ///
 3991    /// If any docks are open, closes all and remembers their positions. If all
 3992    /// docks are closed, restores the last remembered dock configuration.
 3993    fn toggle_all_docks(
 3994        &mut self,
 3995        _: &ToggleAllDocks,
 3996        window: &mut Window,
 3997        cx: &mut Context<Self>,
 3998    ) {
 3999        let open_dock_positions = self.get_open_dock_positions(cx);
 4000
 4001        if !open_dock_positions.is_empty() {
 4002            self.close_all_docks(window, cx);
 4003        } else if !self.last_open_dock_positions.is_empty() {
 4004            self.restore_last_open_docks(window, cx);
 4005        }
 4006    }
 4007
 4008    /// Reopens docks from the most recently remembered configuration.
 4009    ///
 4010    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4011    /// and clears the stored positions.
 4012    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4013        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4014
 4015        for position in positions_to_open {
 4016            let dock = self.dock_at_position(position);
 4017            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4018        }
 4019
 4020        cx.focus_self(window);
 4021        cx.notify();
 4022        self.serialize_workspace(window, cx);
 4023    }
 4024
 4025    /// Transfer focus to the panel of the given type.
 4026    pub fn focus_panel<T: Panel>(
 4027        &mut self,
 4028        window: &mut Window,
 4029        cx: &mut Context<Self>,
 4030    ) -> Option<Entity<T>> {
 4031        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4032        panel.to_any().downcast().ok()
 4033    }
 4034
 4035    /// Focus the panel of the given type if it isn't already focused. If it is
 4036    /// already focused, then transfer focus back to the workspace center.
 4037    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4038    /// panel when transferring focus back to the center.
 4039    pub fn toggle_panel_focus<T: Panel>(
 4040        &mut self,
 4041        window: &mut Window,
 4042        cx: &mut Context<Self>,
 4043    ) -> bool {
 4044        let mut did_focus_panel = false;
 4045        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4046            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4047            did_focus_panel
 4048        });
 4049
 4050        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4051            self.close_panel::<T>(window, cx);
 4052        }
 4053
 4054        telemetry::event!(
 4055            "Panel Button Clicked",
 4056            name = T::persistent_name(),
 4057            toggle_state = did_focus_panel
 4058        );
 4059
 4060        did_focus_panel
 4061    }
 4062
 4063    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4064        if let Some(item) = self.active_item(cx) {
 4065            item.item_focus_handle(cx).focus(window, cx);
 4066        } else {
 4067            log::error!("Could not find a focus target when switching focus to the center panes",);
 4068        }
 4069    }
 4070
 4071    pub fn activate_panel_for_proto_id(
 4072        &mut self,
 4073        panel_id: PanelId,
 4074        window: &mut Window,
 4075        cx: &mut Context<Self>,
 4076    ) -> Option<Arc<dyn PanelHandle>> {
 4077        let mut panel = None;
 4078        for dock in self.all_docks() {
 4079            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4080                panel = dock.update(cx, |dock, cx| {
 4081                    dock.activate_panel(panel_index, window, cx);
 4082                    dock.set_open(true, window, cx);
 4083                    dock.active_panel().cloned()
 4084                });
 4085                break;
 4086            }
 4087        }
 4088
 4089        if panel.is_some() {
 4090            cx.notify();
 4091            self.serialize_workspace(window, cx);
 4092        }
 4093
 4094        panel
 4095    }
 4096
 4097    /// Focus or unfocus the given panel type, depending on the given callback.
 4098    fn focus_or_unfocus_panel<T: Panel>(
 4099        &mut self,
 4100        window: &mut Window,
 4101        cx: &mut Context<Self>,
 4102        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4103    ) -> Option<Arc<dyn PanelHandle>> {
 4104        let mut result_panel = None;
 4105        let mut serialize = false;
 4106        for dock in self.all_docks() {
 4107            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4108                let mut focus_center = false;
 4109                let panel = dock.update(cx, |dock, cx| {
 4110                    dock.activate_panel(panel_index, window, cx);
 4111
 4112                    let panel = dock.active_panel().cloned();
 4113                    if let Some(panel) = panel.as_ref() {
 4114                        if should_focus(&**panel, window, cx) {
 4115                            dock.set_open(true, window, cx);
 4116                            panel.panel_focus_handle(cx).focus(window, cx);
 4117                        } else {
 4118                            focus_center = true;
 4119                        }
 4120                    }
 4121                    panel
 4122                });
 4123
 4124                if focus_center {
 4125                    self.active_pane
 4126                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4127                }
 4128
 4129                result_panel = panel;
 4130                serialize = true;
 4131                break;
 4132            }
 4133        }
 4134
 4135        if serialize {
 4136            self.serialize_workspace(window, cx);
 4137        }
 4138
 4139        cx.notify();
 4140        result_panel
 4141    }
 4142
 4143    /// Open the panel of the given type
 4144    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4145        for dock in self.all_docks() {
 4146            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4147                dock.update(cx, |dock, cx| {
 4148                    dock.activate_panel(panel_index, window, cx);
 4149                    dock.set_open(true, window, cx);
 4150                });
 4151            }
 4152        }
 4153    }
 4154
 4155    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4156        for dock in self.all_docks().iter() {
 4157            dock.update(cx, |dock, cx| {
 4158                if dock.panel::<T>().is_some() {
 4159                    dock.set_open(false, window, cx)
 4160                }
 4161            })
 4162        }
 4163    }
 4164
 4165    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4166        self.all_docks()
 4167            .iter()
 4168            .find_map(|dock| dock.read(cx).panel::<T>())
 4169    }
 4170
 4171    fn dismiss_zoomed_items_to_reveal(
 4172        &mut self,
 4173        dock_to_reveal: Option<DockPosition>,
 4174        window: &mut Window,
 4175        cx: &mut Context<Self>,
 4176    ) {
 4177        // If a center pane is zoomed, unzoom it.
 4178        for pane in &self.panes {
 4179            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4180                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4181            }
 4182        }
 4183
 4184        // If another dock is zoomed, hide it.
 4185        let mut focus_center = false;
 4186        for dock in self.all_docks() {
 4187            dock.update(cx, |dock, cx| {
 4188                if Some(dock.position()) != dock_to_reveal
 4189                    && let Some(panel) = dock.active_panel()
 4190                    && panel.is_zoomed(window, cx)
 4191                {
 4192                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4193                    dock.set_open(false, window, cx);
 4194                }
 4195            });
 4196        }
 4197
 4198        if focus_center {
 4199            self.active_pane
 4200                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4201        }
 4202
 4203        if self.zoomed_position != dock_to_reveal {
 4204            self.zoomed = None;
 4205            self.zoomed_position = None;
 4206            cx.emit(Event::ZoomChanged);
 4207        }
 4208
 4209        cx.notify();
 4210    }
 4211
 4212    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4213        let pane = cx.new(|cx| {
 4214            let mut pane = Pane::new(
 4215                self.weak_handle(),
 4216                self.project.clone(),
 4217                self.pane_history_timestamp.clone(),
 4218                None,
 4219                NewFile.boxed_clone(),
 4220                true,
 4221                window,
 4222                cx,
 4223            );
 4224            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4225            pane
 4226        });
 4227        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4228            .detach();
 4229        self.panes.push(pane.clone());
 4230
 4231        window.focus(&pane.focus_handle(cx), cx);
 4232
 4233        cx.emit(Event::PaneAdded(pane.clone()));
 4234        pane
 4235    }
 4236
 4237    pub fn add_item_to_center(
 4238        &mut self,
 4239        item: Box<dyn ItemHandle>,
 4240        window: &mut Window,
 4241        cx: &mut Context<Self>,
 4242    ) -> bool {
 4243        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4244            if let Some(center_pane) = center_pane.upgrade() {
 4245                center_pane.update(cx, |pane, cx| {
 4246                    pane.add_item(item, true, true, None, window, cx)
 4247                });
 4248                true
 4249            } else {
 4250                false
 4251            }
 4252        } else {
 4253            false
 4254        }
 4255    }
 4256
 4257    pub fn add_item_to_active_pane(
 4258        &mut self,
 4259        item: Box<dyn ItemHandle>,
 4260        destination_index: Option<usize>,
 4261        focus_item: bool,
 4262        window: &mut Window,
 4263        cx: &mut App,
 4264    ) {
 4265        self.add_item(
 4266            self.active_pane.clone(),
 4267            item,
 4268            destination_index,
 4269            false,
 4270            focus_item,
 4271            window,
 4272            cx,
 4273        )
 4274    }
 4275
 4276    pub fn add_item(
 4277        &mut self,
 4278        pane: Entity<Pane>,
 4279        item: Box<dyn ItemHandle>,
 4280        destination_index: Option<usize>,
 4281        activate_pane: bool,
 4282        focus_item: bool,
 4283        window: &mut Window,
 4284        cx: &mut App,
 4285    ) {
 4286        pane.update(cx, |pane, cx| {
 4287            pane.add_item(
 4288                item,
 4289                activate_pane,
 4290                focus_item,
 4291                destination_index,
 4292                window,
 4293                cx,
 4294            )
 4295        });
 4296    }
 4297
 4298    pub fn split_item(
 4299        &mut self,
 4300        split_direction: SplitDirection,
 4301        item: Box<dyn ItemHandle>,
 4302        window: &mut Window,
 4303        cx: &mut Context<Self>,
 4304    ) {
 4305        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4306        self.add_item(new_pane, item, None, true, true, window, cx);
 4307    }
 4308
 4309    pub fn open_abs_path(
 4310        &mut self,
 4311        abs_path: PathBuf,
 4312        options: OpenOptions,
 4313        window: &mut Window,
 4314        cx: &mut Context<Self>,
 4315    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4316        cx.spawn_in(window, async move |workspace, cx| {
 4317            let open_paths_task_result = workspace
 4318                .update_in(cx, |workspace, window, cx| {
 4319                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4320                })
 4321                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4322                .await;
 4323            anyhow::ensure!(
 4324                open_paths_task_result.len() == 1,
 4325                "open abs path {abs_path:?} task returned incorrect number of results"
 4326            );
 4327            match open_paths_task_result
 4328                .into_iter()
 4329                .next()
 4330                .expect("ensured single task result")
 4331            {
 4332                Some(open_result) => {
 4333                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4334                }
 4335                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4336            }
 4337        })
 4338    }
 4339
 4340    pub fn split_abs_path(
 4341        &mut self,
 4342        abs_path: PathBuf,
 4343        visible: bool,
 4344        window: &mut Window,
 4345        cx: &mut Context<Self>,
 4346    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4347        let project_path_task =
 4348            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4349        cx.spawn_in(window, async move |this, cx| {
 4350            let (_, path) = project_path_task.await?;
 4351            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4352                .await
 4353        })
 4354    }
 4355
 4356    pub fn open_path(
 4357        &mut self,
 4358        path: impl Into<ProjectPath>,
 4359        pane: Option<WeakEntity<Pane>>,
 4360        focus_item: bool,
 4361        window: &mut Window,
 4362        cx: &mut App,
 4363    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4364        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4365    }
 4366
 4367    pub fn open_path_preview(
 4368        &mut self,
 4369        path: impl Into<ProjectPath>,
 4370        pane: Option<WeakEntity<Pane>>,
 4371        focus_item: bool,
 4372        allow_preview: bool,
 4373        activate: bool,
 4374        window: &mut Window,
 4375        cx: &mut App,
 4376    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4377        let pane = pane.unwrap_or_else(|| {
 4378            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4379                self.panes
 4380                    .first()
 4381                    .expect("There must be an active pane")
 4382                    .downgrade()
 4383            })
 4384        });
 4385
 4386        let project_path = path.into();
 4387        let task = self.load_path(project_path.clone(), window, cx);
 4388        window.spawn(cx, async move |cx| {
 4389            let (project_entry_id, build_item) = task.await?;
 4390
 4391            pane.update_in(cx, |pane, window, cx| {
 4392                pane.open_item(
 4393                    project_entry_id,
 4394                    project_path,
 4395                    focus_item,
 4396                    allow_preview,
 4397                    activate,
 4398                    None,
 4399                    window,
 4400                    cx,
 4401                    build_item,
 4402                )
 4403            })
 4404        })
 4405    }
 4406
 4407    pub fn split_path(
 4408        &mut self,
 4409        path: impl Into<ProjectPath>,
 4410        window: &mut Window,
 4411        cx: &mut Context<Self>,
 4412    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4413        self.split_path_preview(path, false, None, window, cx)
 4414    }
 4415
 4416    pub fn split_path_preview(
 4417        &mut self,
 4418        path: impl Into<ProjectPath>,
 4419        allow_preview: bool,
 4420        split_direction: Option<SplitDirection>,
 4421        window: &mut Window,
 4422        cx: &mut Context<Self>,
 4423    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4424        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4425            self.panes
 4426                .first()
 4427                .expect("There must be an active pane")
 4428                .downgrade()
 4429        });
 4430
 4431        if let Member::Pane(center_pane) = &self.center.root
 4432            && center_pane.read(cx).items_len() == 0
 4433        {
 4434            return self.open_path(path, Some(pane), true, window, cx);
 4435        }
 4436
 4437        let project_path = path.into();
 4438        let task = self.load_path(project_path.clone(), window, cx);
 4439        cx.spawn_in(window, async move |this, cx| {
 4440            let (project_entry_id, build_item) = task.await?;
 4441            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4442                let pane = pane.upgrade()?;
 4443                let new_pane = this.split_pane(
 4444                    pane,
 4445                    split_direction.unwrap_or(SplitDirection::Right),
 4446                    window,
 4447                    cx,
 4448                );
 4449                new_pane.update(cx, |new_pane, cx| {
 4450                    Some(new_pane.open_item(
 4451                        project_entry_id,
 4452                        project_path,
 4453                        true,
 4454                        allow_preview,
 4455                        true,
 4456                        None,
 4457                        window,
 4458                        cx,
 4459                        build_item,
 4460                    ))
 4461                })
 4462            })
 4463            .map(|option| option.context("pane was dropped"))?
 4464        })
 4465    }
 4466
 4467    fn load_path(
 4468        &mut self,
 4469        path: ProjectPath,
 4470        window: &mut Window,
 4471        cx: &mut App,
 4472    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4473        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4474        registry.open_path(self.project(), &path, window, cx)
 4475    }
 4476
 4477    pub fn find_project_item<T>(
 4478        &self,
 4479        pane: &Entity<Pane>,
 4480        project_item: &Entity<T::Item>,
 4481        cx: &App,
 4482    ) -> Option<Entity<T>>
 4483    where
 4484        T: ProjectItem,
 4485    {
 4486        use project::ProjectItem as _;
 4487        let project_item = project_item.read(cx);
 4488        let entry_id = project_item.entry_id(cx);
 4489        let project_path = project_item.project_path(cx);
 4490
 4491        let mut item = None;
 4492        if let Some(entry_id) = entry_id {
 4493            item = pane.read(cx).item_for_entry(entry_id, cx);
 4494        }
 4495        if item.is_none()
 4496            && let Some(project_path) = project_path
 4497        {
 4498            item = pane.read(cx).item_for_path(project_path, cx);
 4499        }
 4500
 4501        item.and_then(|item| item.downcast::<T>())
 4502    }
 4503
 4504    pub fn is_project_item_open<T>(
 4505        &self,
 4506        pane: &Entity<Pane>,
 4507        project_item: &Entity<T::Item>,
 4508        cx: &App,
 4509    ) -> bool
 4510    where
 4511        T: ProjectItem,
 4512    {
 4513        self.find_project_item::<T>(pane, project_item, cx)
 4514            .is_some()
 4515    }
 4516
 4517    pub fn open_project_item<T>(
 4518        &mut self,
 4519        pane: Entity<Pane>,
 4520        project_item: Entity<T::Item>,
 4521        activate_pane: bool,
 4522        focus_item: bool,
 4523        keep_old_preview: bool,
 4524        allow_new_preview: bool,
 4525        window: &mut Window,
 4526        cx: &mut Context<Self>,
 4527    ) -> Entity<T>
 4528    where
 4529        T: ProjectItem,
 4530    {
 4531        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4532
 4533        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4534            if !keep_old_preview
 4535                && let Some(old_id) = old_item_id
 4536                && old_id != item.item_id()
 4537            {
 4538                // switching to a different item, so unpreview old active item
 4539                pane.update(cx, |pane, _| {
 4540                    pane.unpreview_item_if_preview(old_id);
 4541                });
 4542            }
 4543
 4544            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4545            if !allow_new_preview {
 4546                pane.update(cx, |pane, _| {
 4547                    pane.unpreview_item_if_preview(item.item_id());
 4548                });
 4549            }
 4550            return item;
 4551        }
 4552
 4553        let item = pane.update(cx, |pane, cx| {
 4554            cx.new(|cx| {
 4555                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4556            })
 4557        });
 4558        let mut destination_index = None;
 4559        pane.update(cx, |pane, cx| {
 4560            if !keep_old_preview && let Some(old_id) = old_item_id {
 4561                pane.unpreview_item_if_preview(old_id);
 4562            }
 4563            if allow_new_preview {
 4564                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4565            }
 4566        });
 4567
 4568        self.add_item(
 4569            pane,
 4570            Box::new(item.clone()),
 4571            destination_index,
 4572            activate_pane,
 4573            focus_item,
 4574            window,
 4575            cx,
 4576        );
 4577        item
 4578    }
 4579
 4580    pub fn open_shared_screen(
 4581        &mut self,
 4582        peer_id: PeerId,
 4583        window: &mut Window,
 4584        cx: &mut Context<Self>,
 4585    ) {
 4586        if let Some(shared_screen) =
 4587            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4588        {
 4589            self.active_pane.update(cx, |pane, cx| {
 4590                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4591            });
 4592        }
 4593    }
 4594
 4595    pub fn activate_item(
 4596        &mut self,
 4597        item: &dyn ItemHandle,
 4598        activate_pane: bool,
 4599        focus_item: bool,
 4600        window: &mut Window,
 4601        cx: &mut App,
 4602    ) -> bool {
 4603        let result = self.panes.iter().find_map(|pane| {
 4604            pane.read(cx)
 4605                .index_for_item(item)
 4606                .map(|ix| (pane.clone(), ix))
 4607        });
 4608        if let Some((pane, ix)) = result {
 4609            pane.update(cx, |pane, cx| {
 4610                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4611            });
 4612            true
 4613        } else {
 4614            false
 4615        }
 4616    }
 4617
 4618    fn activate_pane_at_index(
 4619        &mut self,
 4620        action: &ActivatePane,
 4621        window: &mut Window,
 4622        cx: &mut Context<Self>,
 4623    ) {
 4624        let panes = self.center.panes();
 4625        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4626            window.focus(&pane.focus_handle(cx), cx);
 4627        } else {
 4628            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4629                .detach();
 4630        }
 4631    }
 4632
 4633    fn move_item_to_pane_at_index(
 4634        &mut self,
 4635        action: &MoveItemToPane,
 4636        window: &mut Window,
 4637        cx: &mut Context<Self>,
 4638    ) {
 4639        let panes = self.center.panes();
 4640        let destination = match panes.get(action.destination) {
 4641            Some(&destination) => destination.clone(),
 4642            None => {
 4643                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4644                    return;
 4645                }
 4646                let direction = SplitDirection::Right;
 4647                let split_off_pane = self
 4648                    .find_pane_in_direction(direction, cx)
 4649                    .unwrap_or_else(|| self.active_pane.clone());
 4650                let new_pane = self.add_pane(window, cx);
 4651                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4652                new_pane
 4653            }
 4654        };
 4655
 4656        if action.clone {
 4657            if self
 4658                .active_pane
 4659                .read(cx)
 4660                .active_item()
 4661                .is_some_and(|item| item.can_split(cx))
 4662            {
 4663                clone_active_item(
 4664                    self.database_id(),
 4665                    &self.active_pane,
 4666                    &destination,
 4667                    action.focus,
 4668                    window,
 4669                    cx,
 4670                );
 4671                return;
 4672            }
 4673        }
 4674        move_active_item(
 4675            &self.active_pane,
 4676            &destination,
 4677            action.focus,
 4678            true,
 4679            window,
 4680            cx,
 4681        )
 4682    }
 4683
 4684    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4685        let panes = self.center.panes();
 4686        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4687            let next_ix = (ix + 1) % panes.len();
 4688            let next_pane = panes[next_ix].clone();
 4689            window.focus(&next_pane.focus_handle(cx), cx);
 4690        }
 4691    }
 4692
 4693    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4694        let panes = self.center.panes();
 4695        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4696            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4697            let prev_pane = panes[prev_ix].clone();
 4698            window.focus(&prev_pane.focus_handle(cx), cx);
 4699        }
 4700    }
 4701
 4702    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4703        let last_pane = self.center.last_pane();
 4704        window.focus(&last_pane.focus_handle(cx), cx);
 4705    }
 4706
 4707    pub fn activate_pane_in_direction(
 4708        &mut self,
 4709        direction: SplitDirection,
 4710        window: &mut Window,
 4711        cx: &mut App,
 4712    ) {
 4713        use ActivateInDirectionTarget as Target;
 4714        enum Origin {
 4715            Sidebar,
 4716            LeftDock,
 4717            RightDock,
 4718            BottomDock,
 4719            Center,
 4720        }
 4721
 4722        let origin: Origin = if self
 4723            .sidebar_focus_handle
 4724            .as_ref()
 4725            .is_some_and(|h| h.contains_focused(window, cx))
 4726        {
 4727            Origin::Sidebar
 4728        } else {
 4729            [
 4730                (&self.left_dock, Origin::LeftDock),
 4731                (&self.right_dock, Origin::RightDock),
 4732                (&self.bottom_dock, Origin::BottomDock),
 4733            ]
 4734            .into_iter()
 4735            .find_map(|(dock, origin)| {
 4736                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4737                    Some(origin)
 4738                } else {
 4739                    None
 4740                }
 4741            })
 4742            .unwrap_or(Origin::Center)
 4743        };
 4744
 4745        let get_last_active_pane = || {
 4746            let pane = self
 4747                .last_active_center_pane
 4748                .clone()
 4749                .unwrap_or_else(|| {
 4750                    self.panes
 4751                        .first()
 4752                        .expect("There must be an active pane")
 4753                        .downgrade()
 4754                })
 4755                .upgrade()?;
 4756            (pane.read(cx).items_len() != 0).then_some(pane)
 4757        };
 4758
 4759        let try_dock =
 4760            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4761
 4762        let sidebar_target = self
 4763            .sidebar_focus_handle
 4764            .as_ref()
 4765            .map(|h| Target::Sidebar(h.clone()));
 4766
 4767        let target = match (origin, direction) {
 4768            // From the sidebar, only Right navigates into the workspace.
 4769            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4770                .or_else(|| get_last_active_pane().map(Target::Pane))
 4771                .or_else(|| try_dock(&self.bottom_dock))
 4772                .or_else(|| try_dock(&self.right_dock)),
 4773
 4774            (Origin::Sidebar, _) => None,
 4775
 4776            // We're in the center, so we first try to go to a different pane,
 4777            // otherwise try to go to a dock.
 4778            (Origin::Center, direction) => {
 4779                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4780                    Some(Target::Pane(pane))
 4781                } else {
 4782                    match direction {
 4783                        SplitDirection::Up => None,
 4784                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4785                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4786                        SplitDirection::Right => try_dock(&self.right_dock),
 4787                    }
 4788                }
 4789            }
 4790
 4791            (Origin::LeftDock, SplitDirection::Right) => {
 4792                if let Some(last_active_pane) = get_last_active_pane() {
 4793                    Some(Target::Pane(last_active_pane))
 4794                } else {
 4795                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4796                }
 4797            }
 4798
 4799            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4800
 4801            (Origin::LeftDock, SplitDirection::Down)
 4802            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4803
 4804            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4805            (Origin::BottomDock, SplitDirection::Left) => {
 4806                try_dock(&self.left_dock).or(sidebar_target)
 4807            }
 4808            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4809
 4810            (Origin::RightDock, SplitDirection::Left) => {
 4811                if let Some(last_active_pane) = get_last_active_pane() {
 4812                    Some(Target::Pane(last_active_pane))
 4813                } else {
 4814                    try_dock(&self.bottom_dock)
 4815                        .or_else(|| try_dock(&self.left_dock))
 4816                        .or(sidebar_target)
 4817                }
 4818            }
 4819
 4820            _ => None,
 4821        };
 4822
 4823        match target {
 4824            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4825                let pane = pane.read(cx);
 4826                if let Some(item) = pane.active_item() {
 4827                    item.item_focus_handle(cx).focus(window, cx);
 4828                } else {
 4829                    log::error!(
 4830                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4831                    );
 4832                }
 4833            }
 4834            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4835                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4836                window.defer(cx, move |window, cx| {
 4837                    let dock = dock.read(cx);
 4838                    if let Some(panel) = dock.active_panel() {
 4839                        panel.panel_focus_handle(cx).focus(window, cx);
 4840                    } else {
 4841                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4842                    }
 4843                })
 4844            }
 4845            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4846                focus_handle.focus(window, cx);
 4847            }
 4848            None => {}
 4849        }
 4850    }
 4851
 4852    pub fn move_item_to_pane_in_direction(
 4853        &mut self,
 4854        action: &MoveItemToPaneInDirection,
 4855        window: &mut Window,
 4856        cx: &mut Context<Self>,
 4857    ) {
 4858        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4859            Some(destination) => destination,
 4860            None => {
 4861                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4862                    return;
 4863                }
 4864                let new_pane = self.add_pane(window, cx);
 4865                self.center
 4866                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4867                new_pane
 4868            }
 4869        };
 4870
 4871        if action.clone {
 4872            if self
 4873                .active_pane
 4874                .read(cx)
 4875                .active_item()
 4876                .is_some_and(|item| item.can_split(cx))
 4877            {
 4878                clone_active_item(
 4879                    self.database_id(),
 4880                    &self.active_pane,
 4881                    &destination,
 4882                    action.focus,
 4883                    window,
 4884                    cx,
 4885                );
 4886                return;
 4887            }
 4888        }
 4889        move_active_item(
 4890            &self.active_pane,
 4891            &destination,
 4892            action.focus,
 4893            true,
 4894            window,
 4895            cx,
 4896        );
 4897    }
 4898
 4899    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4900        self.center.bounding_box_for_pane(pane)
 4901    }
 4902
 4903    pub fn find_pane_in_direction(
 4904        &mut self,
 4905        direction: SplitDirection,
 4906        cx: &App,
 4907    ) -> Option<Entity<Pane>> {
 4908        self.center
 4909            .find_pane_in_direction(&self.active_pane, direction, cx)
 4910            .cloned()
 4911    }
 4912
 4913    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4914        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4915            self.center.swap(&self.active_pane, &to, cx);
 4916            cx.notify();
 4917        }
 4918    }
 4919
 4920    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4921        if self
 4922            .center
 4923            .move_to_border(&self.active_pane, direction, cx)
 4924            .unwrap()
 4925        {
 4926            cx.notify();
 4927        }
 4928    }
 4929
 4930    pub fn resize_pane(
 4931        &mut self,
 4932        axis: gpui::Axis,
 4933        amount: Pixels,
 4934        window: &mut Window,
 4935        cx: &mut Context<Self>,
 4936    ) {
 4937        let docks = self.all_docks();
 4938        let active_dock = docks
 4939            .into_iter()
 4940            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4941
 4942        if let Some(dock_entity) = active_dock {
 4943            let dock = dock_entity.read(cx);
 4944            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 4945                return;
 4946            };
 4947            match dock.position() {
 4948                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4949                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4950                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4951            }
 4952        } else {
 4953            self.center
 4954                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4955        }
 4956        cx.notify();
 4957    }
 4958
 4959    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4960        self.center.reset_pane_sizes(cx);
 4961        cx.notify();
 4962    }
 4963
 4964    fn handle_pane_focused(
 4965        &mut self,
 4966        pane: Entity<Pane>,
 4967        window: &mut Window,
 4968        cx: &mut Context<Self>,
 4969    ) {
 4970        // This is explicitly hoisted out of the following check for pane identity as
 4971        // terminal panel panes are not registered as a center panes.
 4972        self.status_bar.update(cx, |status_bar, cx| {
 4973            status_bar.set_active_pane(&pane, window, cx);
 4974        });
 4975        if self.active_pane != pane {
 4976            self.set_active_pane(&pane, window, cx);
 4977        }
 4978
 4979        if self.last_active_center_pane.is_none() {
 4980            self.last_active_center_pane = Some(pane.downgrade());
 4981        }
 4982
 4983        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4984        // This prevents the dock from closing when focus events fire during window activation.
 4985        // We also preserve any dock whose active panel itself has focus — this covers
 4986        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4987        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4988            let dock_read = dock.read(cx);
 4989            if let Some(panel) = dock_read.active_panel() {
 4990                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4991                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4992                {
 4993                    return Some(dock_read.position());
 4994                }
 4995            }
 4996            None
 4997        });
 4998
 4999        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5000        if pane.read(cx).is_zoomed() {
 5001            self.zoomed = Some(pane.downgrade().into());
 5002        } else {
 5003            self.zoomed = None;
 5004        }
 5005        self.zoomed_position = None;
 5006        cx.emit(Event::ZoomChanged);
 5007        self.update_active_view_for_followers(window, cx);
 5008        pane.update(cx, |pane, _| {
 5009            pane.track_alternate_file_items();
 5010        });
 5011
 5012        cx.notify();
 5013    }
 5014
 5015    fn set_active_pane(
 5016        &mut self,
 5017        pane: &Entity<Pane>,
 5018        window: &mut Window,
 5019        cx: &mut Context<Self>,
 5020    ) {
 5021        self.active_pane = pane.clone();
 5022        self.active_item_path_changed(true, window, cx);
 5023        self.last_active_center_pane = Some(pane.downgrade());
 5024    }
 5025
 5026    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5027        self.update_active_view_for_followers(window, cx);
 5028    }
 5029
 5030    fn handle_pane_event(
 5031        &mut self,
 5032        pane: &Entity<Pane>,
 5033        event: &pane::Event,
 5034        window: &mut Window,
 5035        cx: &mut Context<Self>,
 5036    ) {
 5037        let mut serialize_workspace = true;
 5038        match event {
 5039            pane::Event::AddItem { item } => {
 5040                item.added_to_pane(self, pane.clone(), window, cx);
 5041                cx.emit(Event::ItemAdded {
 5042                    item: item.boxed_clone(),
 5043                });
 5044            }
 5045            pane::Event::Split { direction, mode } => {
 5046                match mode {
 5047                    SplitMode::ClonePane => {
 5048                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5049                            .detach();
 5050                    }
 5051                    SplitMode::EmptyPane => {
 5052                        self.split_pane(pane.clone(), *direction, window, cx);
 5053                    }
 5054                    SplitMode::MovePane => {
 5055                        self.split_and_move(pane.clone(), *direction, window, cx);
 5056                    }
 5057                };
 5058            }
 5059            pane::Event::JoinIntoNext => {
 5060                self.join_pane_into_next(pane.clone(), window, cx);
 5061            }
 5062            pane::Event::JoinAll => {
 5063                self.join_all_panes(window, cx);
 5064            }
 5065            pane::Event::Remove { focus_on_pane } => {
 5066                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5067            }
 5068            pane::Event::ActivateItem {
 5069                local,
 5070                focus_changed,
 5071            } => {
 5072                window.invalidate_character_coordinates();
 5073
 5074                pane.update(cx, |pane, _| {
 5075                    pane.track_alternate_file_items();
 5076                });
 5077                if *local {
 5078                    self.unfollow_in_pane(pane, window, cx);
 5079                }
 5080                serialize_workspace = *focus_changed || pane != self.active_pane();
 5081                if pane == self.active_pane() {
 5082                    self.active_item_path_changed(*focus_changed, window, cx);
 5083                    self.update_active_view_for_followers(window, cx);
 5084                } else if *local {
 5085                    self.set_active_pane(pane, window, cx);
 5086                }
 5087            }
 5088            pane::Event::UserSavedItem { item, save_intent } => {
 5089                cx.emit(Event::UserSavedItem {
 5090                    pane: pane.downgrade(),
 5091                    item: item.boxed_clone(),
 5092                    save_intent: *save_intent,
 5093                });
 5094                serialize_workspace = false;
 5095            }
 5096            pane::Event::ChangeItemTitle => {
 5097                if *pane == self.active_pane {
 5098                    self.active_item_path_changed(false, window, cx);
 5099                }
 5100                serialize_workspace = false;
 5101            }
 5102            pane::Event::RemovedItem { item } => {
 5103                cx.emit(Event::ActiveItemChanged);
 5104                self.update_window_edited(window, cx);
 5105                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5106                    && entry.get().entity_id() == pane.entity_id()
 5107                {
 5108                    entry.remove();
 5109                }
 5110                cx.emit(Event::ItemRemoved {
 5111                    item_id: item.item_id(),
 5112                });
 5113            }
 5114            pane::Event::Focus => {
 5115                window.invalidate_character_coordinates();
 5116                self.handle_pane_focused(pane.clone(), window, cx);
 5117            }
 5118            pane::Event::ZoomIn => {
 5119                if *pane == self.active_pane {
 5120                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5121                    if pane.read(cx).has_focus(window, cx) {
 5122                        self.zoomed = Some(pane.downgrade().into());
 5123                        self.zoomed_position = None;
 5124                        cx.emit(Event::ZoomChanged);
 5125                    }
 5126                    cx.notify();
 5127                }
 5128            }
 5129            pane::Event::ZoomOut => {
 5130                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5131                if self.zoomed_position.is_none() {
 5132                    self.zoomed = None;
 5133                    cx.emit(Event::ZoomChanged);
 5134                }
 5135                cx.notify();
 5136            }
 5137            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5138        }
 5139
 5140        if serialize_workspace {
 5141            self.serialize_workspace(window, cx);
 5142        }
 5143    }
 5144
 5145    pub fn unfollow_in_pane(
 5146        &mut self,
 5147        pane: &Entity<Pane>,
 5148        window: &mut Window,
 5149        cx: &mut Context<Workspace>,
 5150    ) -> Option<CollaboratorId> {
 5151        let leader_id = self.leader_for_pane(pane)?;
 5152        self.unfollow(leader_id, window, cx);
 5153        Some(leader_id)
 5154    }
 5155
 5156    pub fn split_pane(
 5157        &mut self,
 5158        pane_to_split: Entity<Pane>,
 5159        split_direction: SplitDirection,
 5160        window: &mut Window,
 5161        cx: &mut Context<Self>,
 5162    ) -> Entity<Pane> {
 5163        let new_pane = self.add_pane(window, cx);
 5164        self.center
 5165            .split(&pane_to_split, &new_pane, split_direction, cx);
 5166        cx.notify();
 5167        new_pane
 5168    }
 5169
 5170    pub fn split_and_move(
 5171        &mut self,
 5172        pane: Entity<Pane>,
 5173        direction: SplitDirection,
 5174        window: &mut Window,
 5175        cx: &mut Context<Self>,
 5176    ) {
 5177        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5178            return;
 5179        };
 5180        let new_pane = self.add_pane(window, cx);
 5181        new_pane.update(cx, |pane, cx| {
 5182            pane.add_item(item, true, true, None, window, cx)
 5183        });
 5184        self.center.split(&pane, &new_pane, direction, cx);
 5185        cx.notify();
 5186    }
 5187
 5188    pub fn split_and_clone(
 5189        &mut self,
 5190        pane: Entity<Pane>,
 5191        direction: SplitDirection,
 5192        window: &mut Window,
 5193        cx: &mut Context<Self>,
 5194    ) -> Task<Option<Entity<Pane>>> {
 5195        let Some(item) = pane.read(cx).active_item() else {
 5196            return Task::ready(None);
 5197        };
 5198        if !item.can_split(cx) {
 5199            return Task::ready(None);
 5200        }
 5201        let task = item.clone_on_split(self.database_id(), window, cx);
 5202        cx.spawn_in(window, async move |this, cx| {
 5203            if let Some(clone) = task.await {
 5204                this.update_in(cx, |this, window, cx| {
 5205                    let new_pane = this.add_pane(window, cx);
 5206                    let nav_history = pane.read(cx).fork_nav_history();
 5207                    new_pane.update(cx, |pane, cx| {
 5208                        pane.set_nav_history(nav_history, cx);
 5209                        pane.add_item(clone, true, true, None, window, cx)
 5210                    });
 5211                    this.center.split(&pane, &new_pane, direction, cx);
 5212                    cx.notify();
 5213                    new_pane
 5214                })
 5215                .ok()
 5216            } else {
 5217                None
 5218            }
 5219        })
 5220    }
 5221
 5222    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5223        let active_item = self.active_pane.read(cx).active_item();
 5224        for pane in &self.panes {
 5225            join_pane_into_active(&self.active_pane, pane, window, cx);
 5226        }
 5227        if let Some(active_item) = active_item {
 5228            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5229        }
 5230        cx.notify();
 5231    }
 5232
 5233    pub fn join_pane_into_next(
 5234        &mut self,
 5235        pane: Entity<Pane>,
 5236        window: &mut Window,
 5237        cx: &mut Context<Self>,
 5238    ) {
 5239        let next_pane = self
 5240            .find_pane_in_direction(SplitDirection::Right, cx)
 5241            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5242            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5243            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5244        let Some(next_pane) = next_pane else {
 5245            return;
 5246        };
 5247        move_all_items(&pane, &next_pane, window, cx);
 5248        cx.notify();
 5249    }
 5250
 5251    fn remove_pane(
 5252        &mut self,
 5253        pane: Entity<Pane>,
 5254        focus_on: Option<Entity<Pane>>,
 5255        window: &mut Window,
 5256        cx: &mut Context<Self>,
 5257    ) {
 5258        if self.center.remove(&pane, cx).unwrap() {
 5259            self.force_remove_pane(&pane, &focus_on, window, cx);
 5260            self.unfollow_in_pane(&pane, window, cx);
 5261            self.last_leaders_by_pane.remove(&pane.downgrade());
 5262            for removed_item in pane.read(cx).items() {
 5263                self.panes_by_item.remove(&removed_item.item_id());
 5264            }
 5265
 5266            cx.notify();
 5267        } else {
 5268            self.active_item_path_changed(true, window, cx);
 5269        }
 5270        cx.emit(Event::PaneRemoved);
 5271    }
 5272
 5273    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5274        &mut self.panes
 5275    }
 5276
 5277    pub fn panes(&self) -> &[Entity<Pane>] {
 5278        &self.panes
 5279    }
 5280
 5281    pub fn active_pane(&self) -> &Entity<Pane> {
 5282        &self.active_pane
 5283    }
 5284
 5285    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5286        for dock in self.all_docks() {
 5287            if dock.focus_handle(cx).contains_focused(window, cx)
 5288                && let Some(pane) = dock
 5289                    .read(cx)
 5290                    .active_panel()
 5291                    .and_then(|panel| panel.pane(cx))
 5292            {
 5293                return pane;
 5294            }
 5295        }
 5296        self.active_pane().clone()
 5297    }
 5298
 5299    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5300        self.find_pane_in_direction(SplitDirection::Right, cx)
 5301            .unwrap_or_else(|| {
 5302                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5303            })
 5304    }
 5305
 5306    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5307        self.pane_for_item_id(handle.item_id())
 5308    }
 5309
 5310    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5311        let weak_pane = self.panes_by_item.get(&item_id)?;
 5312        weak_pane.upgrade()
 5313    }
 5314
 5315    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5316        self.panes
 5317            .iter()
 5318            .find(|pane| pane.entity_id() == entity_id)
 5319            .cloned()
 5320    }
 5321
 5322    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5323        self.follower_states.retain(|leader_id, state| {
 5324            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5325                for item in state.items_by_leader_view_id.values() {
 5326                    item.view.set_leader_id(None, window, cx);
 5327                }
 5328                false
 5329            } else {
 5330                true
 5331            }
 5332        });
 5333        cx.notify();
 5334    }
 5335
 5336    pub fn start_following(
 5337        &mut self,
 5338        leader_id: impl Into<CollaboratorId>,
 5339        window: &mut Window,
 5340        cx: &mut Context<Self>,
 5341    ) -> Option<Task<Result<()>>> {
 5342        let leader_id = leader_id.into();
 5343        let pane = self.active_pane().clone();
 5344
 5345        self.last_leaders_by_pane
 5346            .insert(pane.downgrade(), leader_id);
 5347        self.unfollow(leader_id, window, cx);
 5348        self.unfollow_in_pane(&pane, window, cx);
 5349        self.follower_states.insert(
 5350            leader_id,
 5351            FollowerState {
 5352                center_pane: pane.clone(),
 5353                dock_pane: None,
 5354                active_view_id: None,
 5355                items_by_leader_view_id: Default::default(),
 5356            },
 5357        );
 5358        cx.notify();
 5359
 5360        match leader_id {
 5361            CollaboratorId::PeerId(leader_peer_id) => {
 5362                let room_id = self.active_call()?.room_id(cx)?;
 5363                let project_id = self.project.read(cx).remote_id();
 5364                let request = self.app_state.client.request(proto::Follow {
 5365                    room_id,
 5366                    project_id,
 5367                    leader_id: Some(leader_peer_id),
 5368                });
 5369
 5370                Some(cx.spawn_in(window, async move |this, cx| {
 5371                    let response = request.await?;
 5372                    this.update(cx, |this, _| {
 5373                        let state = this
 5374                            .follower_states
 5375                            .get_mut(&leader_id)
 5376                            .context("following interrupted")?;
 5377                        state.active_view_id = response
 5378                            .active_view
 5379                            .as_ref()
 5380                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5381                        anyhow::Ok(())
 5382                    })??;
 5383                    if let Some(view) = response.active_view {
 5384                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5385                    }
 5386                    this.update_in(cx, |this, window, cx| {
 5387                        this.leader_updated(leader_id, window, cx)
 5388                    })?;
 5389                    Ok(())
 5390                }))
 5391            }
 5392            CollaboratorId::Agent => {
 5393                self.leader_updated(leader_id, window, cx)?;
 5394                Some(Task::ready(Ok(())))
 5395            }
 5396        }
 5397    }
 5398
 5399    pub fn follow_next_collaborator(
 5400        &mut self,
 5401        _: &FollowNextCollaborator,
 5402        window: &mut Window,
 5403        cx: &mut Context<Self>,
 5404    ) {
 5405        let collaborators = self.project.read(cx).collaborators();
 5406        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5407            let mut collaborators = collaborators.keys().copied();
 5408            for peer_id in collaborators.by_ref() {
 5409                if CollaboratorId::PeerId(peer_id) == leader_id {
 5410                    break;
 5411                }
 5412            }
 5413            collaborators.next().map(CollaboratorId::PeerId)
 5414        } else if let Some(last_leader_id) =
 5415            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5416        {
 5417            match last_leader_id {
 5418                CollaboratorId::PeerId(peer_id) => {
 5419                    if collaborators.contains_key(peer_id) {
 5420                        Some(*last_leader_id)
 5421                    } else {
 5422                        None
 5423                    }
 5424                }
 5425                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5426            }
 5427        } else {
 5428            None
 5429        };
 5430
 5431        let pane = self.active_pane.clone();
 5432        let Some(leader_id) = next_leader_id.or_else(|| {
 5433            Some(CollaboratorId::PeerId(
 5434                collaborators.keys().copied().next()?,
 5435            ))
 5436        }) else {
 5437            return;
 5438        };
 5439        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5440            return;
 5441        }
 5442        if let Some(task) = self.start_following(leader_id, window, cx) {
 5443            task.detach_and_log_err(cx)
 5444        }
 5445    }
 5446
 5447    pub fn follow(
 5448        &mut self,
 5449        leader_id: impl Into<CollaboratorId>,
 5450        window: &mut Window,
 5451        cx: &mut Context<Self>,
 5452    ) {
 5453        let leader_id = leader_id.into();
 5454
 5455        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5456            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5457                return;
 5458            };
 5459            let Some(remote_participant) =
 5460                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5461            else {
 5462                return;
 5463            };
 5464
 5465            let project = self.project.read(cx);
 5466
 5467            let other_project_id = match remote_participant.location {
 5468                ParticipantLocation::External => None,
 5469                ParticipantLocation::UnsharedProject => None,
 5470                ParticipantLocation::SharedProject { project_id } => {
 5471                    if Some(project_id) == project.remote_id() {
 5472                        None
 5473                    } else {
 5474                        Some(project_id)
 5475                    }
 5476                }
 5477            };
 5478
 5479            // if they are active in another project, follow there.
 5480            if let Some(project_id) = other_project_id {
 5481                let app_state = self.app_state.clone();
 5482                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5483                    .detach_and_log_err(cx);
 5484            }
 5485        }
 5486
 5487        // if you're already following, find the right pane and focus it.
 5488        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5489            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5490
 5491            return;
 5492        }
 5493
 5494        // Otherwise, follow.
 5495        if let Some(task) = self.start_following(leader_id, window, cx) {
 5496            task.detach_and_log_err(cx)
 5497        }
 5498    }
 5499
 5500    pub fn unfollow(
 5501        &mut self,
 5502        leader_id: impl Into<CollaboratorId>,
 5503        window: &mut Window,
 5504        cx: &mut Context<Self>,
 5505    ) -> Option<()> {
 5506        cx.notify();
 5507
 5508        let leader_id = leader_id.into();
 5509        let state = self.follower_states.remove(&leader_id)?;
 5510        for (_, item) in state.items_by_leader_view_id {
 5511            item.view.set_leader_id(None, window, cx);
 5512        }
 5513
 5514        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5515            let project_id = self.project.read(cx).remote_id();
 5516            let room_id = self.active_call()?.room_id(cx)?;
 5517            self.app_state
 5518                .client
 5519                .send(proto::Unfollow {
 5520                    room_id,
 5521                    project_id,
 5522                    leader_id: Some(leader_peer_id),
 5523                })
 5524                .log_err();
 5525        }
 5526
 5527        Some(())
 5528    }
 5529
 5530    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5531        self.follower_states.contains_key(&id.into())
 5532    }
 5533
 5534    fn active_item_path_changed(
 5535        &mut self,
 5536        focus_changed: bool,
 5537        window: &mut Window,
 5538        cx: &mut Context<Self>,
 5539    ) {
 5540        cx.emit(Event::ActiveItemChanged);
 5541        let active_entry = self.active_project_path(cx);
 5542        self.project.update(cx, |project, cx| {
 5543            project.set_active_path(active_entry.clone(), cx)
 5544        });
 5545
 5546        if focus_changed && let Some(project_path) = &active_entry {
 5547            let git_store_entity = self.project.read(cx).git_store().clone();
 5548            git_store_entity.update(cx, |git_store, cx| {
 5549                git_store.set_active_repo_for_path(project_path, cx);
 5550            });
 5551        }
 5552
 5553        self.update_window_title(window, cx);
 5554    }
 5555
 5556    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5557        let project = self.project().read(cx);
 5558        let mut title = String::new();
 5559
 5560        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5561            let name = {
 5562                let settings_location = SettingsLocation {
 5563                    worktree_id: worktree.read(cx).id(),
 5564                    path: RelPath::empty(),
 5565                };
 5566
 5567                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5568                match &settings.project_name {
 5569                    Some(name) => name.as_str(),
 5570                    None => worktree.read(cx).root_name_str(),
 5571                }
 5572            };
 5573            if i > 0 {
 5574                title.push_str(", ");
 5575            }
 5576            title.push_str(name);
 5577        }
 5578
 5579        if title.is_empty() {
 5580            title = "empty project".to_string();
 5581        }
 5582
 5583        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5584            let filename = path.path.file_name().or_else(|| {
 5585                Some(
 5586                    project
 5587                        .worktree_for_id(path.worktree_id, cx)?
 5588                        .read(cx)
 5589                        .root_name_str(),
 5590                )
 5591            });
 5592
 5593            if let Some(filename) = filename {
 5594                title.push_str("");
 5595                title.push_str(filename.as_ref());
 5596            }
 5597        }
 5598
 5599        if project.is_via_collab() {
 5600            title.push_str("");
 5601        } else if project.is_shared() {
 5602            title.push_str("");
 5603        }
 5604
 5605        if let Some(last_title) = self.last_window_title.as_ref()
 5606            && &title == last_title
 5607        {
 5608            return;
 5609        }
 5610        window.set_window_title(&title);
 5611        SystemWindowTabController::update_tab_title(
 5612            cx,
 5613            window.window_handle().window_id(),
 5614            SharedString::from(&title),
 5615        );
 5616        self.last_window_title = Some(title);
 5617    }
 5618
 5619    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5620        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5621        if is_edited != self.window_edited {
 5622            self.window_edited = is_edited;
 5623            window.set_window_edited(self.window_edited)
 5624        }
 5625    }
 5626
 5627    fn update_item_dirty_state(
 5628        &mut self,
 5629        item: &dyn ItemHandle,
 5630        window: &mut Window,
 5631        cx: &mut App,
 5632    ) {
 5633        let is_dirty = item.is_dirty(cx);
 5634        let item_id = item.item_id();
 5635        let was_dirty = self.dirty_items.contains_key(&item_id);
 5636        if is_dirty == was_dirty {
 5637            return;
 5638        }
 5639        if was_dirty {
 5640            self.dirty_items.remove(&item_id);
 5641            self.update_window_edited(window, cx);
 5642            return;
 5643        }
 5644
 5645        let workspace = self.weak_handle();
 5646        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5647            return;
 5648        };
 5649        let on_release_callback = Box::new(move |cx: &mut App| {
 5650            window_handle
 5651                .update(cx, |_, window, cx| {
 5652                    workspace
 5653                        .update(cx, |workspace, cx| {
 5654                            workspace.dirty_items.remove(&item_id);
 5655                            workspace.update_window_edited(window, cx)
 5656                        })
 5657                        .ok();
 5658                })
 5659                .ok();
 5660        });
 5661
 5662        let s = item.on_release(cx, on_release_callback);
 5663        self.dirty_items.insert(item_id, s);
 5664        self.update_window_edited(window, cx);
 5665    }
 5666
 5667    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5668        if self.notifications.is_empty() {
 5669            None
 5670        } else {
 5671            Some(
 5672                div()
 5673                    .absolute()
 5674                    .right_3()
 5675                    .bottom_3()
 5676                    .w_112()
 5677                    .h_full()
 5678                    .flex()
 5679                    .flex_col()
 5680                    .justify_end()
 5681                    .gap_2()
 5682                    .children(
 5683                        self.notifications
 5684                            .iter()
 5685                            .map(|(_, notification)| notification.clone().into_any()),
 5686                    ),
 5687            )
 5688        }
 5689    }
 5690
 5691    // RPC handlers
 5692
 5693    fn active_view_for_follower(
 5694        &self,
 5695        follower_project_id: Option<u64>,
 5696        window: &mut Window,
 5697        cx: &mut Context<Self>,
 5698    ) -> Option<proto::View> {
 5699        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5700        let item = item?;
 5701        let leader_id = self
 5702            .pane_for(&*item)
 5703            .and_then(|pane| self.leader_for_pane(&pane));
 5704        let leader_peer_id = match leader_id {
 5705            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5706            Some(CollaboratorId::Agent) | None => None,
 5707        };
 5708
 5709        let item_handle = item.to_followable_item_handle(cx)?;
 5710        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5711        let variant = item_handle.to_state_proto(window, cx)?;
 5712
 5713        if item_handle.is_project_item(window, cx)
 5714            && (follower_project_id.is_none()
 5715                || follower_project_id != self.project.read(cx).remote_id())
 5716        {
 5717            return None;
 5718        }
 5719
 5720        Some(proto::View {
 5721            id: id.to_proto(),
 5722            leader_id: leader_peer_id,
 5723            variant: Some(variant),
 5724            panel_id: panel_id.map(|id| id as i32),
 5725        })
 5726    }
 5727
 5728    fn handle_follow(
 5729        &mut self,
 5730        follower_project_id: Option<u64>,
 5731        window: &mut Window,
 5732        cx: &mut Context<Self>,
 5733    ) -> proto::FollowResponse {
 5734        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5735
 5736        cx.notify();
 5737        proto::FollowResponse {
 5738            views: active_view.iter().cloned().collect(),
 5739            active_view,
 5740        }
 5741    }
 5742
 5743    fn handle_update_followers(
 5744        &mut self,
 5745        leader_id: PeerId,
 5746        message: proto::UpdateFollowers,
 5747        _window: &mut Window,
 5748        _cx: &mut Context<Self>,
 5749    ) {
 5750        self.leader_updates_tx
 5751            .unbounded_send((leader_id, message))
 5752            .ok();
 5753    }
 5754
 5755    async fn process_leader_update(
 5756        this: &WeakEntity<Self>,
 5757        leader_id: PeerId,
 5758        update: proto::UpdateFollowers,
 5759        cx: &mut AsyncWindowContext,
 5760    ) -> Result<()> {
 5761        match update.variant.context("invalid update")? {
 5762            proto::update_followers::Variant::CreateView(view) => {
 5763                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5764                let should_add_view = this.update(cx, |this, _| {
 5765                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5766                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5767                    } else {
 5768                        anyhow::Ok(false)
 5769                    }
 5770                })??;
 5771
 5772                if should_add_view {
 5773                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5774                }
 5775            }
 5776            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5777                let should_add_view = this.update(cx, |this, _| {
 5778                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5779                        state.active_view_id = update_active_view
 5780                            .view
 5781                            .as_ref()
 5782                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5783
 5784                        if state.active_view_id.is_some_and(|view_id| {
 5785                            !state.items_by_leader_view_id.contains_key(&view_id)
 5786                        }) {
 5787                            anyhow::Ok(true)
 5788                        } else {
 5789                            anyhow::Ok(false)
 5790                        }
 5791                    } else {
 5792                        anyhow::Ok(false)
 5793                    }
 5794                })??;
 5795
 5796                if should_add_view && let Some(view) = update_active_view.view {
 5797                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5798                }
 5799            }
 5800            proto::update_followers::Variant::UpdateView(update_view) => {
 5801                let variant = update_view.variant.context("missing update view variant")?;
 5802                let id = update_view.id.context("missing update view id")?;
 5803                let mut tasks = Vec::new();
 5804                this.update_in(cx, |this, window, cx| {
 5805                    let project = this.project.clone();
 5806                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5807                        let view_id = ViewId::from_proto(id.clone())?;
 5808                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5809                            tasks.push(item.view.apply_update_proto(
 5810                                &project,
 5811                                variant.clone(),
 5812                                window,
 5813                                cx,
 5814                            ));
 5815                        }
 5816                    }
 5817                    anyhow::Ok(())
 5818                })??;
 5819                try_join_all(tasks).await.log_err();
 5820            }
 5821        }
 5822        this.update_in(cx, |this, window, cx| {
 5823            this.leader_updated(leader_id, window, cx)
 5824        })?;
 5825        Ok(())
 5826    }
 5827
 5828    async fn add_view_from_leader(
 5829        this: WeakEntity<Self>,
 5830        leader_id: PeerId,
 5831        view: &proto::View,
 5832        cx: &mut AsyncWindowContext,
 5833    ) -> Result<()> {
 5834        let this = this.upgrade().context("workspace dropped")?;
 5835
 5836        let Some(id) = view.id.clone() else {
 5837            anyhow::bail!("no id for view");
 5838        };
 5839        let id = ViewId::from_proto(id)?;
 5840        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5841
 5842        let pane = this.update(cx, |this, _cx| {
 5843            let state = this
 5844                .follower_states
 5845                .get(&leader_id.into())
 5846                .context("stopped following")?;
 5847            anyhow::Ok(state.pane().clone())
 5848        })?;
 5849        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5850            let client = this.read(cx).client().clone();
 5851            pane.items().find_map(|item| {
 5852                let item = item.to_followable_item_handle(cx)?;
 5853                if item.remote_id(&client, window, cx) == Some(id) {
 5854                    Some(item)
 5855                } else {
 5856                    None
 5857                }
 5858            })
 5859        })?;
 5860        let item = if let Some(existing_item) = existing_item {
 5861            existing_item
 5862        } else {
 5863            let variant = view.variant.clone();
 5864            anyhow::ensure!(variant.is_some(), "missing view variant");
 5865
 5866            let task = cx.update(|window, cx| {
 5867                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5868            })?;
 5869
 5870            let Some(task) = task else {
 5871                anyhow::bail!(
 5872                    "failed to construct view from leader (maybe from a different version of zed?)"
 5873                );
 5874            };
 5875
 5876            let mut new_item = task.await?;
 5877            pane.update_in(cx, |pane, window, cx| {
 5878                let mut item_to_remove = None;
 5879                for (ix, item) in pane.items().enumerate() {
 5880                    if let Some(item) = item.to_followable_item_handle(cx) {
 5881                        match new_item.dedup(item.as_ref(), window, cx) {
 5882                            Some(item::Dedup::KeepExisting) => {
 5883                                new_item =
 5884                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5885                                break;
 5886                            }
 5887                            Some(item::Dedup::ReplaceExisting) => {
 5888                                item_to_remove = Some((ix, item.item_id()));
 5889                                break;
 5890                            }
 5891                            None => {}
 5892                        }
 5893                    }
 5894                }
 5895
 5896                if let Some((ix, id)) = item_to_remove {
 5897                    pane.remove_item(id, false, false, window, cx);
 5898                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5899                }
 5900            })?;
 5901
 5902            new_item
 5903        };
 5904
 5905        this.update_in(cx, |this, window, cx| {
 5906            let state = this.follower_states.get_mut(&leader_id.into())?;
 5907            item.set_leader_id(Some(leader_id.into()), window, cx);
 5908            state.items_by_leader_view_id.insert(
 5909                id,
 5910                FollowerView {
 5911                    view: item,
 5912                    location: panel_id,
 5913                },
 5914            );
 5915
 5916            Some(())
 5917        })
 5918        .context("no follower state")?;
 5919
 5920        Ok(())
 5921    }
 5922
 5923    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5924        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5925            return;
 5926        };
 5927
 5928        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5929            let buffer_entity_id = agent_location.buffer.entity_id();
 5930            let view_id = ViewId {
 5931                creator: CollaboratorId::Agent,
 5932                id: buffer_entity_id.as_u64(),
 5933            };
 5934            follower_state.active_view_id = Some(view_id);
 5935
 5936            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5937                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5938                hash_map::Entry::Vacant(entry) => {
 5939                    let existing_view =
 5940                        follower_state
 5941                            .center_pane
 5942                            .read(cx)
 5943                            .items()
 5944                            .find_map(|item| {
 5945                                let item = item.to_followable_item_handle(cx)?;
 5946                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5947                                    && item.project_item_model_ids(cx).as_slice()
 5948                                        == [buffer_entity_id]
 5949                                {
 5950                                    Some(item)
 5951                                } else {
 5952                                    None
 5953                                }
 5954                            });
 5955                    let view = existing_view.or_else(|| {
 5956                        agent_location.buffer.upgrade().and_then(|buffer| {
 5957                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5958                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5959                            })?
 5960                            .to_followable_item_handle(cx)
 5961                        })
 5962                    });
 5963
 5964                    view.map(|view| {
 5965                        entry.insert(FollowerView {
 5966                            view,
 5967                            location: None,
 5968                        })
 5969                    })
 5970                }
 5971            };
 5972
 5973            if let Some(item) = item {
 5974                item.view
 5975                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5976                item.view
 5977                    .update_agent_location(agent_location.position, window, cx);
 5978            }
 5979        } else {
 5980            follower_state.active_view_id = None;
 5981        }
 5982
 5983        self.leader_updated(CollaboratorId::Agent, window, cx);
 5984    }
 5985
 5986    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5987        let mut is_project_item = true;
 5988        let mut update = proto::UpdateActiveView::default();
 5989        if window.is_window_active() {
 5990            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5991
 5992            if let Some(item) = active_item
 5993                && item.item_focus_handle(cx).contains_focused(window, cx)
 5994            {
 5995                let leader_id = self
 5996                    .pane_for(&*item)
 5997                    .and_then(|pane| self.leader_for_pane(&pane));
 5998                let leader_peer_id = match leader_id {
 5999                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6000                    Some(CollaboratorId::Agent) | None => None,
 6001                };
 6002
 6003                if let Some(item) = item.to_followable_item_handle(cx) {
 6004                    let id = item
 6005                        .remote_id(&self.app_state.client, window, cx)
 6006                        .map(|id| id.to_proto());
 6007
 6008                    if let Some(id) = id
 6009                        && let Some(variant) = item.to_state_proto(window, cx)
 6010                    {
 6011                        let view = Some(proto::View {
 6012                            id,
 6013                            leader_id: leader_peer_id,
 6014                            variant: Some(variant),
 6015                            panel_id: panel_id.map(|id| id as i32),
 6016                        });
 6017
 6018                        is_project_item = item.is_project_item(window, cx);
 6019                        update = proto::UpdateActiveView { view };
 6020                    };
 6021                }
 6022            }
 6023        }
 6024
 6025        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6026        if active_view_id != self.last_active_view_id.as_ref() {
 6027            self.last_active_view_id = active_view_id.cloned();
 6028            self.update_followers(
 6029                is_project_item,
 6030                proto::update_followers::Variant::UpdateActiveView(update),
 6031                window,
 6032                cx,
 6033            );
 6034        }
 6035    }
 6036
 6037    fn active_item_for_followers(
 6038        &self,
 6039        window: &mut Window,
 6040        cx: &mut App,
 6041    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6042        let mut active_item = None;
 6043        let mut panel_id = None;
 6044        for dock in self.all_docks() {
 6045            if dock.focus_handle(cx).contains_focused(window, cx)
 6046                && let Some(panel) = dock.read(cx).active_panel()
 6047                && let Some(pane) = panel.pane(cx)
 6048                && let Some(item) = pane.read(cx).active_item()
 6049            {
 6050                active_item = Some(item);
 6051                panel_id = panel.remote_id();
 6052                break;
 6053            }
 6054        }
 6055
 6056        if active_item.is_none() {
 6057            active_item = self.active_pane().read(cx).active_item();
 6058        }
 6059        (active_item, panel_id)
 6060    }
 6061
 6062    fn update_followers(
 6063        &self,
 6064        project_only: bool,
 6065        update: proto::update_followers::Variant,
 6066        _: &mut Window,
 6067        cx: &mut App,
 6068    ) -> Option<()> {
 6069        // If this update only applies to for followers in the current project,
 6070        // then skip it unless this project is shared. If it applies to all
 6071        // followers, regardless of project, then set `project_id` to none,
 6072        // indicating that it goes to all followers.
 6073        let project_id = if project_only {
 6074            Some(self.project.read(cx).remote_id()?)
 6075        } else {
 6076            None
 6077        };
 6078        self.app_state().workspace_store.update(cx, |store, cx| {
 6079            store.update_followers(project_id, update, cx)
 6080        })
 6081    }
 6082
 6083    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6084        self.follower_states.iter().find_map(|(leader_id, state)| {
 6085            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6086                Some(*leader_id)
 6087            } else {
 6088                None
 6089            }
 6090        })
 6091    }
 6092
 6093    fn leader_updated(
 6094        &mut self,
 6095        leader_id: impl Into<CollaboratorId>,
 6096        window: &mut Window,
 6097        cx: &mut Context<Self>,
 6098    ) -> Option<Box<dyn ItemHandle>> {
 6099        cx.notify();
 6100
 6101        let leader_id = leader_id.into();
 6102        let (panel_id, item) = match leader_id {
 6103            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6104            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6105        };
 6106
 6107        let state = self.follower_states.get(&leader_id)?;
 6108        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6109        let pane;
 6110        if let Some(panel_id) = panel_id {
 6111            pane = self
 6112                .activate_panel_for_proto_id(panel_id, window, cx)?
 6113                .pane(cx)?;
 6114            let state = self.follower_states.get_mut(&leader_id)?;
 6115            state.dock_pane = Some(pane.clone());
 6116        } else {
 6117            pane = state.center_pane.clone();
 6118            let state = self.follower_states.get_mut(&leader_id)?;
 6119            if let Some(dock_pane) = state.dock_pane.take() {
 6120                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6121            }
 6122        }
 6123
 6124        pane.update(cx, |pane, cx| {
 6125            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6126            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6127                pane.activate_item(index, false, false, window, cx);
 6128            } else {
 6129                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6130            }
 6131
 6132            if focus_active_item {
 6133                pane.focus_active_item(window, cx)
 6134            }
 6135        });
 6136
 6137        Some(item)
 6138    }
 6139
 6140    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6141        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6142        let active_view_id = state.active_view_id?;
 6143        Some(
 6144            state
 6145                .items_by_leader_view_id
 6146                .get(&active_view_id)?
 6147                .view
 6148                .boxed_clone(),
 6149        )
 6150    }
 6151
 6152    fn active_item_for_peer(
 6153        &self,
 6154        peer_id: PeerId,
 6155        window: &mut Window,
 6156        cx: &mut Context<Self>,
 6157    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6158        let call = self.active_call()?;
 6159        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6160        let leader_in_this_app;
 6161        let leader_in_this_project;
 6162        match participant.location {
 6163            ParticipantLocation::SharedProject { project_id } => {
 6164                leader_in_this_app = true;
 6165                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6166            }
 6167            ParticipantLocation::UnsharedProject => {
 6168                leader_in_this_app = true;
 6169                leader_in_this_project = false;
 6170            }
 6171            ParticipantLocation::External => {
 6172                leader_in_this_app = false;
 6173                leader_in_this_project = false;
 6174            }
 6175        };
 6176        let state = self.follower_states.get(&peer_id.into())?;
 6177        let mut item_to_activate = None;
 6178        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6179            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6180                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6181            {
 6182                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6183            }
 6184        } else if let Some(shared_screen) =
 6185            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6186        {
 6187            item_to_activate = Some((None, Box::new(shared_screen)));
 6188        }
 6189        item_to_activate
 6190    }
 6191
 6192    fn shared_screen_for_peer(
 6193        &self,
 6194        peer_id: PeerId,
 6195        pane: &Entity<Pane>,
 6196        window: &mut Window,
 6197        cx: &mut App,
 6198    ) -> Option<Entity<SharedScreen>> {
 6199        self.active_call()?
 6200            .create_shared_screen(peer_id, pane, window, cx)
 6201    }
 6202
 6203    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6204        if window.is_window_active() {
 6205            self.update_active_view_for_followers(window, cx);
 6206
 6207            if let Some(database_id) = self.database_id {
 6208                let db = WorkspaceDb::global(cx);
 6209                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6210                    .detach();
 6211            }
 6212        } else {
 6213            for pane in &self.panes {
 6214                pane.update(cx, |pane, cx| {
 6215                    if let Some(item) = pane.active_item() {
 6216                        item.workspace_deactivated(window, cx);
 6217                    }
 6218                    for item in pane.items() {
 6219                        if matches!(
 6220                            item.workspace_settings(cx).autosave,
 6221                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6222                        ) {
 6223                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6224                                .detach_and_log_err(cx);
 6225                        }
 6226                    }
 6227                });
 6228            }
 6229        }
 6230    }
 6231
 6232    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6233        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6234    }
 6235
 6236    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6237        self.active_call.as_ref().map(|(call, _)| call.clone())
 6238    }
 6239
 6240    fn on_active_call_event(
 6241        &mut self,
 6242        event: &ActiveCallEvent,
 6243        window: &mut Window,
 6244        cx: &mut Context<Self>,
 6245    ) {
 6246        match event {
 6247            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6248            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6249                self.leader_updated(participant_id, window, cx);
 6250            }
 6251        }
 6252    }
 6253
 6254    pub fn database_id(&self) -> Option<WorkspaceId> {
 6255        self.database_id
 6256    }
 6257
 6258    #[cfg(any(test, feature = "test-support"))]
 6259    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6260        self.database_id = Some(id);
 6261    }
 6262
 6263    pub fn session_id(&self) -> Option<String> {
 6264        self.session_id.clone()
 6265    }
 6266
 6267    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6268        let Some(display) = window.display(cx) else {
 6269            return Task::ready(());
 6270        };
 6271        let Ok(display_uuid) = display.uuid() else {
 6272            return Task::ready(());
 6273        };
 6274
 6275        let window_bounds = window.inner_window_bounds();
 6276        let database_id = self.database_id;
 6277        let has_paths = !self.root_paths(cx).is_empty();
 6278        let db = WorkspaceDb::global(cx);
 6279        let kvp = db::kvp::KeyValueStore::global(cx);
 6280
 6281        cx.background_executor().spawn(async move {
 6282            if !has_paths {
 6283                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6284                    .await
 6285                    .log_err();
 6286            }
 6287            if let Some(database_id) = database_id {
 6288                db.set_window_open_status(
 6289                    database_id,
 6290                    SerializedWindowBounds(window_bounds),
 6291                    display_uuid,
 6292                )
 6293                .await
 6294                .log_err();
 6295            } else {
 6296                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6297                    .await
 6298                    .log_err();
 6299            }
 6300        })
 6301    }
 6302
 6303    /// Bypass the 200ms serialization throttle and write workspace state to
 6304    /// the DB immediately. Returns a task the caller can await to ensure the
 6305    /// write completes. Used by the quit handler so the most recent state
 6306    /// isn't lost to a pending throttle timer when the process exits.
 6307    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6308        self._schedule_serialize_workspace.take();
 6309        self._serialize_workspace_task.take();
 6310        self.bounds_save_task_queued.take();
 6311
 6312        let bounds_task = self.save_window_bounds(window, cx);
 6313        let serialize_task = self.serialize_workspace_internal(window, cx);
 6314        cx.spawn(async move |_| {
 6315            bounds_task.await;
 6316            serialize_task.await;
 6317        })
 6318    }
 6319
 6320    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6321        let project = self.project().read(cx);
 6322        project
 6323            .visible_worktrees(cx)
 6324            .map(|worktree| worktree.read(cx).abs_path())
 6325            .collect::<Vec<_>>()
 6326    }
 6327
 6328    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6329        match member {
 6330            Member::Axis(PaneAxis { members, .. }) => {
 6331                for child in members.iter() {
 6332                    self.remove_panes(child.clone(), window, cx)
 6333                }
 6334            }
 6335            Member::Pane(pane) => {
 6336                self.force_remove_pane(&pane, &None, window, cx);
 6337            }
 6338        }
 6339    }
 6340
 6341    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6342        self.session_id.take();
 6343        self.serialize_workspace_internal(window, cx)
 6344    }
 6345
 6346    fn force_remove_pane(
 6347        &mut self,
 6348        pane: &Entity<Pane>,
 6349        focus_on: &Option<Entity<Pane>>,
 6350        window: &mut Window,
 6351        cx: &mut Context<Workspace>,
 6352    ) {
 6353        self.panes.retain(|p| p != pane);
 6354        if let Some(focus_on) = focus_on {
 6355            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6356        } else if self.active_pane() == pane {
 6357            self.panes
 6358                .last()
 6359                .unwrap()
 6360                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6361        }
 6362        if self.last_active_center_pane == Some(pane.downgrade()) {
 6363            self.last_active_center_pane = None;
 6364        }
 6365        cx.notify();
 6366    }
 6367
 6368    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6369        if self._schedule_serialize_workspace.is_none() {
 6370            self._schedule_serialize_workspace =
 6371                Some(cx.spawn_in(window, async move |this, cx| {
 6372                    cx.background_executor()
 6373                        .timer(SERIALIZATION_THROTTLE_TIME)
 6374                        .await;
 6375                    this.update_in(cx, |this, window, cx| {
 6376                        this._serialize_workspace_task =
 6377                            Some(this.serialize_workspace_internal(window, cx));
 6378                        this._schedule_serialize_workspace.take();
 6379                    })
 6380                    .log_err();
 6381                }));
 6382        }
 6383    }
 6384
 6385    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6386        let Some(database_id) = self.database_id() else {
 6387            return Task::ready(());
 6388        };
 6389
 6390        fn serialize_pane_handle(
 6391            pane_handle: &Entity<Pane>,
 6392            window: &mut Window,
 6393            cx: &mut App,
 6394        ) -> SerializedPane {
 6395            let (items, active, pinned_count) = {
 6396                let pane = pane_handle.read(cx);
 6397                let active_item_id = pane.active_item().map(|item| item.item_id());
 6398                (
 6399                    pane.items()
 6400                        .filter_map(|handle| {
 6401                            let handle = handle.to_serializable_item_handle(cx)?;
 6402
 6403                            Some(SerializedItem {
 6404                                kind: Arc::from(handle.serialized_item_kind()),
 6405                                item_id: handle.item_id().as_u64(),
 6406                                active: Some(handle.item_id()) == active_item_id,
 6407                                preview: pane.is_active_preview_item(handle.item_id()),
 6408                            })
 6409                        })
 6410                        .collect::<Vec<_>>(),
 6411                    pane.has_focus(window, cx),
 6412                    pane.pinned_count(),
 6413                )
 6414            };
 6415
 6416            SerializedPane::new(items, active, pinned_count)
 6417        }
 6418
 6419        fn build_serialized_pane_group(
 6420            pane_group: &Member,
 6421            window: &mut Window,
 6422            cx: &mut App,
 6423        ) -> SerializedPaneGroup {
 6424            match pane_group {
 6425                Member::Axis(PaneAxis {
 6426                    axis,
 6427                    members,
 6428                    flexes,
 6429                    bounding_boxes: _,
 6430                }) => SerializedPaneGroup::Group {
 6431                    axis: SerializedAxis(*axis),
 6432                    children: members
 6433                        .iter()
 6434                        .map(|member| build_serialized_pane_group(member, window, cx))
 6435                        .collect::<Vec<_>>(),
 6436                    flexes: Some(flexes.lock().clone()),
 6437                },
 6438                Member::Pane(pane_handle) => {
 6439                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6440                }
 6441            }
 6442        }
 6443
 6444        fn build_serialized_docks(
 6445            this: &Workspace,
 6446            window: &mut Window,
 6447            cx: &mut App,
 6448        ) -> DockStructure {
 6449            this.capture_dock_state(window, cx)
 6450        }
 6451
 6452        match self.workspace_location(cx) {
 6453            WorkspaceLocation::Location(location, paths) => {
 6454                let breakpoints = self.project.update(cx, |project, cx| {
 6455                    project
 6456                        .breakpoint_store()
 6457                        .read(cx)
 6458                        .all_source_breakpoints(cx)
 6459                });
 6460                let user_toolchains = self
 6461                    .project
 6462                    .read(cx)
 6463                    .user_toolchains(cx)
 6464                    .unwrap_or_default();
 6465
 6466                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6467                let docks = build_serialized_docks(self, window, cx);
 6468                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6469
 6470                let serialized_workspace = SerializedWorkspace {
 6471                    id: database_id,
 6472                    location,
 6473                    paths,
 6474                    center_group,
 6475                    window_bounds,
 6476                    display: Default::default(),
 6477                    docks,
 6478                    centered_layout: self.centered_layout,
 6479                    session_id: self.session_id.clone(),
 6480                    breakpoints,
 6481                    window_id: Some(window.window_handle().window_id().as_u64()),
 6482                    user_toolchains,
 6483                };
 6484
 6485                let db = WorkspaceDb::global(cx);
 6486                window.spawn(cx, async move |_| {
 6487                    db.save_workspace(serialized_workspace).await;
 6488                })
 6489            }
 6490            WorkspaceLocation::DetachFromSession => {
 6491                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6492                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6493                // Save dock state for empty local workspaces
 6494                let docks = build_serialized_docks(self, window, cx);
 6495                let db = WorkspaceDb::global(cx);
 6496                let kvp = db::kvp::KeyValueStore::global(cx);
 6497                window.spawn(cx, async move |_| {
 6498                    db.set_window_open_status(
 6499                        database_id,
 6500                        window_bounds,
 6501                        display.unwrap_or_default(),
 6502                    )
 6503                    .await
 6504                    .log_err();
 6505                    db.set_session_id(database_id, None).await.log_err();
 6506                    persistence::write_default_dock_state(&kvp, docks)
 6507                        .await
 6508                        .log_err();
 6509                })
 6510            }
 6511            WorkspaceLocation::None => {
 6512                // Save dock state for empty non-local workspaces
 6513                let docks = build_serialized_docks(self, window, cx);
 6514                let kvp = db::kvp::KeyValueStore::global(cx);
 6515                window.spawn(cx, async move |_| {
 6516                    persistence::write_default_dock_state(&kvp, docks)
 6517                        .await
 6518                        .log_err();
 6519                })
 6520            }
 6521        }
 6522    }
 6523
 6524    fn has_any_items_open(&self, cx: &App) -> bool {
 6525        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6526    }
 6527
 6528    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6529        let paths = PathList::new(&self.root_paths(cx));
 6530        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6531            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6532        } else if self.project.read(cx).is_local() {
 6533            if !paths.is_empty() || self.has_any_items_open(cx) {
 6534                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6535            } else {
 6536                WorkspaceLocation::DetachFromSession
 6537            }
 6538        } else {
 6539            WorkspaceLocation::None
 6540        }
 6541    }
 6542
 6543    fn update_history(&self, cx: &mut App) {
 6544        let Some(id) = self.database_id() else {
 6545            return;
 6546        };
 6547        if !self.project.read(cx).is_local() {
 6548            return;
 6549        }
 6550        if let Some(manager) = HistoryManager::global(cx) {
 6551            let paths = PathList::new(&self.root_paths(cx));
 6552            manager.update(cx, |this, cx| {
 6553                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6554            });
 6555        }
 6556    }
 6557
 6558    async fn serialize_items(
 6559        this: &WeakEntity<Self>,
 6560        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6561        cx: &mut AsyncWindowContext,
 6562    ) -> Result<()> {
 6563        const CHUNK_SIZE: usize = 200;
 6564
 6565        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6566
 6567        while let Some(items_received) = serializable_items.next().await {
 6568            let unique_items =
 6569                items_received
 6570                    .into_iter()
 6571                    .fold(HashMap::default(), |mut acc, item| {
 6572                        acc.entry(item.item_id()).or_insert(item);
 6573                        acc
 6574                    });
 6575
 6576            // We use into_iter() here so that the references to the items are moved into
 6577            // the tasks and not kept alive while we're sleeping.
 6578            for (_, item) in unique_items.into_iter() {
 6579                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6580                    item.serialize(workspace, false, window, cx)
 6581                }) {
 6582                    cx.background_spawn(async move { task.await.log_err() })
 6583                        .detach();
 6584                }
 6585            }
 6586
 6587            cx.background_executor()
 6588                .timer(SERIALIZATION_THROTTLE_TIME)
 6589                .await;
 6590        }
 6591
 6592        Ok(())
 6593    }
 6594
 6595    pub(crate) fn enqueue_item_serialization(
 6596        &mut self,
 6597        item: Box<dyn SerializableItemHandle>,
 6598    ) -> Result<()> {
 6599        self.serializable_items_tx
 6600            .unbounded_send(item)
 6601            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6602    }
 6603
 6604    pub(crate) fn load_workspace(
 6605        serialized_workspace: SerializedWorkspace,
 6606        paths_to_open: Vec<Option<ProjectPath>>,
 6607        window: &mut Window,
 6608        cx: &mut Context<Workspace>,
 6609    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6610        cx.spawn_in(window, async move |workspace, cx| {
 6611            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6612
 6613            let mut center_group = None;
 6614            let mut center_items = None;
 6615
 6616            // Traverse the splits tree and add to things
 6617            if let Some((group, active_pane, items)) = serialized_workspace
 6618                .center_group
 6619                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6620                .await
 6621            {
 6622                center_items = Some(items);
 6623                center_group = Some((group, active_pane))
 6624            }
 6625
 6626            let mut items_by_project_path = HashMap::default();
 6627            let mut item_ids_by_kind = HashMap::default();
 6628            let mut all_deserialized_items = Vec::default();
 6629            cx.update(|_, cx| {
 6630                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6631                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6632                        item_ids_by_kind
 6633                            .entry(serializable_item_handle.serialized_item_kind())
 6634                            .or_insert(Vec::new())
 6635                            .push(item.item_id().as_u64() as ItemId);
 6636                    }
 6637
 6638                    if let Some(project_path) = item.project_path(cx) {
 6639                        items_by_project_path.insert(project_path, item.clone());
 6640                    }
 6641                    all_deserialized_items.push(item);
 6642                }
 6643            })?;
 6644
 6645            let opened_items = paths_to_open
 6646                .into_iter()
 6647                .map(|path_to_open| {
 6648                    path_to_open
 6649                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6650                })
 6651                .collect::<Vec<_>>();
 6652
 6653            // Remove old panes from workspace panes list
 6654            workspace.update_in(cx, |workspace, window, cx| {
 6655                if let Some((center_group, active_pane)) = center_group {
 6656                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6657
 6658                    // Swap workspace center group
 6659                    workspace.center = PaneGroup::with_root(center_group);
 6660                    workspace.center.set_is_center(true);
 6661                    workspace.center.mark_positions(cx);
 6662
 6663                    if let Some(active_pane) = active_pane {
 6664                        workspace.set_active_pane(&active_pane, window, cx);
 6665                        cx.focus_self(window);
 6666                    } else {
 6667                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6668                    }
 6669                }
 6670
 6671                let docks = serialized_workspace.docks;
 6672
 6673                for (dock, serialized_dock) in [
 6674                    (&mut workspace.right_dock, docks.right),
 6675                    (&mut workspace.left_dock, docks.left),
 6676                    (&mut workspace.bottom_dock, docks.bottom),
 6677                ]
 6678                .iter_mut()
 6679                {
 6680                    dock.update(cx, |dock, cx| {
 6681                        dock.serialized_dock = Some(serialized_dock.clone());
 6682                        dock.restore_state(window, cx);
 6683                    });
 6684                }
 6685
 6686                cx.notify();
 6687            })?;
 6688
 6689            let _ = project
 6690                .update(cx, |project, cx| {
 6691                    project
 6692                        .breakpoint_store()
 6693                        .update(cx, |breakpoint_store, cx| {
 6694                            breakpoint_store
 6695                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6696                        })
 6697                })
 6698                .await;
 6699
 6700            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6701            // after loading the items, we might have different items and in order to avoid
 6702            // the database filling up, we delete items that haven't been loaded now.
 6703            //
 6704            // The items that have been loaded, have been saved after they've been added to the workspace.
 6705            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6706                item_ids_by_kind
 6707                    .into_iter()
 6708                    .map(|(item_kind, loaded_items)| {
 6709                        SerializableItemRegistry::cleanup(
 6710                            item_kind,
 6711                            serialized_workspace.id,
 6712                            loaded_items,
 6713                            window,
 6714                            cx,
 6715                        )
 6716                        .log_err()
 6717                    })
 6718                    .collect::<Vec<_>>()
 6719            })?;
 6720
 6721            futures::future::join_all(clean_up_tasks).await;
 6722
 6723            workspace
 6724                .update_in(cx, |workspace, window, cx| {
 6725                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6726                    workspace.serialize_workspace_internal(window, cx).detach();
 6727
 6728                    // Ensure that we mark the window as edited if we did load dirty items
 6729                    workspace.update_window_edited(window, cx);
 6730                })
 6731                .ok();
 6732
 6733            Ok(opened_items)
 6734        })
 6735    }
 6736
 6737    pub fn key_context(&self, cx: &App) -> KeyContext {
 6738        let mut context = KeyContext::new_with_defaults();
 6739        context.add("Workspace");
 6740        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6741        if let Some(status) = self
 6742            .debugger_provider
 6743            .as_ref()
 6744            .and_then(|provider| provider.active_thread_state(cx))
 6745        {
 6746            match status {
 6747                ThreadStatus::Running | ThreadStatus::Stepping => {
 6748                    context.add("debugger_running");
 6749                }
 6750                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6751                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6752            }
 6753        }
 6754
 6755        if self.left_dock.read(cx).is_open() {
 6756            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6757                context.set("left_dock", active_panel.panel_key());
 6758            }
 6759        }
 6760
 6761        if self.right_dock.read(cx).is_open() {
 6762            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6763                context.set("right_dock", active_panel.panel_key());
 6764            }
 6765        }
 6766
 6767        if self.bottom_dock.read(cx).is_open() {
 6768            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6769                context.set("bottom_dock", active_panel.panel_key());
 6770            }
 6771        }
 6772
 6773        context
 6774    }
 6775
 6776    /// Multiworkspace uses this to add workspace action handling to itself
 6777    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6778        self.add_workspace_actions_listeners(div, window, cx)
 6779            .on_action(cx.listener(
 6780                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6781                    for action in &action_sequence.0 {
 6782                        window.dispatch_action(action.boxed_clone(), cx);
 6783                    }
 6784                },
 6785            ))
 6786            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6787            .on_action(cx.listener(Self::close_all_items_and_panes))
 6788            .on_action(cx.listener(Self::close_item_in_all_panes))
 6789            .on_action(cx.listener(Self::save_all))
 6790            .on_action(cx.listener(Self::send_keystrokes))
 6791            .on_action(cx.listener(Self::add_folder_to_project))
 6792            .on_action(cx.listener(Self::follow_next_collaborator))
 6793            .on_action(cx.listener(Self::activate_pane_at_index))
 6794            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6795            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6796            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6797            .on_action(cx.listener(Self::toggle_theme_mode))
 6798            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6799                let pane = workspace.active_pane().clone();
 6800                workspace.unfollow_in_pane(&pane, window, cx);
 6801            }))
 6802            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6803                workspace
 6804                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6805                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6806            }))
 6807            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6808                workspace
 6809                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6810                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6811            }))
 6812            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6813                workspace
 6814                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6815                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6816            }))
 6817            .on_action(
 6818                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6819                    workspace.activate_previous_pane(window, cx)
 6820                }),
 6821            )
 6822            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6823                workspace.activate_next_pane(window, cx)
 6824            }))
 6825            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6826                workspace.activate_last_pane(window, cx)
 6827            }))
 6828            .on_action(
 6829                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6830                    workspace.activate_next_window(cx)
 6831                }),
 6832            )
 6833            .on_action(
 6834                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6835                    workspace.activate_previous_window(cx)
 6836                }),
 6837            )
 6838            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6839                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6840            }))
 6841            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6842                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6843            }))
 6844            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6845                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6846            }))
 6847            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6848                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6849            }))
 6850            .on_action(cx.listener(
 6851                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6852                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6853                },
 6854            ))
 6855            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6856                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6857            }))
 6858            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6859                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6860            }))
 6861            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6862                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6863            }))
 6864            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6865                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6866            }))
 6867            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6868                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6869                    SplitDirection::Down,
 6870                    SplitDirection::Up,
 6871                    SplitDirection::Right,
 6872                    SplitDirection::Left,
 6873                ];
 6874                for dir in DIRECTION_PRIORITY {
 6875                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6876                        workspace.swap_pane_in_direction(dir, cx);
 6877                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6878                        break;
 6879                    }
 6880                }
 6881            }))
 6882            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6883                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6884            }))
 6885            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6886                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6887            }))
 6888            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6889                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6890            }))
 6891            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6892                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6893            }))
 6894            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6895                this.toggle_dock(DockPosition::Left, window, cx);
 6896            }))
 6897            .on_action(cx.listener(
 6898                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6899                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6900                },
 6901            ))
 6902            .on_action(cx.listener(
 6903                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6904                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6905                },
 6906            ))
 6907            .on_action(cx.listener(
 6908                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6909                    if !workspace.close_active_dock(window, cx) {
 6910                        cx.propagate();
 6911                    }
 6912                },
 6913            ))
 6914            .on_action(
 6915                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6916                    workspace.close_all_docks(window, cx);
 6917                }),
 6918            )
 6919            .on_action(cx.listener(Self::toggle_all_docks))
 6920            .on_action(cx.listener(
 6921                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6922                    workspace.clear_all_notifications(cx);
 6923                },
 6924            ))
 6925            .on_action(cx.listener(
 6926                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6927                    workspace.clear_navigation_history(window, cx);
 6928                },
 6929            ))
 6930            .on_action(cx.listener(
 6931                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6932                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6933                        workspace.suppress_notification(&notification_id, cx);
 6934                    }
 6935                },
 6936            ))
 6937            .on_action(cx.listener(
 6938                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6939                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6940                },
 6941            ))
 6942            .on_action(
 6943                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6944                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6945                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6946                            trusted_worktrees.clear_trusted_paths()
 6947                        });
 6948                        let db = WorkspaceDb::global(cx);
 6949                        cx.spawn(async move |_, cx| {
 6950                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6951                                cx.update(|cx| reload(cx));
 6952                            }
 6953                        })
 6954                        .detach();
 6955                    }
 6956                }),
 6957            )
 6958            .on_action(cx.listener(
 6959                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6960                    workspace.reopen_closed_item(window, cx).detach();
 6961                },
 6962            ))
 6963            .on_action(cx.listener(
 6964                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6965                    for dock in workspace.all_docks() {
 6966                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6967                            let panel = dock.read(cx).active_panel().cloned();
 6968                            if let Some(panel) = panel {
 6969                                dock.update(cx, |dock, cx| {
 6970                                    dock.set_panel_size_state(
 6971                                        panel.as_ref(),
 6972                                        dock::PanelSizeState::default(),
 6973                                        cx,
 6974                                    );
 6975                                });
 6976                            }
 6977                            return;
 6978                        }
 6979                    }
 6980                },
 6981            ))
 6982            .on_action(cx.listener(
 6983                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 6984                    for dock in workspace.all_docks() {
 6985                        let panel = dock.read(cx).visible_panel().cloned();
 6986                        if let Some(panel) = panel {
 6987                            dock.update(cx, |dock, cx| {
 6988                                dock.set_panel_size_state(
 6989                                    panel.as_ref(),
 6990                                    dock::PanelSizeState::default(),
 6991                                    cx,
 6992                                );
 6993                            });
 6994                        }
 6995                    }
 6996                },
 6997            ))
 6998            .on_action(cx.listener(
 6999                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7000                    adjust_active_dock_size_by_px(
 7001                        px_with_ui_font_fallback(act.px, cx),
 7002                        workspace,
 7003                        window,
 7004                        cx,
 7005                    );
 7006                },
 7007            ))
 7008            .on_action(cx.listener(
 7009                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7010                    adjust_active_dock_size_by_px(
 7011                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7012                        workspace,
 7013                        window,
 7014                        cx,
 7015                    );
 7016                },
 7017            ))
 7018            .on_action(cx.listener(
 7019                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7020                    adjust_open_docks_size_by_px(
 7021                        px_with_ui_font_fallback(act.px, cx),
 7022                        workspace,
 7023                        window,
 7024                        cx,
 7025                    );
 7026                },
 7027            ))
 7028            .on_action(cx.listener(
 7029                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7030                    adjust_open_docks_size_by_px(
 7031                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7032                        workspace,
 7033                        window,
 7034                        cx,
 7035                    );
 7036                },
 7037            ))
 7038            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7039            .on_action(cx.listener(
 7040                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, 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 next_index = if current_index + 1 < items_len {
 7063                                                current_index + 1
 7064                                            } else {
 7065                                                0
 7066                                            };
 7067                                            pane.activate_item(
 7068                                                next_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::ActivatePreviousItem, 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 mut recent_pane: Option<Entity<Pane>> = None;
 7087                                let mut recent_timestamp = 0;
 7088                                for pane_handle in workspace.panes() {
 7089                                    let pane = pane_handle.read(cx);
 7090                                    for entry in pane.activation_history() {
 7091                                        if entry.timestamp > recent_timestamp {
 7092                                            recent_timestamp = entry.timestamp;
 7093                                            recent_pane = Some(pane_handle.clone());
 7094                                        }
 7095                                    }
 7096                                }
 7097
 7098                                if let Some(pane) = recent_pane {
 7099                                    pane.update(cx, |pane, cx| {
 7100                                        let current_index = pane.active_item_index();
 7101                                        let items_len = pane.items_len();
 7102                                        if items_len > 0 {
 7103                                            let prev_index = if current_index > 0 {
 7104                                                current_index - 1
 7105                                            } else {
 7106                                                items_len.saturating_sub(1)
 7107                                            };
 7108                                            pane.activate_item(
 7109                                                prev_index, false, false, window, cx,
 7110                                            );
 7111                                        }
 7112                                    });
 7113                                    return;
 7114                                }
 7115                            }
 7116                        }
 7117                    }
 7118                    cx.propagate();
 7119                },
 7120            ))
 7121            .on_action(cx.listener(
 7122                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7123                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7124                        let dock = active_dock.read(cx);
 7125                        if let Some(active_panel) = dock.active_panel() {
 7126                            if active_panel.pane(cx).is_none() {
 7127                                let active_pane = workspace.active_pane().clone();
 7128                                active_pane.update(cx, |pane, cx| {
 7129                                    pane.close_active_item(action, window, cx)
 7130                                        .detach_and_log_err(cx);
 7131                                });
 7132                                return;
 7133                            }
 7134                        }
 7135                    }
 7136                    cx.propagate();
 7137                },
 7138            ))
 7139            .on_action(
 7140                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7141                    let pane = workspace.active_pane().clone();
 7142                    if let Some(item) = pane.read(cx).active_item() {
 7143                        item.toggle_read_only(window, cx);
 7144                    }
 7145                }),
 7146            )
 7147            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7148                workspace.focus_center_pane(window, cx);
 7149            }))
 7150            .on_action(cx.listener(Workspace::cancel))
 7151    }
 7152
 7153    #[cfg(any(test, feature = "test-support"))]
 7154    pub fn set_random_database_id(&mut self) {
 7155        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7156    }
 7157
 7158    #[cfg(any(test, feature = "test-support"))]
 7159    pub(crate) fn test_new(
 7160        project: Entity<Project>,
 7161        window: &mut Window,
 7162        cx: &mut Context<Self>,
 7163    ) -> Self {
 7164        use node_runtime::NodeRuntime;
 7165        use session::Session;
 7166
 7167        let client = project.read(cx).client();
 7168        let user_store = project.read(cx).user_store();
 7169        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7170        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7171        window.activate_window();
 7172        let app_state = Arc::new(AppState {
 7173            languages: project.read(cx).languages().clone(),
 7174            workspace_store,
 7175            client,
 7176            user_store,
 7177            fs: project.read(cx).fs().clone(),
 7178            build_window_options: |_, _| Default::default(),
 7179            node_runtime: NodeRuntime::unavailable(),
 7180            session,
 7181        });
 7182        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7183        workspace
 7184            .active_pane
 7185            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7186        workspace
 7187    }
 7188
 7189    pub fn register_action<A: Action>(
 7190        &mut self,
 7191        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7192    ) -> &mut Self {
 7193        let callback = Arc::new(callback);
 7194
 7195        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7196            let callback = callback.clone();
 7197            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7198                (callback)(workspace, event, window, cx)
 7199            }))
 7200        }));
 7201        self
 7202    }
 7203    pub fn register_action_renderer(
 7204        &mut self,
 7205        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7206    ) -> &mut Self {
 7207        self.workspace_actions.push(Box::new(callback));
 7208        self
 7209    }
 7210
 7211    fn add_workspace_actions_listeners(
 7212        &self,
 7213        mut div: Div,
 7214        window: &mut Window,
 7215        cx: &mut Context<Self>,
 7216    ) -> Div {
 7217        for action in self.workspace_actions.iter() {
 7218            div = (action)(div, self, window, cx)
 7219        }
 7220        div
 7221    }
 7222
 7223    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7224        self.modal_layer.read(cx).has_active_modal()
 7225    }
 7226
 7227    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7228        self.modal_layer
 7229            .read(cx)
 7230            .is_active_modal_command_palette(cx)
 7231    }
 7232
 7233    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7234        self.modal_layer.read(cx).active_modal()
 7235    }
 7236
 7237    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7238    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7239    /// If no modal is active, the new modal will be shown.
 7240    ///
 7241    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7242    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7243    /// will not be shown.
 7244    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7245    where
 7246        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7247    {
 7248        self.modal_layer.update(cx, |modal_layer, cx| {
 7249            modal_layer.toggle_modal(window, cx, build)
 7250        })
 7251    }
 7252
 7253    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7254        self.modal_layer
 7255            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7256    }
 7257
 7258    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7259        self.toast_layer
 7260            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7261    }
 7262
 7263    pub fn toggle_centered_layout(
 7264        &mut self,
 7265        _: &ToggleCenteredLayout,
 7266        _: &mut Window,
 7267        cx: &mut Context<Self>,
 7268    ) {
 7269        self.centered_layout = !self.centered_layout;
 7270        if let Some(database_id) = self.database_id() {
 7271            let db = WorkspaceDb::global(cx);
 7272            let centered_layout = self.centered_layout;
 7273            cx.background_spawn(async move {
 7274                db.set_centered_layout(database_id, centered_layout).await
 7275            })
 7276            .detach_and_log_err(cx);
 7277        }
 7278        cx.notify();
 7279    }
 7280
 7281    fn adjust_padding(padding: Option<f32>) -> f32 {
 7282        padding
 7283            .unwrap_or(CenteredPaddingSettings::default().0)
 7284            .clamp(
 7285                CenteredPaddingSettings::MIN_PADDING,
 7286                CenteredPaddingSettings::MAX_PADDING,
 7287            )
 7288    }
 7289
 7290    fn render_dock(
 7291        &self,
 7292        position: DockPosition,
 7293        dock: &Entity<Dock>,
 7294        window: &mut Window,
 7295        cx: &mut App,
 7296    ) -> Option<Div> {
 7297        if self.zoomed_position == Some(position) {
 7298            return None;
 7299        }
 7300
 7301        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7302            let pane = panel.pane(cx)?;
 7303            let follower_states = &self.follower_states;
 7304            leader_border_for_pane(follower_states, &pane, window, cx)
 7305        });
 7306
 7307        let mut container = div()
 7308            .flex()
 7309            .overflow_hidden()
 7310            .flex_none()
 7311            .child(dock.clone())
 7312            .children(leader_border);
 7313
 7314        // Apply sizing only when the dock is open. When closed the dock is still
 7315        // included in the element tree so its focus handle remains mounted — without
 7316        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7317        let dock = dock.read(cx);
 7318        if let Some(panel) = dock.visible_panel() {
 7319            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7320            if position.axis() == Axis::Horizontal {
 7321                let use_flexible = panel.has_flexible_size(window, cx);
 7322                let flex_grow = if use_flexible {
 7323                    size_state
 7324                        .and_then(|state| state.flex)
 7325                        .or_else(|| self.default_dock_flex(position))
 7326                } else {
 7327                    None
 7328                };
 7329                if let Some(grow) = flex_grow {
 7330                    let grow = grow.max(0.001);
 7331                    let style = container.style();
 7332                    style.flex_grow = Some(grow);
 7333                    style.flex_shrink = Some(1.0);
 7334                    style.flex_basis = Some(relative(0.).into());
 7335                } else {
 7336                    let size = size_state
 7337                        .and_then(|state| state.size)
 7338                        .unwrap_or_else(|| panel.default_size(window, cx));
 7339                    container = container.w(size);
 7340                }
 7341            } else {
 7342                let size = size_state
 7343                    .and_then(|state| state.size)
 7344                    .unwrap_or_else(|| panel.default_size(window, cx));
 7345                container = container.h(size);
 7346            }
 7347        }
 7348
 7349        Some(container)
 7350    }
 7351
 7352    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7353        window
 7354            .root::<MultiWorkspace>()
 7355            .flatten()
 7356            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7357    }
 7358
 7359    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7360        self.zoomed.as_ref()
 7361    }
 7362
 7363    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7364        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7365            return;
 7366        };
 7367        let windows = cx.windows();
 7368        let next_window =
 7369            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7370                || {
 7371                    windows
 7372                        .iter()
 7373                        .cycle()
 7374                        .skip_while(|window| window.window_id() != current_window_id)
 7375                        .nth(1)
 7376                },
 7377            );
 7378
 7379        if let Some(window) = next_window {
 7380            window
 7381                .update(cx, |_, window, _| window.activate_window())
 7382                .ok();
 7383        }
 7384    }
 7385
 7386    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7387        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7388            return;
 7389        };
 7390        let windows = cx.windows();
 7391        let prev_window =
 7392            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7393                || {
 7394                    windows
 7395                        .iter()
 7396                        .rev()
 7397                        .cycle()
 7398                        .skip_while(|window| window.window_id() != current_window_id)
 7399                        .nth(1)
 7400                },
 7401            );
 7402
 7403        if let Some(window) = prev_window {
 7404            window
 7405                .update(cx, |_, window, _| window.activate_window())
 7406                .ok();
 7407        }
 7408    }
 7409
 7410    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7411        if cx.stop_active_drag(window) {
 7412        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7413            dismiss_app_notification(&notification_id, cx);
 7414        } else {
 7415            cx.propagate();
 7416        }
 7417    }
 7418
 7419    fn resize_dock(
 7420        &mut self,
 7421        dock_pos: DockPosition,
 7422        new_size: Pixels,
 7423        window: &mut Window,
 7424        cx: &mut Context<Self>,
 7425    ) {
 7426        match dock_pos {
 7427            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7428            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7429            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7430        }
 7431    }
 7432
 7433    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7434        let workspace_width = self.bounds.size.width;
 7435        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7436
 7437        self.right_dock.read_with(cx, |right_dock, cx| {
 7438            let right_dock_size = right_dock
 7439                .stored_active_panel_size(window, cx)
 7440                .unwrap_or(Pixels::ZERO);
 7441            if right_dock_size + size > workspace_width {
 7442                size = workspace_width - right_dock_size
 7443            }
 7444        });
 7445
 7446        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7447        self.left_dock.update(cx, |left_dock, cx| {
 7448            if WorkspaceSettings::get_global(cx)
 7449                .resize_all_panels_in_dock
 7450                .contains(&DockPosition::Left)
 7451            {
 7452                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7453            } else {
 7454                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7455            }
 7456        });
 7457    }
 7458
 7459    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7460        let workspace_width = self.bounds.size.width;
 7461        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7462        self.left_dock.read_with(cx, |left_dock, cx| {
 7463            let left_dock_size = left_dock
 7464                .stored_active_panel_size(window, cx)
 7465                .unwrap_or(Pixels::ZERO);
 7466            if left_dock_size + size > workspace_width {
 7467                size = workspace_width - left_dock_size
 7468            }
 7469        });
 7470        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7471        self.right_dock.update(cx, |right_dock, cx| {
 7472            if WorkspaceSettings::get_global(cx)
 7473                .resize_all_panels_in_dock
 7474                .contains(&DockPosition::Right)
 7475            {
 7476                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7477            } else {
 7478                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7479            }
 7480        });
 7481    }
 7482
 7483    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7484        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7485        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7486            if WorkspaceSettings::get_global(cx)
 7487                .resize_all_panels_in_dock
 7488                .contains(&DockPosition::Bottom)
 7489            {
 7490                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7491            } else {
 7492                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7493            }
 7494        });
 7495    }
 7496
 7497    fn toggle_edit_predictions_all_files(
 7498        &mut self,
 7499        _: &ToggleEditPrediction,
 7500        _window: &mut Window,
 7501        cx: &mut Context<Self>,
 7502    ) {
 7503        let fs = self.project().read(cx).fs().clone();
 7504        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7505        update_settings_file(fs, cx, move |file, _| {
 7506            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7507        });
 7508    }
 7509
 7510    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7511        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7512        let next_mode = match current_mode {
 7513            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7514                theme_settings::ThemeAppearanceMode::Dark
 7515            }
 7516            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7517                theme_settings::ThemeAppearanceMode::Light
 7518            }
 7519            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7520                match cx.theme().appearance() {
 7521                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7522                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7523                }
 7524            }
 7525        };
 7526
 7527        let fs = self.project().read(cx).fs().clone();
 7528        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7529            theme_settings::set_mode(settings, next_mode);
 7530        });
 7531    }
 7532
 7533    pub fn show_worktree_trust_security_modal(
 7534        &mut self,
 7535        toggle: bool,
 7536        window: &mut Window,
 7537        cx: &mut Context<Self>,
 7538    ) {
 7539        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7540            if toggle {
 7541                security_modal.update(cx, |security_modal, cx| {
 7542                    security_modal.dismiss(cx);
 7543                })
 7544            } else {
 7545                security_modal.update(cx, |security_modal, cx| {
 7546                    security_modal.refresh_restricted_paths(cx);
 7547                });
 7548            }
 7549        } else {
 7550            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7551                .map(|trusted_worktrees| {
 7552                    trusted_worktrees
 7553                        .read(cx)
 7554                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7555                })
 7556                .unwrap_or(false);
 7557            if has_restricted_worktrees {
 7558                let project = self.project().read(cx);
 7559                let remote_host = project
 7560                    .remote_connection_options(cx)
 7561                    .map(RemoteHostLocation::from);
 7562                let worktree_store = project.worktree_store().downgrade();
 7563                self.toggle_modal(window, cx, |_, cx| {
 7564                    SecurityModal::new(worktree_store, remote_host, cx)
 7565                });
 7566            }
 7567        }
 7568    }
 7569}
 7570
 7571pub trait AnyActiveCall {
 7572    fn entity(&self) -> AnyEntity;
 7573    fn is_in_room(&self, _: &App) -> bool;
 7574    fn room_id(&self, _: &App) -> Option<u64>;
 7575    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7576    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7577    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7578    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7579    fn is_sharing_project(&self, _: &App) -> bool;
 7580    fn has_remote_participants(&self, _: &App) -> bool;
 7581    fn local_participant_is_guest(&self, _: &App) -> bool;
 7582    fn client(&self, _: &App) -> Arc<Client>;
 7583    fn share_on_join(&self, _: &App) -> bool;
 7584    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7585    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7586    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7587    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7588    fn join_project(
 7589        &self,
 7590        _: u64,
 7591        _: Arc<LanguageRegistry>,
 7592        _: Arc<dyn Fs>,
 7593        _: &mut App,
 7594    ) -> Task<Result<Entity<Project>>>;
 7595    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7596    fn subscribe(
 7597        &self,
 7598        _: &mut Window,
 7599        _: &mut Context<Workspace>,
 7600        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7601    ) -> Subscription;
 7602    fn create_shared_screen(
 7603        &self,
 7604        _: PeerId,
 7605        _: &Entity<Pane>,
 7606        _: &mut Window,
 7607        _: &mut App,
 7608    ) -> Option<Entity<SharedScreen>>;
 7609}
 7610
 7611#[derive(Clone)]
 7612pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7613impl Global for GlobalAnyActiveCall {}
 7614
 7615impl GlobalAnyActiveCall {
 7616    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7617        cx.try_global()
 7618    }
 7619
 7620    pub(crate) fn global(cx: &App) -> &Self {
 7621        cx.global()
 7622    }
 7623}
 7624
 7625pub fn merge_conflict_notification_id() -> NotificationId {
 7626    struct MergeConflictNotification;
 7627    NotificationId::unique::<MergeConflictNotification>()
 7628}
 7629
 7630/// Workspace-local view of a remote participant's location.
 7631#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7632pub enum ParticipantLocation {
 7633    SharedProject { project_id: u64 },
 7634    UnsharedProject,
 7635    External,
 7636}
 7637
 7638impl ParticipantLocation {
 7639    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7640        match location
 7641            .and_then(|l| l.variant)
 7642            .context("participant location was not provided")?
 7643        {
 7644            proto::participant_location::Variant::SharedProject(project) => {
 7645                Ok(Self::SharedProject {
 7646                    project_id: project.id,
 7647                })
 7648            }
 7649            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7650            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7651        }
 7652    }
 7653}
 7654/// Workspace-local view of a remote collaborator's state.
 7655/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7656#[derive(Clone)]
 7657pub struct RemoteCollaborator {
 7658    pub user: Arc<User>,
 7659    pub peer_id: PeerId,
 7660    pub location: ParticipantLocation,
 7661    pub participant_index: ParticipantIndex,
 7662}
 7663
 7664pub enum ActiveCallEvent {
 7665    ParticipantLocationChanged { participant_id: PeerId },
 7666    RemoteVideoTracksChanged { participant_id: PeerId },
 7667}
 7668
 7669fn leader_border_for_pane(
 7670    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7671    pane: &Entity<Pane>,
 7672    _: &Window,
 7673    cx: &App,
 7674) -> Option<Div> {
 7675    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7676        if state.pane() == pane {
 7677            Some((*leader_id, state))
 7678        } else {
 7679            None
 7680        }
 7681    })?;
 7682
 7683    let mut leader_color = match leader_id {
 7684        CollaboratorId::PeerId(leader_peer_id) => {
 7685            let leader = GlobalAnyActiveCall::try_global(cx)?
 7686                .0
 7687                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7688
 7689            cx.theme()
 7690                .players()
 7691                .color_for_participant(leader.participant_index.0)
 7692                .cursor
 7693        }
 7694        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7695    };
 7696    leader_color.fade_out(0.3);
 7697    Some(
 7698        div()
 7699            .absolute()
 7700            .size_full()
 7701            .left_0()
 7702            .top_0()
 7703            .border_2()
 7704            .border_color(leader_color),
 7705    )
 7706}
 7707
 7708fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7709    ZED_WINDOW_POSITION
 7710        .zip(*ZED_WINDOW_SIZE)
 7711        .map(|(position, size)| Bounds {
 7712            origin: position,
 7713            size,
 7714        })
 7715}
 7716
 7717fn open_items(
 7718    serialized_workspace: Option<SerializedWorkspace>,
 7719    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7720    window: &mut Window,
 7721    cx: &mut Context<Workspace>,
 7722) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7723    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7724        Workspace::load_workspace(
 7725            serialized_workspace,
 7726            project_paths_to_open
 7727                .iter()
 7728                .map(|(_, project_path)| project_path)
 7729                .cloned()
 7730                .collect(),
 7731            window,
 7732            cx,
 7733        )
 7734    });
 7735
 7736    cx.spawn_in(window, async move |workspace, cx| {
 7737        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7738
 7739        if let Some(restored_items) = restored_items {
 7740            let restored_items = restored_items.await?;
 7741
 7742            let restored_project_paths = restored_items
 7743                .iter()
 7744                .filter_map(|item| {
 7745                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7746                        .ok()
 7747                        .flatten()
 7748                })
 7749                .collect::<HashSet<_>>();
 7750
 7751            for restored_item in restored_items {
 7752                opened_items.push(restored_item.map(Ok));
 7753            }
 7754
 7755            project_paths_to_open
 7756                .iter_mut()
 7757                .for_each(|(_, project_path)| {
 7758                    if let Some(project_path_to_open) = project_path
 7759                        && restored_project_paths.contains(project_path_to_open)
 7760                    {
 7761                        *project_path = None;
 7762                    }
 7763                });
 7764        } else {
 7765            for _ in 0..project_paths_to_open.len() {
 7766                opened_items.push(None);
 7767            }
 7768        }
 7769        assert!(opened_items.len() == project_paths_to_open.len());
 7770
 7771        let tasks =
 7772            project_paths_to_open
 7773                .into_iter()
 7774                .enumerate()
 7775                .map(|(ix, (abs_path, project_path))| {
 7776                    let workspace = workspace.clone();
 7777                    cx.spawn(async move |cx| {
 7778                        let file_project_path = project_path?;
 7779                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7780                            workspace.project().update(cx, |project, cx| {
 7781                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7782                            })
 7783                        });
 7784
 7785                        // We only want to open file paths here. If one of the items
 7786                        // here is a directory, it was already opened further above
 7787                        // with a `find_or_create_worktree`.
 7788                        if let Ok(task) = abs_path_task
 7789                            && task.await.is_none_or(|p| p.is_file())
 7790                        {
 7791                            return Some((
 7792                                ix,
 7793                                workspace
 7794                                    .update_in(cx, |workspace, window, cx| {
 7795                                        workspace.open_path(
 7796                                            file_project_path,
 7797                                            None,
 7798                                            true,
 7799                                            window,
 7800                                            cx,
 7801                                        )
 7802                                    })
 7803                                    .log_err()?
 7804                                    .await,
 7805                            ));
 7806                        }
 7807                        None
 7808                    })
 7809                });
 7810
 7811        let tasks = tasks.collect::<Vec<_>>();
 7812
 7813        let tasks = futures::future::join_all(tasks);
 7814        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7815            opened_items[ix] = Some(path_open_result);
 7816        }
 7817
 7818        Ok(opened_items)
 7819    })
 7820}
 7821
 7822#[derive(Clone)]
 7823enum ActivateInDirectionTarget {
 7824    Pane(Entity<Pane>),
 7825    Dock(Entity<Dock>),
 7826    Sidebar(FocusHandle),
 7827}
 7828
 7829fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7830    window
 7831        .update(cx, |multi_workspace, _, cx| {
 7832            let workspace = multi_workspace.workspace().clone();
 7833            workspace.update(cx, |workspace, cx| {
 7834                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7835                    struct DatabaseFailedNotification;
 7836
 7837                    workspace.show_notification(
 7838                        NotificationId::unique::<DatabaseFailedNotification>(),
 7839                        cx,
 7840                        |cx| {
 7841                            cx.new(|cx| {
 7842                                MessageNotification::new("Failed to load the database file.", cx)
 7843                                    .primary_message("File an Issue")
 7844                                    .primary_icon(IconName::Plus)
 7845                                    .primary_on_click(|window, cx| {
 7846                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7847                                    })
 7848                            })
 7849                        },
 7850                    );
 7851                }
 7852            });
 7853        })
 7854        .log_err();
 7855}
 7856
 7857fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7858    if val == 0 {
 7859        ThemeSettings::get_global(cx).ui_font_size(cx)
 7860    } else {
 7861        px(val as f32)
 7862    }
 7863}
 7864
 7865fn adjust_active_dock_size_by_px(
 7866    px: Pixels,
 7867    workspace: &mut Workspace,
 7868    window: &mut Window,
 7869    cx: &mut Context<Workspace>,
 7870) {
 7871    let Some(active_dock) = workspace
 7872        .all_docks()
 7873        .into_iter()
 7874        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7875    else {
 7876        return;
 7877    };
 7878    let dock = active_dock.read(cx);
 7879    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7880        return;
 7881    };
 7882    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7883}
 7884
 7885fn adjust_open_docks_size_by_px(
 7886    px: Pixels,
 7887    workspace: &mut Workspace,
 7888    window: &mut Window,
 7889    cx: &mut Context<Workspace>,
 7890) {
 7891    let docks = workspace
 7892        .all_docks()
 7893        .into_iter()
 7894        .filter_map(|dock_entity| {
 7895            let dock = dock_entity.read(cx);
 7896            if dock.is_open() {
 7897                let dock_pos = dock.position();
 7898                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7899                Some((dock_pos, panel_size + px))
 7900            } else {
 7901                None
 7902            }
 7903        })
 7904        .collect::<Vec<_>>();
 7905
 7906    for (position, new_size) in docks {
 7907        workspace.resize_dock(position, new_size, window, cx);
 7908    }
 7909}
 7910
 7911impl Focusable for Workspace {
 7912    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7913        self.active_pane.focus_handle(cx)
 7914    }
 7915}
 7916
 7917#[derive(Clone)]
 7918struct DraggedDock(DockPosition);
 7919
 7920impl Render for DraggedDock {
 7921    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7922        gpui::Empty
 7923    }
 7924}
 7925
 7926impl Render for Workspace {
 7927    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7928        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7929        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7930            log::info!("Rendered first frame");
 7931        }
 7932
 7933        let centered_layout = self.centered_layout
 7934            && self.center.panes().len() == 1
 7935            && self.active_item(cx).is_some();
 7936        let render_padding = |size| {
 7937            (size > 0.0).then(|| {
 7938                div()
 7939                    .h_full()
 7940                    .w(relative(size))
 7941                    .bg(cx.theme().colors().editor_background)
 7942                    .border_color(cx.theme().colors().pane_group_border)
 7943            })
 7944        };
 7945        let paddings = if centered_layout {
 7946            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7947            (
 7948                render_padding(Self::adjust_padding(
 7949                    settings.left_padding.map(|padding| padding.0),
 7950                )),
 7951                render_padding(Self::adjust_padding(
 7952                    settings.right_padding.map(|padding| padding.0),
 7953                )),
 7954            )
 7955        } else {
 7956            (None, None)
 7957        };
 7958        let ui_font = theme_settings::setup_ui_font(window, cx);
 7959
 7960        let theme = cx.theme().clone();
 7961        let colors = theme.colors();
 7962        let notification_entities = self
 7963            .notifications
 7964            .iter()
 7965            .map(|(_, notification)| notification.entity_id())
 7966            .collect::<Vec<_>>();
 7967        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7968
 7969        div()
 7970            .relative()
 7971            .size_full()
 7972            .flex()
 7973            .flex_col()
 7974            .font(ui_font)
 7975            .gap_0()
 7976                .justify_start()
 7977                .items_start()
 7978                .text_color(colors.text)
 7979                .overflow_hidden()
 7980                .children(self.titlebar_item.clone())
 7981                .on_modifiers_changed(move |_, _, cx| {
 7982                    for &id in &notification_entities {
 7983                        cx.notify(id);
 7984                    }
 7985                })
 7986                .child(
 7987                    div()
 7988                        .size_full()
 7989                        .relative()
 7990                        .flex_1()
 7991                        .flex()
 7992                        .flex_col()
 7993                        .child(
 7994                            div()
 7995                                .id("workspace")
 7996                                .bg(colors.background)
 7997                                .relative()
 7998                                .flex_1()
 7999                                .w_full()
 8000                                .flex()
 8001                                .flex_col()
 8002                                .overflow_hidden()
 8003                                .border_t_1()
 8004                                .border_b_1()
 8005                                .border_color(colors.border)
 8006                                .child({
 8007                                    let this = cx.entity();
 8008                                    canvas(
 8009                                        move |bounds, window, cx| {
 8010                                            this.update(cx, |this, cx| {
 8011                                                let bounds_changed = this.bounds != bounds;
 8012                                                this.bounds = bounds;
 8013
 8014                                                if bounds_changed {
 8015                                                    this.left_dock.update(cx, |dock, cx| {
 8016                                                        dock.clamp_panel_size(
 8017                                                            bounds.size.width,
 8018                                                            window,
 8019                                                            cx,
 8020                                                        )
 8021                                                    });
 8022
 8023                                                    this.right_dock.update(cx, |dock, cx| {
 8024                                                        dock.clamp_panel_size(
 8025                                                            bounds.size.width,
 8026                                                            window,
 8027                                                            cx,
 8028                                                        )
 8029                                                    });
 8030
 8031                                                    this.bottom_dock.update(cx, |dock, cx| {
 8032                                                        dock.clamp_panel_size(
 8033                                                            bounds.size.height,
 8034                                                            window,
 8035                                                            cx,
 8036                                                        )
 8037                                                    });
 8038                                                }
 8039                                            })
 8040                                        },
 8041                                        |_, _, _, _| {},
 8042                                    )
 8043                                    .absolute()
 8044                                    .size_full()
 8045                                })
 8046                                .when(self.zoomed.is_none(), |this| {
 8047                                    this.on_drag_move(cx.listener(
 8048                                        move |workspace,
 8049                                              e: &DragMoveEvent<DraggedDock>,
 8050                                              window,
 8051                                              cx| {
 8052                                            if workspace.previous_dock_drag_coordinates
 8053                                                != Some(e.event.position)
 8054                                            {
 8055                                                workspace.previous_dock_drag_coordinates =
 8056                                                    Some(e.event.position);
 8057
 8058                                                match e.drag(cx).0 {
 8059                                                    DockPosition::Left => {
 8060                                                        workspace.resize_left_dock(
 8061                                                            e.event.position.x
 8062                                                                - workspace.bounds.left(),
 8063                                                            window,
 8064                                                            cx,
 8065                                                        );
 8066                                                    }
 8067                                                    DockPosition::Right => {
 8068                                                        workspace.resize_right_dock(
 8069                                                            workspace.bounds.right()
 8070                                                                - e.event.position.x,
 8071                                                            window,
 8072                                                            cx,
 8073                                                        );
 8074                                                    }
 8075                                                    DockPosition::Bottom => {
 8076                                                        workspace.resize_bottom_dock(
 8077                                                            workspace.bounds.bottom()
 8078                                                                - e.event.position.y,
 8079                                                            window,
 8080                                                            cx,
 8081                                                        );
 8082                                                    }
 8083                                                };
 8084                                                workspace.serialize_workspace(window, cx);
 8085                                            }
 8086                                        },
 8087                                    ))
 8088
 8089                                })
 8090                                .child({
 8091                                    match bottom_dock_layout {
 8092                                        BottomDockLayout::Full => div()
 8093                                            .flex()
 8094                                            .flex_col()
 8095                                            .h_full()
 8096                                            .child(
 8097                                                div()
 8098                                                    .flex()
 8099                                                    .flex_row()
 8100                                                    .flex_1()
 8101                                                    .overflow_hidden()
 8102                                                    .children(self.render_dock(
 8103                                                        DockPosition::Left,
 8104                                                        &self.left_dock,
 8105                                                        window,
 8106                                                        cx,
 8107                                                    ))
 8108
 8109                                                    .child(
 8110                                                        div()
 8111                                                            .flex()
 8112                                                            .flex_col()
 8113                                                            .flex_1()
 8114                                                            .overflow_hidden()
 8115                                                            .child(
 8116                                                                h_flex()
 8117                                                                    .flex_1()
 8118                                                                    .when_some(
 8119                                                                        paddings.0,
 8120                                                                        |this, p| {
 8121                                                                            this.child(
 8122                                                                                p.border_r_1(),
 8123                                                                            )
 8124                                                                        },
 8125                                                                    )
 8126                                                                    .child(self.center.render(
 8127                                                                        self.zoomed.as_ref(),
 8128                                                                        &PaneRenderContext {
 8129                                                                            follower_states:
 8130                                                                                &self.follower_states,
 8131                                                                            active_call: self.active_call(),
 8132                                                                            active_pane: &self.active_pane,
 8133                                                                            app_state: &self.app_state,
 8134                                                                            project: &self.project,
 8135                                                                            workspace: &self.weak_self,
 8136                                                                        },
 8137                                                                        window,
 8138                                                                        cx,
 8139                                                                    ))
 8140                                                                    .when_some(
 8141                                                                        paddings.1,
 8142                                                                        |this, p| {
 8143                                                                            this.child(
 8144                                                                                p.border_l_1(),
 8145                                                                            )
 8146                                                                        },
 8147                                                                    ),
 8148                                                            ),
 8149                                                    )
 8150
 8151                                                    .children(self.render_dock(
 8152                                                        DockPosition::Right,
 8153                                                        &self.right_dock,
 8154                                                        window,
 8155                                                        cx,
 8156                                                    )),
 8157                                            )
 8158                                            .child(div().w_full().children(self.render_dock(
 8159                                                DockPosition::Bottom,
 8160                                                &self.bottom_dock,
 8161                                                window,
 8162                                                cx
 8163                                            ))),
 8164
 8165                                        BottomDockLayout::LeftAligned => div()
 8166                                            .flex()
 8167                                            .flex_row()
 8168                                            .h_full()
 8169                                            .child(
 8170                                                div()
 8171                                                    .flex()
 8172                                                    .flex_col()
 8173                                                    .flex_1()
 8174                                                    .h_full()
 8175                                                    .child(
 8176                                                        div()
 8177                                                            .flex()
 8178                                                            .flex_row()
 8179                                                            .flex_1()
 8180                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8181
 8182                                                            .child(
 8183                                                                div()
 8184                                                                    .flex()
 8185                                                                    .flex_col()
 8186                                                                    .flex_1()
 8187                                                                    .overflow_hidden()
 8188                                                                    .child(
 8189                                                                        h_flex()
 8190                                                                            .flex_1()
 8191                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8192                                                                            .child(self.center.render(
 8193                                                                                self.zoomed.as_ref(),
 8194                                                                                &PaneRenderContext {
 8195                                                                                    follower_states:
 8196                                                                                        &self.follower_states,
 8197                                                                                    active_call: self.active_call(),
 8198                                                                                    active_pane: &self.active_pane,
 8199                                                                                    app_state: &self.app_state,
 8200                                                                                    project: &self.project,
 8201                                                                                    workspace: &self.weak_self,
 8202                                                                                },
 8203                                                                                window,
 8204                                                                                cx,
 8205                                                                            ))
 8206                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8207                                                                    )
 8208                                                            )
 8209
 8210                                                    )
 8211                                                    .child(
 8212                                                        div()
 8213                                                            .w_full()
 8214                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8215                                                    ),
 8216                                            )
 8217                                            .children(self.render_dock(
 8218                                                DockPosition::Right,
 8219                                                &self.right_dock,
 8220                                                window,
 8221                                                cx,
 8222                                            )),
 8223                                        BottomDockLayout::RightAligned => div()
 8224                                            .flex()
 8225                                            .flex_row()
 8226                                            .h_full()
 8227                                            .children(self.render_dock(
 8228                                                DockPosition::Left,
 8229                                                &self.left_dock,
 8230                                                window,
 8231                                                cx,
 8232                                            ))
 8233
 8234                                            .child(
 8235                                                div()
 8236                                                    .flex()
 8237                                                    .flex_col()
 8238                                                    .flex_1()
 8239                                                    .h_full()
 8240                                                    .child(
 8241                                                        div()
 8242                                                            .flex()
 8243                                                            .flex_row()
 8244                                                            .flex_1()
 8245                                                            .child(
 8246                                                                div()
 8247                                                                    .flex()
 8248                                                                    .flex_col()
 8249                                                                    .flex_1()
 8250                                                                    .overflow_hidden()
 8251                                                                    .child(
 8252                                                                        h_flex()
 8253                                                                            .flex_1()
 8254                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8255                                                                            .child(self.center.render(
 8256                                                                                self.zoomed.as_ref(),
 8257                                                                                &PaneRenderContext {
 8258                                                                                    follower_states:
 8259                                                                                        &self.follower_states,
 8260                                                                                    active_call: self.active_call(),
 8261                                                                                    active_pane: &self.active_pane,
 8262                                                                                    app_state: &self.app_state,
 8263                                                                                    project: &self.project,
 8264                                                                                    workspace: &self.weak_self,
 8265                                                                                },
 8266                                                                                window,
 8267                                                                                cx,
 8268                                                                            ))
 8269                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8270                                                                    )
 8271                                                            )
 8272
 8273                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8274                                                    )
 8275                                                    .child(
 8276                                                        div()
 8277                                                            .w_full()
 8278                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8279                                                    ),
 8280                                            ),
 8281                                        BottomDockLayout::Contained => div()
 8282                                            .flex()
 8283                                            .flex_row()
 8284                                            .h_full()
 8285                                            .children(self.render_dock(
 8286                                                DockPosition::Left,
 8287                                                &self.left_dock,
 8288                                                window,
 8289                                                cx,
 8290                                            ))
 8291
 8292                                            .child(
 8293                                                div()
 8294                                                    .flex()
 8295                                                    .flex_col()
 8296                                                    .flex_1()
 8297                                                    .overflow_hidden()
 8298                                                    .child(
 8299                                                        h_flex()
 8300                                                            .flex_1()
 8301                                                            .when_some(paddings.0, |this, p| {
 8302                                                                this.child(p.border_r_1())
 8303                                                            })
 8304                                                            .child(self.center.render(
 8305                                                                self.zoomed.as_ref(),
 8306                                                                &PaneRenderContext {
 8307                                                                    follower_states:
 8308                                                                        &self.follower_states,
 8309                                                                    active_call: self.active_call(),
 8310                                                                    active_pane: &self.active_pane,
 8311                                                                    app_state: &self.app_state,
 8312                                                                    project: &self.project,
 8313                                                                    workspace: &self.weak_self,
 8314                                                                },
 8315                                                                window,
 8316                                                                cx,
 8317                                                            ))
 8318                                                            .when_some(paddings.1, |this, p| {
 8319                                                                this.child(p.border_l_1())
 8320                                                            }),
 8321                                                    )
 8322                                                    .children(self.render_dock(
 8323                                                        DockPosition::Bottom,
 8324                                                        &self.bottom_dock,
 8325                                                        window,
 8326                                                        cx,
 8327                                                    )),
 8328                                            )
 8329
 8330                                            .children(self.render_dock(
 8331                                                DockPosition::Right,
 8332                                                &self.right_dock,
 8333                                                window,
 8334                                                cx,
 8335                                            )),
 8336                                    }
 8337                                })
 8338                                .children(self.zoomed.as_ref().and_then(|view| {
 8339                                    let zoomed_view = view.upgrade()?;
 8340                                    let div = div()
 8341                                        .occlude()
 8342                                        .absolute()
 8343                                        .overflow_hidden()
 8344                                        .border_color(colors.border)
 8345                                        .bg(colors.background)
 8346                                        .child(zoomed_view)
 8347                                        .inset_0()
 8348                                        .shadow_lg();
 8349
 8350                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8351                                       return Some(div);
 8352                                    }
 8353
 8354                                    Some(match self.zoomed_position {
 8355                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8356                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8357                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8358                                        None => {
 8359                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8360                                        }
 8361                                    })
 8362                                }))
 8363                                .children(self.render_notifications(window, cx)),
 8364                        )
 8365                        .when(self.status_bar_visible(cx), |parent| {
 8366                            parent.child(self.status_bar.clone())
 8367                        })
 8368                        .child(self.toast_layer.clone()),
 8369                )
 8370    }
 8371}
 8372
 8373impl WorkspaceStore {
 8374    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8375        Self {
 8376            workspaces: Default::default(),
 8377            _subscriptions: vec![
 8378                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8379                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8380            ],
 8381            client,
 8382        }
 8383    }
 8384
 8385    pub fn update_followers(
 8386        &self,
 8387        project_id: Option<u64>,
 8388        update: proto::update_followers::Variant,
 8389        cx: &App,
 8390    ) -> Option<()> {
 8391        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8392        let room_id = active_call.0.room_id(cx)?;
 8393        self.client
 8394            .send(proto::UpdateFollowers {
 8395                room_id,
 8396                project_id,
 8397                variant: Some(update),
 8398            })
 8399            .log_err()
 8400    }
 8401
 8402    pub async fn handle_follow(
 8403        this: Entity<Self>,
 8404        envelope: TypedEnvelope<proto::Follow>,
 8405        mut cx: AsyncApp,
 8406    ) -> Result<proto::FollowResponse> {
 8407        this.update(&mut cx, |this, cx| {
 8408            let follower = Follower {
 8409                project_id: envelope.payload.project_id,
 8410                peer_id: envelope.original_sender_id()?,
 8411            };
 8412
 8413            let mut response = proto::FollowResponse::default();
 8414
 8415            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8416                let Some(workspace) = weak_workspace.upgrade() else {
 8417                    return false;
 8418                };
 8419                window_handle
 8420                    .update(cx, |_, window, cx| {
 8421                        workspace.update(cx, |workspace, cx| {
 8422                            let handler_response =
 8423                                workspace.handle_follow(follower.project_id, window, cx);
 8424                            if let Some(active_view) = handler_response.active_view
 8425                                && workspace.project.read(cx).remote_id() == follower.project_id
 8426                            {
 8427                                response.active_view = Some(active_view)
 8428                            }
 8429                        });
 8430                    })
 8431                    .is_ok()
 8432            });
 8433
 8434            Ok(response)
 8435        })
 8436    }
 8437
 8438    async fn handle_update_followers(
 8439        this: Entity<Self>,
 8440        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8441        mut cx: AsyncApp,
 8442    ) -> Result<()> {
 8443        let leader_id = envelope.original_sender_id()?;
 8444        let update = envelope.payload;
 8445
 8446        this.update(&mut cx, |this, cx| {
 8447            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8448                let Some(workspace) = weak_workspace.upgrade() else {
 8449                    return false;
 8450                };
 8451                window_handle
 8452                    .update(cx, |_, window, cx| {
 8453                        workspace.update(cx, |workspace, cx| {
 8454                            let project_id = workspace.project.read(cx).remote_id();
 8455                            if update.project_id != project_id && update.project_id.is_some() {
 8456                                return;
 8457                            }
 8458                            workspace.handle_update_followers(
 8459                                leader_id,
 8460                                update.clone(),
 8461                                window,
 8462                                cx,
 8463                            );
 8464                        });
 8465                    })
 8466                    .is_ok()
 8467            });
 8468            Ok(())
 8469        })
 8470    }
 8471
 8472    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8473        self.workspaces.iter().map(|(_, weak)| weak)
 8474    }
 8475
 8476    pub fn workspaces_with_windows(
 8477        &self,
 8478    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8479        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8480    }
 8481}
 8482
 8483impl ViewId {
 8484    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8485        Ok(Self {
 8486            creator: message
 8487                .creator
 8488                .map(CollaboratorId::PeerId)
 8489                .context("creator is missing")?,
 8490            id: message.id,
 8491        })
 8492    }
 8493
 8494    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8495        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8496            Some(proto::ViewId {
 8497                creator: Some(peer_id),
 8498                id: self.id,
 8499            })
 8500        } else {
 8501            None
 8502        }
 8503    }
 8504}
 8505
 8506impl FollowerState {
 8507    fn pane(&self) -> &Entity<Pane> {
 8508        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8509    }
 8510}
 8511
 8512pub trait WorkspaceHandle {
 8513    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8514}
 8515
 8516impl WorkspaceHandle for Entity<Workspace> {
 8517    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8518        self.read(cx)
 8519            .worktrees(cx)
 8520            .flat_map(|worktree| {
 8521                let worktree_id = worktree.read(cx).id();
 8522                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8523                    worktree_id,
 8524                    path: f.path.clone(),
 8525                })
 8526            })
 8527            .collect::<Vec<_>>()
 8528    }
 8529}
 8530
 8531pub async fn last_opened_workspace_location(
 8532    db: &WorkspaceDb,
 8533    fs: &dyn fs::Fs,
 8534) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8535    db.last_workspace(fs)
 8536        .await
 8537        .log_err()
 8538        .flatten()
 8539        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8540}
 8541
 8542pub async fn last_session_workspace_locations(
 8543    db: &WorkspaceDb,
 8544    last_session_id: &str,
 8545    last_session_window_stack: Option<Vec<WindowId>>,
 8546    fs: &dyn fs::Fs,
 8547) -> Option<Vec<SessionWorkspace>> {
 8548    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8549        .await
 8550        .log_err()
 8551}
 8552
 8553pub struct MultiWorkspaceRestoreResult {
 8554    pub window_handle: WindowHandle<MultiWorkspace>,
 8555    pub errors: Vec<anyhow::Error>,
 8556}
 8557
 8558pub async fn restore_multiworkspace(
 8559    multi_workspace: SerializedMultiWorkspace,
 8560    app_state: Arc<AppState>,
 8561    cx: &mut AsyncApp,
 8562) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8563    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8564    let mut group_iter = workspaces.into_iter();
 8565    let first = group_iter
 8566        .next()
 8567        .context("window group must not be empty")?;
 8568
 8569    let window_handle = if first.paths.is_empty() {
 8570        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8571            .await?
 8572    } else {
 8573        let OpenResult { window, .. } = cx
 8574            .update(|cx| {
 8575                Workspace::new_local(
 8576                    first.paths.paths().to_vec(),
 8577                    app_state.clone(),
 8578                    None,
 8579                    None,
 8580                    None,
 8581                    true,
 8582                    cx,
 8583                )
 8584            })
 8585            .await?;
 8586        window
 8587    };
 8588
 8589    let mut errors = Vec::new();
 8590
 8591    for session_workspace in group_iter {
 8592        let error = if session_workspace.paths.is_empty() {
 8593            cx.update(|cx| {
 8594                open_workspace_by_id(
 8595                    session_workspace.workspace_id,
 8596                    app_state.clone(),
 8597                    Some(window_handle),
 8598                    cx,
 8599                )
 8600            })
 8601            .await
 8602            .err()
 8603        } else {
 8604            cx.update(|cx| {
 8605                Workspace::new_local(
 8606                    session_workspace.paths.paths().to_vec(),
 8607                    app_state.clone(),
 8608                    Some(window_handle),
 8609                    None,
 8610                    None,
 8611                    false,
 8612                    cx,
 8613                )
 8614            })
 8615            .await
 8616            .err()
 8617        };
 8618
 8619        if let Some(error) = error {
 8620            errors.push(error);
 8621        }
 8622    }
 8623
 8624    if let Some(target_id) = state.active_workspace_id {
 8625        window_handle
 8626            .update(cx, |multi_workspace, window, cx| {
 8627                let target_index = multi_workspace
 8628                    .workspaces()
 8629                    .iter()
 8630                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8631                if let Some(index) = target_index {
 8632                    multi_workspace.activate_index(index, window, cx);
 8633                } else if !multi_workspace.workspaces().is_empty() {
 8634                    multi_workspace.activate_index(0, window, cx);
 8635                }
 8636            })
 8637            .ok();
 8638    } else {
 8639        window_handle
 8640            .update(cx, |multi_workspace, window, cx| {
 8641                if !multi_workspace.workspaces().is_empty() {
 8642                    multi_workspace.activate_index(0, window, cx);
 8643                }
 8644            })
 8645            .ok();
 8646    }
 8647
 8648    if state.sidebar_open {
 8649        window_handle
 8650            .update(cx, |multi_workspace, _, cx| {
 8651                multi_workspace.open_sidebar(cx);
 8652            })
 8653            .ok();
 8654    }
 8655
 8656    window_handle
 8657        .update(cx, |_, window, _cx| {
 8658            window.activate_window();
 8659        })
 8660        .ok();
 8661
 8662    Ok(MultiWorkspaceRestoreResult {
 8663        window_handle,
 8664        errors,
 8665    })
 8666}
 8667
 8668actions!(
 8669    collab,
 8670    [
 8671        /// Opens the channel notes for the current call.
 8672        ///
 8673        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8674        /// channel in the collab panel.
 8675        ///
 8676        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8677        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8678        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8679        OpenChannelNotes,
 8680        /// Mutes your microphone.
 8681        Mute,
 8682        /// Deafens yourself (mute both microphone and speakers).
 8683        Deafen,
 8684        /// Leaves the current call.
 8685        LeaveCall,
 8686        /// Shares the current project with collaborators.
 8687        ShareProject,
 8688        /// Shares your screen with collaborators.
 8689        ScreenShare,
 8690        /// Copies the current room name and session id for debugging purposes.
 8691        CopyRoomId,
 8692    ]
 8693);
 8694
 8695/// Opens the channel notes for a specific channel by its ID.
 8696#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8697#[action(namespace = collab)]
 8698#[serde(deny_unknown_fields)]
 8699pub struct OpenChannelNotesById {
 8700    pub channel_id: u64,
 8701}
 8702
 8703actions!(
 8704    zed,
 8705    [
 8706        /// Opens the Zed log file.
 8707        OpenLog,
 8708        /// Reveals the Zed log file in the system file manager.
 8709        RevealLogInFileManager
 8710    ]
 8711);
 8712
 8713async fn join_channel_internal(
 8714    channel_id: ChannelId,
 8715    app_state: &Arc<AppState>,
 8716    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8717    requesting_workspace: Option<WeakEntity<Workspace>>,
 8718    active_call: &dyn AnyActiveCall,
 8719    cx: &mut AsyncApp,
 8720) -> Result<bool> {
 8721    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8722        if !active_call.is_in_room(cx) {
 8723            return (false, false);
 8724        }
 8725
 8726        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8727        let should_prompt = active_call.is_sharing_project(cx)
 8728            && active_call.has_remote_participants(cx)
 8729            && !already_in_channel;
 8730        (should_prompt, already_in_channel)
 8731    });
 8732
 8733    if already_in_channel {
 8734        let task = cx.update(|cx| {
 8735            if let Some((project, host)) = active_call.most_active_project(cx) {
 8736                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8737            } else {
 8738                None
 8739            }
 8740        });
 8741        if let Some(task) = task {
 8742            task.await?;
 8743        }
 8744        return anyhow::Ok(true);
 8745    }
 8746
 8747    if should_prompt {
 8748        if let Some(multi_workspace) = requesting_window {
 8749            let answer = multi_workspace
 8750                .update(cx, |_, window, cx| {
 8751                    window.prompt(
 8752                        PromptLevel::Warning,
 8753                        "Do you want to switch channels?",
 8754                        Some("Leaving this call will unshare your current project."),
 8755                        &["Yes, Join Channel", "Cancel"],
 8756                        cx,
 8757                    )
 8758                })?
 8759                .await;
 8760
 8761            if answer == Ok(1) {
 8762                return Ok(false);
 8763            }
 8764        } else {
 8765            return Ok(false);
 8766        }
 8767    }
 8768
 8769    let client = cx.update(|cx| active_call.client(cx));
 8770
 8771    let mut client_status = client.status();
 8772
 8773    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8774    'outer: loop {
 8775        let Some(status) = client_status.recv().await else {
 8776            anyhow::bail!("error connecting");
 8777        };
 8778
 8779        match status {
 8780            Status::Connecting
 8781            | Status::Authenticating
 8782            | Status::Authenticated
 8783            | Status::Reconnecting
 8784            | Status::Reauthenticating
 8785            | Status::Reauthenticated => continue,
 8786            Status::Connected { .. } => break 'outer,
 8787            Status::SignedOut | Status::AuthenticationError => {
 8788                return Err(ErrorCode::SignedOut.into());
 8789            }
 8790            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8791            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8792                return Err(ErrorCode::Disconnected.into());
 8793            }
 8794        }
 8795    }
 8796
 8797    let joined = cx
 8798        .update(|cx| active_call.join_channel(channel_id, cx))
 8799        .await?;
 8800
 8801    if !joined {
 8802        return anyhow::Ok(true);
 8803    }
 8804
 8805    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8806
 8807    let task = cx.update(|cx| {
 8808        if let Some((project, host)) = active_call.most_active_project(cx) {
 8809            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8810        }
 8811
 8812        // If you are the first to join a channel, see if you should share your project.
 8813        if !active_call.has_remote_participants(cx)
 8814            && !active_call.local_participant_is_guest(cx)
 8815            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8816        {
 8817            let project = workspace.update(cx, |workspace, cx| {
 8818                let project = workspace.project.read(cx);
 8819
 8820                if !active_call.share_on_join(cx) {
 8821                    return None;
 8822                }
 8823
 8824                if (project.is_local() || project.is_via_remote_server())
 8825                    && project.visible_worktrees(cx).any(|tree| {
 8826                        tree.read(cx)
 8827                            .root_entry()
 8828                            .is_some_and(|entry| entry.is_dir())
 8829                    })
 8830                {
 8831                    Some(workspace.project.clone())
 8832                } else {
 8833                    None
 8834                }
 8835            });
 8836            if let Some(project) = project {
 8837                let share_task = active_call.share_project(project, cx);
 8838                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8839                    share_task.await?;
 8840                    Ok(())
 8841                }));
 8842            }
 8843        }
 8844
 8845        None
 8846    });
 8847    if let Some(task) = task {
 8848        task.await?;
 8849        return anyhow::Ok(true);
 8850    }
 8851    anyhow::Ok(false)
 8852}
 8853
 8854pub fn join_channel(
 8855    channel_id: ChannelId,
 8856    app_state: Arc<AppState>,
 8857    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8858    requesting_workspace: Option<WeakEntity<Workspace>>,
 8859    cx: &mut App,
 8860) -> Task<Result<()>> {
 8861    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8862    cx.spawn(async move |cx| {
 8863        let result = join_channel_internal(
 8864            channel_id,
 8865            &app_state,
 8866            requesting_window,
 8867            requesting_workspace,
 8868            &*active_call.0,
 8869            cx,
 8870        )
 8871        .await;
 8872
 8873        // join channel succeeded, and opened a window
 8874        if matches!(result, Ok(true)) {
 8875            return anyhow::Ok(());
 8876        }
 8877
 8878        // find an existing workspace to focus and show call controls
 8879        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8880        if active_window.is_none() {
 8881            // no open workspaces, make one to show the error in (blergh)
 8882            let OpenResult {
 8883                window: window_handle,
 8884                ..
 8885            } = cx
 8886                .update(|cx| {
 8887                    Workspace::new_local(
 8888                        vec![],
 8889                        app_state.clone(),
 8890                        requesting_window,
 8891                        None,
 8892                        None,
 8893                        true,
 8894                        cx,
 8895                    )
 8896                })
 8897                .await?;
 8898
 8899            window_handle
 8900                .update(cx, |_, window, _cx| {
 8901                    window.activate_window();
 8902                })
 8903                .ok();
 8904
 8905            if result.is_ok() {
 8906                cx.update(|cx| {
 8907                    cx.dispatch_action(&OpenChannelNotes);
 8908                });
 8909            }
 8910
 8911            active_window = Some(window_handle);
 8912        }
 8913
 8914        if let Err(err) = result {
 8915            log::error!("failed to join channel: {}", err);
 8916            if let Some(active_window) = active_window {
 8917                active_window
 8918                    .update(cx, |_, window, cx| {
 8919                        let detail: SharedString = match err.error_code() {
 8920                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8921                            ErrorCode::UpgradeRequired => concat!(
 8922                                "Your are running an unsupported version of Zed. ",
 8923                                "Please update to continue."
 8924                            )
 8925                            .into(),
 8926                            ErrorCode::NoSuchChannel => concat!(
 8927                                "No matching channel was found. ",
 8928                                "Please check the link and try again."
 8929                            )
 8930                            .into(),
 8931                            ErrorCode::Forbidden => concat!(
 8932                                "This channel is private, and you do not have access. ",
 8933                                "Please ask someone to add you and try again."
 8934                            )
 8935                            .into(),
 8936                            ErrorCode::Disconnected => {
 8937                                "Please check your internet connection and try again.".into()
 8938                            }
 8939                            _ => format!("{}\n\nPlease try again.", err).into(),
 8940                        };
 8941                        window.prompt(
 8942                            PromptLevel::Critical,
 8943                            "Failed to join channel",
 8944                            Some(&detail),
 8945                            &["Ok"],
 8946                            cx,
 8947                        )
 8948                    })?
 8949                    .await
 8950                    .ok();
 8951            }
 8952        }
 8953
 8954        // return ok, we showed the error to the user.
 8955        anyhow::Ok(())
 8956    })
 8957}
 8958
 8959pub async fn get_any_active_multi_workspace(
 8960    app_state: Arc<AppState>,
 8961    mut cx: AsyncApp,
 8962) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8963    // find an existing workspace to focus and show call controls
 8964    let active_window = activate_any_workspace_window(&mut cx);
 8965    if active_window.is_none() {
 8966        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8967            .await?;
 8968    }
 8969    activate_any_workspace_window(&mut cx).context("could not open zed")
 8970}
 8971
 8972fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8973    cx.update(|cx| {
 8974        if let Some(workspace_window) = cx
 8975            .active_window()
 8976            .and_then(|window| window.downcast::<MultiWorkspace>())
 8977        {
 8978            return Some(workspace_window);
 8979        }
 8980
 8981        for window in cx.windows() {
 8982            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8983                workspace_window
 8984                    .update(cx, |_, window, _| window.activate_window())
 8985                    .ok();
 8986                return Some(workspace_window);
 8987            }
 8988        }
 8989        None
 8990    })
 8991}
 8992
 8993pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8994    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8995}
 8996
 8997pub fn workspace_windows_for_location(
 8998    serialized_location: &SerializedWorkspaceLocation,
 8999    cx: &App,
 9000) -> Vec<WindowHandle<MultiWorkspace>> {
 9001    cx.windows()
 9002        .into_iter()
 9003        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9004        .filter(|multi_workspace| {
 9005            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9006                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9007                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9008                }
 9009                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9010                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9011                    a.distro_name == b.distro_name
 9012                }
 9013                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9014                    a.container_id == b.container_id
 9015                }
 9016                #[cfg(any(test, feature = "test-support"))]
 9017                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9018                    a.id == b.id
 9019                }
 9020                _ => false,
 9021            };
 9022
 9023            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9024                multi_workspace.workspaces().iter().any(|workspace| {
 9025                    match workspace.read(cx).workspace_location(cx) {
 9026                        WorkspaceLocation::Location(location, _) => {
 9027                            match (&location, serialized_location) {
 9028                                (
 9029                                    SerializedWorkspaceLocation::Local,
 9030                                    SerializedWorkspaceLocation::Local,
 9031                                ) => true,
 9032                                (
 9033                                    SerializedWorkspaceLocation::Remote(a),
 9034                                    SerializedWorkspaceLocation::Remote(b),
 9035                                ) => same_host(a, b),
 9036                                _ => false,
 9037                            }
 9038                        }
 9039                        _ => false,
 9040                    }
 9041                })
 9042            })
 9043        })
 9044        .collect()
 9045}
 9046
 9047pub async fn find_existing_workspace(
 9048    abs_paths: &[PathBuf],
 9049    open_options: &OpenOptions,
 9050    location: &SerializedWorkspaceLocation,
 9051    cx: &mut AsyncApp,
 9052) -> (
 9053    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9054    OpenVisible,
 9055) {
 9056    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9057    let mut open_visible = OpenVisible::All;
 9058    let mut best_match = None;
 9059
 9060    if open_options.open_new_workspace != Some(true) {
 9061        cx.update(|cx| {
 9062            for window in workspace_windows_for_location(location, cx) {
 9063                if let Ok(multi_workspace) = window.read(cx) {
 9064                    for workspace in multi_workspace.workspaces() {
 9065                        let project = workspace.read(cx).project.read(cx);
 9066                        let m = project.visibility_for_paths(
 9067                            abs_paths,
 9068                            open_options.open_new_workspace == None,
 9069                            cx,
 9070                        );
 9071                        if m > best_match {
 9072                            existing = Some((window, workspace.clone()));
 9073                            best_match = m;
 9074                        } else if best_match.is_none()
 9075                            && open_options.open_new_workspace == Some(false)
 9076                        {
 9077                            existing = Some((window, workspace.clone()))
 9078                        }
 9079                    }
 9080                }
 9081            }
 9082        });
 9083
 9084        let all_paths_are_files = existing
 9085            .as_ref()
 9086            .and_then(|(_, target_workspace)| {
 9087                cx.update(|cx| {
 9088                    let workspace = target_workspace.read(cx);
 9089                    let project = workspace.project.read(cx);
 9090                    let path_style = workspace.path_style(cx);
 9091                    Some(!abs_paths.iter().any(|path| {
 9092                        let path = util::paths::SanitizedPath::new(path);
 9093                        project.worktrees(cx).any(|worktree| {
 9094                            let worktree = worktree.read(cx);
 9095                            let abs_path = worktree.abs_path();
 9096                            path_style
 9097                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9098                                .and_then(|rel| worktree.entry_for_path(&rel))
 9099                                .is_some_and(|e| e.is_dir())
 9100                        })
 9101                    }))
 9102                })
 9103            })
 9104            .unwrap_or(false);
 9105
 9106        if open_options.open_new_workspace.is_none()
 9107            && existing.is_some()
 9108            && open_options.wait
 9109            && all_paths_are_files
 9110        {
 9111            cx.update(|cx| {
 9112                let windows = workspace_windows_for_location(location, cx);
 9113                let window = cx
 9114                    .active_window()
 9115                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9116                    .filter(|window| windows.contains(window))
 9117                    .or_else(|| windows.into_iter().next());
 9118                if let Some(window) = window {
 9119                    if let Ok(multi_workspace) = window.read(cx) {
 9120                        let active_workspace = multi_workspace.workspace().clone();
 9121                        existing = Some((window, active_workspace));
 9122                        open_visible = OpenVisible::None;
 9123                    }
 9124                }
 9125            });
 9126        }
 9127    }
 9128    (existing, open_visible)
 9129}
 9130
 9131#[derive(Default, Clone)]
 9132pub struct OpenOptions {
 9133    pub visible: Option<OpenVisible>,
 9134    pub focus: Option<bool>,
 9135    pub open_new_workspace: Option<bool>,
 9136    pub wait: bool,
 9137    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 9138    pub env: Option<HashMap<String, String>>,
 9139}
 9140
 9141/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9142/// or [`Workspace::open_workspace_for_paths`].
 9143pub struct OpenResult {
 9144    pub window: WindowHandle<MultiWorkspace>,
 9145    pub workspace: Entity<Workspace>,
 9146    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9147}
 9148
 9149/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9150pub fn open_workspace_by_id(
 9151    workspace_id: WorkspaceId,
 9152    app_state: Arc<AppState>,
 9153    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9154    cx: &mut App,
 9155) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9156    let project_handle = Project::local(
 9157        app_state.client.clone(),
 9158        app_state.node_runtime.clone(),
 9159        app_state.user_store.clone(),
 9160        app_state.languages.clone(),
 9161        app_state.fs.clone(),
 9162        None,
 9163        project::LocalProjectFlags {
 9164            init_worktree_trust: true,
 9165            ..project::LocalProjectFlags::default()
 9166        },
 9167        cx,
 9168    );
 9169
 9170    let db = WorkspaceDb::global(cx);
 9171    let kvp = db::kvp::KeyValueStore::global(cx);
 9172    cx.spawn(async move |cx| {
 9173        let serialized_workspace = db
 9174            .workspace_for_id(workspace_id)
 9175            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9176
 9177        let centered_layout = serialized_workspace.centered_layout;
 9178
 9179        let (window, workspace) = if let Some(window) = requesting_window {
 9180            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9181                let workspace = cx.new(|cx| {
 9182                    let mut workspace = Workspace::new(
 9183                        Some(workspace_id),
 9184                        project_handle.clone(),
 9185                        app_state.clone(),
 9186                        window,
 9187                        cx,
 9188                    );
 9189                    workspace.centered_layout = centered_layout;
 9190                    workspace
 9191                });
 9192                multi_workspace.add_workspace(workspace.clone(), cx);
 9193                workspace
 9194            })?;
 9195            (window, workspace)
 9196        } else {
 9197            let window_bounds_override = window_bounds_env_override();
 9198
 9199            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9200                (Some(WindowBounds::Windowed(bounds)), None)
 9201            } else if let Some(display) = serialized_workspace.display
 9202                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9203            {
 9204                (Some(bounds.0), Some(display))
 9205            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9206                (Some(bounds), Some(display))
 9207            } else {
 9208                (None, None)
 9209            };
 9210
 9211            let options = cx.update(|cx| {
 9212                let mut options = (app_state.build_window_options)(display, cx);
 9213                options.window_bounds = window_bounds;
 9214                options
 9215            });
 9216
 9217            let window = cx.open_window(options, {
 9218                let app_state = app_state.clone();
 9219                let project_handle = project_handle.clone();
 9220                move |window, cx| {
 9221                    let workspace = cx.new(|cx| {
 9222                        let mut workspace = Workspace::new(
 9223                            Some(workspace_id),
 9224                            project_handle,
 9225                            app_state,
 9226                            window,
 9227                            cx,
 9228                        );
 9229                        workspace.centered_layout = centered_layout;
 9230                        workspace
 9231                    });
 9232                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9233                }
 9234            })?;
 9235
 9236            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9237                multi_workspace.workspace().clone()
 9238            })?;
 9239
 9240            (window, workspace)
 9241        };
 9242
 9243        notify_if_database_failed(window, cx);
 9244
 9245        // Restore items from the serialized workspace
 9246        window
 9247            .update(cx, |_, window, cx| {
 9248                workspace.update(cx, |_workspace, cx| {
 9249                    open_items(Some(serialized_workspace), vec![], window, cx)
 9250                })
 9251            })?
 9252            .await?;
 9253
 9254        window.update(cx, |_, window, cx| {
 9255            workspace.update(cx, |workspace, cx| {
 9256                workspace.serialize_workspace(window, cx);
 9257            });
 9258        })?;
 9259
 9260        Ok(window)
 9261    })
 9262}
 9263
 9264#[allow(clippy::type_complexity)]
 9265pub fn open_paths(
 9266    abs_paths: &[PathBuf],
 9267    app_state: Arc<AppState>,
 9268    open_options: OpenOptions,
 9269    cx: &mut App,
 9270) -> Task<anyhow::Result<OpenResult>> {
 9271    let abs_paths = abs_paths.to_vec();
 9272    #[cfg(target_os = "windows")]
 9273    let wsl_path = abs_paths
 9274        .iter()
 9275        .find_map(|p| util::paths::WslPath::from_path(p));
 9276
 9277    cx.spawn(async move |cx| {
 9278        let (mut existing, mut open_visible) = find_existing_workspace(
 9279            &abs_paths,
 9280            &open_options,
 9281            &SerializedWorkspaceLocation::Local,
 9282            cx,
 9283        )
 9284        .await;
 9285
 9286        // Fallback: if no workspace contains the paths and all paths are files,
 9287        // prefer an existing local workspace window (active window first).
 9288        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9289            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9290            let all_metadatas = futures::future::join_all(all_paths)
 9291                .await
 9292                .into_iter()
 9293                .filter_map(|result| result.ok().flatten())
 9294                .collect::<Vec<_>>();
 9295
 9296            if all_metadatas.iter().all(|file| !file.is_dir) {
 9297                cx.update(|cx| {
 9298                    let windows = workspace_windows_for_location(
 9299                        &SerializedWorkspaceLocation::Local,
 9300                        cx,
 9301                    );
 9302                    let window = cx
 9303                        .active_window()
 9304                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9305                        .filter(|window| windows.contains(window))
 9306                        .or_else(|| windows.into_iter().next());
 9307                    if let Some(window) = window {
 9308                        if let Ok(multi_workspace) = window.read(cx) {
 9309                            let active_workspace = multi_workspace.workspace().clone();
 9310                            existing = Some((window, active_workspace));
 9311                            open_visible = OpenVisible::None;
 9312                        }
 9313                    }
 9314                });
 9315            }
 9316        }
 9317
 9318        let result = if let Some((existing, target_workspace)) = existing {
 9319            let open_task = existing
 9320                .update(cx, |multi_workspace, window, cx| {
 9321                    window.activate_window();
 9322                    multi_workspace.activate(target_workspace.clone(), cx);
 9323                    target_workspace.update(cx, |workspace, cx| {
 9324                        workspace.open_paths(
 9325                            abs_paths,
 9326                            OpenOptions {
 9327                                visible: Some(open_visible),
 9328                                ..Default::default()
 9329                            },
 9330                            None,
 9331                            window,
 9332                            cx,
 9333                        )
 9334                    })
 9335                })?
 9336                .await;
 9337
 9338            _ = existing.update(cx, |multi_workspace, _, cx| {
 9339                let workspace = multi_workspace.workspace().clone();
 9340                workspace.update(cx, |workspace, cx| {
 9341                    for item in open_task.iter().flatten() {
 9342                        if let Err(e) = item {
 9343                            workspace.show_error(&e, cx);
 9344                        }
 9345                    }
 9346                });
 9347            });
 9348
 9349            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9350        } else {
 9351            let result = cx
 9352                .update(move |cx| {
 9353                    Workspace::new_local(
 9354                        abs_paths,
 9355                        app_state.clone(),
 9356                        open_options.replace_window,
 9357                        open_options.env,
 9358                        None,
 9359                        true,
 9360                        cx,
 9361                    )
 9362                })
 9363                .await;
 9364
 9365            if let Ok(ref result) = result {
 9366                result.window
 9367                    .update(cx, |_, window, _cx| {
 9368                        window.activate_window();
 9369                    })
 9370                    .log_err();
 9371            }
 9372
 9373            result
 9374        };
 9375
 9376        #[cfg(target_os = "windows")]
 9377        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9378            && let Ok(ref result) = result
 9379        {
 9380            result.window
 9381                .update(cx, move |multi_workspace, _window, cx| {
 9382                    struct OpenInWsl;
 9383                    let workspace = multi_workspace.workspace().clone();
 9384                    workspace.update(cx, |workspace, cx| {
 9385                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9386                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9387                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9388                            cx.new(move |cx| {
 9389                                MessageNotification::new(msg, cx)
 9390                                    .primary_message("Open in WSL")
 9391                                    .primary_icon(IconName::FolderOpen)
 9392                                    .primary_on_click(move |window, cx| {
 9393                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9394                                                distro: remote::WslConnectionOptions {
 9395                                                        distro_name: distro.clone(),
 9396                                                    user: None,
 9397                                                },
 9398                                                paths: vec![path.clone().into()],
 9399                                            }), cx)
 9400                                    })
 9401                            })
 9402                        });
 9403                    });
 9404                })
 9405                .unwrap();
 9406        };
 9407        result
 9408    })
 9409}
 9410
 9411pub fn open_new(
 9412    open_options: OpenOptions,
 9413    app_state: Arc<AppState>,
 9414    cx: &mut App,
 9415    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9416) -> Task<anyhow::Result<()>> {
 9417    let task = Workspace::new_local(
 9418        Vec::new(),
 9419        app_state,
 9420        open_options.replace_window,
 9421        open_options.env,
 9422        Some(Box::new(init)),
 9423        true,
 9424        cx,
 9425    );
 9426    cx.spawn(async move |cx| {
 9427        let OpenResult { window, .. } = task.await?;
 9428        window
 9429            .update(cx, |_, window, _cx| {
 9430                window.activate_window();
 9431            })
 9432            .ok();
 9433        Ok(())
 9434    })
 9435}
 9436
 9437pub fn create_and_open_local_file(
 9438    path: &'static Path,
 9439    window: &mut Window,
 9440    cx: &mut Context<Workspace>,
 9441    default_content: impl 'static + Send + FnOnce() -> Rope,
 9442) -> Task<Result<Box<dyn ItemHandle>>> {
 9443    cx.spawn_in(window, async move |workspace, cx| {
 9444        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9445        if !fs.is_file(path).await {
 9446            fs.create_file(path, Default::default()).await?;
 9447            fs.save(path, &default_content(), Default::default())
 9448                .await?;
 9449        }
 9450
 9451        workspace
 9452            .update_in(cx, |workspace, window, cx| {
 9453                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9454                    let path = workspace
 9455                        .project
 9456                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9457                    cx.spawn_in(window, async move |workspace, cx| {
 9458                        let path = path.await?;
 9459
 9460                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9461
 9462                        let mut items = workspace
 9463                            .update_in(cx, |workspace, window, cx| {
 9464                                workspace.open_paths(
 9465                                    vec![path.to_path_buf()],
 9466                                    OpenOptions {
 9467                                        visible: Some(OpenVisible::None),
 9468                                        ..Default::default()
 9469                                    },
 9470                                    None,
 9471                                    window,
 9472                                    cx,
 9473                                )
 9474                            })?
 9475                            .await;
 9476                        let item = items.pop().flatten();
 9477                        item.with_context(|| format!("path {path:?} is not a file"))?
 9478                    })
 9479                })
 9480            })?
 9481            .await?
 9482            .await
 9483    })
 9484}
 9485
 9486pub fn open_remote_project_with_new_connection(
 9487    window: WindowHandle<MultiWorkspace>,
 9488    remote_connection: Arc<dyn RemoteConnection>,
 9489    cancel_rx: oneshot::Receiver<()>,
 9490    delegate: Arc<dyn RemoteClientDelegate>,
 9491    app_state: Arc<AppState>,
 9492    paths: Vec<PathBuf>,
 9493    cx: &mut App,
 9494) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9495    cx.spawn(async move |cx| {
 9496        let (workspace_id, serialized_workspace) =
 9497            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9498                .await?;
 9499
 9500        let session = match cx
 9501            .update(|cx| {
 9502                remote::RemoteClient::new(
 9503                    ConnectionIdentifier::Workspace(workspace_id.0),
 9504                    remote_connection,
 9505                    cancel_rx,
 9506                    delegate,
 9507                    cx,
 9508                )
 9509            })
 9510            .await?
 9511        {
 9512            Some(result) => result,
 9513            None => return Ok(Vec::new()),
 9514        };
 9515
 9516        let project = cx.update(|cx| {
 9517            project::Project::remote(
 9518                session,
 9519                app_state.client.clone(),
 9520                app_state.node_runtime.clone(),
 9521                app_state.user_store.clone(),
 9522                app_state.languages.clone(),
 9523                app_state.fs.clone(),
 9524                true,
 9525                cx,
 9526            )
 9527        });
 9528
 9529        open_remote_project_inner(
 9530            project,
 9531            paths,
 9532            workspace_id,
 9533            serialized_workspace,
 9534            app_state,
 9535            window,
 9536            cx,
 9537        )
 9538        .await
 9539    })
 9540}
 9541
 9542pub fn open_remote_project_with_existing_connection(
 9543    connection_options: RemoteConnectionOptions,
 9544    project: Entity<Project>,
 9545    paths: Vec<PathBuf>,
 9546    app_state: Arc<AppState>,
 9547    window: WindowHandle<MultiWorkspace>,
 9548    cx: &mut AsyncApp,
 9549) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9550    cx.spawn(async move |cx| {
 9551        let (workspace_id, serialized_workspace) =
 9552            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9553
 9554        open_remote_project_inner(
 9555            project,
 9556            paths,
 9557            workspace_id,
 9558            serialized_workspace,
 9559            app_state,
 9560            window,
 9561            cx,
 9562        )
 9563        .await
 9564    })
 9565}
 9566
 9567async fn open_remote_project_inner(
 9568    project: Entity<Project>,
 9569    paths: Vec<PathBuf>,
 9570    workspace_id: WorkspaceId,
 9571    serialized_workspace: Option<SerializedWorkspace>,
 9572    app_state: Arc<AppState>,
 9573    window: WindowHandle<MultiWorkspace>,
 9574    cx: &mut AsyncApp,
 9575) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9576    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9577    let toolchains = db.toolchains(workspace_id).await?;
 9578    for (toolchain, worktree_path, path) in toolchains {
 9579        project
 9580            .update(cx, |this, cx| {
 9581                let Some(worktree_id) =
 9582                    this.find_worktree(&worktree_path, cx)
 9583                        .and_then(|(worktree, rel_path)| {
 9584                            if rel_path.is_empty() {
 9585                                Some(worktree.read(cx).id())
 9586                            } else {
 9587                                None
 9588                            }
 9589                        })
 9590                else {
 9591                    return Task::ready(None);
 9592                };
 9593
 9594                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9595            })
 9596            .await;
 9597    }
 9598    let mut project_paths_to_open = vec![];
 9599    let mut project_path_errors = vec![];
 9600
 9601    for path in paths {
 9602        let result = cx
 9603            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9604            .await;
 9605        match result {
 9606            Ok((_, project_path)) => {
 9607                project_paths_to_open.push((path.clone(), Some(project_path)));
 9608            }
 9609            Err(error) => {
 9610                project_path_errors.push(error);
 9611            }
 9612        };
 9613    }
 9614
 9615    if project_paths_to_open.is_empty() {
 9616        return Err(project_path_errors.pop().context("no paths given")?);
 9617    }
 9618
 9619    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9620        telemetry::event!("SSH Project Opened");
 9621
 9622        let new_workspace = cx.new(|cx| {
 9623            let mut workspace =
 9624                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9625            workspace.update_history(cx);
 9626
 9627            if let Some(ref serialized) = serialized_workspace {
 9628                workspace.centered_layout = serialized.centered_layout;
 9629            }
 9630
 9631            workspace
 9632        });
 9633
 9634        multi_workspace.activate(new_workspace.clone(), cx);
 9635        new_workspace
 9636    })?;
 9637
 9638    let items = window
 9639        .update(cx, |_, window, cx| {
 9640            window.activate_window();
 9641            workspace.update(cx, |_workspace, cx| {
 9642                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9643            })
 9644        })?
 9645        .await?;
 9646
 9647    workspace.update(cx, |workspace, cx| {
 9648        for error in project_path_errors {
 9649            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9650                if let Some(path) = error.error_tag("path") {
 9651                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9652                }
 9653            } else {
 9654                workspace.show_error(&error, cx)
 9655            }
 9656        }
 9657    });
 9658
 9659    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9660}
 9661
 9662fn deserialize_remote_project(
 9663    connection_options: RemoteConnectionOptions,
 9664    paths: Vec<PathBuf>,
 9665    cx: &AsyncApp,
 9666) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9667    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9668    cx.background_spawn(async move {
 9669        let remote_connection_id = db
 9670            .get_or_create_remote_connection(connection_options)
 9671            .await?;
 9672
 9673        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9674
 9675        let workspace_id = if let Some(workspace_id) =
 9676            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9677        {
 9678            workspace_id
 9679        } else {
 9680            db.next_id().await?
 9681        };
 9682
 9683        Ok((workspace_id, serialized_workspace))
 9684    })
 9685}
 9686
 9687pub fn join_in_room_project(
 9688    project_id: u64,
 9689    follow_user_id: u64,
 9690    app_state: Arc<AppState>,
 9691    cx: &mut App,
 9692) -> Task<Result<()>> {
 9693    let windows = cx.windows();
 9694    cx.spawn(async move |cx| {
 9695        let existing_window_and_workspace: Option<(
 9696            WindowHandle<MultiWorkspace>,
 9697            Entity<Workspace>,
 9698        )> = windows.into_iter().find_map(|window_handle| {
 9699            window_handle
 9700                .downcast::<MultiWorkspace>()
 9701                .and_then(|window_handle| {
 9702                    window_handle
 9703                        .update(cx, |multi_workspace, _window, cx| {
 9704                            for workspace in multi_workspace.workspaces() {
 9705                                if workspace.read(cx).project().read(cx).remote_id()
 9706                                    == Some(project_id)
 9707                                {
 9708                                    return Some((window_handle, workspace.clone()));
 9709                                }
 9710                            }
 9711                            None
 9712                        })
 9713                        .unwrap_or(None)
 9714                })
 9715        });
 9716
 9717        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9718            existing_window_and_workspace
 9719        {
 9720            existing_window
 9721                .update(cx, |multi_workspace, _, cx| {
 9722                    multi_workspace.activate(target_workspace, cx);
 9723                })
 9724                .ok();
 9725            existing_window
 9726        } else {
 9727            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9728            let project = cx
 9729                .update(|cx| {
 9730                    active_call.0.join_project(
 9731                        project_id,
 9732                        app_state.languages.clone(),
 9733                        app_state.fs.clone(),
 9734                        cx,
 9735                    )
 9736                })
 9737                .await?;
 9738
 9739            let window_bounds_override = window_bounds_env_override();
 9740            cx.update(|cx| {
 9741                let mut options = (app_state.build_window_options)(None, cx);
 9742                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9743                cx.open_window(options, |window, cx| {
 9744                    let workspace = cx.new(|cx| {
 9745                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9746                    });
 9747                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9748                })
 9749            })?
 9750        };
 9751
 9752        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9753            cx.activate(true);
 9754            window.activate_window();
 9755
 9756            // We set the active workspace above, so this is the correct workspace.
 9757            let workspace = multi_workspace.workspace().clone();
 9758            workspace.update(cx, |workspace, cx| {
 9759                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9760                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9761                    .or_else(|| {
 9762                        // If we couldn't follow the given user, follow the host instead.
 9763                        let collaborator = workspace
 9764                            .project()
 9765                            .read(cx)
 9766                            .collaborators()
 9767                            .values()
 9768                            .find(|collaborator| collaborator.is_host)?;
 9769                        Some(collaborator.peer_id)
 9770                    });
 9771
 9772                if let Some(follow_peer_id) = follow_peer_id {
 9773                    workspace.follow(follow_peer_id, window, cx);
 9774                }
 9775            });
 9776        })?;
 9777
 9778        anyhow::Ok(())
 9779    })
 9780}
 9781
 9782pub fn reload(cx: &mut App) {
 9783    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9784    let mut workspace_windows = cx
 9785        .windows()
 9786        .into_iter()
 9787        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9788        .collect::<Vec<_>>();
 9789
 9790    // If multiple windows have unsaved changes, and need a save prompt,
 9791    // prompt in the active window before switching to a different window.
 9792    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9793
 9794    let mut prompt = None;
 9795    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9796        prompt = window
 9797            .update(cx, |_, window, cx| {
 9798                window.prompt(
 9799                    PromptLevel::Info,
 9800                    "Are you sure you want to restart?",
 9801                    None,
 9802                    &["Restart", "Cancel"],
 9803                    cx,
 9804                )
 9805            })
 9806            .ok();
 9807    }
 9808
 9809    cx.spawn(async move |cx| {
 9810        if let Some(prompt) = prompt {
 9811            let answer = prompt.await?;
 9812            if answer != 0 {
 9813                return anyhow::Ok(());
 9814            }
 9815        }
 9816
 9817        // If the user cancels any save prompt, then keep the app open.
 9818        for window in workspace_windows {
 9819            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9820                let workspace = multi_workspace.workspace().clone();
 9821                workspace.update(cx, |workspace, cx| {
 9822                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9823                })
 9824            }) && !should_close.await?
 9825            {
 9826                return anyhow::Ok(());
 9827            }
 9828        }
 9829        cx.update(|cx| cx.restart());
 9830        anyhow::Ok(())
 9831    })
 9832    .detach_and_log_err(cx);
 9833}
 9834
 9835fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9836    let mut parts = value.split(',');
 9837    let x: usize = parts.next()?.parse().ok()?;
 9838    let y: usize = parts.next()?.parse().ok()?;
 9839    Some(point(px(x as f32), px(y as f32)))
 9840}
 9841
 9842fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9843    let mut parts = value.split(',');
 9844    let width: usize = parts.next()?.parse().ok()?;
 9845    let height: usize = parts.next()?.parse().ok()?;
 9846    Some(size(px(width as f32), px(height as f32)))
 9847}
 9848
 9849/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9850/// appropriate.
 9851///
 9852/// The `border_radius_tiling` parameter allows overriding which corners get
 9853/// rounded, independently of the actual window tiling state. This is used
 9854/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9855/// we want square corners on the left (so the sidebar appears flush with the
 9856/// window edge) but we still need the shadow padding for proper visual
 9857/// appearance. Unlike actual window tiling, this only affects border radius -
 9858/// not padding or shadows.
 9859pub fn client_side_decorations(
 9860    element: impl IntoElement,
 9861    window: &mut Window,
 9862    cx: &mut App,
 9863    border_radius_tiling: Tiling,
 9864) -> Stateful<Div> {
 9865    const BORDER_SIZE: Pixels = px(1.0);
 9866    let decorations = window.window_decorations();
 9867    let tiling = match decorations {
 9868        Decorations::Server => Tiling::default(),
 9869        Decorations::Client { tiling } => tiling,
 9870    };
 9871
 9872    match decorations {
 9873        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9874        Decorations::Server => window.set_client_inset(px(0.0)),
 9875    }
 9876
 9877    struct GlobalResizeEdge(ResizeEdge);
 9878    impl Global for GlobalResizeEdge {}
 9879
 9880    div()
 9881        .id("window-backdrop")
 9882        .bg(transparent_black())
 9883        .map(|div| match decorations {
 9884            Decorations::Server => div,
 9885            Decorations::Client { .. } => div
 9886                .when(
 9887                    !(tiling.top
 9888                        || tiling.right
 9889                        || border_radius_tiling.top
 9890                        || border_radius_tiling.right),
 9891                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9892                )
 9893                .when(
 9894                    !(tiling.top
 9895                        || tiling.left
 9896                        || border_radius_tiling.top
 9897                        || border_radius_tiling.left),
 9898                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9899                )
 9900                .when(
 9901                    !(tiling.bottom
 9902                        || tiling.right
 9903                        || border_radius_tiling.bottom
 9904                        || border_radius_tiling.right),
 9905                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9906                )
 9907                .when(
 9908                    !(tiling.bottom
 9909                        || tiling.left
 9910                        || border_radius_tiling.bottom
 9911                        || border_radius_tiling.left),
 9912                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9913                )
 9914                .when(!tiling.top, |div| {
 9915                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9916                })
 9917                .when(!tiling.bottom, |div| {
 9918                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9919                })
 9920                .when(!tiling.left, |div| {
 9921                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9922                })
 9923                .when(!tiling.right, |div| {
 9924                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9925                })
 9926                .on_mouse_move(move |e, window, cx| {
 9927                    let size = window.window_bounds().get_bounds().size;
 9928                    let pos = e.position;
 9929
 9930                    let new_edge =
 9931                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9932
 9933                    let edge = cx.try_global::<GlobalResizeEdge>();
 9934                    if new_edge != edge.map(|edge| edge.0) {
 9935                        window
 9936                            .window_handle()
 9937                            .update(cx, |workspace, _, cx| {
 9938                                cx.notify(workspace.entity_id());
 9939                            })
 9940                            .ok();
 9941                    }
 9942                })
 9943                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9944                    let size = window.window_bounds().get_bounds().size;
 9945                    let pos = e.position;
 9946
 9947                    let edge = match resize_edge(
 9948                        pos,
 9949                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9950                        size,
 9951                        tiling,
 9952                    ) {
 9953                        Some(value) => value,
 9954                        None => return,
 9955                    };
 9956
 9957                    window.start_window_resize(edge);
 9958                }),
 9959        })
 9960        .size_full()
 9961        .child(
 9962            div()
 9963                .cursor(CursorStyle::Arrow)
 9964                .map(|div| match decorations {
 9965                    Decorations::Server => div,
 9966                    Decorations::Client { .. } => div
 9967                        .border_color(cx.theme().colors().border)
 9968                        .when(
 9969                            !(tiling.top
 9970                                || tiling.right
 9971                                || border_radius_tiling.top
 9972                                || border_radius_tiling.right),
 9973                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9974                        )
 9975                        .when(
 9976                            !(tiling.top
 9977                                || tiling.left
 9978                                || border_radius_tiling.top
 9979                                || border_radius_tiling.left),
 9980                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9981                        )
 9982                        .when(
 9983                            !(tiling.bottom
 9984                                || tiling.right
 9985                                || border_radius_tiling.bottom
 9986                                || border_radius_tiling.right),
 9987                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9988                        )
 9989                        .when(
 9990                            !(tiling.bottom
 9991                                || tiling.left
 9992                                || border_radius_tiling.bottom
 9993                                || border_radius_tiling.left),
 9994                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9995                        )
 9996                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9997                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9998                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9999                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10000                        .when(!tiling.is_tiled(), |div| {
10001                            div.shadow(vec![gpui::BoxShadow {
10002                                color: Hsla {
10003                                    h: 0.,
10004                                    s: 0.,
10005                                    l: 0.,
10006                                    a: 0.4,
10007                                },
10008                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10009                                spread_radius: px(0.),
10010                                offset: point(px(0.0), px(0.0)),
10011                            }])
10012                        }),
10013                })
10014                .on_mouse_move(|_e, _, cx| {
10015                    cx.stop_propagation();
10016                })
10017                .size_full()
10018                .child(element),
10019        )
10020        .map(|div| match decorations {
10021            Decorations::Server => div,
10022            Decorations::Client { tiling, .. } => div.child(
10023                canvas(
10024                    |_bounds, window, _| {
10025                        window.insert_hitbox(
10026                            Bounds::new(
10027                                point(px(0.0), px(0.0)),
10028                                window.window_bounds().get_bounds().size,
10029                            ),
10030                            HitboxBehavior::Normal,
10031                        )
10032                    },
10033                    move |_bounds, hitbox, window, cx| {
10034                        let mouse = window.mouse_position();
10035                        let size = window.window_bounds().get_bounds().size;
10036                        let Some(edge) =
10037                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10038                        else {
10039                            return;
10040                        };
10041                        cx.set_global(GlobalResizeEdge(edge));
10042                        window.set_cursor_style(
10043                            match edge {
10044                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10045                                ResizeEdge::Left | ResizeEdge::Right => {
10046                                    CursorStyle::ResizeLeftRight
10047                                }
10048                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10049                                    CursorStyle::ResizeUpLeftDownRight
10050                                }
10051                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10052                                    CursorStyle::ResizeUpRightDownLeft
10053                                }
10054                            },
10055                            &hitbox,
10056                        );
10057                    },
10058                )
10059                .size_full()
10060                .absolute(),
10061            ),
10062        })
10063}
10064
10065fn resize_edge(
10066    pos: Point<Pixels>,
10067    shadow_size: Pixels,
10068    window_size: Size<Pixels>,
10069    tiling: Tiling,
10070) -> Option<ResizeEdge> {
10071    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10072    if bounds.contains(&pos) {
10073        return None;
10074    }
10075
10076    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10077    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10078    if !tiling.top && top_left_bounds.contains(&pos) {
10079        return Some(ResizeEdge::TopLeft);
10080    }
10081
10082    let top_right_bounds = Bounds::new(
10083        Point::new(window_size.width - corner_size.width, px(0.)),
10084        corner_size,
10085    );
10086    if !tiling.top && top_right_bounds.contains(&pos) {
10087        return Some(ResizeEdge::TopRight);
10088    }
10089
10090    let bottom_left_bounds = Bounds::new(
10091        Point::new(px(0.), window_size.height - corner_size.height),
10092        corner_size,
10093    );
10094    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10095        return Some(ResizeEdge::BottomLeft);
10096    }
10097
10098    let bottom_right_bounds = Bounds::new(
10099        Point::new(
10100            window_size.width - corner_size.width,
10101            window_size.height - corner_size.height,
10102        ),
10103        corner_size,
10104    );
10105    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10106        return Some(ResizeEdge::BottomRight);
10107    }
10108
10109    if !tiling.top && pos.y < shadow_size {
10110        Some(ResizeEdge::Top)
10111    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10112        Some(ResizeEdge::Bottom)
10113    } else if !tiling.left && pos.x < shadow_size {
10114        Some(ResizeEdge::Left)
10115    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10116        Some(ResizeEdge::Right)
10117    } else {
10118        None
10119    }
10120}
10121
10122fn join_pane_into_active(
10123    active_pane: &Entity<Pane>,
10124    pane: &Entity<Pane>,
10125    window: &mut Window,
10126    cx: &mut App,
10127) {
10128    if pane == active_pane {
10129    } else if pane.read(cx).items_len() == 0 {
10130        pane.update(cx, |_, cx| {
10131            cx.emit(pane::Event::Remove {
10132                focus_on_pane: None,
10133            });
10134        })
10135    } else {
10136        move_all_items(pane, active_pane, window, cx);
10137    }
10138}
10139
10140fn move_all_items(
10141    from_pane: &Entity<Pane>,
10142    to_pane: &Entity<Pane>,
10143    window: &mut Window,
10144    cx: &mut App,
10145) {
10146    let destination_is_different = from_pane != to_pane;
10147    let mut moved_items = 0;
10148    for (item_ix, item_handle) in from_pane
10149        .read(cx)
10150        .items()
10151        .enumerate()
10152        .map(|(ix, item)| (ix, item.clone()))
10153        .collect::<Vec<_>>()
10154    {
10155        let ix = item_ix - moved_items;
10156        if destination_is_different {
10157            // Close item from previous pane
10158            from_pane.update(cx, |source, cx| {
10159                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10160            });
10161            moved_items += 1;
10162        }
10163
10164        // This automatically removes duplicate items in the pane
10165        to_pane.update(cx, |destination, cx| {
10166            destination.add_item(item_handle, true, true, None, window, cx);
10167            window.focus(&destination.focus_handle(cx), cx)
10168        });
10169    }
10170}
10171
10172pub fn move_item(
10173    source: &Entity<Pane>,
10174    destination: &Entity<Pane>,
10175    item_id_to_move: EntityId,
10176    destination_index: usize,
10177    activate: bool,
10178    window: &mut Window,
10179    cx: &mut App,
10180) {
10181    let Some((item_ix, item_handle)) = source
10182        .read(cx)
10183        .items()
10184        .enumerate()
10185        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10186        .map(|(ix, item)| (ix, item.clone()))
10187    else {
10188        // Tab was closed during drag
10189        return;
10190    };
10191
10192    if source != destination {
10193        // Close item from previous pane
10194        source.update(cx, |source, cx| {
10195            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10196        });
10197    }
10198
10199    // This automatically removes duplicate items in the pane
10200    destination.update(cx, |destination, cx| {
10201        destination.add_item_inner(
10202            item_handle,
10203            activate,
10204            activate,
10205            activate,
10206            Some(destination_index),
10207            window,
10208            cx,
10209        );
10210        if activate {
10211            window.focus(&destination.focus_handle(cx), cx)
10212        }
10213    });
10214}
10215
10216pub fn move_active_item(
10217    source: &Entity<Pane>,
10218    destination: &Entity<Pane>,
10219    focus_destination: bool,
10220    close_if_empty: bool,
10221    window: &mut Window,
10222    cx: &mut App,
10223) {
10224    if source == destination {
10225        return;
10226    }
10227    let Some(active_item) = source.read(cx).active_item() else {
10228        return;
10229    };
10230    source.update(cx, |source_pane, cx| {
10231        let item_id = active_item.item_id();
10232        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10233        destination.update(cx, |target_pane, cx| {
10234            target_pane.add_item(
10235                active_item,
10236                focus_destination,
10237                focus_destination,
10238                Some(target_pane.items_len()),
10239                window,
10240                cx,
10241            );
10242        });
10243    });
10244}
10245
10246pub fn clone_active_item(
10247    workspace_id: Option<WorkspaceId>,
10248    source: &Entity<Pane>,
10249    destination: &Entity<Pane>,
10250    focus_destination: bool,
10251    window: &mut Window,
10252    cx: &mut App,
10253) {
10254    if source == destination {
10255        return;
10256    }
10257    let Some(active_item) = source.read(cx).active_item() else {
10258        return;
10259    };
10260    if !active_item.can_split(cx) {
10261        return;
10262    }
10263    let destination = destination.downgrade();
10264    let task = active_item.clone_on_split(workspace_id, window, cx);
10265    window
10266        .spawn(cx, async move |cx| {
10267            let Some(clone) = task.await else {
10268                return;
10269            };
10270            destination
10271                .update_in(cx, |target_pane, window, cx| {
10272                    target_pane.add_item(
10273                        clone,
10274                        focus_destination,
10275                        focus_destination,
10276                        Some(target_pane.items_len()),
10277                        window,
10278                        cx,
10279                    );
10280                })
10281                .log_err();
10282        })
10283        .detach();
10284}
10285
10286#[derive(Debug)]
10287pub struct WorkspacePosition {
10288    pub window_bounds: Option<WindowBounds>,
10289    pub display: Option<Uuid>,
10290    pub centered_layout: bool,
10291}
10292
10293pub fn remote_workspace_position_from_db(
10294    connection_options: RemoteConnectionOptions,
10295    paths_to_open: &[PathBuf],
10296    cx: &App,
10297) -> Task<Result<WorkspacePosition>> {
10298    let paths = paths_to_open.to_vec();
10299    let db = WorkspaceDb::global(cx);
10300    let kvp = db::kvp::KeyValueStore::global(cx);
10301
10302    cx.background_spawn(async move {
10303        let remote_connection_id = db
10304            .get_or_create_remote_connection(connection_options)
10305            .await
10306            .context("fetching serialized ssh project")?;
10307        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10308
10309        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10310            (Some(WindowBounds::Windowed(bounds)), None)
10311        } else {
10312            let restorable_bounds = serialized_workspace
10313                .as_ref()
10314                .and_then(|workspace| {
10315                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10316                })
10317                .or_else(|| persistence::read_default_window_bounds(&kvp));
10318
10319            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10320                (Some(serialized_bounds), Some(serialized_display))
10321            } else {
10322                (None, None)
10323            }
10324        };
10325
10326        let centered_layout = serialized_workspace
10327            .as_ref()
10328            .map(|w| w.centered_layout)
10329            .unwrap_or(false);
10330
10331        Ok(WorkspacePosition {
10332            window_bounds,
10333            display,
10334            centered_layout,
10335        })
10336    })
10337}
10338
10339pub fn with_active_or_new_workspace(
10340    cx: &mut App,
10341    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10342) {
10343    match cx
10344        .active_window()
10345        .and_then(|w| w.downcast::<MultiWorkspace>())
10346    {
10347        Some(multi_workspace) => {
10348            cx.defer(move |cx| {
10349                multi_workspace
10350                    .update(cx, |multi_workspace, window, cx| {
10351                        let workspace = multi_workspace.workspace().clone();
10352                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10353                    })
10354                    .log_err();
10355            });
10356        }
10357        None => {
10358            let app_state = AppState::global(cx);
10359            open_new(
10360                OpenOptions::default(),
10361                app_state,
10362                cx,
10363                move |workspace, window, cx| f(workspace, window, cx),
10364            )
10365            .detach_and_log_err(cx);
10366        }
10367    }
10368}
10369
10370/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10371/// key. This migration path only runs once per panel per workspace.
10372fn load_legacy_panel_size(
10373    panel_key: &str,
10374    dock_position: DockPosition,
10375    workspace: &Workspace,
10376    cx: &mut App,
10377) -> Option<Pixels> {
10378    #[derive(Deserialize)]
10379    struct LegacyPanelState {
10380        #[serde(default)]
10381        width: Option<Pixels>,
10382        #[serde(default)]
10383        height: Option<Pixels>,
10384    }
10385
10386    let workspace_id = workspace
10387        .database_id()
10388        .map(|id| i64::from(id).to_string())
10389        .or_else(|| workspace.session_id())?;
10390
10391    let legacy_key = match panel_key {
10392        "ProjectPanel" => {
10393            format!("{}-{:?}", "ProjectPanel", workspace_id)
10394        }
10395        "OutlinePanel" => {
10396            format!("{}-{:?}", "OutlinePanel", workspace_id)
10397        }
10398        "GitPanel" => {
10399            format!("{}-{:?}", "GitPanel", workspace_id)
10400        }
10401        "TerminalPanel" => {
10402            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10403        }
10404        _ => return None,
10405    };
10406
10407    let kvp = db::kvp::KeyValueStore::global(cx);
10408    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10409    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10410    let size = match dock_position {
10411        DockPosition::Bottom => state.height,
10412        DockPosition::Left | DockPosition::Right => state.width,
10413    }?;
10414
10415    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10416        .detach_and_log_err(cx);
10417
10418    Some(size)
10419}
10420
10421#[cfg(test)]
10422mod tests {
10423    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10424
10425    use super::*;
10426    use crate::{
10427        dock::{PanelEvent, test::TestPanel},
10428        item::{
10429            ItemBufferKind, ItemEvent,
10430            test::{TestItem, TestProjectItem},
10431        },
10432    };
10433    use fs::FakeFs;
10434    use gpui::{
10435        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10436        UpdateGlobal, VisualTestContext, px,
10437    };
10438    use project::{Project, ProjectEntryId};
10439    use serde_json::json;
10440    use settings::SettingsStore;
10441    use util::path;
10442    use util::rel_path::rel_path;
10443
10444    #[gpui::test]
10445    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10446        init_test(cx);
10447
10448        let fs = FakeFs::new(cx.executor());
10449        let project = Project::test(fs, [], cx).await;
10450        let (workspace, cx) =
10451            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10452
10453        // Adding an item with no ambiguity renders the tab without detail.
10454        let item1 = cx.new(|cx| {
10455            let mut item = TestItem::new(cx);
10456            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10457            item
10458        });
10459        workspace.update_in(cx, |workspace, window, cx| {
10460            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10461        });
10462        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10463
10464        // Adding an item that creates ambiguity increases the level of detail on
10465        // both tabs.
10466        let item2 = cx.new_window_entity(|_window, cx| {
10467            let mut item = TestItem::new(cx);
10468            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10469            item
10470        });
10471        workspace.update_in(cx, |workspace, window, cx| {
10472            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10473        });
10474        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10475        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10476
10477        // Adding an item that creates ambiguity increases the level of detail only
10478        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10479        // we stop at the highest detail available.
10480        let item3 = cx.new(|cx| {
10481            let mut item = TestItem::new(cx);
10482            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10483            item
10484        });
10485        workspace.update_in(cx, |workspace, window, cx| {
10486            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10487        });
10488        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10489        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10490        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10491    }
10492
10493    #[gpui::test]
10494    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10495        init_test(cx);
10496
10497        let fs = FakeFs::new(cx.executor());
10498        fs.insert_tree(
10499            "/root1",
10500            json!({
10501                "one.txt": "",
10502                "two.txt": "",
10503            }),
10504        )
10505        .await;
10506        fs.insert_tree(
10507            "/root2",
10508            json!({
10509                "three.txt": "",
10510            }),
10511        )
10512        .await;
10513
10514        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10515        let (workspace, cx) =
10516            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10517        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10518        let worktree_id = project.update(cx, |project, cx| {
10519            project.worktrees(cx).next().unwrap().read(cx).id()
10520        });
10521
10522        let item1 = cx.new(|cx| {
10523            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10524        });
10525        let item2 = cx.new(|cx| {
10526            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10527        });
10528
10529        // Add an item to an empty pane
10530        workspace.update_in(cx, |workspace, window, cx| {
10531            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10532        });
10533        project.update(cx, |project, cx| {
10534            assert_eq!(
10535                project.active_entry(),
10536                project
10537                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10538                    .map(|e| e.id)
10539            );
10540        });
10541        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10542
10543        // Add a second item to a non-empty pane
10544        workspace.update_in(cx, |workspace, window, cx| {
10545            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10546        });
10547        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10548        project.update(cx, |project, cx| {
10549            assert_eq!(
10550                project.active_entry(),
10551                project
10552                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10553                    .map(|e| e.id)
10554            );
10555        });
10556
10557        // Close the active item
10558        pane.update_in(cx, |pane, window, cx| {
10559            pane.close_active_item(&Default::default(), window, cx)
10560        })
10561        .await
10562        .unwrap();
10563        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10564        project.update(cx, |project, cx| {
10565            assert_eq!(
10566                project.active_entry(),
10567                project
10568                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10569                    .map(|e| e.id)
10570            );
10571        });
10572
10573        // Add a project folder
10574        project
10575            .update(cx, |project, cx| {
10576                project.find_or_create_worktree("root2", true, cx)
10577            })
10578            .await
10579            .unwrap();
10580        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10581
10582        // Remove a project folder
10583        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10584        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10585    }
10586
10587    #[gpui::test]
10588    async fn test_close_window(cx: &mut TestAppContext) {
10589        init_test(cx);
10590
10591        let fs = FakeFs::new(cx.executor());
10592        fs.insert_tree("/root", json!({ "one": "" })).await;
10593
10594        let project = Project::test(fs, ["root".as_ref()], cx).await;
10595        let (workspace, cx) =
10596            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10597
10598        // When there are no dirty items, there's nothing to do.
10599        let item1 = cx.new(TestItem::new);
10600        workspace.update_in(cx, |w, window, cx| {
10601            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10602        });
10603        let task = workspace.update_in(cx, |w, window, cx| {
10604            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10605        });
10606        assert!(task.await.unwrap());
10607
10608        // When there are dirty untitled items, prompt to save each one. If the user
10609        // cancels any prompt, then abort.
10610        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10611        let item3 = cx.new(|cx| {
10612            TestItem::new(cx)
10613                .with_dirty(true)
10614                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10615        });
10616        workspace.update_in(cx, |w, window, cx| {
10617            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10618            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10619        });
10620        let task = workspace.update_in(cx, |w, window, cx| {
10621            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10622        });
10623        cx.executor().run_until_parked();
10624        cx.simulate_prompt_answer("Cancel"); // cancel save all
10625        cx.executor().run_until_parked();
10626        assert!(!cx.has_pending_prompt());
10627        assert!(!task.await.unwrap());
10628    }
10629
10630    #[gpui::test]
10631    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10632        init_test(cx);
10633
10634        let fs = FakeFs::new(cx.executor());
10635        fs.insert_tree("/root", json!({ "one": "" })).await;
10636
10637        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10638        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10639        let multi_workspace_handle =
10640            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10641        cx.run_until_parked();
10642
10643        let workspace_a = multi_workspace_handle
10644            .read_with(cx, |mw, _| mw.workspace().clone())
10645            .unwrap();
10646
10647        let workspace_b = multi_workspace_handle
10648            .update(cx, |mw, window, cx| {
10649                mw.test_add_workspace(project_b, window, cx)
10650            })
10651            .unwrap();
10652
10653        // Activate workspace A
10654        multi_workspace_handle
10655            .update(cx, |mw, window, cx| {
10656                mw.activate_index(0, window, cx);
10657            })
10658            .unwrap();
10659
10660        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10661
10662        // Workspace A has a clean item
10663        let item_a = cx.new(TestItem::new);
10664        workspace_a.update_in(cx, |w, window, cx| {
10665            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10666        });
10667
10668        // Workspace B has a dirty item
10669        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10670        workspace_b.update_in(cx, |w, window, cx| {
10671            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10672        });
10673
10674        // Verify workspace A is active
10675        multi_workspace_handle
10676            .read_with(cx, |mw, _| {
10677                assert_eq!(mw.active_workspace_index(), 0);
10678            })
10679            .unwrap();
10680
10681        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10682        multi_workspace_handle
10683            .update(cx, |mw, window, cx| {
10684                mw.close_window(&CloseWindow, window, cx);
10685            })
10686            .unwrap();
10687        cx.run_until_parked();
10688
10689        // Workspace B should now be active since it has dirty items that need attention
10690        multi_workspace_handle
10691            .read_with(cx, |mw, _| {
10692                assert_eq!(
10693                    mw.active_workspace_index(),
10694                    1,
10695                    "workspace B should be activated when it prompts"
10696                );
10697            })
10698            .unwrap();
10699
10700        // User cancels the save prompt from workspace B
10701        cx.simulate_prompt_answer("Cancel");
10702        cx.run_until_parked();
10703
10704        // Window should still exist because workspace B's close was cancelled
10705        assert!(
10706            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10707            "window should still exist after cancelling one workspace's close"
10708        );
10709    }
10710
10711    #[gpui::test]
10712    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10713        init_test(cx);
10714
10715        // Register TestItem as a serializable item
10716        cx.update(|cx| {
10717            register_serializable_item::<TestItem>(cx);
10718        });
10719
10720        let fs = FakeFs::new(cx.executor());
10721        fs.insert_tree("/root", json!({ "one": "" })).await;
10722
10723        let project = Project::test(fs, ["root".as_ref()], cx).await;
10724        let (workspace, cx) =
10725            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10726
10727        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10728        let item1 = cx.new(|cx| {
10729            TestItem::new(cx)
10730                .with_dirty(true)
10731                .with_serialize(|| Some(Task::ready(Ok(()))))
10732        });
10733        let item2 = cx.new(|cx| {
10734            TestItem::new(cx)
10735                .with_dirty(true)
10736                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10737                .with_serialize(|| Some(Task::ready(Ok(()))))
10738        });
10739        workspace.update_in(cx, |w, window, cx| {
10740            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10741            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10742        });
10743        let task = workspace.update_in(cx, |w, window, cx| {
10744            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10745        });
10746        assert!(task.await.unwrap());
10747    }
10748
10749    #[gpui::test]
10750    async fn test_close_pane_items(cx: &mut TestAppContext) {
10751        init_test(cx);
10752
10753        let fs = FakeFs::new(cx.executor());
10754
10755        let project = Project::test(fs, None, cx).await;
10756        let (workspace, cx) =
10757            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10758
10759        let item1 = cx.new(|cx| {
10760            TestItem::new(cx)
10761                .with_dirty(true)
10762                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10763        });
10764        let item2 = cx.new(|cx| {
10765            TestItem::new(cx)
10766                .with_dirty(true)
10767                .with_conflict(true)
10768                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10769        });
10770        let item3 = cx.new(|cx| {
10771            TestItem::new(cx)
10772                .with_dirty(true)
10773                .with_conflict(true)
10774                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10775        });
10776        let item4 = cx.new(|cx| {
10777            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10778                let project_item = TestProjectItem::new_untitled(cx);
10779                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10780                project_item
10781            }])
10782        });
10783        let pane = workspace.update_in(cx, |workspace, window, cx| {
10784            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10785            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10786            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10787            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10788            workspace.active_pane().clone()
10789        });
10790
10791        let close_items = pane.update_in(cx, |pane, window, cx| {
10792            pane.activate_item(1, true, true, window, cx);
10793            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10794            let item1_id = item1.item_id();
10795            let item3_id = item3.item_id();
10796            let item4_id = item4.item_id();
10797            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10798                [item1_id, item3_id, item4_id].contains(&id)
10799            })
10800        });
10801        cx.executor().run_until_parked();
10802
10803        assert!(cx.has_pending_prompt());
10804        cx.simulate_prompt_answer("Save all");
10805
10806        cx.executor().run_until_parked();
10807
10808        // Item 1 is saved. There's a prompt to save item 3.
10809        pane.update(cx, |pane, cx| {
10810            assert_eq!(item1.read(cx).save_count, 1);
10811            assert_eq!(item1.read(cx).save_as_count, 0);
10812            assert_eq!(item1.read(cx).reload_count, 0);
10813            assert_eq!(pane.items_len(), 3);
10814            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10815        });
10816        assert!(cx.has_pending_prompt());
10817
10818        // Cancel saving item 3.
10819        cx.simulate_prompt_answer("Discard");
10820        cx.executor().run_until_parked();
10821
10822        // Item 3 is reloaded. There's a prompt to save item 4.
10823        pane.update(cx, |pane, cx| {
10824            assert_eq!(item3.read(cx).save_count, 0);
10825            assert_eq!(item3.read(cx).save_as_count, 0);
10826            assert_eq!(item3.read(cx).reload_count, 1);
10827            assert_eq!(pane.items_len(), 2);
10828            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10829        });
10830
10831        // There's a prompt for a path for item 4.
10832        cx.simulate_new_path_selection(|_| Some(Default::default()));
10833        close_items.await.unwrap();
10834
10835        // The requested items are closed.
10836        pane.update(cx, |pane, cx| {
10837            assert_eq!(item4.read(cx).save_count, 0);
10838            assert_eq!(item4.read(cx).save_as_count, 1);
10839            assert_eq!(item4.read(cx).reload_count, 0);
10840            assert_eq!(pane.items_len(), 1);
10841            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10842        });
10843    }
10844
10845    #[gpui::test]
10846    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10847        init_test(cx);
10848
10849        let fs = FakeFs::new(cx.executor());
10850        let project = Project::test(fs, [], cx).await;
10851        let (workspace, cx) =
10852            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10853
10854        // Create several workspace items with single project entries, and two
10855        // workspace items with multiple project entries.
10856        let single_entry_items = (0..=4)
10857            .map(|project_entry_id| {
10858                cx.new(|cx| {
10859                    TestItem::new(cx)
10860                        .with_dirty(true)
10861                        .with_project_items(&[dirty_project_item(
10862                            project_entry_id,
10863                            &format!("{project_entry_id}.txt"),
10864                            cx,
10865                        )])
10866                })
10867            })
10868            .collect::<Vec<_>>();
10869        let item_2_3 = cx.new(|cx| {
10870            TestItem::new(cx)
10871                .with_dirty(true)
10872                .with_buffer_kind(ItemBufferKind::Multibuffer)
10873                .with_project_items(&[
10874                    single_entry_items[2].read(cx).project_items[0].clone(),
10875                    single_entry_items[3].read(cx).project_items[0].clone(),
10876                ])
10877        });
10878        let item_3_4 = cx.new(|cx| {
10879            TestItem::new(cx)
10880                .with_dirty(true)
10881                .with_buffer_kind(ItemBufferKind::Multibuffer)
10882                .with_project_items(&[
10883                    single_entry_items[3].read(cx).project_items[0].clone(),
10884                    single_entry_items[4].read(cx).project_items[0].clone(),
10885                ])
10886        });
10887
10888        // Create two panes that contain the following project entries:
10889        //   left pane:
10890        //     multi-entry items:   (2, 3)
10891        //     single-entry items:  0, 2, 3, 4
10892        //   right pane:
10893        //     single-entry items:  4, 1
10894        //     multi-entry items:   (3, 4)
10895        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10896            let left_pane = workspace.active_pane().clone();
10897            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10898            workspace.add_item_to_active_pane(
10899                single_entry_items[0].boxed_clone(),
10900                None,
10901                true,
10902                window,
10903                cx,
10904            );
10905            workspace.add_item_to_active_pane(
10906                single_entry_items[2].boxed_clone(),
10907                None,
10908                true,
10909                window,
10910                cx,
10911            );
10912            workspace.add_item_to_active_pane(
10913                single_entry_items[3].boxed_clone(),
10914                None,
10915                true,
10916                window,
10917                cx,
10918            );
10919            workspace.add_item_to_active_pane(
10920                single_entry_items[4].boxed_clone(),
10921                None,
10922                true,
10923                window,
10924                cx,
10925            );
10926
10927            let right_pane =
10928                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10929
10930            let boxed_clone = single_entry_items[1].boxed_clone();
10931            let right_pane = window.spawn(cx, async move |cx| {
10932                right_pane.await.inspect(|right_pane| {
10933                    right_pane
10934                        .update_in(cx, |pane, window, cx| {
10935                            pane.add_item(boxed_clone, true, true, None, window, cx);
10936                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10937                        })
10938                        .unwrap();
10939                })
10940            });
10941
10942            (left_pane, right_pane)
10943        });
10944        let right_pane = right_pane.await.unwrap();
10945        cx.focus(&right_pane);
10946
10947        let close = right_pane.update_in(cx, |pane, window, cx| {
10948            pane.close_all_items(&CloseAllItems::default(), window, cx)
10949                .unwrap()
10950        });
10951        cx.executor().run_until_parked();
10952
10953        let msg = cx.pending_prompt().unwrap().0;
10954        assert!(msg.contains("1.txt"));
10955        assert!(!msg.contains("2.txt"));
10956        assert!(!msg.contains("3.txt"));
10957        assert!(!msg.contains("4.txt"));
10958
10959        // With best-effort close, cancelling item 1 keeps it open but items 4
10960        // and (3,4) still close since their entries exist in left pane.
10961        cx.simulate_prompt_answer("Cancel");
10962        close.await;
10963
10964        right_pane.read_with(cx, |pane, _| {
10965            assert_eq!(pane.items_len(), 1);
10966        });
10967
10968        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10969        left_pane
10970            .update_in(cx, |left_pane, window, cx| {
10971                left_pane.close_item_by_id(
10972                    single_entry_items[3].entity_id(),
10973                    SaveIntent::Skip,
10974                    window,
10975                    cx,
10976                )
10977            })
10978            .await
10979            .unwrap();
10980
10981        let close = left_pane.update_in(cx, |pane, window, cx| {
10982            pane.close_all_items(&CloseAllItems::default(), window, cx)
10983                .unwrap()
10984        });
10985        cx.executor().run_until_parked();
10986
10987        let details = cx.pending_prompt().unwrap().1;
10988        assert!(details.contains("0.txt"));
10989        assert!(details.contains("3.txt"));
10990        assert!(details.contains("4.txt"));
10991        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10992        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10993        // assert!(!details.contains("2.txt"));
10994
10995        cx.simulate_prompt_answer("Save all");
10996        cx.executor().run_until_parked();
10997        close.await;
10998
10999        left_pane.read_with(cx, |pane, _| {
11000            assert_eq!(pane.items_len(), 0);
11001        });
11002    }
11003
11004    #[gpui::test]
11005    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11006        init_test(cx);
11007
11008        let fs = FakeFs::new(cx.executor());
11009        let project = Project::test(fs, [], cx).await;
11010        let (workspace, cx) =
11011            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11012        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11013
11014        let item = cx.new(|cx| {
11015            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11016        });
11017        let item_id = item.entity_id();
11018        workspace.update_in(cx, |workspace, window, cx| {
11019            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11020        });
11021
11022        // Autosave on window change.
11023        item.update(cx, |item, cx| {
11024            SettingsStore::update_global(cx, |settings, cx| {
11025                settings.update_user_settings(cx, |settings| {
11026                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11027                })
11028            });
11029            item.is_dirty = true;
11030        });
11031
11032        // Deactivating the window saves the file.
11033        cx.deactivate_window();
11034        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11035
11036        // Re-activating the window doesn't save the file.
11037        cx.update(|window, _| window.activate_window());
11038        cx.executor().run_until_parked();
11039        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11040
11041        // Autosave on focus change.
11042        item.update_in(cx, |item, window, cx| {
11043            cx.focus_self(window);
11044            SettingsStore::update_global(cx, |settings, cx| {
11045                settings.update_user_settings(cx, |settings| {
11046                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11047                })
11048            });
11049            item.is_dirty = true;
11050        });
11051        // Blurring the item saves the file.
11052        item.update_in(cx, |_, window, _| window.blur());
11053        cx.executor().run_until_parked();
11054        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11055
11056        // Deactivating the window still saves the file.
11057        item.update_in(cx, |item, window, cx| {
11058            cx.focus_self(window);
11059            item.is_dirty = true;
11060        });
11061        cx.deactivate_window();
11062        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11063
11064        // Autosave after delay.
11065        item.update(cx, |item, cx| {
11066            SettingsStore::update_global(cx, |settings, cx| {
11067                settings.update_user_settings(cx, |settings| {
11068                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11069                        milliseconds: 500.into(),
11070                    });
11071                })
11072            });
11073            item.is_dirty = true;
11074            cx.emit(ItemEvent::Edit);
11075        });
11076
11077        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11078        cx.executor().advance_clock(Duration::from_millis(250));
11079        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11080
11081        // After delay expires, the file is saved.
11082        cx.executor().advance_clock(Duration::from_millis(250));
11083        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11084
11085        // Autosave after delay, should save earlier than delay if tab is closed
11086        item.update(cx, |item, cx| {
11087            item.is_dirty = true;
11088            cx.emit(ItemEvent::Edit);
11089        });
11090        cx.executor().advance_clock(Duration::from_millis(250));
11091        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11092
11093        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11094        pane.update_in(cx, |pane, window, cx| {
11095            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11096        })
11097        .await
11098        .unwrap();
11099        assert!(!cx.has_pending_prompt());
11100        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11101
11102        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11103        workspace.update_in(cx, |workspace, window, cx| {
11104            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11105        });
11106        item.update_in(cx, |item, _window, cx| {
11107            item.is_dirty = true;
11108            for project_item in &mut item.project_items {
11109                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11110            }
11111        });
11112        cx.run_until_parked();
11113        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11114
11115        // Autosave on focus change, ensuring closing the tab counts as such.
11116        item.update(cx, |item, cx| {
11117            SettingsStore::update_global(cx, |settings, cx| {
11118                settings.update_user_settings(cx, |settings| {
11119                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11120                })
11121            });
11122            item.is_dirty = true;
11123            for project_item in &mut item.project_items {
11124                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11125            }
11126        });
11127
11128        pane.update_in(cx, |pane, window, cx| {
11129            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11130        })
11131        .await
11132        .unwrap();
11133        assert!(!cx.has_pending_prompt());
11134        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11135
11136        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11137        workspace.update_in(cx, |workspace, window, cx| {
11138            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11139        });
11140        item.update_in(cx, |item, window, cx| {
11141            item.project_items[0].update(cx, |item, _| {
11142                item.entry_id = None;
11143            });
11144            item.is_dirty = true;
11145            window.blur();
11146        });
11147        cx.run_until_parked();
11148        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11149
11150        // Ensure autosave is prevented for deleted files also when closing the buffer.
11151        let _close_items = pane.update_in(cx, |pane, window, cx| {
11152            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11153        });
11154        cx.run_until_parked();
11155        assert!(cx.has_pending_prompt());
11156        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11157    }
11158
11159    #[gpui::test]
11160    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11161        init_test(cx);
11162
11163        let fs = FakeFs::new(cx.executor());
11164        let project = Project::test(fs, [], cx).await;
11165        let (workspace, cx) =
11166            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11167
11168        // Create a multibuffer-like item with two child focus handles,
11169        // simulating individual buffer editors within a multibuffer.
11170        let item = cx.new(|cx| {
11171            TestItem::new(cx)
11172                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11173                .with_child_focus_handles(2, cx)
11174        });
11175        workspace.update_in(cx, |workspace, window, cx| {
11176            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11177        });
11178
11179        // Set autosave to OnFocusChange and focus the first child handle,
11180        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11181        item.update_in(cx, |item, window, cx| {
11182            SettingsStore::update_global(cx, |settings, cx| {
11183                settings.update_user_settings(cx, |settings| {
11184                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11185                })
11186            });
11187            item.is_dirty = true;
11188            window.focus(&item.child_focus_handles[0], cx);
11189        });
11190        cx.executor().run_until_parked();
11191        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11192
11193        // Moving focus from one child to another within the same item should
11194        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11195        item.update_in(cx, |item, window, cx| {
11196            window.focus(&item.child_focus_handles[1], cx);
11197        });
11198        cx.executor().run_until_parked();
11199        item.read_with(cx, |item, _| {
11200            assert_eq!(
11201                item.save_count, 0,
11202                "Switching focus between children within the same item should not autosave"
11203            );
11204        });
11205
11206        // Blurring the item saves the file. This is the core regression scenario:
11207        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11208        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11209        // the leaf is always a child focus handle, so `on_blur` never detected
11210        // focus leaving the item.
11211        item.update_in(cx, |_, window, _| window.blur());
11212        cx.executor().run_until_parked();
11213        item.read_with(cx, |item, _| {
11214            assert_eq!(
11215                item.save_count, 1,
11216                "Blurring should trigger autosave when focus was on a child of the item"
11217            );
11218        });
11219
11220        // Deactivating the window should also trigger autosave when a child of
11221        // the multibuffer item currently owns focus.
11222        item.update_in(cx, |item, window, cx| {
11223            item.is_dirty = true;
11224            window.focus(&item.child_focus_handles[0], cx);
11225        });
11226        cx.executor().run_until_parked();
11227        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11228
11229        cx.deactivate_window();
11230        item.read_with(cx, |item, _| {
11231            assert_eq!(
11232                item.save_count, 2,
11233                "Deactivating window should trigger autosave when focus was on a child"
11234            );
11235        });
11236    }
11237
11238    #[gpui::test]
11239    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11240        init_test(cx);
11241
11242        let fs = FakeFs::new(cx.executor());
11243
11244        let project = Project::test(fs, [], cx).await;
11245        let (workspace, cx) =
11246            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11247
11248        let item = cx.new(|cx| {
11249            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11250        });
11251        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11252        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11253        let toolbar_notify_count = Rc::new(RefCell::new(0));
11254
11255        workspace.update_in(cx, |workspace, window, cx| {
11256            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11257            let toolbar_notification_count = toolbar_notify_count.clone();
11258            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11259                *toolbar_notification_count.borrow_mut() += 1
11260            })
11261            .detach();
11262        });
11263
11264        pane.read_with(cx, |pane, _| {
11265            assert!(!pane.can_navigate_backward());
11266            assert!(!pane.can_navigate_forward());
11267        });
11268
11269        item.update_in(cx, |item, _, cx| {
11270            item.set_state("one".to_string(), cx);
11271        });
11272
11273        // Toolbar must be notified to re-render the navigation buttons
11274        assert_eq!(*toolbar_notify_count.borrow(), 1);
11275
11276        pane.read_with(cx, |pane, _| {
11277            assert!(pane.can_navigate_backward());
11278            assert!(!pane.can_navigate_forward());
11279        });
11280
11281        workspace
11282            .update_in(cx, |workspace, window, cx| {
11283                workspace.go_back(pane.downgrade(), window, cx)
11284            })
11285            .await
11286            .unwrap();
11287
11288        assert_eq!(*toolbar_notify_count.borrow(), 2);
11289        pane.read_with(cx, |pane, _| {
11290            assert!(!pane.can_navigate_backward());
11291            assert!(pane.can_navigate_forward());
11292        });
11293    }
11294
11295    /// Tests that the navigation history deduplicates entries for the same item.
11296    ///
11297    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11298    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11299    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11300    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11301    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11302    ///
11303    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11304    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11305    #[gpui::test]
11306    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11307        init_test(cx);
11308
11309        let fs = FakeFs::new(cx.executor());
11310        let project = Project::test(fs, [], cx).await;
11311        let (workspace, cx) =
11312            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11313
11314        let item_a = cx.new(|cx| {
11315            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11316        });
11317        let item_b = cx.new(|cx| {
11318            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11319        });
11320        let item_c = cx.new(|cx| {
11321            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11322        });
11323
11324        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11325
11326        workspace.update_in(cx, |workspace, window, cx| {
11327            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11328            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11329            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11330        });
11331
11332        workspace.update_in(cx, |workspace, window, cx| {
11333            workspace.activate_item(&item_a, false, false, window, cx);
11334        });
11335        cx.run_until_parked();
11336
11337        workspace.update_in(cx, |workspace, window, cx| {
11338            workspace.activate_item(&item_b, false, false, window, cx);
11339        });
11340        cx.run_until_parked();
11341
11342        workspace.update_in(cx, |workspace, window, cx| {
11343            workspace.activate_item(&item_a, false, false, window, cx);
11344        });
11345        cx.run_until_parked();
11346
11347        workspace.update_in(cx, |workspace, window, cx| {
11348            workspace.activate_item(&item_b, false, false, window, cx);
11349        });
11350        cx.run_until_parked();
11351
11352        workspace.update_in(cx, |workspace, window, cx| {
11353            workspace.activate_item(&item_a, false, false, window, cx);
11354        });
11355        cx.run_until_parked();
11356
11357        workspace.update_in(cx, |workspace, window, cx| {
11358            workspace.activate_item(&item_b, false, false, window, cx);
11359        });
11360        cx.run_until_parked();
11361
11362        workspace.update_in(cx, |workspace, window, cx| {
11363            workspace.activate_item(&item_c, false, false, window, cx);
11364        });
11365        cx.run_until_parked();
11366
11367        let backward_count = pane.read_with(cx, |pane, cx| {
11368            let mut count = 0;
11369            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11370                count += 1;
11371            });
11372            count
11373        });
11374        assert!(
11375            backward_count <= 4,
11376            "Should have at most 4 entries, got {}",
11377            backward_count
11378        );
11379
11380        workspace
11381            .update_in(cx, |workspace, window, cx| {
11382                workspace.go_back(pane.downgrade(), window, cx)
11383            })
11384            .await
11385            .unwrap();
11386
11387        let active_item = workspace.read_with(cx, |workspace, cx| {
11388            workspace.active_item(cx).unwrap().item_id()
11389        });
11390        assert_eq!(
11391            active_item,
11392            item_b.entity_id(),
11393            "After first go_back, should be at item B"
11394        );
11395
11396        workspace
11397            .update_in(cx, |workspace, window, cx| {
11398                workspace.go_back(pane.downgrade(), window, cx)
11399            })
11400            .await
11401            .unwrap();
11402
11403        let active_item = workspace.read_with(cx, |workspace, cx| {
11404            workspace.active_item(cx).unwrap().item_id()
11405        });
11406        assert_eq!(
11407            active_item,
11408            item_a.entity_id(),
11409            "After second go_back, should be at item A"
11410        );
11411
11412        pane.read_with(cx, |pane, _| {
11413            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11414        });
11415    }
11416
11417    #[gpui::test]
11418    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11419        init_test(cx);
11420        let fs = FakeFs::new(cx.executor());
11421        let project = Project::test(fs, [], cx).await;
11422        let (multi_workspace, cx) =
11423            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11424        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11425
11426        workspace.update_in(cx, |workspace, window, cx| {
11427            let first_item = cx.new(|cx| {
11428                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11429            });
11430            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11431            workspace.split_pane(
11432                workspace.active_pane().clone(),
11433                SplitDirection::Right,
11434                window,
11435                cx,
11436            );
11437            workspace.split_pane(
11438                workspace.active_pane().clone(),
11439                SplitDirection::Right,
11440                window,
11441                cx,
11442            );
11443        });
11444
11445        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11446            let panes = workspace.center.panes();
11447            assert!(panes.len() >= 2);
11448            (
11449                panes.first().expect("at least one pane").entity_id(),
11450                panes.last().expect("at least one pane").entity_id(),
11451            )
11452        });
11453
11454        workspace.update_in(cx, |workspace, window, cx| {
11455            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11456        });
11457        workspace.update(cx, |workspace, _| {
11458            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11459            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11460        });
11461
11462        cx.dispatch_action(ActivateLastPane);
11463
11464        workspace.update(cx, |workspace, _| {
11465            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11466        });
11467    }
11468
11469    #[gpui::test]
11470    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11471        init_test(cx);
11472        let fs = FakeFs::new(cx.executor());
11473
11474        let project = Project::test(fs, [], cx).await;
11475        let (workspace, cx) =
11476            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11477
11478        let panel = workspace.update_in(cx, |workspace, window, cx| {
11479            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11480            workspace.add_panel(panel.clone(), window, cx);
11481
11482            workspace
11483                .right_dock()
11484                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11485
11486            panel
11487        });
11488
11489        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11490        pane.update_in(cx, |pane, window, cx| {
11491            let item = cx.new(TestItem::new);
11492            pane.add_item(Box::new(item), true, true, None, window, cx);
11493        });
11494
11495        // Transfer focus from center to panel
11496        workspace.update_in(cx, |workspace, window, cx| {
11497            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11498        });
11499
11500        workspace.update_in(cx, |workspace, window, cx| {
11501            assert!(workspace.right_dock().read(cx).is_open());
11502            assert!(!panel.is_zoomed(window, cx));
11503            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11504        });
11505
11506        // Transfer focus from panel to center
11507        workspace.update_in(cx, |workspace, window, cx| {
11508            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11509        });
11510
11511        workspace.update_in(cx, |workspace, window, cx| {
11512            assert!(workspace.right_dock().read(cx).is_open());
11513            assert!(!panel.is_zoomed(window, cx));
11514            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11515            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11516        });
11517
11518        // Close the dock
11519        workspace.update_in(cx, |workspace, window, cx| {
11520            workspace.toggle_dock(DockPosition::Right, window, cx);
11521        });
11522
11523        workspace.update_in(cx, |workspace, window, cx| {
11524            assert!(!workspace.right_dock().read(cx).is_open());
11525            assert!(!panel.is_zoomed(window, cx));
11526            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11527            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11528        });
11529
11530        // Open the dock
11531        workspace.update_in(cx, |workspace, window, cx| {
11532            workspace.toggle_dock(DockPosition::Right, window, cx);
11533        });
11534
11535        workspace.update_in(cx, |workspace, window, cx| {
11536            assert!(workspace.right_dock().read(cx).is_open());
11537            assert!(!panel.is_zoomed(window, cx));
11538            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11539        });
11540
11541        // Focus and zoom panel
11542        panel.update_in(cx, |panel, window, cx| {
11543            cx.focus_self(window);
11544            panel.set_zoomed(true, window, cx)
11545        });
11546
11547        workspace.update_in(cx, |workspace, window, cx| {
11548            assert!(workspace.right_dock().read(cx).is_open());
11549            assert!(panel.is_zoomed(window, cx));
11550            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11551        });
11552
11553        // Transfer focus to the center closes the dock
11554        workspace.update_in(cx, |workspace, window, cx| {
11555            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11556        });
11557
11558        workspace.update_in(cx, |workspace, window, cx| {
11559            assert!(!workspace.right_dock().read(cx).is_open());
11560            assert!(panel.is_zoomed(window, cx));
11561            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11562        });
11563
11564        // Transferring focus back to the panel keeps it zoomed
11565        workspace.update_in(cx, |workspace, window, cx| {
11566            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11567        });
11568
11569        workspace.update_in(cx, |workspace, window, cx| {
11570            assert!(workspace.right_dock().read(cx).is_open());
11571            assert!(panel.is_zoomed(window, cx));
11572            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11573        });
11574
11575        // Close the dock while it is zoomed
11576        workspace.update_in(cx, |workspace, window, cx| {
11577            workspace.toggle_dock(DockPosition::Right, window, cx)
11578        });
11579
11580        workspace.update_in(cx, |workspace, window, cx| {
11581            assert!(!workspace.right_dock().read(cx).is_open());
11582            assert!(panel.is_zoomed(window, cx));
11583            assert!(workspace.zoomed.is_none());
11584            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11585        });
11586
11587        // Opening the dock, when it's zoomed, retains focus
11588        workspace.update_in(cx, |workspace, window, cx| {
11589            workspace.toggle_dock(DockPosition::Right, window, cx)
11590        });
11591
11592        workspace.update_in(cx, |workspace, window, cx| {
11593            assert!(workspace.right_dock().read(cx).is_open());
11594            assert!(panel.is_zoomed(window, cx));
11595            assert!(workspace.zoomed.is_some());
11596            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11597        });
11598
11599        // Unzoom and close the panel, zoom the active pane.
11600        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11601        workspace.update_in(cx, |workspace, window, cx| {
11602            workspace.toggle_dock(DockPosition::Right, window, cx)
11603        });
11604        pane.update_in(cx, |pane, window, cx| {
11605            pane.toggle_zoom(&Default::default(), window, cx)
11606        });
11607
11608        // Opening a dock unzooms the pane.
11609        workspace.update_in(cx, |workspace, window, cx| {
11610            workspace.toggle_dock(DockPosition::Right, window, cx)
11611        });
11612        workspace.update_in(cx, |workspace, window, cx| {
11613            let pane = pane.read(cx);
11614            assert!(!pane.is_zoomed());
11615            assert!(!pane.focus_handle(cx).is_focused(window));
11616            assert!(workspace.right_dock().read(cx).is_open());
11617            assert!(workspace.zoomed.is_none());
11618        });
11619    }
11620
11621    #[gpui::test]
11622    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11623        init_test(cx);
11624        let fs = FakeFs::new(cx.executor());
11625
11626        let project = Project::test(fs, [], cx).await;
11627        let (workspace, cx) =
11628            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11629
11630        let panel = workspace.update_in(cx, |workspace, window, cx| {
11631            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11632            workspace.add_panel(panel.clone(), window, cx);
11633            panel
11634        });
11635
11636        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11637        pane.update_in(cx, |pane, window, cx| {
11638            let item = cx.new(TestItem::new);
11639            pane.add_item(Box::new(item), true, true, None, window, cx);
11640        });
11641
11642        // Enable close_panel_on_toggle
11643        cx.update_global(|store: &mut SettingsStore, cx| {
11644            store.update_user_settings(cx, |settings| {
11645                settings.workspace.close_panel_on_toggle = Some(true);
11646            });
11647        });
11648
11649        // Panel starts closed. Toggling should open and focus it.
11650        workspace.update_in(cx, |workspace, window, cx| {
11651            assert!(!workspace.right_dock().read(cx).is_open());
11652            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11653        });
11654
11655        workspace.update_in(cx, |workspace, window, cx| {
11656            assert!(
11657                workspace.right_dock().read(cx).is_open(),
11658                "Dock should be open after toggling from center"
11659            );
11660            assert!(
11661                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11662                "Panel should be focused after toggling from center"
11663            );
11664        });
11665
11666        // Panel is open and focused. Toggling should close the panel and
11667        // return focus to the center.
11668        workspace.update_in(cx, |workspace, window, cx| {
11669            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11670        });
11671
11672        workspace.update_in(cx, |workspace, window, cx| {
11673            assert!(
11674                !workspace.right_dock().read(cx).is_open(),
11675                "Dock should be closed after toggling from focused panel"
11676            );
11677            assert!(
11678                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11679                "Panel should not be focused after toggling from focused panel"
11680            );
11681        });
11682
11683        // Open the dock and focus something else so the panel is open but not
11684        // focused. Toggling should focus the panel (not close it).
11685        workspace.update_in(cx, |workspace, window, cx| {
11686            workspace
11687                .right_dock()
11688                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11689            window.focus(&pane.read(cx).focus_handle(cx), cx);
11690        });
11691
11692        workspace.update_in(cx, |workspace, window, cx| {
11693            assert!(workspace.right_dock().read(cx).is_open());
11694            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11695            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11696        });
11697
11698        workspace.update_in(cx, |workspace, window, cx| {
11699            assert!(
11700                workspace.right_dock().read(cx).is_open(),
11701                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11702            );
11703            assert!(
11704                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11705                "Panel should be focused after toggling an open-but-unfocused panel"
11706            );
11707        });
11708
11709        // Now disable the setting and verify the original behavior: toggling
11710        // from a focused panel moves focus to center but leaves the dock open.
11711        cx.update_global(|store: &mut SettingsStore, cx| {
11712            store.update_user_settings(cx, |settings| {
11713                settings.workspace.close_panel_on_toggle = Some(false);
11714            });
11715        });
11716
11717        workspace.update_in(cx, |workspace, window, cx| {
11718            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11719        });
11720
11721        workspace.update_in(cx, |workspace, window, cx| {
11722            assert!(
11723                workspace.right_dock().read(cx).is_open(),
11724                "Dock should remain open when setting is disabled"
11725            );
11726            assert!(
11727                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11728                "Panel should not be focused after toggling with setting disabled"
11729            );
11730        });
11731    }
11732
11733    #[gpui::test]
11734    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11735        init_test(cx);
11736        let fs = FakeFs::new(cx.executor());
11737
11738        let project = Project::test(fs, [], cx).await;
11739        let (workspace, cx) =
11740            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11741
11742        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11743            workspace.active_pane().clone()
11744        });
11745
11746        // Add an item to the pane so it can be zoomed
11747        workspace.update_in(cx, |workspace, window, cx| {
11748            let item = cx.new(TestItem::new);
11749            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11750        });
11751
11752        // Initially not zoomed
11753        workspace.update_in(cx, |workspace, _window, cx| {
11754            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11755            assert!(
11756                workspace.zoomed.is_none(),
11757                "Workspace should track no zoomed pane"
11758            );
11759            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11760        });
11761
11762        // Zoom In
11763        pane.update_in(cx, |pane, window, cx| {
11764            pane.zoom_in(&crate::ZoomIn, window, cx);
11765        });
11766
11767        workspace.update_in(cx, |workspace, window, cx| {
11768            assert!(
11769                pane.read(cx).is_zoomed(),
11770                "Pane should be zoomed after ZoomIn"
11771            );
11772            assert!(
11773                workspace.zoomed.is_some(),
11774                "Workspace should track the zoomed pane"
11775            );
11776            assert!(
11777                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11778                "ZoomIn should focus the pane"
11779            );
11780        });
11781
11782        // Zoom In again is a no-op
11783        pane.update_in(cx, |pane, window, cx| {
11784            pane.zoom_in(&crate::ZoomIn, window, cx);
11785        });
11786
11787        workspace.update_in(cx, |workspace, window, cx| {
11788            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11789            assert!(
11790                workspace.zoomed.is_some(),
11791                "Workspace still tracks zoomed pane"
11792            );
11793            assert!(
11794                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11795                "Pane remains focused after repeated ZoomIn"
11796            );
11797        });
11798
11799        // Zoom Out
11800        pane.update_in(cx, |pane, window, cx| {
11801            pane.zoom_out(&crate::ZoomOut, window, cx);
11802        });
11803
11804        workspace.update_in(cx, |workspace, _window, cx| {
11805            assert!(
11806                !pane.read(cx).is_zoomed(),
11807                "Pane should unzoom after ZoomOut"
11808            );
11809            assert!(
11810                workspace.zoomed.is_none(),
11811                "Workspace clears zoom tracking after ZoomOut"
11812            );
11813        });
11814
11815        // Zoom Out again is a no-op
11816        pane.update_in(cx, |pane, window, cx| {
11817            pane.zoom_out(&crate::ZoomOut, window, cx);
11818        });
11819
11820        workspace.update_in(cx, |workspace, _window, cx| {
11821            assert!(
11822                !pane.read(cx).is_zoomed(),
11823                "Second ZoomOut keeps pane unzoomed"
11824            );
11825            assert!(
11826                workspace.zoomed.is_none(),
11827                "Workspace remains without zoomed pane"
11828            );
11829        });
11830    }
11831
11832    #[gpui::test]
11833    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11834        init_test(cx);
11835        let fs = FakeFs::new(cx.executor());
11836
11837        let project = Project::test(fs, [], cx).await;
11838        let (workspace, cx) =
11839            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11840        workspace.update_in(cx, |workspace, window, cx| {
11841            // Open two docks
11842            let left_dock = workspace.dock_at_position(DockPosition::Left);
11843            let right_dock = workspace.dock_at_position(DockPosition::Right);
11844
11845            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11846            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11847
11848            assert!(left_dock.read(cx).is_open());
11849            assert!(right_dock.read(cx).is_open());
11850        });
11851
11852        workspace.update_in(cx, |workspace, window, cx| {
11853            // Toggle all docks - should close both
11854            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11855
11856            let left_dock = workspace.dock_at_position(DockPosition::Left);
11857            let right_dock = workspace.dock_at_position(DockPosition::Right);
11858            assert!(!left_dock.read(cx).is_open());
11859            assert!(!right_dock.read(cx).is_open());
11860        });
11861
11862        workspace.update_in(cx, |workspace, window, cx| {
11863            // Toggle again - should reopen both
11864            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11865
11866            let left_dock = workspace.dock_at_position(DockPosition::Left);
11867            let right_dock = workspace.dock_at_position(DockPosition::Right);
11868            assert!(left_dock.read(cx).is_open());
11869            assert!(right_dock.read(cx).is_open());
11870        });
11871    }
11872
11873    #[gpui::test]
11874    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11875        init_test(cx);
11876        let fs = FakeFs::new(cx.executor());
11877
11878        let project = Project::test(fs, [], cx).await;
11879        let (workspace, cx) =
11880            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11881        workspace.update_in(cx, |workspace, window, cx| {
11882            // Open two docks
11883            let left_dock = workspace.dock_at_position(DockPosition::Left);
11884            let right_dock = workspace.dock_at_position(DockPosition::Right);
11885
11886            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11887            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11888
11889            assert!(left_dock.read(cx).is_open());
11890            assert!(right_dock.read(cx).is_open());
11891        });
11892
11893        workspace.update_in(cx, |workspace, window, cx| {
11894            // Close them manually
11895            workspace.toggle_dock(DockPosition::Left, window, cx);
11896            workspace.toggle_dock(DockPosition::Right, window, cx);
11897
11898            let left_dock = workspace.dock_at_position(DockPosition::Left);
11899            let right_dock = workspace.dock_at_position(DockPosition::Right);
11900            assert!(!left_dock.read(cx).is_open());
11901            assert!(!right_dock.read(cx).is_open());
11902        });
11903
11904        workspace.update_in(cx, |workspace, window, cx| {
11905            // Toggle all docks - only last closed (right dock) should reopen
11906            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11907
11908            let left_dock = workspace.dock_at_position(DockPosition::Left);
11909            let right_dock = workspace.dock_at_position(DockPosition::Right);
11910            assert!(!left_dock.read(cx).is_open());
11911            assert!(right_dock.read(cx).is_open());
11912        });
11913    }
11914
11915    #[gpui::test]
11916    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11917        init_test(cx);
11918        let fs = FakeFs::new(cx.executor());
11919        let project = Project::test(fs, [], cx).await;
11920        let (multi_workspace, cx) =
11921            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11922        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11923
11924        // Open two docks (left and right) with one panel each
11925        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11926            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11927            workspace.add_panel(left_panel.clone(), window, cx);
11928
11929            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11930            workspace.add_panel(right_panel.clone(), window, cx);
11931
11932            workspace.toggle_dock(DockPosition::Left, window, cx);
11933            workspace.toggle_dock(DockPosition::Right, window, cx);
11934
11935            // Verify initial state
11936            assert!(
11937                workspace.left_dock().read(cx).is_open(),
11938                "Left dock should be open"
11939            );
11940            assert_eq!(
11941                workspace
11942                    .left_dock()
11943                    .read(cx)
11944                    .visible_panel()
11945                    .unwrap()
11946                    .panel_id(),
11947                left_panel.panel_id(),
11948                "Left panel should be visible in left dock"
11949            );
11950            assert!(
11951                workspace.right_dock().read(cx).is_open(),
11952                "Right dock should be open"
11953            );
11954            assert_eq!(
11955                workspace
11956                    .right_dock()
11957                    .read(cx)
11958                    .visible_panel()
11959                    .unwrap()
11960                    .panel_id(),
11961                right_panel.panel_id(),
11962                "Right panel should be visible in right dock"
11963            );
11964            assert!(
11965                !workspace.bottom_dock().read(cx).is_open(),
11966                "Bottom dock should be closed"
11967            );
11968
11969            (left_panel, right_panel)
11970        });
11971
11972        // Focus the left panel and move it to the next position (bottom dock)
11973        workspace.update_in(cx, |workspace, window, cx| {
11974            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11975            assert!(
11976                left_panel.read(cx).focus_handle(cx).is_focused(window),
11977                "Left panel should be focused"
11978            );
11979        });
11980
11981        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11982
11983        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11984        workspace.update(cx, |workspace, cx| {
11985            assert!(
11986                !workspace.left_dock().read(cx).is_open(),
11987                "Left dock should be closed"
11988            );
11989            assert!(
11990                workspace.bottom_dock().read(cx).is_open(),
11991                "Bottom dock should now be open"
11992            );
11993            assert_eq!(
11994                left_panel.read(cx).position,
11995                DockPosition::Bottom,
11996                "Left panel should now be in the bottom dock"
11997            );
11998            assert_eq!(
11999                workspace
12000                    .bottom_dock()
12001                    .read(cx)
12002                    .visible_panel()
12003                    .unwrap()
12004                    .panel_id(),
12005                left_panel.panel_id(),
12006                "Left panel should be the visible panel in the bottom dock"
12007            );
12008        });
12009
12010        // Toggle all docks off
12011        workspace.update_in(cx, |workspace, window, cx| {
12012            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12013            assert!(
12014                !workspace.left_dock().read(cx).is_open(),
12015                "Left dock should be closed"
12016            );
12017            assert!(
12018                !workspace.right_dock().read(cx).is_open(),
12019                "Right dock should be closed"
12020            );
12021            assert!(
12022                !workspace.bottom_dock().read(cx).is_open(),
12023                "Bottom dock should be closed"
12024            );
12025        });
12026
12027        // Toggle all docks back on and verify positions are restored
12028        workspace.update_in(cx, |workspace, window, cx| {
12029            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12030            assert!(
12031                !workspace.left_dock().read(cx).is_open(),
12032                "Left dock should remain closed"
12033            );
12034            assert!(
12035                workspace.right_dock().read(cx).is_open(),
12036                "Right dock should remain open"
12037            );
12038            assert!(
12039                workspace.bottom_dock().read(cx).is_open(),
12040                "Bottom dock should remain open"
12041            );
12042            assert_eq!(
12043                left_panel.read(cx).position,
12044                DockPosition::Bottom,
12045                "Left panel should remain in the bottom dock"
12046            );
12047            assert_eq!(
12048                right_panel.read(cx).position,
12049                DockPosition::Right,
12050                "Right panel should remain in the right dock"
12051            );
12052            assert_eq!(
12053                workspace
12054                    .bottom_dock()
12055                    .read(cx)
12056                    .visible_panel()
12057                    .unwrap()
12058                    .panel_id(),
12059                left_panel.panel_id(),
12060                "Left panel should be the visible panel in the right dock"
12061            );
12062        });
12063    }
12064
12065    #[gpui::test]
12066    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12067        init_test(cx);
12068
12069        let fs = FakeFs::new(cx.executor());
12070
12071        let project = Project::test(fs, None, cx).await;
12072        let (workspace, cx) =
12073            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12074
12075        // Let's arrange the panes like this:
12076        //
12077        // +-----------------------+
12078        // |         top           |
12079        // +------+--------+-------+
12080        // | left | center | right |
12081        // +------+--------+-------+
12082        // |        bottom         |
12083        // +-----------------------+
12084
12085        let top_item = cx.new(|cx| {
12086            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12087        });
12088        let bottom_item = cx.new(|cx| {
12089            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12090        });
12091        let left_item = cx.new(|cx| {
12092            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12093        });
12094        let right_item = cx.new(|cx| {
12095            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12096        });
12097        let center_item = cx.new(|cx| {
12098            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12099        });
12100
12101        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12102            let top_pane_id = workspace.active_pane().entity_id();
12103            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12104            workspace.split_pane(
12105                workspace.active_pane().clone(),
12106                SplitDirection::Down,
12107                window,
12108                cx,
12109            );
12110            top_pane_id
12111        });
12112        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12113            let bottom_pane_id = workspace.active_pane().entity_id();
12114            workspace.add_item_to_active_pane(
12115                Box::new(bottom_item.clone()),
12116                None,
12117                false,
12118                window,
12119                cx,
12120            );
12121            workspace.split_pane(
12122                workspace.active_pane().clone(),
12123                SplitDirection::Up,
12124                window,
12125                cx,
12126            );
12127            bottom_pane_id
12128        });
12129        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12130            let left_pane_id = workspace.active_pane().entity_id();
12131            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12132            workspace.split_pane(
12133                workspace.active_pane().clone(),
12134                SplitDirection::Right,
12135                window,
12136                cx,
12137            );
12138            left_pane_id
12139        });
12140        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12141            let right_pane_id = workspace.active_pane().entity_id();
12142            workspace.add_item_to_active_pane(
12143                Box::new(right_item.clone()),
12144                None,
12145                false,
12146                window,
12147                cx,
12148            );
12149            workspace.split_pane(
12150                workspace.active_pane().clone(),
12151                SplitDirection::Left,
12152                window,
12153                cx,
12154            );
12155            right_pane_id
12156        });
12157        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12158            let center_pane_id = workspace.active_pane().entity_id();
12159            workspace.add_item_to_active_pane(
12160                Box::new(center_item.clone()),
12161                None,
12162                false,
12163                window,
12164                cx,
12165            );
12166            center_pane_id
12167        });
12168        cx.executor().run_until_parked();
12169
12170        workspace.update_in(cx, |workspace, window, cx| {
12171            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12172
12173            // Join into next from center pane into right
12174            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12175        });
12176
12177        workspace.update_in(cx, |workspace, window, cx| {
12178            let active_pane = workspace.active_pane();
12179            assert_eq!(right_pane_id, active_pane.entity_id());
12180            assert_eq!(2, active_pane.read(cx).items_len());
12181            let item_ids_in_pane =
12182                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12183            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12184            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12185
12186            // Join into next from right pane into bottom
12187            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12188        });
12189
12190        workspace.update_in(cx, |workspace, window, cx| {
12191            let active_pane = workspace.active_pane();
12192            assert_eq!(bottom_pane_id, active_pane.entity_id());
12193            assert_eq!(3, active_pane.read(cx).items_len());
12194            let item_ids_in_pane =
12195                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12196            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12197            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12198            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12199
12200            // Join into next from bottom pane into left
12201            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12202        });
12203
12204        workspace.update_in(cx, |workspace, window, cx| {
12205            let active_pane = workspace.active_pane();
12206            assert_eq!(left_pane_id, active_pane.entity_id());
12207            assert_eq!(4, active_pane.read(cx).items_len());
12208            let item_ids_in_pane =
12209                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12210            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12211            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12212            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12213            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12214
12215            // Join into next from left pane into top
12216            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12217        });
12218
12219        workspace.update_in(cx, |workspace, window, cx| {
12220            let active_pane = workspace.active_pane();
12221            assert_eq!(top_pane_id, active_pane.entity_id());
12222            assert_eq!(5, active_pane.read(cx).items_len());
12223            let item_ids_in_pane =
12224                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12225            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12226            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12227            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12228            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12229            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12230
12231            // Single pane left: no-op
12232            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12233        });
12234
12235        workspace.update(cx, |workspace, _cx| {
12236            let active_pane = workspace.active_pane();
12237            assert_eq!(top_pane_id, active_pane.entity_id());
12238        });
12239    }
12240
12241    fn add_an_item_to_active_pane(
12242        cx: &mut VisualTestContext,
12243        workspace: &Entity<Workspace>,
12244        item_id: u64,
12245    ) -> Entity<TestItem> {
12246        let item = cx.new(|cx| {
12247            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12248                item_id,
12249                "item{item_id}.txt",
12250                cx,
12251            )])
12252        });
12253        workspace.update_in(cx, |workspace, window, cx| {
12254            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12255        });
12256        item
12257    }
12258
12259    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12260        workspace.update_in(cx, |workspace, window, cx| {
12261            workspace.split_pane(
12262                workspace.active_pane().clone(),
12263                SplitDirection::Right,
12264                window,
12265                cx,
12266            )
12267        })
12268    }
12269
12270    #[gpui::test]
12271    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12272        init_test(cx);
12273        let fs = FakeFs::new(cx.executor());
12274        let project = Project::test(fs, None, cx).await;
12275        let (workspace, cx) =
12276            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12277
12278        add_an_item_to_active_pane(cx, &workspace, 1);
12279        split_pane(cx, &workspace);
12280        add_an_item_to_active_pane(cx, &workspace, 2);
12281        split_pane(cx, &workspace); // empty pane
12282        split_pane(cx, &workspace);
12283        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12284
12285        cx.executor().run_until_parked();
12286
12287        workspace.update(cx, |workspace, cx| {
12288            let num_panes = workspace.panes().len();
12289            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12290            let active_item = workspace
12291                .active_pane()
12292                .read(cx)
12293                .active_item()
12294                .expect("item is in focus");
12295
12296            assert_eq!(num_panes, 4);
12297            assert_eq!(num_items_in_current_pane, 1);
12298            assert_eq!(active_item.item_id(), last_item.item_id());
12299        });
12300
12301        workspace.update_in(cx, |workspace, window, cx| {
12302            workspace.join_all_panes(window, cx);
12303        });
12304
12305        workspace.update(cx, |workspace, cx| {
12306            let num_panes = workspace.panes().len();
12307            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12308            let active_item = workspace
12309                .active_pane()
12310                .read(cx)
12311                .active_item()
12312                .expect("item is in focus");
12313
12314            assert_eq!(num_panes, 1);
12315            assert_eq!(num_items_in_current_pane, 3);
12316            assert_eq!(active_item.item_id(), last_item.item_id());
12317        });
12318    }
12319
12320    #[gpui::test]
12321    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12322        init_test(cx);
12323        let fs = FakeFs::new(cx.executor());
12324
12325        let project = Project::test(fs, [], cx).await;
12326        let (multi_workspace, cx) =
12327            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12328        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12329
12330        workspace.update(cx, |workspace, _cx| {
12331            workspace.bounds.size.width = px(800.);
12332        });
12333
12334        workspace.update_in(cx, |workspace, window, cx| {
12335            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12336            workspace.add_panel(panel, window, cx);
12337            workspace.toggle_dock(DockPosition::Right, window, cx);
12338        });
12339
12340        let (panel, resized_width, ratio_basis_width) =
12341            workspace.update_in(cx, |workspace, window, cx| {
12342                let item = cx.new(|cx| {
12343                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12344                });
12345                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12346
12347                let dock = workspace.right_dock().read(cx);
12348                let workspace_width = workspace.bounds.size.width;
12349                let initial_width = workspace
12350                    .dock_size(&dock, window, cx)
12351                    .expect("flexible dock should have an initial width");
12352
12353                assert_eq!(initial_width, workspace_width / 2.);
12354
12355                workspace.resize_right_dock(px(300.), window, cx);
12356
12357                let dock = workspace.right_dock().read(cx);
12358                let resized_width = workspace
12359                    .dock_size(&dock, window, cx)
12360                    .expect("flexible dock should keep its resized width");
12361
12362                assert_eq!(resized_width, px(300.));
12363
12364                let panel = workspace
12365                    .right_dock()
12366                    .read(cx)
12367                    .visible_panel()
12368                    .expect("flexible dock should have a visible panel")
12369                    .panel_id();
12370
12371                (panel, resized_width, workspace_width)
12372            });
12373
12374        workspace.update_in(cx, |workspace, window, cx| {
12375            workspace.toggle_dock(DockPosition::Right, window, cx);
12376            workspace.toggle_dock(DockPosition::Right, window, cx);
12377
12378            let dock = workspace.right_dock().read(cx);
12379            let reopened_width = workspace
12380                .dock_size(&dock, window, cx)
12381                .expect("flexible dock should restore when reopened");
12382
12383            assert_eq!(reopened_width, resized_width);
12384
12385            let right_dock = workspace.right_dock().read(cx);
12386            let flexible_panel = right_dock
12387                .visible_panel()
12388                .expect("flexible dock should still have a visible panel");
12389            assert_eq!(flexible_panel.panel_id(), panel);
12390            assert_eq!(
12391                right_dock
12392                    .stored_panel_size_state(flexible_panel.as_ref())
12393                    .and_then(|size_state| size_state.flex),
12394                Some(
12395                    resized_width.to_f64() as f32
12396                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12397                )
12398            );
12399        });
12400
12401        workspace.update_in(cx, |workspace, window, cx| {
12402            workspace.split_pane(
12403                workspace.active_pane().clone(),
12404                SplitDirection::Right,
12405                window,
12406                cx,
12407            );
12408
12409            let dock = workspace.right_dock().read(cx);
12410            let split_width = workspace
12411                .dock_size(&dock, window, cx)
12412                .expect("flexible dock should keep its user-resized proportion");
12413
12414            assert_eq!(split_width, px(300.));
12415
12416            workspace.bounds.size.width = px(1600.);
12417
12418            let dock = workspace.right_dock().read(cx);
12419            let resized_window_width = workspace
12420                .dock_size(&dock, window, cx)
12421                .expect("flexible dock should preserve proportional size on window resize");
12422
12423            assert_eq!(
12424                resized_window_width,
12425                workspace.bounds.size.width
12426                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12427            );
12428        });
12429    }
12430
12431    #[gpui::test]
12432    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12433        init_test(cx);
12434        let fs = FakeFs::new(cx.executor());
12435
12436        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12437        {
12438            let project = Project::test(fs.clone(), [], cx).await;
12439            let (multi_workspace, cx) =
12440                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12441            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12442
12443            workspace.update(cx, |workspace, _cx| {
12444                workspace.set_random_database_id();
12445                workspace.bounds.size.width = px(800.);
12446            });
12447
12448            let panel = workspace.update_in(cx, |workspace, window, cx| {
12449                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12450                workspace.add_panel(panel.clone(), window, cx);
12451                workspace.toggle_dock(DockPosition::Left, window, cx);
12452                panel
12453            });
12454
12455            workspace.update_in(cx, |workspace, window, cx| {
12456                workspace.resize_left_dock(px(350.), window, cx);
12457            });
12458
12459            cx.run_until_parked();
12460
12461            let persisted = workspace.read_with(cx, |workspace, cx| {
12462                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12463            });
12464            assert_eq!(
12465                persisted.and_then(|s| s.size),
12466                Some(px(350.)),
12467                "fixed-width panel size should be persisted to KVP"
12468            );
12469
12470            // Remove the panel and re-add a fresh instance with the same key.
12471            // The new instance should have its size state restored from KVP.
12472            workspace.update_in(cx, |workspace, window, cx| {
12473                workspace.remove_panel(&panel, window, cx);
12474            });
12475
12476            workspace.update_in(cx, |workspace, window, cx| {
12477                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12478                workspace.add_panel(new_panel, window, cx);
12479
12480                let left_dock = workspace.left_dock().read(cx);
12481                let size_state = left_dock
12482                    .panel::<TestPanel>()
12483                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12484                assert_eq!(
12485                    size_state.and_then(|s| s.size),
12486                    Some(px(350.)),
12487                    "re-added fixed-width panel should restore persisted size from KVP"
12488                );
12489            });
12490        }
12491
12492        // Flexible panel: both pixel size and ratio are persisted and restored.
12493        {
12494            let project = Project::test(fs.clone(), [], cx).await;
12495            let (multi_workspace, cx) =
12496                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12497            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12498
12499            workspace.update(cx, |workspace, _cx| {
12500                workspace.set_random_database_id();
12501                workspace.bounds.size.width = px(800.);
12502            });
12503
12504            let panel = workspace.update_in(cx, |workspace, window, cx| {
12505                let item = cx.new(|cx| {
12506                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12507                });
12508                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12509
12510                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12511                workspace.add_panel(panel.clone(), window, cx);
12512                workspace.toggle_dock(DockPosition::Right, window, cx);
12513                panel
12514            });
12515
12516            workspace.update_in(cx, |workspace, window, cx| {
12517                workspace.resize_right_dock(px(300.), window, cx);
12518            });
12519
12520            cx.run_until_parked();
12521
12522            let persisted = workspace
12523                .read_with(cx, |workspace, cx| {
12524                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12525                })
12526                .expect("flexible panel state should be persisted to KVP");
12527            assert_eq!(
12528                persisted.size, None,
12529                "flexible panel should not persist a redundant pixel size"
12530            );
12531            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12532
12533            // Remove the panel and re-add: both size and ratio should be restored.
12534            workspace.update_in(cx, |workspace, window, cx| {
12535                workspace.remove_panel(&panel, window, cx);
12536            });
12537
12538            workspace.update_in(cx, |workspace, window, cx| {
12539                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12540                workspace.add_panel(new_panel, window, cx);
12541
12542                let right_dock = workspace.right_dock().read(cx);
12543                let size_state = right_dock
12544                    .panel::<TestPanel>()
12545                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12546                    .expect("re-added flexible panel should have restored size state from KVP");
12547                assert_eq!(
12548                    size_state.size, None,
12549                    "re-added flexible panel should not have a persisted pixel size"
12550                );
12551                assert_eq!(
12552                    size_state.flex,
12553                    Some(original_ratio),
12554                    "re-added flexible panel should restore persisted flex"
12555                );
12556            });
12557        }
12558    }
12559
12560    #[gpui::test]
12561    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12562        init_test(cx);
12563        let fs = FakeFs::new(cx.executor());
12564
12565        let project = Project::test(fs, [], cx).await;
12566        let (multi_workspace, cx) =
12567            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12568        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12569
12570        workspace.update(cx, |workspace, _cx| {
12571            workspace.bounds.size.width = px(900.);
12572        });
12573
12574        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12575        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12576        // and the center pane each take half the workspace width.
12577        workspace.update_in(cx, |workspace, window, cx| {
12578            let item = cx.new(|cx| {
12579                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12580            });
12581            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12582
12583            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12584            workspace.add_panel(panel, window, cx);
12585            workspace.toggle_dock(DockPosition::Left, window, cx);
12586
12587            let left_dock = workspace.left_dock().read(cx);
12588            let left_width = workspace
12589                .dock_size(&left_dock, window, cx)
12590                .expect("left dock should have an active panel");
12591
12592            assert_eq!(
12593                left_width,
12594                workspace.bounds.size.width / 2.,
12595                "flexible left panel should split evenly with the center pane"
12596            );
12597        });
12598
12599        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12600        // change horizontal width fractions, so the flexible panel stays at the same
12601        // width as each half of the split.
12602        workspace.update_in(cx, |workspace, window, cx| {
12603            workspace.split_pane(
12604                workspace.active_pane().clone(),
12605                SplitDirection::Down,
12606                window,
12607                cx,
12608            );
12609
12610            let left_dock = workspace.left_dock().read(cx);
12611            let left_width = workspace
12612                .dock_size(&left_dock, window, cx)
12613                .expect("left dock should still have an active panel after vertical split");
12614
12615            assert_eq!(
12616                left_width,
12617                workspace.bounds.size.width / 2.,
12618                "flexible left panel width should match each vertically-split pane"
12619            );
12620        });
12621
12622        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12623        // size reduces the available width, so the flexible left panel and the center
12624        // panes all shrink proportionally to accommodate it.
12625        workspace.update_in(cx, |workspace, window, cx| {
12626            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12627            workspace.add_panel(panel, window, cx);
12628            workspace.toggle_dock(DockPosition::Right, window, cx);
12629
12630            let right_dock = workspace.right_dock().read(cx);
12631            let right_width = workspace
12632                .dock_size(&right_dock, window, cx)
12633                .expect("right dock should have an active panel");
12634
12635            let left_dock = workspace.left_dock().read(cx);
12636            let left_width = workspace
12637                .dock_size(&left_dock, window, cx)
12638                .expect("left dock should still have an active panel");
12639
12640            let available_width = workspace.bounds.size.width - right_width;
12641            assert_eq!(
12642                left_width,
12643                available_width / 2.,
12644                "flexible left panel should shrink proportionally as the right dock takes space"
12645            );
12646        });
12647
12648        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12649        // flex sizing and the workspace width is divided among left-flex, center
12650        // (implicit flex 1.0), and right-flex.
12651        workspace.update_in(cx, |workspace, window, cx| {
12652            let right_dock = workspace.right_dock().clone();
12653            let right_panel = right_dock
12654                .read(cx)
12655                .visible_panel()
12656                .expect("right dock should have a visible panel")
12657                .clone();
12658            workspace.toggle_dock_panel_flexible_size(
12659                &right_dock,
12660                right_panel.as_ref(),
12661                window,
12662                cx,
12663            );
12664
12665            let right_dock = right_dock.read(cx);
12666            let right_panel = right_dock
12667                .visible_panel()
12668                .expect("right dock should still have a visible panel");
12669            assert!(
12670                right_panel.has_flexible_size(window, cx),
12671                "right panel should now be flexible"
12672            );
12673
12674            let right_size_state = right_dock
12675                .stored_panel_size_state(right_panel.as_ref())
12676                .expect("right panel should have a stored size state after toggling");
12677            let right_flex = right_size_state
12678                .flex
12679                .expect("right panel should have a flex value after toggling");
12680
12681            let left_dock = workspace.left_dock().read(cx);
12682            let left_width = workspace
12683                .dock_size(&left_dock, window, cx)
12684                .expect("left dock should still have an active panel");
12685            let right_width = workspace
12686                .dock_size(&right_dock, window, cx)
12687                .expect("right dock should still have an active panel");
12688
12689            let left_flex = workspace
12690                .default_dock_flex(DockPosition::Left)
12691                .expect("left dock should have a default flex");
12692
12693            let total_flex = left_flex + 1.0 + right_flex;
12694            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12695            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12696            assert_eq!(
12697                left_width, expected_left,
12698                "flexible left panel should share workspace width via flex ratios"
12699            );
12700            assert_eq!(
12701                right_width, expected_right,
12702                "flexible right panel should share workspace width via flex ratios"
12703            );
12704        });
12705    }
12706
12707    struct TestModal(FocusHandle);
12708
12709    impl TestModal {
12710        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12711            Self(cx.focus_handle())
12712        }
12713    }
12714
12715    impl EventEmitter<DismissEvent> for TestModal {}
12716
12717    impl Focusable for TestModal {
12718        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12719            self.0.clone()
12720        }
12721    }
12722
12723    impl ModalView for TestModal {}
12724
12725    impl Render for TestModal {
12726        fn render(
12727            &mut self,
12728            _window: &mut Window,
12729            _cx: &mut Context<TestModal>,
12730        ) -> impl IntoElement {
12731            div().track_focus(&self.0)
12732        }
12733    }
12734
12735    #[gpui::test]
12736    async fn test_panels(cx: &mut gpui::TestAppContext) {
12737        init_test(cx);
12738        let fs = FakeFs::new(cx.executor());
12739
12740        let project = Project::test(fs, [], cx).await;
12741        let (multi_workspace, cx) =
12742            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12743        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12744
12745        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12746            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12747            workspace.add_panel(panel_1.clone(), window, cx);
12748            workspace.toggle_dock(DockPosition::Left, window, cx);
12749            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12750            workspace.add_panel(panel_2.clone(), window, cx);
12751            workspace.toggle_dock(DockPosition::Right, window, cx);
12752
12753            let left_dock = workspace.left_dock();
12754            assert_eq!(
12755                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12756                panel_1.panel_id()
12757            );
12758            assert_eq!(
12759                workspace.dock_size(&left_dock.read(cx), window, cx),
12760                Some(px(300.))
12761            );
12762
12763            workspace.resize_left_dock(px(1337.), window, cx);
12764            assert_eq!(
12765                workspace
12766                    .right_dock()
12767                    .read(cx)
12768                    .visible_panel()
12769                    .unwrap()
12770                    .panel_id(),
12771                panel_2.panel_id(),
12772            );
12773
12774            (panel_1, panel_2)
12775        });
12776
12777        // Move panel_1 to the right
12778        panel_1.update_in(cx, |panel_1, window, cx| {
12779            panel_1.set_position(DockPosition::Right, window, cx)
12780        });
12781
12782        workspace.update_in(cx, |workspace, window, cx| {
12783            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12784            // Since it was the only panel on the left, the left dock should now be closed.
12785            assert!(!workspace.left_dock().read(cx).is_open());
12786            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12787            let right_dock = workspace.right_dock();
12788            assert_eq!(
12789                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12790                panel_1.panel_id()
12791            );
12792            assert_eq!(
12793                right_dock
12794                    .read(cx)
12795                    .active_panel_size()
12796                    .unwrap()
12797                    .size
12798                    .unwrap(),
12799                px(1337.)
12800            );
12801
12802            // Now we move panel_2 to the left
12803            panel_2.set_position(DockPosition::Left, window, cx);
12804        });
12805
12806        workspace.update(cx, |workspace, cx| {
12807            // Since panel_2 was not visible on the right, we don't open the left dock.
12808            assert!(!workspace.left_dock().read(cx).is_open());
12809            // And the right dock is unaffected in its displaying of panel_1
12810            assert!(workspace.right_dock().read(cx).is_open());
12811            assert_eq!(
12812                workspace
12813                    .right_dock()
12814                    .read(cx)
12815                    .visible_panel()
12816                    .unwrap()
12817                    .panel_id(),
12818                panel_1.panel_id(),
12819            );
12820        });
12821
12822        // Move panel_1 back to the left
12823        panel_1.update_in(cx, |panel_1, window, cx| {
12824            panel_1.set_position(DockPosition::Left, window, cx)
12825        });
12826
12827        workspace.update_in(cx, |workspace, window, cx| {
12828            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12829            let left_dock = workspace.left_dock();
12830            assert!(left_dock.read(cx).is_open());
12831            assert_eq!(
12832                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12833                panel_1.panel_id()
12834            );
12835            assert_eq!(
12836                workspace.dock_size(&left_dock.read(cx), window, cx),
12837                Some(px(1337.))
12838            );
12839            // And the right dock should be closed as it no longer has any panels.
12840            assert!(!workspace.right_dock().read(cx).is_open());
12841
12842            // Now we move panel_1 to the bottom
12843            panel_1.set_position(DockPosition::Bottom, window, cx);
12844        });
12845
12846        workspace.update_in(cx, |workspace, window, cx| {
12847            // Since panel_1 was visible on the left, we close the left dock.
12848            assert!(!workspace.left_dock().read(cx).is_open());
12849            // The bottom dock is sized based on the panel's default size,
12850            // since the panel orientation changed from vertical to horizontal.
12851            let bottom_dock = workspace.bottom_dock();
12852            assert_eq!(
12853                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12854                Some(px(300.))
12855            );
12856            // Close bottom dock and move panel_1 back to the left.
12857            bottom_dock.update(cx, |bottom_dock, cx| {
12858                bottom_dock.set_open(false, window, cx)
12859            });
12860            panel_1.set_position(DockPosition::Left, window, cx);
12861        });
12862
12863        // Emit activated event on panel 1
12864        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12865
12866        // Now the left dock is open and panel_1 is active and focused.
12867        workspace.update_in(cx, |workspace, window, cx| {
12868            let left_dock = workspace.left_dock();
12869            assert!(left_dock.read(cx).is_open());
12870            assert_eq!(
12871                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12872                panel_1.panel_id(),
12873            );
12874            assert!(panel_1.focus_handle(cx).is_focused(window));
12875        });
12876
12877        // Emit closed event on panel 2, which is not active
12878        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12879
12880        // Wo don't close the left dock, because panel_2 wasn't the active panel
12881        workspace.update(cx, |workspace, cx| {
12882            let left_dock = workspace.left_dock();
12883            assert!(left_dock.read(cx).is_open());
12884            assert_eq!(
12885                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12886                panel_1.panel_id(),
12887            );
12888        });
12889
12890        // Emitting a ZoomIn event shows the panel as zoomed.
12891        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12892        workspace.read_with(cx, |workspace, _| {
12893            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12894            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12895        });
12896
12897        // Move panel to another dock while it is zoomed
12898        panel_1.update_in(cx, |panel, window, cx| {
12899            panel.set_position(DockPosition::Right, window, cx)
12900        });
12901        workspace.read_with(cx, |workspace, _| {
12902            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12903
12904            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12905        });
12906
12907        // This is a helper for getting a:
12908        // - valid focus on an element,
12909        // - that isn't a part of the panes and panels system of the Workspace,
12910        // - and doesn't trigger the 'on_focus_lost' API.
12911        let focus_other_view = {
12912            let workspace = workspace.clone();
12913            move |cx: &mut VisualTestContext| {
12914                workspace.update_in(cx, |workspace, window, cx| {
12915                    if workspace.active_modal::<TestModal>(cx).is_some() {
12916                        workspace.toggle_modal(window, cx, TestModal::new);
12917                        workspace.toggle_modal(window, cx, TestModal::new);
12918                    } else {
12919                        workspace.toggle_modal(window, cx, TestModal::new);
12920                    }
12921                })
12922            }
12923        };
12924
12925        // If focus is transferred to another view that's not a panel or another pane, we still show
12926        // the panel as zoomed.
12927        focus_other_view(cx);
12928        workspace.read_with(cx, |workspace, _| {
12929            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12930            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12931        });
12932
12933        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12934        workspace.update_in(cx, |_workspace, window, cx| {
12935            cx.focus_self(window);
12936        });
12937        workspace.read_with(cx, |workspace, _| {
12938            assert_eq!(workspace.zoomed, None);
12939            assert_eq!(workspace.zoomed_position, None);
12940        });
12941
12942        // If focus is transferred again to another view that's not a panel or a pane, we won't
12943        // show the panel as zoomed because it wasn't zoomed before.
12944        focus_other_view(cx);
12945        workspace.read_with(cx, |workspace, _| {
12946            assert_eq!(workspace.zoomed, None);
12947            assert_eq!(workspace.zoomed_position, None);
12948        });
12949
12950        // When the panel is activated, it is zoomed again.
12951        cx.dispatch_action(ToggleRightDock);
12952        workspace.read_with(cx, |workspace, _| {
12953            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12954            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12955        });
12956
12957        // Emitting a ZoomOut event unzooms the panel.
12958        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12959        workspace.read_with(cx, |workspace, _| {
12960            assert_eq!(workspace.zoomed, None);
12961            assert_eq!(workspace.zoomed_position, None);
12962        });
12963
12964        // Emit closed event on panel 1, which is active
12965        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12966
12967        // Now the left dock is closed, because panel_1 was the active panel
12968        workspace.update(cx, |workspace, cx| {
12969            let right_dock = workspace.right_dock();
12970            assert!(!right_dock.read(cx).is_open());
12971        });
12972    }
12973
12974    #[gpui::test]
12975    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12976        init_test(cx);
12977
12978        let fs = FakeFs::new(cx.background_executor.clone());
12979        let project = Project::test(fs, [], cx).await;
12980        let (workspace, cx) =
12981            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12982        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12983
12984        let dirty_regular_buffer = cx.new(|cx| {
12985            TestItem::new(cx)
12986                .with_dirty(true)
12987                .with_label("1.txt")
12988                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12989        });
12990        let dirty_regular_buffer_2 = cx.new(|cx| {
12991            TestItem::new(cx)
12992                .with_dirty(true)
12993                .with_label("2.txt")
12994                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12995        });
12996        let dirty_multi_buffer_with_both = cx.new(|cx| {
12997            TestItem::new(cx)
12998                .with_dirty(true)
12999                .with_buffer_kind(ItemBufferKind::Multibuffer)
13000                .with_label("Fake Project Search")
13001                .with_project_items(&[
13002                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13003                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13004                ])
13005        });
13006        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13007        workspace.update_in(cx, |workspace, window, cx| {
13008            workspace.add_item(
13009                pane.clone(),
13010                Box::new(dirty_regular_buffer.clone()),
13011                None,
13012                false,
13013                false,
13014                window,
13015                cx,
13016            );
13017            workspace.add_item(
13018                pane.clone(),
13019                Box::new(dirty_regular_buffer_2.clone()),
13020                None,
13021                false,
13022                false,
13023                window,
13024                cx,
13025            );
13026            workspace.add_item(
13027                pane.clone(),
13028                Box::new(dirty_multi_buffer_with_both.clone()),
13029                None,
13030                false,
13031                false,
13032                window,
13033                cx,
13034            );
13035        });
13036
13037        pane.update_in(cx, |pane, window, cx| {
13038            pane.activate_item(2, true, true, window, cx);
13039            assert_eq!(
13040                pane.active_item().unwrap().item_id(),
13041                multi_buffer_with_both_files_id,
13042                "Should select the multi buffer in the pane"
13043            );
13044        });
13045        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13046            pane.close_other_items(
13047                &CloseOtherItems {
13048                    save_intent: Some(SaveIntent::Save),
13049                    close_pinned: true,
13050                },
13051                None,
13052                window,
13053                cx,
13054            )
13055        });
13056        cx.background_executor.run_until_parked();
13057        assert!(!cx.has_pending_prompt());
13058        close_all_but_multi_buffer_task
13059            .await
13060            .expect("Closing all buffers but the multi buffer failed");
13061        pane.update(cx, |pane, cx| {
13062            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13063            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13064            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13065            assert_eq!(pane.items_len(), 1);
13066            assert_eq!(
13067                pane.active_item().unwrap().item_id(),
13068                multi_buffer_with_both_files_id,
13069                "Should have only the multi buffer left in the pane"
13070            );
13071            assert!(
13072                dirty_multi_buffer_with_both.read(cx).is_dirty,
13073                "The multi buffer containing the unsaved buffer should still be dirty"
13074            );
13075        });
13076
13077        dirty_regular_buffer.update(cx, |buffer, cx| {
13078            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13079        });
13080
13081        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13082            pane.close_active_item(
13083                &CloseActiveItem {
13084                    save_intent: Some(SaveIntent::Close),
13085                    close_pinned: false,
13086                },
13087                window,
13088                cx,
13089            )
13090        });
13091        cx.background_executor.run_until_parked();
13092        assert!(
13093            cx.has_pending_prompt(),
13094            "Dirty multi buffer should prompt a save dialog"
13095        );
13096        cx.simulate_prompt_answer("Save");
13097        cx.background_executor.run_until_parked();
13098        close_multi_buffer_task
13099            .await
13100            .expect("Closing the multi buffer failed");
13101        pane.update(cx, |pane, cx| {
13102            assert_eq!(
13103                dirty_multi_buffer_with_both.read(cx).save_count,
13104                1,
13105                "Multi buffer item should get be saved"
13106            );
13107            // Test impl does not save inner items, so we do not assert them
13108            assert_eq!(
13109                pane.items_len(),
13110                0,
13111                "No more items should be left in the pane"
13112            );
13113            assert!(pane.active_item().is_none());
13114        });
13115    }
13116
13117    #[gpui::test]
13118    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13119        cx: &mut TestAppContext,
13120    ) {
13121        init_test(cx);
13122
13123        let fs = FakeFs::new(cx.background_executor.clone());
13124        let project = Project::test(fs, [], cx).await;
13125        let (workspace, cx) =
13126            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13127        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13128
13129        let dirty_regular_buffer = cx.new(|cx| {
13130            TestItem::new(cx)
13131                .with_dirty(true)
13132                .with_label("1.txt")
13133                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13134        });
13135        let dirty_regular_buffer_2 = cx.new(|cx| {
13136            TestItem::new(cx)
13137                .with_dirty(true)
13138                .with_label("2.txt")
13139                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13140        });
13141        let clear_regular_buffer = cx.new(|cx| {
13142            TestItem::new(cx)
13143                .with_label("3.txt")
13144                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13145        });
13146
13147        let dirty_multi_buffer_with_both = cx.new(|cx| {
13148            TestItem::new(cx)
13149                .with_dirty(true)
13150                .with_buffer_kind(ItemBufferKind::Multibuffer)
13151                .with_label("Fake Project Search")
13152                .with_project_items(&[
13153                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13154                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13155                    clear_regular_buffer.read(cx).project_items[0].clone(),
13156                ])
13157        });
13158        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13159        workspace.update_in(cx, |workspace, window, cx| {
13160            workspace.add_item(
13161                pane.clone(),
13162                Box::new(dirty_regular_buffer.clone()),
13163                None,
13164                false,
13165                false,
13166                window,
13167                cx,
13168            );
13169            workspace.add_item(
13170                pane.clone(),
13171                Box::new(dirty_multi_buffer_with_both.clone()),
13172                None,
13173                false,
13174                false,
13175                window,
13176                cx,
13177            );
13178        });
13179
13180        pane.update_in(cx, |pane, window, cx| {
13181            pane.activate_item(1, true, true, window, cx);
13182            assert_eq!(
13183                pane.active_item().unwrap().item_id(),
13184                multi_buffer_with_both_files_id,
13185                "Should select the multi buffer in the pane"
13186            );
13187        });
13188        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13189            pane.close_active_item(
13190                &CloseActiveItem {
13191                    save_intent: None,
13192                    close_pinned: false,
13193                },
13194                window,
13195                cx,
13196            )
13197        });
13198        cx.background_executor.run_until_parked();
13199        assert!(
13200            cx.has_pending_prompt(),
13201            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13202        );
13203    }
13204
13205    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13206    /// closed when they are deleted from disk.
13207    #[gpui::test]
13208    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13209        init_test(cx);
13210
13211        // Enable the close_on_disk_deletion setting
13212        cx.update_global(|store: &mut SettingsStore, cx| {
13213            store.update_user_settings(cx, |settings| {
13214                settings.workspace.close_on_file_delete = Some(true);
13215            });
13216        });
13217
13218        let fs = FakeFs::new(cx.background_executor.clone());
13219        let project = Project::test(fs, [], cx).await;
13220        let (workspace, cx) =
13221            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13222        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13223
13224        // Create a test item that simulates a file
13225        let item = cx.new(|cx| {
13226            TestItem::new(cx)
13227                .with_label("test.txt")
13228                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13229        });
13230
13231        // Add item to workspace
13232        workspace.update_in(cx, |workspace, window, cx| {
13233            workspace.add_item(
13234                pane.clone(),
13235                Box::new(item.clone()),
13236                None,
13237                false,
13238                false,
13239                window,
13240                cx,
13241            );
13242        });
13243
13244        // Verify the item is in the pane
13245        pane.read_with(cx, |pane, _| {
13246            assert_eq!(pane.items().count(), 1);
13247        });
13248
13249        // Simulate file deletion by setting the item's deleted state
13250        item.update(cx, |item, _| {
13251            item.set_has_deleted_file(true);
13252        });
13253
13254        // Emit UpdateTab event to trigger the close behavior
13255        cx.run_until_parked();
13256        item.update(cx, |_, cx| {
13257            cx.emit(ItemEvent::UpdateTab);
13258        });
13259
13260        // Allow the close operation to complete
13261        cx.run_until_parked();
13262
13263        // Verify the item was automatically closed
13264        pane.read_with(cx, |pane, _| {
13265            assert_eq!(
13266                pane.items().count(),
13267                0,
13268                "Item should be automatically closed when file is deleted"
13269            );
13270        });
13271    }
13272
13273    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13274    /// open with a strikethrough when they are deleted from disk.
13275    #[gpui::test]
13276    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13277        init_test(cx);
13278
13279        // Ensure close_on_disk_deletion is disabled (default)
13280        cx.update_global(|store: &mut SettingsStore, cx| {
13281            store.update_user_settings(cx, |settings| {
13282                settings.workspace.close_on_file_delete = Some(false);
13283            });
13284        });
13285
13286        let fs = FakeFs::new(cx.background_executor.clone());
13287        let project = Project::test(fs, [], cx).await;
13288        let (workspace, cx) =
13289            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13290        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13291
13292        // Create a test item that simulates a file
13293        let item = cx.new(|cx| {
13294            TestItem::new(cx)
13295                .with_label("test.txt")
13296                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13297        });
13298
13299        // Add item to workspace
13300        workspace.update_in(cx, |workspace, window, cx| {
13301            workspace.add_item(
13302                pane.clone(),
13303                Box::new(item.clone()),
13304                None,
13305                false,
13306                false,
13307                window,
13308                cx,
13309            );
13310        });
13311
13312        // Verify the item is in the pane
13313        pane.read_with(cx, |pane, _| {
13314            assert_eq!(pane.items().count(), 1);
13315        });
13316
13317        // Simulate file deletion
13318        item.update(cx, |item, _| {
13319            item.set_has_deleted_file(true);
13320        });
13321
13322        // Emit UpdateTab event
13323        cx.run_until_parked();
13324        item.update(cx, |_, cx| {
13325            cx.emit(ItemEvent::UpdateTab);
13326        });
13327
13328        // Allow any potential close operation to complete
13329        cx.run_until_parked();
13330
13331        // Verify the item remains open (with strikethrough)
13332        pane.read_with(cx, |pane, _| {
13333            assert_eq!(
13334                pane.items().count(),
13335                1,
13336                "Item should remain open when close_on_disk_deletion is disabled"
13337            );
13338        });
13339
13340        // Verify the item shows as deleted
13341        item.read_with(cx, |item, _| {
13342            assert!(
13343                item.has_deleted_file,
13344                "Item should be marked as having deleted file"
13345            );
13346        });
13347    }
13348
13349    /// Tests that dirty files are not automatically closed when deleted from disk,
13350    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13351    /// unsaved changes without being prompted.
13352    #[gpui::test]
13353    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13354        init_test(cx);
13355
13356        // Enable the close_on_file_delete setting
13357        cx.update_global(|store: &mut SettingsStore, cx| {
13358            store.update_user_settings(cx, |settings| {
13359                settings.workspace.close_on_file_delete = Some(true);
13360            });
13361        });
13362
13363        let fs = FakeFs::new(cx.background_executor.clone());
13364        let project = Project::test(fs, [], cx).await;
13365        let (workspace, cx) =
13366            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13367        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13368
13369        // Create a dirty test item
13370        let item = cx.new(|cx| {
13371            TestItem::new(cx)
13372                .with_dirty(true)
13373                .with_label("test.txt")
13374                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13375        });
13376
13377        // Add item to workspace
13378        workspace.update_in(cx, |workspace, window, cx| {
13379            workspace.add_item(
13380                pane.clone(),
13381                Box::new(item.clone()),
13382                None,
13383                false,
13384                false,
13385                window,
13386                cx,
13387            );
13388        });
13389
13390        // Simulate file deletion
13391        item.update(cx, |item, _| {
13392            item.set_has_deleted_file(true);
13393        });
13394
13395        // Emit UpdateTab event to trigger the close behavior
13396        cx.run_until_parked();
13397        item.update(cx, |_, cx| {
13398            cx.emit(ItemEvent::UpdateTab);
13399        });
13400
13401        // Allow any potential close operation to complete
13402        cx.run_until_parked();
13403
13404        // Verify the item remains open (dirty files are not auto-closed)
13405        pane.read_with(cx, |pane, _| {
13406            assert_eq!(
13407                pane.items().count(),
13408                1,
13409                "Dirty items should not be automatically closed even when file is deleted"
13410            );
13411        });
13412
13413        // Verify the item is marked as deleted and still dirty
13414        item.read_with(cx, |item, _| {
13415            assert!(
13416                item.has_deleted_file,
13417                "Item should be marked as having deleted file"
13418            );
13419            assert!(item.is_dirty, "Item should still be dirty");
13420        });
13421    }
13422
13423    /// Tests that navigation history is cleaned up when files are auto-closed
13424    /// due to deletion from disk.
13425    #[gpui::test]
13426    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13427        init_test(cx);
13428
13429        // Enable the close_on_file_delete setting
13430        cx.update_global(|store: &mut SettingsStore, cx| {
13431            store.update_user_settings(cx, |settings| {
13432                settings.workspace.close_on_file_delete = Some(true);
13433            });
13434        });
13435
13436        let fs = FakeFs::new(cx.background_executor.clone());
13437        let project = Project::test(fs, [], cx).await;
13438        let (workspace, cx) =
13439            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13440        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13441
13442        // Create test items
13443        let item1 = cx.new(|cx| {
13444            TestItem::new(cx)
13445                .with_label("test1.txt")
13446                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13447        });
13448        let item1_id = item1.item_id();
13449
13450        let item2 = cx.new(|cx| {
13451            TestItem::new(cx)
13452                .with_label("test2.txt")
13453                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13454        });
13455
13456        // Add items to workspace
13457        workspace.update_in(cx, |workspace, window, cx| {
13458            workspace.add_item(
13459                pane.clone(),
13460                Box::new(item1.clone()),
13461                None,
13462                false,
13463                false,
13464                window,
13465                cx,
13466            );
13467            workspace.add_item(
13468                pane.clone(),
13469                Box::new(item2.clone()),
13470                None,
13471                false,
13472                false,
13473                window,
13474                cx,
13475            );
13476        });
13477
13478        // Activate item1 to ensure it gets navigation entries
13479        pane.update_in(cx, |pane, window, cx| {
13480            pane.activate_item(0, true, true, window, cx);
13481        });
13482
13483        // Switch to item2 and back to create navigation history
13484        pane.update_in(cx, |pane, window, cx| {
13485            pane.activate_item(1, true, true, window, cx);
13486        });
13487        cx.run_until_parked();
13488
13489        pane.update_in(cx, |pane, window, cx| {
13490            pane.activate_item(0, true, true, window, cx);
13491        });
13492        cx.run_until_parked();
13493
13494        // Simulate file deletion for item1
13495        item1.update(cx, |item, _| {
13496            item.set_has_deleted_file(true);
13497        });
13498
13499        // Emit UpdateTab event to trigger the close behavior
13500        item1.update(cx, |_, cx| {
13501            cx.emit(ItemEvent::UpdateTab);
13502        });
13503        cx.run_until_parked();
13504
13505        // Verify item1 was closed
13506        pane.read_with(cx, |pane, _| {
13507            assert_eq!(
13508                pane.items().count(),
13509                1,
13510                "Should have 1 item remaining after auto-close"
13511            );
13512        });
13513
13514        // Check navigation history after close
13515        let has_item = pane.read_with(cx, |pane, cx| {
13516            let mut has_item = false;
13517            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13518                if entry.item.id() == item1_id {
13519                    has_item = true;
13520                }
13521            });
13522            has_item
13523        });
13524
13525        assert!(
13526            !has_item,
13527            "Navigation history should not contain closed item entries"
13528        );
13529    }
13530
13531    #[gpui::test]
13532    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13533        cx: &mut TestAppContext,
13534    ) {
13535        init_test(cx);
13536
13537        let fs = FakeFs::new(cx.background_executor.clone());
13538        let project = Project::test(fs, [], cx).await;
13539        let (workspace, cx) =
13540            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13541        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13542
13543        let dirty_regular_buffer = cx.new(|cx| {
13544            TestItem::new(cx)
13545                .with_dirty(true)
13546                .with_label("1.txt")
13547                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13548        });
13549        let dirty_regular_buffer_2 = cx.new(|cx| {
13550            TestItem::new(cx)
13551                .with_dirty(true)
13552                .with_label("2.txt")
13553                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13554        });
13555        let clear_regular_buffer = cx.new(|cx| {
13556            TestItem::new(cx)
13557                .with_label("3.txt")
13558                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13559        });
13560
13561        let dirty_multi_buffer = cx.new(|cx| {
13562            TestItem::new(cx)
13563                .with_dirty(true)
13564                .with_buffer_kind(ItemBufferKind::Multibuffer)
13565                .with_label("Fake Project Search")
13566                .with_project_items(&[
13567                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13568                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13569                    clear_regular_buffer.read(cx).project_items[0].clone(),
13570                ])
13571        });
13572        workspace.update_in(cx, |workspace, window, cx| {
13573            workspace.add_item(
13574                pane.clone(),
13575                Box::new(dirty_regular_buffer.clone()),
13576                None,
13577                false,
13578                false,
13579                window,
13580                cx,
13581            );
13582            workspace.add_item(
13583                pane.clone(),
13584                Box::new(dirty_regular_buffer_2.clone()),
13585                None,
13586                false,
13587                false,
13588                window,
13589                cx,
13590            );
13591            workspace.add_item(
13592                pane.clone(),
13593                Box::new(dirty_multi_buffer.clone()),
13594                None,
13595                false,
13596                false,
13597                window,
13598                cx,
13599            );
13600        });
13601
13602        pane.update_in(cx, |pane, window, cx| {
13603            pane.activate_item(2, true, true, window, cx);
13604            assert_eq!(
13605                pane.active_item().unwrap().item_id(),
13606                dirty_multi_buffer.item_id(),
13607                "Should select the multi buffer in the pane"
13608            );
13609        });
13610        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13611            pane.close_active_item(
13612                &CloseActiveItem {
13613                    save_intent: None,
13614                    close_pinned: false,
13615                },
13616                window,
13617                cx,
13618            )
13619        });
13620        cx.background_executor.run_until_parked();
13621        assert!(
13622            !cx.has_pending_prompt(),
13623            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13624        );
13625        close_multi_buffer_task
13626            .await
13627            .expect("Closing multi buffer failed");
13628        pane.update(cx, |pane, cx| {
13629            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13630            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13631            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13632            assert_eq!(
13633                pane.items()
13634                    .map(|item| item.item_id())
13635                    .sorted()
13636                    .collect::<Vec<_>>(),
13637                vec![
13638                    dirty_regular_buffer.item_id(),
13639                    dirty_regular_buffer_2.item_id(),
13640                ],
13641                "Should have no multi buffer left in the pane"
13642            );
13643            assert!(dirty_regular_buffer.read(cx).is_dirty);
13644            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13645        });
13646    }
13647
13648    #[gpui::test]
13649    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13650        init_test(cx);
13651        let fs = FakeFs::new(cx.executor());
13652        let project = Project::test(fs, [], cx).await;
13653        let (multi_workspace, cx) =
13654            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13655        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13656
13657        // Add a new panel to the right dock, opening the dock and setting the
13658        // focus to the new panel.
13659        let panel = workspace.update_in(cx, |workspace, window, cx| {
13660            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13661            workspace.add_panel(panel.clone(), window, cx);
13662
13663            workspace
13664                .right_dock()
13665                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13666
13667            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13668
13669            panel
13670        });
13671
13672        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13673        // panel to the next valid position which, in this case, is the left
13674        // dock.
13675        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13676        workspace.update(cx, |workspace, cx| {
13677            assert!(workspace.left_dock().read(cx).is_open());
13678            assert_eq!(panel.read(cx).position, DockPosition::Left);
13679        });
13680
13681        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13682        // panel to the next valid position which, in this case, is the bottom
13683        // dock.
13684        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13685        workspace.update(cx, |workspace, cx| {
13686            assert!(workspace.bottom_dock().read(cx).is_open());
13687            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13688        });
13689
13690        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13691        // around moving the panel to its initial position, the right dock.
13692        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13693        workspace.update(cx, |workspace, cx| {
13694            assert!(workspace.right_dock().read(cx).is_open());
13695            assert_eq!(panel.read(cx).position, DockPosition::Right);
13696        });
13697
13698        // Remove focus from the panel, ensuring that, if the panel is not
13699        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13700        // the panel's position, so the panel is still in the right dock.
13701        workspace.update_in(cx, |workspace, window, cx| {
13702            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13703        });
13704
13705        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13706        workspace.update(cx, |workspace, cx| {
13707            assert!(workspace.right_dock().read(cx).is_open());
13708            assert_eq!(panel.read(cx).position, DockPosition::Right);
13709        });
13710    }
13711
13712    #[gpui::test]
13713    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13714        init_test(cx);
13715
13716        let fs = FakeFs::new(cx.executor());
13717        let project = Project::test(fs, [], cx).await;
13718        let (workspace, cx) =
13719            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13720
13721        let item_1 = cx.new(|cx| {
13722            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13723        });
13724        workspace.update_in(cx, |workspace, window, cx| {
13725            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13726            workspace.move_item_to_pane_in_direction(
13727                &MoveItemToPaneInDirection {
13728                    direction: SplitDirection::Right,
13729                    focus: true,
13730                    clone: false,
13731                },
13732                window,
13733                cx,
13734            );
13735            workspace.move_item_to_pane_at_index(
13736                &MoveItemToPane {
13737                    destination: 3,
13738                    focus: true,
13739                    clone: false,
13740                },
13741                window,
13742                cx,
13743            );
13744
13745            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13746            assert_eq!(
13747                pane_items_paths(&workspace.active_pane, cx),
13748                vec!["first.txt".to_string()],
13749                "Single item was not moved anywhere"
13750            );
13751        });
13752
13753        let item_2 = cx.new(|cx| {
13754            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13755        });
13756        workspace.update_in(cx, |workspace, window, cx| {
13757            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13758            assert_eq!(
13759                pane_items_paths(&workspace.panes[0], cx),
13760                vec!["first.txt".to_string(), "second.txt".to_string()],
13761            );
13762            workspace.move_item_to_pane_in_direction(
13763                &MoveItemToPaneInDirection {
13764                    direction: SplitDirection::Right,
13765                    focus: true,
13766                    clone: false,
13767                },
13768                window,
13769                cx,
13770            );
13771
13772            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13773            assert_eq!(
13774                pane_items_paths(&workspace.panes[0], cx),
13775                vec!["first.txt".to_string()],
13776                "After moving, one item should be left in the original pane"
13777            );
13778            assert_eq!(
13779                pane_items_paths(&workspace.panes[1], cx),
13780                vec!["second.txt".to_string()],
13781                "New item should have been moved to the new pane"
13782            );
13783        });
13784
13785        let item_3 = cx.new(|cx| {
13786            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13787        });
13788        workspace.update_in(cx, |workspace, window, cx| {
13789            let original_pane = workspace.panes[0].clone();
13790            workspace.set_active_pane(&original_pane, window, cx);
13791            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13792            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13793            assert_eq!(
13794                pane_items_paths(&workspace.active_pane, cx),
13795                vec!["first.txt".to_string(), "third.txt".to_string()],
13796                "New pane should be ready to move one item out"
13797            );
13798
13799            workspace.move_item_to_pane_at_index(
13800                &MoveItemToPane {
13801                    destination: 3,
13802                    focus: true,
13803                    clone: false,
13804                },
13805                window,
13806                cx,
13807            );
13808            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13809            assert_eq!(
13810                pane_items_paths(&workspace.active_pane, cx),
13811                vec!["first.txt".to_string()],
13812                "After moving, one item should be left in the original pane"
13813            );
13814            assert_eq!(
13815                pane_items_paths(&workspace.panes[1], cx),
13816                vec!["second.txt".to_string()],
13817                "Previously created pane should be unchanged"
13818            );
13819            assert_eq!(
13820                pane_items_paths(&workspace.panes[2], cx),
13821                vec!["third.txt".to_string()],
13822                "New item should have been moved to the new pane"
13823            );
13824        });
13825    }
13826
13827    #[gpui::test]
13828    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13829        init_test(cx);
13830
13831        let fs = FakeFs::new(cx.executor());
13832        let project = Project::test(fs, [], cx).await;
13833        let (workspace, cx) =
13834            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13835
13836        let item_1 = cx.new(|cx| {
13837            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13838        });
13839        workspace.update_in(cx, |workspace, window, cx| {
13840            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13841            workspace.move_item_to_pane_in_direction(
13842                &MoveItemToPaneInDirection {
13843                    direction: SplitDirection::Right,
13844                    focus: true,
13845                    clone: true,
13846                },
13847                window,
13848                cx,
13849            );
13850        });
13851        cx.run_until_parked();
13852        workspace.update_in(cx, |workspace, window, cx| {
13853            workspace.move_item_to_pane_at_index(
13854                &MoveItemToPane {
13855                    destination: 3,
13856                    focus: true,
13857                    clone: true,
13858                },
13859                window,
13860                cx,
13861            );
13862        });
13863        cx.run_until_parked();
13864
13865        workspace.update(cx, |workspace, cx| {
13866            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13867            for pane in workspace.panes() {
13868                assert_eq!(
13869                    pane_items_paths(pane, cx),
13870                    vec!["first.txt".to_string()],
13871                    "Single item exists in all panes"
13872                );
13873            }
13874        });
13875
13876        // verify that the active pane has been updated after waiting for the
13877        // pane focus event to fire and resolve
13878        workspace.read_with(cx, |workspace, _app| {
13879            assert_eq!(
13880                workspace.active_pane(),
13881                &workspace.panes[2],
13882                "The third pane should be the active one: {:?}",
13883                workspace.panes
13884            );
13885        })
13886    }
13887
13888    #[gpui::test]
13889    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13890        init_test(cx);
13891
13892        let fs = FakeFs::new(cx.executor());
13893        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13894
13895        let project = Project::test(fs, ["root".as_ref()], cx).await;
13896        let (workspace, cx) =
13897            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13898
13899        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13900        // Add item to pane A with project path
13901        let item_a = cx.new(|cx| {
13902            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13903        });
13904        workspace.update_in(cx, |workspace, window, cx| {
13905            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13906        });
13907
13908        // Split to create pane B
13909        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13910            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13911        });
13912
13913        // Add item with SAME project path to pane B, and pin it
13914        let item_b = cx.new(|cx| {
13915            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13916        });
13917        pane_b.update_in(cx, |pane, window, cx| {
13918            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13919            pane.set_pinned_count(1);
13920        });
13921
13922        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13923        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13924
13925        // close_pinned: false should only close the unpinned copy
13926        workspace.update_in(cx, |workspace, window, cx| {
13927            workspace.close_item_in_all_panes(
13928                &CloseItemInAllPanes {
13929                    save_intent: Some(SaveIntent::Close),
13930                    close_pinned: false,
13931                },
13932                window,
13933                cx,
13934            )
13935        });
13936        cx.executor().run_until_parked();
13937
13938        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13939        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13940        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13941        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13942
13943        // Split again, seeing as closing the previous item also closed its
13944        // pane, so only pane remains, which does not allow us to properly test
13945        // that both items close when `close_pinned: true`.
13946        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13947            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13948        });
13949
13950        // Add an item with the same project path to pane C so that
13951        // close_item_in_all_panes can determine what to close across all panes
13952        // (it reads the active item from the active pane, and split_pane
13953        // creates an empty pane).
13954        let item_c = cx.new(|cx| {
13955            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13956        });
13957        pane_c.update_in(cx, |pane, window, cx| {
13958            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13959        });
13960
13961        // close_pinned: true should close the pinned copy too
13962        workspace.update_in(cx, |workspace, window, cx| {
13963            let panes_count = workspace.panes().len();
13964            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13965
13966            workspace.close_item_in_all_panes(
13967                &CloseItemInAllPanes {
13968                    save_intent: Some(SaveIntent::Close),
13969                    close_pinned: true,
13970                },
13971                window,
13972                cx,
13973            )
13974        });
13975        cx.executor().run_until_parked();
13976
13977        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13978        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13979        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13980        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13981    }
13982
13983    mod register_project_item_tests {
13984
13985        use super::*;
13986
13987        // View
13988        struct TestPngItemView {
13989            focus_handle: FocusHandle,
13990        }
13991        // Model
13992        struct TestPngItem {}
13993
13994        impl project::ProjectItem for TestPngItem {
13995            fn try_open(
13996                _project: &Entity<Project>,
13997                path: &ProjectPath,
13998                cx: &mut App,
13999            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14000                if path.path.extension().unwrap() == "png" {
14001                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14002                } else {
14003                    None
14004                }
14005            }
14006
14007            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14008                None
14009            }
14010
14011            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14012                None
14013            }
14014
14015            fn is_dirty(&self) -> bool {
14016                false
14017            }
14018        }
14019
14020        impl Item for TestPngItemView {
14021            type Event = ();
14022            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14023                "".into()
14024            }
14025        }
14026        impl EventEmitter<()> for TestPngItemView {}
14027        impl Focusable for TestPngItemView {
14028            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14029                self.focus_handle.clone()
14030            }
14031        }
14032
14033        impl Render for TestPngItemView {
14034            fn render(
14035                &mut self,
14036                _window: &mut Window,
14037                _cx: &mut Context<Self>,
14038            ) -> impl IntoElement {
14039                Empty
14040            }
14041        }
14042
14043        impl ProjectItem for TestPngItemView {
14044            type Item = TestPngItem;
14045
14046            fn for_project_item(
14047                _project: Entity<Project>,
14048                _pane: Option<&Pane>,
14049                _item: Entity<Self::Item>,
14050                _: &mut Window,
14051                cx: &mut Context<Self>,
14052            ) -> Self
14053            where
14054                Self: Sized,
14055            {
14056                Self {
14057                    focus_handle: cx.focus_handle(),
14058                }
14059            }
14060        }
14061
14062        // View
14063        struct TestIpynbItemView {
14064            focus_handle: FocusHandle,
14065        }
14066        // Model
14067        struct TestIpynbItem {}
14068
14069        impl project::ProjectItem for TestIpynbItem {
14070            fn try_open(
14071                _project: &Entity<Project>,
14072                path: &ProjectPath,
14073                cx: &mut App,
14074            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14075                if path.path.extension().unwrap() == "ipynb" {
14076                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14077                } else {
14078                    None
14079                }
14080            }
14081
14082            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14083                None
14084            }
14085
14086            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14087                None
14088            }
14089
14090            fn is_dirty(&self) -> bool {
14091                false
14092            }
14093        }
14094
14095        impl Item for TestIpynbItemView {
14096            type Event = ();
14097            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14098                "".into()
14099            }
14100        }
14101        impl EventEmitter<()> for TestIpynbItemView {}
14102        impl Focusable for TestIpynbItemView {
14103            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14104                self.focus_handle.clone()
14105            }
14106        }
14107
14108        impl Render for TestIpynbItemView {
14109            fn render(
14110                &mut self,
14111                _window: &mut Window,
14112                _cx: &mut Context<Self>,
14113            ) -> impl IntoElement {
14114                Empty
14115            }
14116        }
14117
14118        impl ProjectItem for TestIpynbItemView {
14119            type Item = TestIpynbItem;
14120
14121            fn for_project_item(
14122                _project: Entity<Project>,
14123                _pane: Option<&Pane>,
14124                _item: Entity<Self::Item>,
14125                _: &mut Window,
14126                cx: &mut Context<Self>,
14127            ) -> Self
14128            where
14129                Self: Sized,
14130            {
14131                Self {
14132                    focus_handle: cx.focus_handle(),
14133                }
14134            }
14135        }
14136
14137        struct TestAlternatePngItemView {
14138            focus_handle: FocusHandle,
14139        }
14140
14141        impl Item for TestAlternatePngItemView {
14142            type Event = ();
14143            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14144                "".into()
14145            }
14146        }
14147
14148        impl EventEmitter<()> for TestAlternatePngItemView {}
14149        impl Focusable for TestAlternatePngItemView {
14150            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14151                self.focus_handle.clone()
14152            }
14153        }
14154
14155        impl Render for TestAlternatePngItemView {
14156            fn render(
14157                &mut self,
14158                _window: &mut Window,
14159                _cx: &mut Context<Self>,
14160            ) -> impl IntoElement {
14161                Empty
14162            }
14163        }
14164
14165        impl ProjectItem for TestAlternatePngItemView {
14166            type Item = TestPngItem;
14167
14168            fn for_project_item(
14169                _project: Entity<Project>,
14170                _pane: Option<&Pane>,
14171                _item: Entity<Self::Item>,
14172                _: &mut Window,
14173                cx: &mut Context<Self>,
14174            ) -> Self
14175            where
14176                Self: Sized,
14177            {
14178                Self {
14179                    focus_handle: cx.focus_handle(),
14180                }
14181            }
14182        }
14183
14184        #[gpui::test]
14185        async fn test_register_project_item(cx: &mut TestAppContext) {
14186            init_test(cx);
14187
14188            cx.update(|cx| {
14189                register_project_item::<TestPngItemView>(cx);
14190                register_project_item::<TestIpynbItemView>(cx);
14191            });
14192
14193            let fs = FakeFs::new(cx.executor());
14194            fs.insert_tree(
14195                "/root1",
14196                json!({
14197                    "one.png": "BINARYDATAHERE",
14198                    "two.ipynb": "{ totally a notebook }",
14199                    "three.txt": "editing text, sure why not?"
14200                }),
14201            )
14202            .await;
14203
14204            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14205            let (workspace, cx) =
14206                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14207
14208            let worktree_id = project.update(cx, |project, cx| {
14209                project.worktrees(cx).next().unwrap().read(cx).id()
14210            });
14211
14212            let handle = workspace
14213                .update_in(cx, |workspace, window, cx| {
14214                    let project_path = (worktree_id, rel_path("one.png"));
14215                    workspace.open_path(project_path, None, true, window, cx)
14216                })
14217                .await
14218                .unwrap();
14219
14220            // Now we can check if the handle we got back errored or not
14221            assert_eq!(
14222                handle.to_any_view().entity_type(),
14223                TypeId::of::<TestPngItemView>()
14224            );
14225
14226            let handle = workspace
14227                .update_in(cx, |workspace, window, cx| {
14228                    let project_path = (worktree_id, rel_path("two.ipynb"));
14229                    workspace.open_path(project_path, None, true, window, cx)
14230                })
14231                .await
14232                .unwrap();
14233
14234            assert_eq!(
14235                handle.to_any_view().entity_type(),
14236                TypeId::of::<TestIpynbItemView>()
14237            );
14238
14239            let handle = workspace
14240                .update_in(cx, |workspace, window, cx| {
14241                    let project_path = (worktree_id, rel_path("three.txt"));
14242                    workspace.open_path(project_path, None, true, window, cx)
14243                })
14244                .await;
14245            assert!(handle.is_err());
14246        }
14247
14248        #[gpui::test]
14249        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14250            init_test(cx);
14251
14252            cx.update(|cx| {
14253                register_project_item::<TestPngItemView>(cx);
14254                register_project_item::<TestAlternatePngItemView>(cx);
14255            });
14256
14257            let fs = FakeFs::new(cx.executor());
14258            fs.insert_tree(
14259                "/root1",
14260                json!({
14261                    "one.png": "BINARYDATAHERE",
14262                    "two.ipynb": "{ totally a notebook }",
14263                    "three.txt": "editing text, sure why not?"
14264                }),
14265            )
14266            .await;
14267            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14268            let (workspace, cx) =
14269                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14270            let worktree_id = project.update(cx, |project, cx| {
14271                project.worktrees(cx).next().unwrap().read(cx).id()
14272            });
14273
14274            let handle = workspace
14275                .update_in(cx, |workspace, window, cx| {
14276                    let project_path = (worktree_id, rel_path("one.png"));
14277                    workspace.open_path(project_path, None, true, window, cx)
14278                })
14279                .await
14280                .unwrap();
14281
14282            // This _must_ be the second item registered
14283            assert_eq!(
14284                handle.to_any_view().entity_type(),
14285                TypeId::of::<TestAlternatePngItemView>()
14286            );
14287
14288            let handle = workspace
14289                .update_in(cx, |workspace, window, cx| {
14290                    let project_path = (worktree_id, rel_path("three.txt"));
14291                    workspace.open_path(project_path, None, true, window, cx)
14292                })
14293                .await;
14294            assert!(handle.is_err());
14295        }
14296    }
14297
14298    #[gpui::test]
14299    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14300        init_test(cx);
14301
14302        let fs = FakeFs::new(cx.executor());
14303        let project = Project::test(fs, [], cx).await;
14304        let (workspace, _cx) =
14305            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14306
14307        // Test with status bar shown (default)
14308        workspace.read_with(cx, |workspace, cx| {
14309            let visible = workspace.status_bar_visible(cx);
14310            assert!(visible, "Status bar should be visible by default");
14311        });
14312
14313        // Test with status bar hidden
14314        cx.update_global(|store: &mut SettingsStore, cx| {
14315            store.update_user_settings(cx, |settings| {
14316                settings.status_bar.get_or_insert_default().show = Some(false);
14317            });
14318        });
14319
14320        workspace.read_with(cx, |workspace, cx| {
14321            let visible = workspace.status_bar_visible(cx);
14322            assert!(!visible, "Status bar should be hidden when show is false");
14323        });
14324
14325        // Test with status bar shown explicitly
14326        cx.update_global(|store: &mut SettingsStore, cx| {
14327            store.update_user_settings(cx, |settings| {
14328                settings.status_bar.get_or_insert_default().show = Some(true);
14329            });
14330        });
14331
14332        workspace.read_with(cx, |workspace, cx| {
14333            let visible = workspace.status_bar_visible(cx);
14334            assert!(visible, "Status bar should be visible when show is true");
14335        });
14336    }
14337
14338    #[gpui::test]
14339    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14340        init_test(cx);
14341
14342        let fs = FakeFs::new(cx.executor());
14343        let project = Project::test(fs, [], cx).await;
14344        let (multi_workspace, cx) =
14345            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14346        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14347        let panel = workspace.update_in(cx, |workspace, window, cx| {
14348            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14349            workspace.add_panel(panel.clone(), window, cx);
14350
14351            workspace
14352                .right_dock()
14353                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14354
14355            panel
14356        });
14357
14358        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14359        let item_a = cx.new(TestItem::new);
14360        let item_b = cx.new(TestItem::new);
14361        let item_a_id = item_a.entity_id();
14362        let item_b_id = item_b.entity_id();
14363
14364        pane.update_in(cx, |pane, window, cx| {
14365            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14366            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14367        });
14368
14369        pane.read_with(cx, |pane, _| {
14370            assert_eq!(pane.items_len(), 2);
14371            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14372        });
14373
14374        workspace.update_in(cx, |workspace, window, cx| {
14375            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14376        });
14377
14378        workspace.update_in(cx, |_, window, cx| {
14379            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14380        });
14381
14382        // Assert that the `pane::CloseActiveItem` action is handled at the
14383        // workspace level when one of the dock panels is focused and, in that
14384        // case, the center pane's active item is closed but the focus is not
14385        // moved.
14386        cx.dispatch_action(pane::CloseActiveItem::default());
14387        cx.run_until_parked();
14388
14389        pane.read_with(cx, |pane, _| {
14390            assert_eq!(pane.items_len(), 1);
14391            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14392        });
14393
14394        workspace.update_in(cx, |workspace, window, cx| {
14395            assert!(workspace.right_dock().read(cx).is_open());
14396            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14397        });
14398    }
14399
14400    #[gpui::test]
14401    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14402        init_test(cx);
14403        let fs = FakeFs::new(cx.executor());
14404
14405        let project_a = Project::test(fs.clone(), [], cx).await;
14406        let project_b = Project::test(fs, [], cx).await;
14407
14408        let multi_workspace_handle =
14409            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14410        cx.run_until_parked();
14411
14412        let workspace_a = multi_workspace_handle
14413            .read_with(cx, |mw, _| mw.workspace().clone())
14414            .unwrap();
14415
14416        let _workspace_b = multi_workspace_handle
14417            .update(cx, |mw, window, cx| {
14418                mw.test_add_workspace(project_b, window, cx)
14419            })
14420            .unwrap();
14421
14422        // Switch to workspace A
14423        multi_workspace_handle
14424            .update(cx, |mw, window, cx| {
14425                mw.activate_index(0, window, cx);
14426            })
14427            .unwrap();
14428
14429        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14430
14431        // Add a panel to workspace A's right dock and open the dock
14432        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14433            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14434            workspace.add_panel(panel.clone(), window, cx);
14435            workspace
14436                .right_dock()
14437                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14438            panel
14439        });
14440
14441        // Focus the panel through the workspace (matching existing test pattern)
14442        workspace_a.update_in(cx, |workspace, window, cx| {
14443            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14444        });
14445
14446        // Zoom the panel
14447        panel.update_in(cx, |panel, window, cx| {
14448            panel.set_zoomed(true, window, cx);
14449        });
14450
14451        // Verify the panel is zoomed and the dock is open
14452        workspace_a.update_in(cx, |workspace, window, cx| {
14453            assert!(
14454                workspace.right_dock().read(cx).is_open(),
14455                "dock should be open before switch"
14456            );
14457            assert!(
14458                panel.is_zoomed(window, cx),
14459                "panel should be zoomed before switch"
14460            );
14461            assert!(
14462                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14463                "panel should be focused before switch"
14464            );
14465        });
14466
14467        // Switch to workspace B
14468        multi_workspace_handle
14469            .update(cx, |mw, window, cx| {
14470                mw.activate_index(1, window, cx);
14471            })
14472            .unwrap();
14473        cx.run_until_parked();
14474
14475        // Switch back to workspace A
14476        multi_workspace_handle
14477            .update(cx, |mw, window, cx| {
14478                mw.activate_index(0, window, cx);
14479            })
14480            .unwrap();
14481        cx.run_until_parked();
14482
14483        // Verify the panel is still zoomed and the dock is still open
14484        workspace_a.update_in(cx, |workspace, window, cx| {
14485            assert!(
14486                workspace.right_dock().read(cx).is_open(),
14487                "dock should still be open after switching back"
14488            );
14489            assert!(
14490                panel.is_zoomed(window, cx),
14491                "panel should still be zoomed after switching back"
14492            );
14493        });
14494    }
14495
14496    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14497        pane.read(cx)
14498            .items()
14499            .flat_map(|item| {
14500                item.project_paths(cx)
14501                    .into_iter()
14502                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14503            })
14504            .collect()
14505    }
14506
14507    pub fn init_test(cx: &mut TestAppContext) {
14508        cx.update(|cx| {
14509            let settings_store = SettingsStore::test(cx);
14510            cx.set_global(settings_store);
14511            cx.set_global(db::AppDatabase::test_new());
14512            theme_settings::init(theme::LoadThemes::JustBase, cx);
14513        });
14514    }
14515
14516    #[gpui::test]
14517    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14518        use settings::{ThemeName, ThemeSelection};
14519        use theme::SystemAppearance;
14520        use zed_actions::theme::ToggleMode;
14521
14522        init_test(cx);
14523
14524        let fs = FakeFs::new(cx.executor());
14525        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14526
14527        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14528            .await;
14529
14530        // Build a test project and workspace view so the test can invoke
14531        // the workspace action handler the same way the UI would.
14532        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14533        let (workspace, cx) =
14534            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14535
14536        // Seed the settings file with a plain static light theme so the
14537        // first toggle always starts from a known persisted state.
14538        workspace.update_in(cx, |_workspace, _window, cx| {
14539            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14540            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14541                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14542            });
14543        });
14544        cx.executor().advance_clock(Duration::from_millis(200));
14545        cx.run_until_parked();
14546
14547        // Confirm the initial persisted settings contain the static theme
14548        // we just wrote before any toggling happens.
14549        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14550        assert!(settings_text.contains(r#""theme": "One Light""#));
14551
14552        // Toggle once. This should migrate the persisted theme settings
14553        // into light/dark slots and enable system mode.
14554        workspace.update_in(cx, |workspace, window, cx| {
14555            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14556        });
14557        cx.executor().advance_clock(Duration::from_millis(200));
14558        cx.run_until_parked();
14559
14560        // 1. Static -> Dynamic
14561        // this assertion checks theme changed from static to dynamic.
14562        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14563        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14564        assert_eq!(
14565            parsed["theme"],
14566            serde_json::json!({
14567                "mode": "system",
14568                "light": "One Light",
14569                "dark": "One Dark"
14570            })
14571        );
14572
14573        // 2. Toggle again, suppose it will change the mode to light
14574        workspace.update_in(cx, |workspace, window, cx| {
14575            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14576        });
14577        cx.executor().advance_clock(Duration::from_millis(200));
14578        cx.run_until_parked();
14579
14580        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14581        assert!(settings_text.contains(r#""mode": "light""#));
14582    }
14583
14584    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14585        let item = TestProjectItem::new(id, path, cx);
14586        item.update(cx, |item, _| {
14587            item.is_dirty = true;
14588        });
14589        item
14590    }
14591
14592    #[gpui::test]
14593    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14594        cx: &mut gpui::TestAppContext,
14595    ) {
14596        init_test(cx);
14597        let fs = FakeFs::new(cx.executor());
14598
14599        let project = Project::test(fs, [], cx).await;
14600        let (workspace, cx) =
14601            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14602
14603        let panel = workspace.update_in(cx, |workspace, window, cx| {
14604            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14605            workspace.add_panel(panel.clone(), window, cx);
14606            workspace
14607                .right_dock()
14608                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14609            panel
14610        });
14611
14612        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14613        pane.update_in(cx, |pane, window, cx| {
14614            let item = cx.new(TestItem::new);
14615            pane.add_item(Box::new(item), true, true, None, window, cx);
14616        });
14617
14618        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14619        // mirrors the real-world flow and avoids side effects from directly
14620        // focusing the panel while the center pane is active.
14621        workspace.update_in(cx, |workspace, window, cx| {
14622            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14623        });
14624
14625        panel.update_in(cx, |panel, window, cx| {
14626            panel.set_zoomed(true, window, cx);
14627        });
14628
14629        workspace.update_in(cx, |workspace, window, cx| {
14630            assert!(workspace.right_dock().read(cx).is_open());
14631            assert!(panel.is_zoomed(window, cx));
14632            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14633        });
14634
14635        // Simulate a spurious pane::Event::Focus on the center pane while the
14636        // panel still has focus. This mirrors what happens during macOS window
14637        // activation: the center pane fires a focus event even though actual
14638        // focus remains on the dock panel.
14639        pane.update_in(cx, |_, _, cx| {
14640            cx.emit(pane::Event::Focus);
14641        });
14642
14643        // The dock must remain open because the panel had focus at the time the
14644        // event was processed. Before the fix, dock_to_preserve was None for
14645        // panels that don't implement pane(), causing the dock to close.
14646        workspace.update_in(cx, |workspace, window, cx| {
14647            assert!(
14648                workspace.right_dock().read(cx).is_open(),
14649                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14650            );
14651            assert!(panel.is_zoomed(window, cx));
14652        });
14653    }
14654
14655    #[gpui::test]
14656    async fn test_panels_stay_open_after_position_change_and_settings_update(
14657        cx: &mut gpui::TestAppContext,
14658    ) {
14659        init_test(cx);
14660        let fs = FakeFs::new(cx.executor());
14661        let project = Project::test(fs, [], cx).await;
14662        let (workspace, cx) =
14663            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14664
14665        // Add two panels to the left dock and open it.
14666        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14667            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14668            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14669            workspace.add_panel(panel_a.clone(), window, cx);
14670            workspace.add_panel(panel_b.clone(), window, cx);
14671            workspace.left_dock().update(cx, |dock, cx| {
14672                dock.set_open(true, window, cx);
14673                dock.activate_panel(0, window, cx);
14674            });
14675            (panel_a, panel_b)
14676        });
14677
14678        workspace.update_in(cx, |workspace, _, cx| {
14679            assert!(workspace.left_dock().read(cx).is_open());
14680        });
14681
14682        // Simulate a feature flag changing default dock positions: both panels
14683        // move from Left to Right.
14684        workspace.update_in(cx, |_workspace, _window, cx| {
14685            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14686            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14687            cx.update_global::<SettingsStore, _>(|_, _| {});
14688        });
14689
14690        // Both panels should now be in the right dock.
14691        workspace.update_in(cx, |workspace, _, cx| {
14692            let right_dock = workspace.right_dock().read(cx);
14693            assert_eq!(right_dock.panels_len(), 2);
14694        });
14695
14696        // Open the right dock and activate panel_b (simulating the user
14697        // opening the panel after it moved).
14698        workspace.update_in(cx, |workspace, window, cx| {
14699            workspace.right_dock().update(cx, |dock, cx| {
14700                dock.set_open(true, window, cx);
14701                dock.activate_panel(1, window, cx);
14702            });
14703        });
14704
14705        // Now trigger another SettingsStore change
14706        workspace.update_in(cx, |_workspace, _window, cx| {
14707            cx.update_global::<SettingsStore, _>(|_, _| {});
14708        });
14709
14710        workspace.update_in(cx, |workspace, _, cx| {
14711            assert!(
14712                workspace.right_dock().read(cx).is_open(),
14713                "Right dock should still be open after a settings change"
14714            );
14715            assert_eq!(
14716                workspace.right_dock().read(cx).panels_len(),
14717                2,
14718                "Both panels should still be in the right dock"
14719            );
14720        });
14721    }
14722}