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, SidebarEvent, 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(
  668            Vec::new(),
  669            app_state.clone(),
  670            None,
  671            None,
  672            None,
  673            OpenMode::Replace,
  674            cx,
  675        );
  676        cx.spawn(async move |cx| {
  677            let OpenResult { window, .. } = task.await?;
  678            window.update(cx, |multi_workspace, window, cx| {
  679                window.activate_window();
  680                let workspace = multi_workspace.workspace().clone();
  681                workspace.update(cx, |workspace, cx| {
  682                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  683                });
  684            })?;
  685            anyhow::Ok(())
  686        })
  687        .detach_and_log_err(cx);
  688    }
  689}
  690
  691pub fn prompt_for_open_path_and_open(
  692    workspace: &mut Workspace,
  693    app_state: Arc<AppState>,
  694    options: PathPromptOptions,
  695    create_new_window: bool,
  696    window: &mut Window,
  697    cx: &mut Context<Workspace>,
  698) {
  699    let paths = workspace.prompt_for_open_path(
  700        options,
  701        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  702        window,
  703        cx,
  704    );
  705    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  706    cx.spawn_in(window, async move |this, cx| {
  707        let Some(paths) = paths.await.log_err().flatten() else {
  708            return;
  709        };
  710        if !create_new_window {
  711            if let Some(handle) = multi_workspace_handle {
  712                if let Some(task) = handle
  713                    .update(cx, |multi_workspace, window, cx| {
  714                        multi_workspace.open_project(paths, OpenMode::Replace, window, cx)
  715                    })
  716                    .log_err()
  717                {
  718                    task.await.log_err();
  719                }
  720                return;
  721            }
  722        }
  723        if let Some(task) = this
  724            .update_in(cx, |this, window, cx| {
  725                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  726            })
  727            .log_err()
  728        {
  729            task.await.log_err();
  730        }
  731    })
  732    .detach();
  733}
  734
  735pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  736    component::init();
  737    theme_preview::init(cx);
  738    toast_layer::init(cx);
  739    history_manager::init(app_state.fs.clone(), cx);
  740
  741    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  742        .on_action(|_: &Reload, cx| reload(cx))
  743        .on_action(|_: &Open, cx: &mut App| {
  744            let app_state = AppState::global(cx);
  745            prompt_and_open_paths(
  746                app_state,
  747                PathPromptOptions {
  748                    files: true,
  749                    directories: true,
  750                    multiple: true,
  751                    prompt: None,
  752                },
  753                cx,
  754            );
  755        })
  756        .on_action(|_: &OpenFiles, cx: &mut App| {
  757            let directories = cx.can_select_mixed_files_and_dirs();
  758            let app_state = AppState::global(cx);
  759            prompt_and_open_paths(
  760                app_state,
  761                PathPromptOptions {
  762                    files: true,
  763                    directories,
  764                    multiple: true,
  765                    prompt: None,
  766                },
  767                cx,
  768            );
  769        });
  770}
  771
  772type BuildProjectItemFn =
  773    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  774
  775type BuildProjectItemForPathFn =
  776    fn(
  777        &Entity<Project>,
  778        &ProjectPath,
  779        &mut Window,
  780        &mut App,
  781    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  782
  783#[derive(Clone, Default)]
  784struct ProjectItemRegistry {
  785    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  786    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  787}
  788
  789impl ProjectItemRegistry {
  790    fn register<T: ProjectItem>(&mut self) {
  791        self.build_project_item_fns_by_type.insert(
  792            TypeId::of::<T::Item>(),
  793            |item, project, pane, window, cx| {
  794                let item = item.downcast().unwrap();
  795                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  796                    as Box<dyn ItemHandle>
  797            },
  798        );
  799        self.build_project_item_for_path_fns
  800            .push(|project, project_path, window, cx| {
  801                let project_path = project_path.clone();
  802                let is_file = project
  803                    .read(cx)
  804                    .entry_for_path(&project_path, cx)
  805                    .is_some_and(|entry| entry.is_file());
  806                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  807                let is_local = project.read(cx).is_local();
  808                let project_item =
  809                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  810                let project = project.clone();
  811                Some(window.spawn(cx, async move |cx| {
  812                    match project_item.await.with_context(|| {
  813                        format!(
  814                            "opening project path {:?}",
  815                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  816                        )
  817                    }) {
  818                        Ok(project_item) => {
  819                            let project_item = project_item;
  820                            let project_entry_id: Option<ProjectEntryId> =
  821                                project_item.read_with(cx, project::ProjectItem::entry_id);
  822                            let build_workspace_item = Box::new(
  823                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  824                                    Box::new(cx.new(|cx| {
  825                                        T::for_project_item(
  826                                            project,
  827                                            Some(pane),
  828                                            project_item,
  829                                            window,
  830                                            cx,
  831                                        )
  832                                    })) as Box<dyn ItemHandle>
  833                                },
  834                            ) as Box<_>;
  835                            Ok((project_entry_id, build_workspace_item))
  836                        }
  837                        Err(e) => {
  838                            log::warn!("Failed to open a project item: {e:#}");
  839                            if e.error_code() == ErrorCode::Internal {
  840                                if let Some(abs_path) =
  841                                    entry_abs_path.as_deref().filter(|_| is_file)
  842                                {
  843                                    if let Some(broken_project_item_view) =
  844                                        cx.update(|window, cx| {
  845                                            T::for_broken_project_item(
  846                                                abs_path, is_local, &e, window, cx,
  847                                            )
  848                                        })?
  849                                    {
  850                                        let build_workspace_item = Box::new(
  851                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  852                                                cx.new(|_| broken_project_item_view).boxed_clone()
  853                                            },
  854                                        )
  855                                        as Box<_>;
  856                                        return Ok((None, build_workspace_item));
  857                                    }
  858                                }
  859                            }
  860                            Err(e)
  861                        }
  862                    }
  863                }))
  864            });
  865    }
  866
  867    fn open_path(
  868        &self,
  869        project: &Entity<Project>,
  870        path: &ProjectPath,
  871        window: &mut Window,
  872        cx: &mut App,
  873    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  874        let Some(open_project_item) = self
  875            .build_project_item_for_path_fns
  876            .iter()
  877            .rev()
  878            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  879        else {
  880            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  881        };
  882        open_project_item
  883    }
  884
  885    fn build_item<T: project::ProjectItem>(
  886        &self,
  887        item: Entity<T>,
  888        project: Entity<Project>,
  889        pane: Option<&Pane>,
  890        window: &mut Window,
  891        cx: &mut App,
  892    ) -> Option<Box<dyn ItemHandle>> {
  893        let build = self
  894            .build_project_item_fns_by_type
  895            .get(&TypeId::of::<T>())?;
  896        Some(build(item.into_any(), project, pane, window, cx))
  897    }
  898}
  899
  900type WorkspaceItemBuilder =
  901    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  902
  903impl Global for ProjectItemRegistry {}
  904
  905/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  906/// items will get a chance to open the file, starting from the project item that
  907/// was added last.
  908pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  909    cx.default_global::<ProjectItemRegistry>().register::<I>();
  910}
  911
  912#[derive(Default)]
  913pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  914
  915struct FollowableViewDescriptor {
  916    from_state_proto: fn(
  917        Entity<Workspace>,
  918        ViewId,
  919        &mut Option<proto::view::Variant>,
  920        &mut Window,
  921        &mut App,
  922    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  923    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  924}
  925
  926impl Global for FollowableViewRegistry {}
  927
  928impl FollowableViewRegistry {
  929    pub fn register<I: FollowableItem>(cx: &mut App) {
  930        cx.default_global::<Self>().0.insert(
  931            TypeId::of::<I>(),
  932            FollowableViewDescriptor {
  933                from_state_proto: |workspace, id, state, window, cx| {
  934                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  935                        cx.foreground_executor()
  936                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  937                    })
  938                },
  939                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  940            },
  941        );
  942    }
  943
  944    pub fn from_state_proto(
  945        workspace: Entity<Workspace>,
  946        view_id: ViewId,
  947        mut state: Option<proto::view::Variant>,
  948        window: &mut Window,
  949        cx: &mut App,
  950    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  951        cx.update_default_global(|this: &mut Self, cx| {
  952            this.0.values().find_map(|descriptor| {
  953                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  954            })
  955        })
  956    }
  957
  958    pub fn to_followable_view(
  959        view: impl Into<AnyView>,
  960        cx: &App,
  961    ) -> Option<Box<dyn FollowableItemHandle>> {
  962        let this = cx.try_global::<Self>()?;
  963        let view = view.into();
  964        let descriptor = this.0.get(&view.entity_type())?;
  965        Some((descriptor.to_followable_view)(&view))
  966    }
  967}
  968
  969#[derive(Copy, Clone)]
  970struct SerializableItemDescriptor {
  971    deserialize: fn(
  972        Entity<Project>,
  973        WeakEntity<Workspace>,
  974        WorkspaceId,
  975        ItemId,
  976        &mut Window,
  977        &mut Context<Pane>,
  978    ) -> Task<Result<Box<dyn ItemHandle>>>,
  979    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  980    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  981}
  982
  983#[derive(Default)]
  984struct SerializableItemRegistry {
  985    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  986    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  987}
  988
  989impl Global for SerializableItemRegistry {}
  990
  991impl SerializableItemRegistry {
  992    fn deserialize(
  993        item_kind: &str,
  994        project: Entity<Project>,
  995        workspace: WeakEntity<Workspace>,
  996        workspace_id: WorkspaceId,
  997        item_item: ItemId,
  998        window: &mut Window,
  999        cx: &mut Context<Pane>,
 1000    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1001        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1002            return Task::ready(Err(anyhow!(
 1003                "cannot deserialize {}, descriptor not found",
 1004                item_kind
 1005            )));
 1006        };
 1007
 1008        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1009    }
 1010
 1011    fn cleanup(
 1012        item_kind: &str,
 1013        workspace_id: WorkspaceId,
 1014        loaded_items: Vec<ItemId>,
 1015        window: &mut Window,
 1016        cx: &mut App,
 1017    ) -> Task<Result<()>> {
 1018        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1019            return Task::ready(Err(anyhow!(
 1020                "cannot cleanup {}, descriptor not found",
 1021                item_kind
 1022            )));
 1023        };
 1024
 1025        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1026    }
 1027
 1028    fn view_to_serializable_item_handle(
 1029        view: AnyView,
 1030        cx: &App,
 1031    ) -> Option<Box<dyn SerializableItemHandle>> {
 1032        let this = cx.try_global::<Self>()?;
 1033        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1034        Some((descriptor.view_to_serializable_item)(view))
 1035    }
 1036
 1037    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1038        let this = cx.try_global::<Self>()?;
 1039        this.descriptors_by_kind.get(item_kind).copied()
 1040    }
 1041}
 1042
 1043pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1044    let serialized_item_kind = I::serialized_item_kind();
 1045
 1046    let registry = cx.default_global::<SerializableItemRegistry>();
 1047    let descriptor = SerializableItemDescriptor {
 1048        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1049            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1050            cx.foreground_executor()
 1051                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1052        },
 1053        cleanup: |workspace_id, loaded_items, window, cx| {
 1054            I::cleanup(workspace_id, loaded_items, window, cx)
 1055        },
 1056        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1057    };
 1058    registry
 1059        .descriptors_by_kind
 1060        .insert(Arc::from(serialized_item_kind), descriptor);
 1061    registry
 1062        .descriptors_by_type
 1063        .insert(TypeId::of::<I>(), descriptor);
 1064}
 1065
 1066pub struct AppState {
 1067    pub languages: Arc<LanguageRegistry>,
 1068    pub client: Arc<Client>,
 1069    pub user_store: Entity<UserStore>,
 1070    pub workspace_store: Entity<WorkspaceStore>,
 1071    pub fs: Arc<dyn fs::Fs>,
 1072    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1073    pub node_runtime: NodeRuntime,
 1074    pub session: Entity<AppSession>,
 1075}
 1076
 1077struct GlobalAppState(Arc<AppState>);
 1078
 1079impl Global for GlobalAppState {}
 1080
 1081pub struct WorkspaceStore {
 1082    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1083    client: Arc<Client>,
 1084    _subscriptions: Vec<client::Subscription>,
 1085}
 1086
 1087#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1088pub enum CollaboratorId {
 1089    PeerId(PeerId),
 1090    Agent,
 1091}
 1092
 1093impl From<PeerId> for CollaboratorId {
 1094    fn from(peer_id: PeerId) -> Self {
 1095        CollaboratorId::PeerId(peer_id)
 1096    }
 1097}
 1098
 1099impl From<&PeerId> for CollaboratorId {
 1100    fn from(peer_id: &PeerId) -> Self {
 1101        CollaboratorId::PeerId(*peer_id)
 1102    }
 1103}
 1104
 1105#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1106struct Follower {
 1107    project_id: Option<u64>,
 1108    peer_id: PeerId,
 1109}
 1110
 1111impl AppState {
 1112    #[track_caller]
 1113    pub fn global(cx: &App) -> Arc<Self> {
 1114        cx.global::<GlobalAppState>().0.clone()
 1115    }
 1116    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1117        cx.try_global::<GlobalAppState>()
 1118            .map(|state| state.0.clone())
 1119    }
 1120    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1121        cx.set_global(GlobalAppState(state));
 1122    }
 1123
 1124    #[cfg(any(test, feature = "test-support"))]
 1125    pub fn test(cx: &mut App) -> Arc<Self> {
 1126        use fs::Fs;
 1127        use node_runtime::NodeRuntime;
 1128        use session::Session;
 1129        use settings::SettingsStore;
 1130
 1131        if !cx.has_global::<SettingsStore>() {
 1132            let settings_store = SettingsStore::test(cx);
 1133            cx.set_global(settings_store);
 1134        }
 1135
 1136        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1137        <dyn Fs>::set_global(fs.clone(), cx);
 1138        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1139        let clock = Arc::new(clock::FakeSystemClock::new());
 1140        let http_client = http_client::FakeHttpClient::with_404_response();
 1141        let client = Client::new(clock, http_client, cx);
 1142        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1143        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1144        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1145
 1146        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1147        client::init(&client, cx);
 1148
 1149        Arc::new(Self {
 1150            client,
 1151            fs,
 1152            languages,
 1153            user_store,
 1154            workspace_store,
 1155            node_runtime: NodeRuntime::unavailable(),
 1156            build_window_options: |_, _| Default::default(),
 1157            session,
 1158        })
 1159    }
 1160}
 1161
 1162struct DelayedDebouncedEditAction {
 1163    task: Option<Task<()>>,
 1164    cancel_channel: Option<oneshot::Sender<()>>,
 1165}
 1166
 1167impl DelayedDebouncedEditAction {
 1168    fn new() -> DelayedDebouncedEditAction {
 1169        DelayedDebouncedEditAction {
 1170            task: None,
 1171            cancel_channel: None,
 1172        }
 1173    }
 1174
 1175    fn fire_new<F>(
 1176        &mut self,
 1177        delay: Duration,
 1178        window: &mut Window,
 1179        cx: &mut Context<Workspace>,
 1180        func: F,
 1181    ) where
 1182        F: 'static
 1183            + Send
 1184            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1185    {
 1186        if let Some(channel) = self.cancel_channel.take() {
 1187            _ = channel.send(());
 1188        }
 1189
 1190        let (sender, mut receiver) = oneshot::channel::<()>();
 1191        self.cancel_channel = Some(sender);
 1192
 1193        let previous_task = self.task.take();
 1194        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1195            let mut timer = cx.background_executor().timer(delay).fuse();
 1196            if let Some(previous_task) = previous_task {
 1197                previous_task.await;
 1198            }
 1199
 1200            futures::select_biased! {
 1201                _ = receiver => return,
 1202                    _ = timer => {}
 1203            }
 1204
 1205            if let Some(result) = workspace
 1206                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1207                .log_err()
 1208            {
 1209                result.await.log_err();
 1210            }
 1211        }));
 1212    }
 1213}
 1214
 1215pub enum Event {
 1216    PaneAdded(Entity<Pane>),
 1217    PaneRemoved,
 1218    ItemAdded {
 1219        item: Box<dyn ItemHandle>,
 1220    },
 1221    ActiveItemChanged,
 1222    ItemRemoved {
 1223        item_id: EntityId,
 1224    },
 1225    UserSavedItem {
 1226        pane: WeakEntity<Pane>,
 1227        item: Box<dyn WeakItemHandle>,
 1228        save_intent: SaveIntent,
 1229    },
 1230    ContactRequestedJoin(u64),
 1231    WorkspaceCreated(WeakEntity<Workspace>),
 1232    OpenBundledFile {
 1233        text: Cow<'static, str>,
 1234        title: &'static str,
 1235        language: &'static str,
 1236    },
 1237    ZoomChanged,
 1238    ModalOpened,
 1239    Activate,
 1240    PanelAdded(AnyView),
 1241}
 1242
 1243#[derive(Debug, Clone)]
 1244pub enum OpenVisible {
 1245    All,
 1246    None,
 1247    OnlyFiles,
 1248    OnlyDirectories,
 1249}
 1250
 1251enum WorkspaceLocation {
 1252    // Valid local paths or SSH project to serialize
 1253    Location(SerializedWorkspaceLocation, PathList),
 1254    // No valid location found hence clear session id
 1255    DetachFromSession,
 1256    // No valid location found to serialize
 1257    None,
 1258}
 1259
 1260type PromptForNewPath = Box<
 1261    dyn Fn(
 1262        &mut Workspace,
 1263        DirectoryLister,
 1264        Option<String>,
 1265        &mut Window,
 1266        &mut Context<Workspace>,
 1267    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1268>;
 1269
 1270type PromptForOpenPath = Box<
 1271    dyn Fn(
 1272        &mut Workspace,
 1273        DirectoryLister,
 1274        &mut Window,
 1275        &mut Context<Workspace>,
 1276    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1277>;
 1278
 1279#[derive(Default)]
 1280struct DispatchingKeystrokes {
 1281    dispatched: HashSet<Vec<Keystroke>>,
 1282    queue: VecDeque<Keystroke>,
 1283    task: Option<Shared<Task<()>>>,
 1284}
 1285
 1286/// Collects everything project-related for a certain window opened.
 1287/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1288///
 1289/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1290/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1291/// that can be used to register a global action to be triggered from any place in the window.
 1292pub struct Workspace {
 1293    weak_self: WeakEntity<Self>,
 1294    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1295    zoomed: Option<AnyWeakView>,
 1296    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1297    zoomed_position: Option<DockPosition>,
 1298    center: PaneGroup,
 1299    left_dock: Entity<Dock>,
 1300    bottom_dock: Entity<Dock>,
 1301    right_dock: Entity<Dock>,
 1302    panes: Vec<Entity<Pane>>,
 1303    active_worktree_override: Option<WorktreeId>,
 1304    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1305    active_pane: Entity<Pane>,
 1306    last_active_center_pane: Option<WeakEntity<Pane>>,
 1307    last_active_view_id: Option<proto::ViewId>,
 1308    status_bar: Entity<StatusBar>,
 1309    pub(crate) modal_layer: Entity<ModalLayer>,
 1310    toast_layer: Entity<ToastLayer>,
 1311    titlebar_item: Option<AnyView>,
 1312    notifications: Notifications,
 1313    suppressed_notifications: HashSet<NotificationId>,
 1314    project: Entity<Project>,
 1315    follower_states: HashMap<CollaboratorId, FollowerState>,
 1316    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1317    window_edited: bool,
 1318    last_window_title: Option<String>,
 1319    dirty_items: HashMap<EntityId, Subscription>,
 1320    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1321    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1322    database_id: Option<WorkspaceId>,
 1323    app_state: Arc<AppState>,
 1324    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1325    _subscriptions: Vec<Subscription>,
 1326    _apply_leader_updates: Task<Result<()>>,
 1327    _observe_current_user: Task<Result<()>>,
 1328    _schedule_serialize_workspace: Option<Task<()>>,
 1329    _serialize_workspace_task: Option<Task<()>>,
 1330    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1331    pane_history_timestamp: Arc<AtomicUsize>,
 1332    bounds: Bounds<Pixels>,
 1333    pub centered_layout: bool,
 1334    bounds_save_task_queued: Option<Task<()>>,
 1335    on_prompt_for_new_path: Option<PromptForNewPath>,
 1336    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1337    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1338    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1339    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1340    _items_serializer: Task<Result<()>>,
 1341    session_id: Option<String>,
 1342    scheduled_tasks: Vec<Task<()>>,
 1343    last_open_dock_positions: Vec<DockPosition>,
 1344    removing: bool,
 1345    _panels_task: Option<Task<Result<()>>>,
 1346    sidebar_focus_handle: Option<FocusHandle>,
 1347    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1348}
 1349
 1350impl EventEmitter<Event> for Workspace {}
 1351
 1352#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1353pub struct ViewId {
 1354    pub creator: CollaboratorId,
 1355    pub id: u64,
 1356}
 1357
 1358pub struct FollowerState {
 1359    center_pane: Entity<Pane>,
 1360    dock_pane: Option<Entity<Pane>>,
 1361    active_view_id: Option<ViewId>,
 1362    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1363}
 1364
 1365struct FollowerView {
 1366    view: Box<dyn FollowableItemHandle>,
 1367    location: Option<proto::PanelId>,
 1368}
 1369
 1370#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1371pub enum OpenMode {
 1372    /// Open the workspace in a new window.
 1373    NewWindow,
 1374    /// Add to the window's multi workspace without activating it (used during deserialization).
 1375    Add,
 1376    /// Add to the window's multi workspace and activate it.
 1377    #[default]
 1378    Activate,
 1379    /// Replace the currently active workspace, and any of it's linked workspaces
 1380    Replace,
 1381}
 1382
 1383impl Workspace {
 1384    pub fn new(
 1385        workspace_id: Option<WorkspaceId>,
 1386        project: Entity<Project>,
 1387        app_state: Arc<AppState>,
 1388        window: &mut Window,
 1389        cx: &mut Context<Self>,
 1390    ) -> Self {
 1391        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1392            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1393                if let TrustedWorktreesEvent::Trusted(..) = e {
 1394                    // Do not persist auto trusted worktrees
 1395                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1396                        worktrees_store.update(cx, |worktrees_store, cx| {
 1397                            worktrees_store.schedule_serialization(
 1398                                cx,
 1399                                |new_trusted_worktrees, cx| {
 1400                                    let timeout =
 1401                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1402                                    let db = WorkspaceDb::global(cx);
 1403                                    cx.background_spawn(async move {
 1404                                        timeout.await;
 1405                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1406                                            .await
 1407                                            .log_err();
 1408                                    })
 1409                                },
 1410                            )
 1411                        });
 1412                    }
 1413                }
 1414            })
 1415            .detach();
 1416
 1417            cx.observe_global::<SettingsStore>(|_, cx| {
 1418                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1419                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1420                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1421                            trusted_worktrees.auto_trust_all(cx);
 1422                        })
 1423                    }
 1424                }
 1425            })
 1426            .detach();
 1427        }
 1428
 1429        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1430            match event {
 1431                project::Event::RemoteIdChanged(_) => {
 1432                    this.update_window_title(window, cx);
 1433                }
 1434
 1435                project::Event::CollaboratorLeft(peer_id) => {
 1436                    this.collaborator_left(*peer_id, window, cx);
 1437                }
 1438
 1439                &project::Event::WorktreeRemoved(_) => {
 1440                    this.update_window_title(window, cx);
 1441                    this.serialize_workspace(window, cx);
 1442                    this.update_history(cx);
 1443                }
 1444
 1445                &project::Event::WorktreeAdded(id) => {
 1446                    this.update_window_title(window, cx);
 1447                    if this
 1448                        .project()
 1449                        .read(cx)
 1450                        .worktree_for_id(id, cx)
 1451                        .is_some_and(|wt| wt.read(cx).is_visible())
 1452                    {
 1453                        this.serialize_workspace(window, cx);
 1454                        this.update_history(cx);
 1455                    }
 1456                }
 1457                project::Event::WorktreeUpdatedEntries(..) => {
 1458                    this.update_window_title(window, cx);
 1459                    this.serialize_workspace(window, cx);
 1460                }
 1461
 1462                project::Event::DisconnectedFromHost => {
 1463                    this.update_window_edited(window, cx);
 1464                    let leaders_to_unfollow =
 1465                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1466                    for leader_id in leaders_to_unfollow {
 1467                        this.unfollow(leader_id, window, cx);
 1468                    }
 1469                }
 1470
 1471                project::Event::DisconnectedFromRemote {
 1472                    server_not_running: _,
 1473                } => {
 1474                    this.update_window_edited(window, cx);
 1475                }
 1476
 1477                project::Event::Closed => {
 1478                    window.remove_window();
 1479                }
 1480
 1481                project::Event::DeletedEntry(_, entry_id) => {
 1482                    for pane in this.panes.iter() {
 1483                        pane.update(cx, |pane, cx| {
 1484                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1485                        });
 1486                    }
 1487                }
 1488
 1489                project::Event::Toast {
 1490                    notification_id,
 1491                    message,
 1492                    link,
 1493                } => this.show_notification(
 1494                    NotificationId::named(notification_id.clone()),
 1495                    cx,
 1496                    |cx| {
 1497                        let mut notification = MessageNotification::new(message.clone(), cx);
 1498                        if let Some(link) = link {
 1499                            notification = notification
 1500                                .more_info_message(link.label)
 1501                                .more_info_url(link.url);
 1502                        }
 1503
 1504                        cx.new(|_| notification)
 1505                    },
 1506                ),
 1507
 1508                project::Event::HideToast { notification_id } => {
 1509                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1510                }
 1511
 1512                project::Event::LanguageServerPrompt(request) => {
 1513                    struct LanguageServerPrompt;
 1514
 1515                    this.show_notification(
 1516                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1517                        cx,
 1518                        |cx| {
 1519                            cx.new(|cx| {
 1520                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1521                            })
 1522                        },
 1523                    );
 1524                }
 1525
 1526                project::Event::AgentLocationChanged => {
 1527                    this.handle_agent_location_changed(window, cx)
 1528                }
 1529
 1530                _ => {}
 1531            }
 1532            cx.notify()
 1533        })
 1534        .detach();
 1535
 1536        cx.subscribe_in(
 1537            &project.read(cx).breakpoint_store(),
 1538            window,
 1539            |workspace, _, event, window, cx| match event {
 1540                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1541                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1542                    workspace.serialize_workspace(window, cx);
 1543                }
 1544                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1545            },
 1546        )
 1547        .detach();
 1548        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1549            cx.subscribe_in(
 1550                &toolchain_store,
 1551                window,
 1552                |workspace, _, event, window, cx| match event {
 1553                    ToolchainStoreEvent::CustomToolchainsModified => {
 1554                        workspace.serialize_workspace(window, cx);
 1555                    }
 1556                    _ => {}
 1557                },
 1558            )
 1559            .detach();
 1560        }
 1561
 1562        cx.on_focus_lost(window, |this, window, cx| {
 1563            let focus_handle = this.focus_handle(cx);
 1564            window.focus(&focus_handle, cx);
 1565        })
 1566        .detach();
 1567
 1568        let weak_handle = cx.entity().downgrade();
 1569        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1570
 1571        let center_pane = cx.new(|cx| {
 1572            let mut center_pane = Pane::new(
 1573                weak_handle.clone(),
 1574                project.clone(),
 1575                pane_history_timestamp.clone(),
 1576                None,
 1577                NewFile.boxed_clone(),
 1578                true,
 1579                window,
 1580                cx,
 1581            );
 1582            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1583            center_pane.set_should_display_welcome_page(true);
 1584            center_pane
 1585        });
 1586        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1587            .detach();
 1588
 1589        window.focus(&center_pane.focus_handle(cx), cx);
 1590
 1591        cx.emit(Event::PaneAdded(center_pane.clone()));
 1592
 1593        let any_window_handle = window.window_handle();
 1594        app_state.workspace_store.update(cx, |store, _| {
 1595            store
 1596                .workspaces
 1597                .insert((any_window_handle, weak_handle.clone()));
 1598        });
 1599
 1600        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1601        let mut connection_status = app_state.client.status();
 1602        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1603            current_user.next().await;
 1604            connection_status.next().await;
 1605            let mut stream =
 1606                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1607
 1608            while stream.recv().await.is_some() {
 1609                this.update(cx, |_, cx| cx.notify())?;
 1610            }
 1611            anyhow::Ok(())
 1612        });
 1613
 1614        // All leader updates are enqueued and then processed in a single task, so
 1615        // that each asynchronous operation can be run in order.
 1616        let (leader_updates_tx, mut leader_updates_rx) =
 1617            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1618        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1619            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1620                Self::process_leader_update(&this, leader_id, update, cx)
 1621                    .await
 1622                    .log_err();
 1623            }
 1624
 1625            Ok(())
 1626        });
 1627
 1628        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1629        let modal_layer = cx.new(|_| ModalLayer::new());
 1630        let toast_layer = cx.new(|_| ToastLayer::new());
 1631        cx.subscribe(
 1632            &modal_layer,
 1633            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1634                cx.emit(Event::ModalOpened);
 1635            },
 1636        )
 1637        .detach();
 1638
 1639        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1640        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1641        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1642        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1643        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1644        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1645        let multi_workspace = window
 1646            .root::<MultiWorkspace>()
 1647            .flatten()
 1648            .map(|mw| mw.downgrade());
 1649        let status_bar = cx.new(|cx| {
 1650            let mut status_bar =
 1651                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1652            status_bar.add_left_item(left_dock_buttons, window, cx);
 1653            status_bar.add_right_item(right_dock_buttons, window, cx);
 1654            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1655            status_bar
 1656        });
 1657
 1658        let session_id = app_state.session.read(cx).id().to_owned();
 1659
 1660        let mut active_call = None;
 1661        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1662            let subscriptions =
 1663                vec![
 1664                    call.0
 1665                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1666                ];
 1667            active_call = Some((call, subscriptions));
 1668        }
 1669
 1670        let (serializable_items_tx, serializable_items_rx) =
 1671            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1672        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1673            Self::serialize_items(&this, serializable_items_rx, cx).await
 1674        });
 1675
 1676        let subscriptions = vec![
 1677            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1678            cx.observe_window_bounds(window, move |this, window, cx| {
 1679                if this.bounds_save_task_queued.is_some() {
 1680                    return;
 1681                }
 1682                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1683                    cx.background_executor()
 1684                        .timer(Duration::from_millis(100))
 1685                        .await;
 1686                    this.update_in(cx, |this, window, cx| {
 1687                        this.save_window_bounds(window, cx).detach();
 1688                        this.bounds_save_task_queued.take();
 1689                    })
 1690                    .ok();
 1691                }));
 1692                cx.notify();
 1693            }),
 1694            cx.observe_window_appearance(window, |_, window, cx| {
 1695                let window_appearance = window.appearance();
 1696
 1697                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1698
 1699                theme_settings::reload_theme(cx);
 1700                theme_settings::reload_icon_theme(cx);
 1701            }),
 1702            cx.on_release({
 1703                let weak_handle = weak_handle.clone();
 1704                move |this, cx| {
 1705                    this.app_state.workspace_store.update(cx, move |store, _| {
 1706                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1707                    })
 1708                }
 1709            }),
 1710        ];
 1711
 1712        cx.defer_in(window, move |this, window, cx| {
 1713            this.update_window_title(window, cx);
 1714            this.show_initial_notifications(cx);
 1715        });
 1716
 1717        let mut center = PaneGroup::new(center_pane.clone());
 1718        center.set_is_center(true);
 1719        center.mark_positions(cx);
 1720
 1721        Workspace {
 1722            weak_self: weak_handle.clone(),
 1723            zoomed: None,
 1724            zoomed_position: None,
 1725            previous_dock_drag_coordinates: None,
 1726            center,
 1727            panes: vec![center_pane.clone()],
 1728            panes_by_item: Default::default(),
 1729            active_pane: center_pane.clone(),
 1730            last_active_center_pane: Some(center_pane.downgrade()),
 1731            last_active_view_id: None,
 1732            status_bar,
 1733            modal_layer,
 1734            toast_layer,
 1735            titlebar_item: None,
 1736            active_worktree_override: None,
 1737            notifications: Notifications::default(),
 1738            suppressed_notifications: HashSet::default(),
 1739            left_dock,
 1740            bottom_dock,
 1741            right_dock,
 1742            _panels_task: None,
 1743            project: project.clone(),
 1744            follower_states: Default::default(),
 1745            last_leaders_by_pane: Default::default(),
 1746            dispatching_keystrokes: Default::default(),
 1747            window_edited: false,
 1748            last_window_title: None,
 1749            dirty_items: Default::default(),
 1750            active_call,
 1751            database_id: workspace_id,
 1752            app_state,
 1753            _observe_current_user,
 1754            _apply_leader_updates,
 1755            _schedule_serialize_workspace: None,
 1756            _serialize_workspace_task: None,
 1757            _schedule_serialize_ssh_paths: None,
 1758            leader_updates_tx,
 1759            _subscriptions: subscriptions,
 1760            pane_history_timestamp,
 1761            workspace_actions: Default::default(),
 1762            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1763            bounds: Default::default(),
 1764            centered_layout: false,
 1765            bounds_save_task_queued: None,
 1766            on_prompt_for_new_path: None,
 1767            on_prompt_for_open_path: None,
 1768            terminal_provider: None,
 1769            debugger_provider: None,
 1770            serializable_items_tx,
 1771            _items_serializer,
 1772            session_id: Some(session_id),
 1773
 1774            scheduled_tasks: Vec::new(),
 1775            last_open_dock_positions: Vec::new(),
 1776            removing: false,
 1777            sidebar_focus_handle: None,
 1778            multi_workspace,
 1779        }
 1780    }
 1781
 1782    pub fn new_local(
 1783        abs_paths: Vec<PathBuf>,
 1784        app_state: Arc<AppState>,
 1785        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1786        env: Option<HashMap<String, String>>,
 1787        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1788        open_mode: OpenMode,
 1789        cx: &mut App,
 1790    ) -> Task<anyhow::Result<OpenResult>> {
 1791        let project_handle = Project::local(
 1792            app_state.client.clone(),
 1793            app_state.node_runtime.clone(),
 1794            app_state.user_store.clone(),
 1795            app_state.languages.clone(),
 1796            app_state.fs.clone(),
 1797            env,
 1798            Default::default(),
 1799            cx,
 1800        );
 1801
 1802        let db = WorkspaceDb::global(cx);
 1803        let kvp = db::kvp::KeyValueStore::global(cx);
 1804        cx.spawn(async move |cx| {
 1805            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1806            for path in abs_paths.into_iter() {
 1807                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1808                    paths_to_open.push(canonical)
 1809                } else {
 1810                    paths_to_open.push(path)
 1811                }
 1812            }
 1813
 1814            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1815
 1816            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1817                paths_to_open = paths.ordered_paths().cloned().collect();
 1818                if !paths.is_lexicographically_ordered() {
 1819                    project_handle.update(cx, |project, cx| {
 1820                        project.set_worktrees_reordered(true, cx);
 1821                    });
 1822                }
 1823            }
 1824
 1825            // Get project paths for all of the abs_paths
 1826            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1827                Vec::with_capacity(paths_to_open.len());
 1828
 1829            for path in paths_to_open.into_iter() {
 1830                if let Some((_, project_entry)) = cx
 1831                    .update(|cx| {
 1832                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1833                    })
 1834                    .await
 1835                    .log_err()
 1836                {
 1837                    project_paths.push((path, Some(project_entry)));
 1838                } else {
 1839                    project_paths.push((path, None));
 1840                }
 1841            }
 1842
 1843            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1844                serialized_workspace.id
 1845            } else {
 1846                db.next_id().await.unwrap_or_else(|_| Default::default())
 1847            };
 1848
 1849            let toolchains = db.toolchains(workspace_id).await?;
 1850
 1851            for (toolchain, worktree_path, path) in toolchains {
 1852                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1853                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1854                    this.find_worktree(&worktree_path, cx)
 1855                        .and_then(|(worktree, rel_path)| {
 1856                            if rel_path.is_empty() {
 1857                                Some(worktree.read(cx).id())
 1858                            } else {
 1859                                None
 1860                            }
 1861                        })
 1862                }) else {
 1863                    // We did not find a worktree with a given path, but that's whatever.
 1864                    continue;
 1865                };
 1866                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1867                    continue;
 1868                }
 1869
 1870                project_handle
 1871                    .update(cx, |this, cx| {
 1872                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1873                    })
 1874                    .await;
 1875            }
 1876            if let Some(workspace) = serialized_workspace.as_ref() {
 1877                project_handle.update(cx, |this, cx| {
 1878                    for (scope, toolchains) in &workspace.user_toolchains {
 1879                        for toolchain in toolchains {
 1880                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1881                        }
 1882                    }
 1883                });
 1884            }
 1885
 1886            let window_to_replace = match open_mode {
 1887                OpenMode::NewWindow => None,
 1888                _ => requesting_window,
 1889            };
 1890
 1891            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1892                if let Some(window) = window_to_replace {
 1893                    let centered_layout = serialized_workspace
 1894                        .as_ref()
 1895                        .map(|w| w.centered_layout)
 1896                        .unwrap_or(false);
 1897
 1898                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1899                        let workspace = cx.new(|cx| {
 1900                            let mut workspace = Workspace::new(
 1901                                Some(workspace_id),
 1902                                project_handle.clone(),
 1903                                app_state.clone(),
 1904                                window,
 1905                                cx,
 1906                            );
 1907
 1908                            workspace.centered_layout = centered_layout;
 1909
 1910                            // Call init callback to add items before window renders
 1911                            if let Some(init) = init {
 1912                                init(&mut workspace, window, cx);
 1913                            }
 1914
 1915                            workspace
 1916                        });
 1917                        match open_mode {
 1918                            OpenMode::Replace => {
 1919                                multi_workspace.replace(workspace.clone(), &*window, cx);
 1920                            }
 1921                            OpenMode::Activate => {
 1922                                multi_workspace.activate(workspace.clone(), window, cx);
 1923                            }
 1924                            OpenMode::Add => {
 1925                                multi_workspace.add(workspace.clone(), &*window, cx);
 1926                            }
 1927                            OpenMode::NewWindow => {
 1928                                unreachable!()
 1929                            }
 1930                        }
 1931                        workspace
 1932                    })?;
 1933                    (window, workspace)
 1934                } else {
 1935                    let window_bounds_override = window_bounds_env_override();
 1936
 1937                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1938                        (Some(WindowBounds::Windowed(bounds)), None)
 1939                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1940                        && let Some(display) = workspace.display
 1941                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1942                    {
 1943                        // Reopening an existing workspace - restore its saved bounds
 1944                        (Some(bounds.0), Some(display))
 1945                    } else if let Some((display, bounds)) =
 1946                        persistence::read_default_window_bounds(&kvp)
 1947                    {
 1948                        // New or empty workspace - use the last known window bounds
 1949                        (Some(bounds), Some(display))
 1950                    } else {
 1951                        // New window - let GPUI's default_bounds() handle cascading
 1952                        (None, None)
 1953                    };
 1954
 1955                    // Use the serialized workspace to construct the new window
 1956                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1957                    options.window_bounds = window_bounds;
 1958                    let centered_layout = serialized_workspace
 1959                        .as_ref()
 1960                        .map(|w| w.centered_layout)
 1961                        .unwrap_or(false);
 1962                    let window = cx.open_window(options, {
 1963                        let app_state = app_state.clone();
 1964                        let project_handle = project_handle.clone();
 1965                        move |window, cx| {
 1966                            let workspace = cx.new(|cx| {
 1967                                let mut workspace = Workspace::new(
 1968                                    Some(workspace_id),
 1969                                    project_handle,
 1970                                    app_state,
 1971                                    window,
 1972                                    cx,
 1973                                );
 1974                                workspace.centered_layout = centered_layout;
 1975
 1976                                // Call init callback to add items before window renders
 1977                                if let Some(init) = init {
 1978                                    init(&mut workspace, window, cx);
 1979                                }
 1980
 1981                                workspace
 1982                            });
 1983                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1984                        }
 1985                    })?;
 1986                    let workspace =
 1987                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1988                            multi_workspace.workspace().clone()
 1989                        })?;
 1990                    (window, workspace)
 1991                };
 1992
 1993            notify_if_database_failed(window, cx);
 1994            // Check if this is an empty workspace (no paths to open)
 1995            // An empty workspace is one where project_paths is empty
 1996            let is_empty_workspace = project_paths.is_empty();
 1997            // Check if serialized workspace has paths before it's moved
 1998            let serialized_workspace_has_paths = serialized_workspace
 1999                .as_ref()
 2000                .map(|ws| !ws.paths.is_empty())
 2001                .unwrap_or(false);
 2002
 2003            let opened_items = window
 2004                .update(cx, |_, window, cx| {
 2005                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2006                        open_items(serialized_workspace, project_paths, window, cx)
 2007                    })
 2008                })?
 2009                .await
 2010                .unwrap_or_default();
 2011
 2012            // Restore default dock state for empty workspaces
 2013            // Only restore if:
 2014            // 1. This is an empty workspace (no paths), AND
 2015            // 2. The serialized workspace either doesn't exist or has no paths
 2016            if is_empty_workspace && !serialized_workspace_has_paths {
 2017                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2018                    window
 2019                        .update(cx, |_, window, cx| {
 2020                            workspace.update(cx, |workspace, cx| {
 2021                                for (dock, serialized_dock) in [
 2022                                    (&workspace.right_dock, &default_docks.right),
 2023                                    (&workspace.left_dock, &default_docks.left),
 2024                                    (&workspace.bottom_dock, &default_docks.bottom),
 2025                                ] {
 2026                                    dock.update(cx, |dock, cx| {
 2027                                        dock.serialized_dock = Some(serialized_dock.clone());
 2028                                        dock.restore_state(window, cx);
 2029                                    });
 2030                                }
 2031                                cx.notify();
 2032                            });
 2033                        })
 2034                        .log_err();
 2035                }
 2036            }
 2037
 2038            window
 2039                .update(cx, |_, _window, cx| {
 2040                    workspace.update(cx, |this: &mut Workspace, cx| {
 2041                        this.update_history(cx);
 2042                    });
 2043                })
 2044                .log_err();
 2045            Ok(OpenResult {
 2046                window,
 2047                workspace,
 2048                opened_items,
 2049            })
 2050        })
 2051    }
 2052
 2053    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2054        self.weak_self.clone()
 2055    }
 2056
 2057    pub fn left_dock(&self) -> &Entity<Dock> {
 2058        &self.left_dock
 2059    }
 2060
 2061    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2062        &self.bottom_dock
 2063    }
 2064
 2065    pub fn set_bottom_dock_layout(
 2066        &mut self,
 2067        layout: BottomDockLayout,
 2068        window: &mut Window,
 2069        cx: &mut Context<Self>,
 2070    ) {
 2071        let fs = self.project().read(cx).fs();
 2072        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2073            content.workspace.bottom_dock_layout = Some(layout);
 2074        });
 2075
 2076        cx.notify();
 2077        self.serialize_workspace(window, cx);
 2078    }
 2079
 2080    pub fn right_dock(&self) -> &Entity<Dock> {
 2081        &self.right_dock
 2082    }
 2083
 2084    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2085        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2086    }
 2087
 2088    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2089        let left_dock = self.left_dock.read(cx);
 2090        let left_visible = left_dock.is_open();
 2091        let left_active_panel = left_dock
 2092            .active_panel()
 2093            .map(|panel| panel.persistent_name().to_string());
 2094        // `zoomed_position` is kept in sync with individual panel zoom state
 2095        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2096        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2097
 2098        let right_dock = self.right_dock.read(cx);
 2099        let right_visible = right_dock.is_open();
 2100        let right_active_panel = right_dock
 2101            .active_panel()
 2102            .map(|panel| panel.persistent_name().to_string());
 2103        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2104
 2105        let bottom_dock = self.bottom_dock.read(cx);
 2106        let bottom_visible = bottom_dock.is_open();
 2107        let bottom_active_panel = bottom_dock
 2108            .active_panel()
 2109            .map(|panel| panel.persistent_name().to_string());
 2110        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2111
 2112        DockStructure {
 2113            left: DockData {
 2114                visible: left_visible,
 2115                active_panel: left_active_panel,
 2116                zoom: left_dock_zoom,
 2117            },
 2118            right: DockData {
 2119                visible: right_visible,
 2120                active_panel: right_active_panel,
 2121                zoom: right_dock_zoom,
 2122            },
 2123            bottom: DockData {
 2124                visible: bottom_visible,
 2125                active_panel: bottom_active_panel,
 2126                zoom: bottom_dock_zoom,
 2127            },
 2128        }
 2129    }
 2130
 2131    pub fn set_dock_structure(
 2132        &self,
 2133        docks: DockStructure,
 2134        window: &mut Window,
 2135        cx: &mut Context<Self>,
 2136    ) {
 2137        for (dock, data) in [
 2138            (&self.left_dock, docks.left),
 2139            (&self.bottom_dock, docks.bottom),
 2140            (&self.right_dock, docks.right),
 2141        ] {
 2142            dock.update(cx, |dock, cx| {
 2143                dock.serialized_dock = Some(data);
 2144                dock.restore_state(window, cx);
 2145            });
 2146        }
 2147    }
 2148
 2149    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2150        self.items(cx)
 2151            .filter_map(|item| {
 2152                let project_path = item.project_path(cx)?;
 2153                self.project.read(cx).absolute_path(&project_path, cx)
 2154            })
 2155            .collect()
 2156    }
 2157
 2158    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2159        match position {
 2160            DockPosition::Left => &self.left_dock,
 2161            DockPosition::Bottom => &self.bottom_dock,
 2162            DockPosition::Right => &self.right_dock,
 2163        }
 2164    }
 2165
 2166    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2167        self.all_docks().into_iter().find_map(|dock| {
 2168            let dock = dock.read(cx);
 2169            dock.has_agent_panel(cx).then_some(dock.position())
 2170        })
 2171    }
 2172
 2173    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2174        self.all_docks().into_iter().find_map(|dock| {
 2175            let dock = dock.read(cx);
 2176            let panel = dock.panel::<T>()?;
 2177            dock.stored_panel_size_state(&panel)
 2178        })
 2179    }
 2180
 2181    pub fn persisted_panel_size_state(
 2182        &self,
 2183        panel_key: &'static str,
 2184        cx: &App,
 2185    ) -> Option<dock::PanelSizeState> {
 2186        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2187    }
 2188
 2189    pub fn persist_panel_size_state(
 2190        &self,
 2191        panel_key: &str,
 2192        size_state: dock::PanelSizeState,
 2193        cx: &mut App,
 2194    ) {
 2195        let Some(workspace_id) = self
 2196            .database_id()
 2197            .map(|id| i64::from(id).to_string())
 2198            .or(self.session_id())
 2199        else {
 2200            return;
 2201        };
 2202
 2203        let kvp = db::kvp::KeyValueStore::global(cx);
 2204        let panel_key = panel_key.to_string();
 2205        cx.background_spawn(async move {
 2206            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2207            scope
 2208                .write(
 2209                    format!("{workspace_id}:{panel_key}"),
 2210                    serde_json::to_string(&size_state)?,
 2211                )
 2212                .await
 2213        })
 2214        .detach_and_log_err(cx);
 2215    }
 2216
 2217    pub fn set_panel_size_state<T: Panel>(
 2218        &mut self,
 2219        size_state: dock::PanelSizeState,
 2220        window: &mut Window,
 2221        cx: &mut Context<Self>,
 2222    ) -> bool {
 2223        let Some(panel) = self.panel::<T>(cx) else {
 2224            return false;
 2225        };
 2226
 2227        let dock = self.dock_at_position(panel.position(window, cx));
 2228        let did_set = dock.update(cx, |dock, cx| {
 2229            dock.set_panel_size_state(&panel, size_state, cx)
 2230        });
 2231
 2232        if did_set {
 2233            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2234        }
 2235
 2236        did_set
 2237    }
 2238
 2239    pub fn toggle_dock_panel_flexible_size(
 2240        &self,
 2241        dock: &Entity<Dock>,
 2242        panel: &dyn PanelHandle,
 2243        window: &mut Window,
 2244        cx: &mut App,
 2245    ) {
 2246        let position = dock.read(cx).position();
 2247        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2248        let current_flex =
 2249            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2250        dock.update(cx, |dock, cx| {
 2251            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2252        });
 2253    }
 2254
 2255    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2256        let panel = dock.active_panel()?;
 2257        let size_state = dock
 2258            .stored_panel_size_state(panel.as_ref())
 2259            .unwrap_or_default();
 2260        let position = dock.position();
 2261
 2262        let use_flex = panel.has_flexible_size(window, cx);
 2263
 2264        if position.axis() == Axis::Horizontal
 2265            && use_flex
 2266            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2267        {
 2268            let workspace_width = self.bounds.size.width;
 2269            if workspace_width <= Pixels::ZERO {
 2270                return None;
 2271            }
 2272            let flex = flex.max(0.001);
 2273            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2274            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2275                // Both docks are flex items sharing the full workspace width.
 2276                let total_flex = flex + 1.0 + opposite_flex;
 2277                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2278            } else {
 2279                // Opposite dock is fixed-width; flex items share (W - fixed).
 2280                let opposite_fixed = opposite
 2281                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2282                    .unwrap_or_default();
 2283                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2284                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2285            }
 2286        }
 2287
 2288        Some(
 2289            size_state
 2290                .size
 2291                .unwrap_or_else(|| panel.default_size(window, cx)),
 2292        )
 2293    }
 2294
 2295    pub fn dock_flex_for_size(
 2296        &self,
 2297        position: DockPosition,
 2298        size: Pixels,
 2299        window: &Window,
 2300        cx: &App,
 2301    ) -> Option<f32> {
 2302        if position.axis() != Axis::Horizontal {
 2303            return None;
 2304        }
 2305
 2306        let workspace_width = self.bounds.size.width;
 2307        if workspace_width <= Pixels::ZERO {
 2308            return None;
 2309        }
 2310
 2311        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2312        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2313            let size = size.clamp(px(0.), workspace_width - px(1.));
 2314            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2315        } else {
 2316            let opposite_width = opposite
 2317                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2318                .unwrap_or_default();
 2319            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2320            let remaining = (available - size).max(px(1.));
 2321            Some((size / remaining).max(0.0))
 2322        }
 2323    }
 2324
 2325    fn opposite_dock_panel_and_size_state(
 2326        &self,
 2327        position: DockPosition,
 2328        window: &Window,
 2329        cx: &App,
 2330    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2331        let opposite_position = match position {
 2332            DockPosition::Left => DockPosition::Right,
 2333            DockPosition::Right => DockPosition::Left,
 2334            DockPosition::Bottom => return None,
 2335        };
 2336
 2337        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2338        let panel = opposite_dock.visible_panel()?;
 2339        let mut size_state = opposite_dock
 2340            .stored_panel_size_state(panel.as_ref())
 2341            .unwrap_or_default();
 2342        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2343            size_state.flex = self.default_dock_flex(opposite_position);
 2344        }
 2345        Some((panel.clone(), size_state))
 2346    }
 2347
 2348    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2349        if position.axis() != Axis::Horizontal {
 2350            return None;
 2351        }
 2352
 2353        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2354        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2355    }
 2356
 2357    pub fn is_edited(&self) -> bool {
 2358        self.window_edited
 2359    }
 2360
 2361    pub fn add_panel<T: Panel>(
 2362        &mut self,
 2363        panel: Entity<T>,
 2364        window: &mut Window,
 2365        cx: &mut Context<Self>,
 2366    ) {
 2367        let focus_handle = panel.panel_focus_handle(cx);
 2368        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2369            .detach();
 2370
 2371        let dock_position = panel.position(window, cx);
 2372        let dock = self.dock_at_position(dock_position);
 2373        let any_panel = panel.to_any();
 2374        let persisted_size_state =
 2375            self.persisted_panel_size_state(T::panel_key(), cx)
 2376                .or_else(|| {
 2377                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2378                        let state = dock::PanelSizeState {
 2379                            size: Some(size),
 2380                            flex: None,
 2381                        };
 2382                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2383                        state
 2384                    })
 2385                });
 2386
 2387        dock.update(cx, |dock, cx| {
 2388            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2389            if let Some(size_state) = persisted_size_state {
 2390                dock.set_panel_size_state(&panel, size_state, cx);
 2391            }
 2392            index
 2393        });
 2394
 2395        cx.emit(Event::PanelAdded(any_panel));
 2396    }
 2397
 2398    pub fn remove_panel<T: Panel>(
 2399        &mut self,
 2400        panel: &Entity<T>,
 2401        window: &mut Window,
 2402        cx: &mut Context<Self>,
 2403    ) {
 2404        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2405            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2406        }
 2407    }
 2408
 2409    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2410        &self.status_bar
 2411    }
 2412
 2413    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2414        self.sidebar_focus_handle = handle;
 2415    }
 2416
 2417    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2418        StatusBarSettings::get_global(cx).show
 2419    }
 2420
 2421    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2422        self.multi_workspace.as_ref()
 2423    }
 2424
 2425    pub fn set_multi_workspace(
 2426        &mut self,
 2427        multi_workspace: WeakEntity<MultiWorkspace>,
 2428        cx: &mut App,
 2429    ) {
 2430        self.status_bar.update(cx, |status_bar, cx| {
 2431            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2432        });
 2433        self.multi_workspace = Some(multi_workspace);
 2434    }
 2435
 2436    pub fn app_state(&self) -> &Arc<AppState> {
 2437        &self.app_state
 2438    }
 2439
 2440    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2441        self._panels_task = Some(task);
 2442    }
 2443
 2444    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2445        self._panels_task.take()
 2446    }
 2447
 2448    pub fn user_store(&self) -> &Entity<UserStore> {
 2449        &self.app_state.user_store
 2450    }
 2451
 2452    pub fn project(&self) -> &Entity<Project> {
 2453        &self.project
 2454    }
 2455
 2456    pub fn path_style(&self, cx: &App) -> PathStyle {
 2457        self.project.read(cx).path_style(cx)
 2458    }
 2459
 2460    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2461        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2462
 2463        for pane_handle in &self.panes {
 2464            let pane = pane_handle.read(cx);
 2465
 2466            for entry in pane.activation_history() {
 2467                history.insert(
 2468                    entry.entity_id,
 2469                    history
 2470                        .get(&entry.entity_id)
 2471                        .cloned()
 2472                        .unwrap_or(0)
 2473                        .max(entry.timestamp),
 2474                );
 2475            }
 2476        }
 2477
 2478        history
 2479    }
 2480
 2481    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2482        let mut recent_item: Option<Entity<T>> = None;
 2483        let mut recent_timestamp = 0;
 2484        for pane_handle in &self.panes {
 2485            let pane = pane_handle.read(cx);
 2486            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2487                pane.items().map(|item| (item.item_id(), item)).collect();
 2488            for entry in pane.activation_history() {
 2489                if entry.timestamp > recent_timestamp
 2490                    && let Some(&item) = item_map.get(&entry.entity_id)
 2491                    && let Some(typed_item) = item.act_as::<T>(cx)
 2492                {
 2493                    recent_timestamp = entry.timestamp;
 2494                    recent_item = Some(typed_item);
 2495                }
 2496            }
 2497        }
 2498        recent_item
 2499    }
 2500
 2501    pub fn recent_navigation_history_iter(
 2502        &self,
 2503        cx: &App,
 2504    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2505        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2506        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2507
 2508        for pane in &self.panes {
 2509            let pane = pane.read(cx);
 2510
 2511            pane.nav_history()
 2512                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2513                    if let Some(fs_path) = &fs_path {
 2514                        abs_paths_opened
 2515                            .entry(fs_path.clone())
 2516                            .or_default()
 2517                            .insert(project_path.clone());
 2518                    }
 2519                    let timestamp = entry.timestamp;
 2520                    match history.entry(project_path) {
 2521                        hash_map::Entry::Occupied(mut entry) => {
 2522                            let (_, old_timestamp) = entry.get();
 2523                            if &timestamp > old_timestamp {
 2524                                entry.insert((fs_path, timestamp));
 2525                            }
 2526                        }
 2527                        hash_map::Entry::Vacant(entry) => {
 2528                            entry.insert((fs_path, timestamp));
 2529                        }
 2530                    }
 2531                });
 2532
 2533            if let Some(item) = pane.active_item()
 2534                && let Some(project_path) = item.project_path(cx)
 2535            {
 2536                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2537
 2538                if let Some(fs_path) = &fs_path {
 2539                    abs_paths_opened
 2540                        .entry(fs_path.clone())
 2541                        .or_default()
 2542                        .insert(project_path.clone());
 2543                }
 2544
 2545                history.insert(project_path, (fs_path, std::usize::MAX));
 2546            }
 2547        }
 2548
 2549        history
 2550            .into_iter()
 2551            .sorted_by_key(|(_, (_, order))| *order)
 2552            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2553            .rev()
 2554            .filter(move |(history_path, abs_path)| {
 2555                let latest_project_path_opened = abs_path
 2556                    .as_ref()
 2557                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2558                    .and_then(|project_paths| {
 2559                        project_paths
 2560                            .iter()
 2561                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2562                    });
 2563
 2564                latest_project_path_opened.is_none_or(|path| path == history_path)
 2565            })
 2566    }
 2567
 2568    pub fn recent_navigation_history(
 2569        &self,
 2570        limit: Option<usize>,
 2571        cx: &App,
 2572    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2573        self.recent_navigation_history_iter(cx)
 2574            .take(limit.unwrap_or(usize::MAX))
 2575            .collect()
 2576    }
 2577
 2578    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2579        for pane in &self.panes {
 2580            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2581        }
 2582    }
 2583
 2584    fn navigate_history(
 2585        &mut self,
 2586        pane: WeakEntity<Pane>,
 2587        mode: NavigationMode,
 2588        window: &mut Window,
 2589        cx: &mut Context<Workspace>,
 2590    ) -> Task<Result<()>> {
 2591        self.navigate_history_impl(
 2592            pane,
 2593            mode,
 2594            window,
 2595            &mut |history, cx| history.pop(mode, cx),
 2596            cx,
 2597        )
 2598    }
 2599
 2600    fn navigate_tag_history(
 2601        &mut self,
 2602        pane: WeakEntity<Pane>,
 2603        mode: TagNavigationMode,
 2604        window: &mut Window,
 2605        cx: &mut Context<Workspace>,
 2606    ) -> Task<Result<()>> {
 2607        self.navigate_history_impl(
 2608            pane,
 2609            NavigationMode::Normal,
 2610            window,
 2611            &mut |history, _cx| history.pop_tag(mode),
 2612            cx,
 2613        )
 2614    }
 2615
 2616    fn navigate_history_impl(
 2617        &mut self,
 2618        pane: WeakEntity<Pane>,
 2619        mode: NavigationMode,
 2620        window: &mut Window,
 2621        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2622        cx: &mut Context<Workspace>,
 2623    ) -> Task<Result<()>> {
 2624        let to_load = if let Some(pane) = pane.upgrade() {
 2625            pane.update(cx, |pane, cx| {
 2626                window.focus(&pane.focus_handle(cx), cx);
 2627                loop {
 2628                    // Retrieve the weak item handle from the history.
 2629                    let entry = cb(pane.nav_history_mut(), cx)?;
 2630
 2631                    // If the item is still present in this pane, then activate it.
 2632                    if let Some(index) = entry
 2633                        .item
 2634                        .upgrade()
 2635                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2636                    {
 2637                        let prev_active_item_index = pane.active_item_index();
 2638                        pane.nav_history_mut().set_mode(mode);
 2639                        pane.activate_item(index, true, true, window, cx);
 2640                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2641
 2642                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2643                        if let Some(data) = entry.data {
 2644                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2645                        }
 2646
 2647                        if navigated {
 2648                            break None;
 2649                        }
 2650                    } else {
 2651                        // If the item is no longer present in this pane, then retrieve its
 2652                        // path info in order to reopen it.
 2653                        break pane
 2654                            .nav_history()
 2655                            .path_for_item(entry.item.id())
 2656                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2657                    }
 2658                }
 2659            })
 2660        } else {
 2661            None
 2662        };
 2663
 2664        if let Some((project_path, abs_path, entry)) = to_load {
 2665            // If the item was no longer present, then load it again from its previous path, first try the local path
 2666            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2667
 2668            cx.spawn_in(window, async move  |workspace, cx| {
 2669                let open_by_project_path = open_by_project_path.await;
 2670                let mut navigated = false;
 2671                match open_by_project_path
 2672                    .with_context(|| format!("Navigating to {project_path:?}"))
 2673                {
 2674                    Ok((project_entry_id, build_item)) => {
 2675                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2676                            pane.nav_history_mut().set_mode(mode);
 2677                            pane.active_item().map(|p| p.item_id())
 2678                        })?;
 2679
 2680                        pane.update_in(cx, |pane, window, cx| {
 2681                            let item = pane.open_item(
 2682                                project_entry_id,
 2683                                project_path,
 2684                                true,
 2685                                entry.is_preview,
 2686                                true,
 2687                                None,
 2688                                window, cx,
 2689                                build_item,
 2690                            );
 2691                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2692                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2693                            if let Some(data) = entry.data {
 2694                                navigated |= item.navigate(data, window, cx);
 2695                            }
 2696                        })?;
 2697                    }
 2698                    Err(open_by_project_path_e) => {
 2699                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2700                        // and its worktree is now dropped
 2701                        if let Some(abs_path) = abs_path {
 2702                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2703                                pane.nav_history_mut().set_mode(mode);
 2704                                pane.active_item().map(|p| p.item_id())
 2705                            })?;
 2706                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2707                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2708                            })?;
 2709                            match open_by_abs_path
 2710                                .await
 2711                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2712                            {
 2713                                Ok(item) => {
 2714                                    pane.update_in(cx, |pane, window, cx| {
 2715                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2716                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2717                                        if let Some(data) = entry.data {
 2718                                            navigated |= item.navigate(data, window, cx);
 2719                                        }
 2720                                    })?;
 2721                                }
 2722                                Err(open_by_abs_path_e) => {
 2723                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2724                                }
 2725                            }
 2726                        }
 2727                    }
 2728                }
 2729
 2730                if !navigated {
 2731                    workspace
 2732                        .update_in(cx, |workspace, window, cx| {
 2733                            Self::navigate_history(workspace, pane, mode, window, cx)
 2734                        })?
 2735                        .await?;
 2736                }
 2737
 2738                Ok(())
 2739            })
 2740        } else {
 2741            Task::ready(Ok(()))
 2742        }
 2743    }
 2744
 2745    pub fn go_back(
 2746        &mut self,
 2747        pane: WeakEntity<Pane>,
 2748        window: &mut Window,
 2749        cx: &mut Context<Workspace>,
 2750    ) -> Task<Result<()>> {
 2751        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2752    }
 2753
 2754    pub fn go_forward(
 2755        &mut self,
 2756        pane: WeakEntity<Pane>,
 2757        window: &mut Window,
 2758        cx: &mut Context<Workspace>,
 2759    ) -> Task<Result<()>> {
 2760        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2761    }
 2762
 2763    pub fn reopen_closed_item(
 2764        &mut self,
 2765        window: &mut Window,
 2766        cx: &mut Context<Workspace>,
 2767    ) -> Task<Result<()>> {
 2768        self.navigate_history(
 2769            self.active_pane().downgrade(),
 2770            NavigationMode::ReopeningClosedItem,
 2771            window,
 2772            cx,
 2773        )
 2774    }
 2775
 2776    pub fn client(&self) -> &Arc<Client> {
 2777        &self.app_state.client
 2778    }
 2779
 2780    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2781        self.titlebar_item = Some(item);
 2782        cx.notify();
 2783    }
 2784
 2785    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2786        self.on_prompt_for_new_path = Some(prompt)
 2787    }
 2788
 2789    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2790        self.on_prompt_for_open_path = Some(prompt)
 2791    }
 2792
 2793    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2794        self.terminal_provider = Some(Box::new(provider));
 2795    }
 2796
 2797    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2798        self.debugger_provider = Some(Arc::new(provider));
 2799    }
 2800
 2801    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2802        self.debugger_provider.clone()
 2803    }
 2804
 2805    pub fn prompt_for_open_path(
 2806        &mut self,
 2807        path_prompt_options: PathPromptOptions,
 2808        lister: DirectoryLister,
 2809        window: &mut Window,
 2810        cx: &mut Context<Self>,
 2811    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2812        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2813            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2814            let rx = prompt(self, lister, window, cx);
 2815            self.on_prompt_for_open_path = Some(prompt);
 2816            rx
 2817        } else {
 2818            let (tx, rx) = oneshot::channel();
 2819            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2820
 2821            cx.spawn_in(window, async move |workspace, cx| {
 2822                let Ok(result) = abs_path.await else {
 2823                    return Ok(());
 2824                };
 2825
 2826                match result {
 2827                    Ok(result) => {
 2828                        tx.send(result).ok();
 2829                    }
 2830                    Err(err) => {
 2831                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2832                            workspace.show_portal_error(err.to_string(), cx);
 2833                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2834                            let rx = prompt(workspace, lister, window, cx);
 2835                            workspace.on_prompt_for_open_path = Some(prompt);
 2836                            rx
 2837                        })?;
 2838                        if let Ok(path) = rx.await {
 2839                            tx.send(path).ok();
 2840                        }
 2841                    }
 2842                };
 2843                anyhow::Ok(())
 2844            })
 2845            .detach();
 2846
 2847            rx
 2848        }
 2849    }
 2850
 2851    pub fn prompt_for_new_path(
 2852        &mut self,
 2853        lister: DirectoryLister,
 2854        suggested_name: Option<String>,
 2855        window: &mut Window,
 2856        cx: &mut Context<Self>,
 2857    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2858        if self.project.read(cx).is_via_collab()
 2859            || self.project.read(cx).is_via_remote_server()
 2860            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2861        {
 2862            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2863            let rx = prompt(self, lister, suggested_name, window, cx);
 2864            self.on_prompt_for_new_path = Some(prompt);
 2865            return rx;
 2866        }
 2867
 2868        let (tx, rx) = oneshot::channel();
 2869        cx.spawn_in(window, async move |workspace, cx| {
 2870            let abs_path = workspace.update(cx, |workspace, cx| {
 2871                let relative_to = workspace
 2872                    .most_recent_active_path(cx)
 2873                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2874                    .or_else(|| {
 2875                        let project = workspace.project.read(cx);
 2876                        project.visible_worktrees(cx).find_map(|worktree| {
 2877                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2878                        })
 2879                    })
 2880                    .or_else(std::env::home_dir)
 2881                    .unwrap_or_else(|| PathBuf::from(""));
 2882                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2883            })?;
 2884            let abs_path = match abs_path.await? {
 2885                Ok(path) => path,
 2886                Err(err) => {
 2887                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2888                        workspace.show_portal_error(err.to_string(), cx);
 2889
 2890                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2891                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2892                        workspace.on_prompt_for_new_path = Some(prompt);
 2893                        rx
 2894                    })?;
 2895                    if let Ok(path) = rx.await {
 2896                        tx.send(path).ok();
 2897                    }
 2898                    return anyhow::Ok(());
 2899                }
 2900            };
 2901
 2902            tx.send(abs_path.map(|path| vec![path])).ok();
 2903            anyhow::Ok(())
 2904        })
 2905        .detach();
 2906
 2907        rx
 2908    }
 2909
 2910    pub fn titlebar_item(&self) -> Option<AnyView> {
 2911        self.titlebar_item.clone()
 2912    }
 2913
 2914    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2915    /// When set, git-related operations should use this worktree instead of deriving
 2916    /// the active worktree from the focused file.
 2917    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2918        self.active_worktree_override
 2919    }
 2920
 2921    pub fn set_active_worktree_override(
 2922        &mut self,
 2923        worktree_id: Option<WorktreeId>,
 2924        cx: &mut Context<Self>,
 2925    ) {
 2926        self.active_worktree_override = worktree_id;
 2927        cx.notify();
 2928    }
 2929
 2930    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2931        self.active_worktree_override = None;
 2932        cx.notify();
 2933    }
 2934
 2935    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2936    ///
 2937    /// If the given workspace has a local project, then it will be passed
 2938    /// to the callback. Otherwise, a new empty window will be created.
 2939    pub fn with_local_workspace<T, F>(
 2940        &mut self,
 2941        window: &mut Window,
 2942        cx: &mut Context<Self>,
 2943        callback: F,
 2944    ) -> Task<Result<T>>
 2945    where
 2946        T: 'static,
 2947        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2948    {
 2949        if self.project.read(cx).is_local() {
 2950            Task::ready(Ok(callback(self, window, cx)))
 2951        } else {
 2952            let env = self.project.read(cx).cli_environment(cx);
 2953            let task = Self::new_local(
 2954                Vec::new(),
 2955                self.app_state.clone(),
 2956                None,
 2957                env,
 2958                None,
 2959                OpenMode::Activate,
 2960                cx,
 2961            );
 2962            cx.spawn_in(window, async move |_vh, cx| {
 2963                let OpenResult {
 2964                    window: multi_workspace_window,
 2965                    ..
 2966                } = task.await?;
 2967                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2968                    let workspace = multi_workspace.workspace().clone();
 2969                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2970                })
 2971            })
 2972        }
 2973    }
 2974
 2975    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2976    ///
 2977    /// If the given workspace has a local project, then it will be passed
 2978    /// to the callback. Otherwise, a new empty window will be created.
 2979    pub fn with_local_or_wsl_workspace<T, F>(
 2980        &mut self,
 2981        window: &mut Window,
 2982        cx: &mut Context<Self>,
 2983        callback: F,
 2984    ) -> Task<Result<T>>
 2985    where
 2986        T: 'static,
 2987        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2988    {
 2989        let project = self.project.read(cx);
 2990        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2991            Task::ready(Ok(callback(self, window, cx)))
 2992        } else {
 2993            let env = self.project.read(cx).cli_environment(cx);
 2994            let task = Self::new_local(
 2995                Vec::new(),
 2996                self.app_state.clone(),
 2997                None,
 2998                env,
 2999                None,
 3000                OpenMode::Activate,
 3001                cx,
 3002            );
 3003            cx.spawn_in(window, async move |_vh, cx| {
 3004                let OpenResult {
 3005                    window: multi_workspace_window,
 3006                    ..
 3007                } = task.await?;
 3008                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3009                    let workspace = multi_workspace.workspace().clone();
 3010                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3011                })
 3012            })
 3013        }
 3014    }
 3015
 3016    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3017        self.project.read(cx).worktrees(cx)
 3018    }
 3019
 3020    pub fn visible_worktrees<'a>(
 3021        &self,
 3022        cx: &'a App,
 3023    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3024        self.project.read(cx).visible_worktrees(cx)
 3025    }
 3026
 3027    #[cfg(any(test, feature = "test-support"))]
 3028    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3029        let futures = self
 3030            .worktrees(cx)
 3031            .filter_map(|worktree| worktree.read(cx).as_local())
 3032            .map(|worktree| worktree.scan_complete())
 3033            .collect::<Vec<_>>();
 3034        async move {
 3035            for future in futures {
 3036                future.await;
 3037            }
 3038        }
 3039    }
 3040
 3041    pub fn close_global(cx: &mut App) {
 3042        cx.defer(|cx| {
 3043            cx.windows().iter().find(|window| {
 3044                window
 3045                    .update(cx, |_, window, _| {
 3046                        if window.is_window_active() {
 3047                            //This can only get called when the window's project connection has been lost
 3048                            //so we don't need to prompt the user for anything and instead just close the window
 3049                            window.remove_window();
 3050                            true
 3051                        } else {
 3052                            false
 3053                        }
 3054                    })
 3055                    .unwrap_or(false)
 3056            });
 3057        });
 3058    }
 3059
 3060    pub fn move_focused_panel_to_next_position(
 3061        &mut self,
 3062        _: &MoveFocusedPanelToNextPosition,
 3063        window: &mut Window,
 3064        cx: &mut Context<Self>,
 3065    ) {
 3066        let docks = self.all_docks();
 3067        let active_dock = docks
 3068            .into_iter()
 3069            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3070
 3071        if let Some(dock) = active_dock {
 3072            dock.update(cx, |dock, cx| {
 3073                let active_panel = dock
 3074                    .active_panel()
 3075                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3076
 3077                if let Some(panel) = active_panel {
 3078                    panel.move_to_next_position(window, cx);
 3079                }
 3080            })
 3081        }
 3082    }
 3083
 3084    pub fn prepare_to_close(
 3085        &mut self,
 3086        close_intent: CloseIntent,
 3087        window: &mut Window,
 3088        cx: &mut Context<Self>,
 3089    ) -> Task<Result<bool>> {
 3090        let active_call = self.active_global_call();
 3091
 3092        cx.spawn_in(window, async move |this, cx| {
 3093            this.update(cx, |this, _| {
 3094                if close_intent == CloseIntent::CloseWindow {
 3095                    this.removing = true;
 3096                }
 3097            })?;
 3098
 3099            let workspace_count = cx.update(|_window, cx| {
 3100                cx.windows()
 3101                    .iter()
 3102                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3103                    .count()
 3104            })?;
 3105
 3106            #[cfg(target_os = "macos")]
 3107            let save_last_workspace = false;
 3108
 3109            // On Linux and Windows, closing the last window should restore the last workspace.
 3110            #[cfg(not(target_os = "macos"))]
 3111            let save_last_workspace = {
 3112                let remaining_workspaces = cx.update(|_window, cx| {
 3113                    cx.windows()
 3114                        .iter()
 3115                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3116                        .filter_map(|multi_workspace| {
 3117                            multi_workspace
 3118                                .update(cx, |multi_workspace, _, cx| {
 3119                                    multi_workspace.workspace().read(cx).removing
 3120                                })
 3121                                .ok()
 3122                        })
 3123                        .filter(|removing| !removing)
 3124                        .count()
 3125                })?;
 3126
 3127                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3128            };
 3129
 3130            if let Some(active_call) = active_call
 3131                && workspace_count == 1
 3132                && cx
 3133                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3134                    .unwrap_or(false)
 3135            {
 3136                if close_intent == CloseIntent::CloseWindow {
 3137                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3138                    let answer = cx.update(|window, cx| {
 3139                        window.prompt(
 3140                            PromptLevel::Warning,
 3141                            "Do you want to leave the current call?",
 3142                            None,
 3143                            &["Close window and hang up", "Cancel"],
 3144                            cx,
 3145                        )
 3146                    })?;
 3147
 3148                    if answer.await.log_err() == Some(1) {
 3149                        return anyhow::Ok(false);
 3150                    } else {
 3151                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3152                            task.await.log_err();
 3153                        }
 3154                    }
 3155                }
 3156                if close_intent == CloseIntent::ReplaceWindow {
 3157                    _ = cx.update(|_window, cx| {
 3158                        let multi_workspace = cx
 3159                            .windows()
 3160                            .iter()
 3161                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3162                            .next()
 3163                            .unwrap();
 3164                        let project = multi_workspace
 3165                            .read(cx)?
 3166                            .workspace()
 3167                            .read(cx)
 3168                            .project
 3169                            .clone();
 3170                        if project.read(cx).is_shared() {
 3171                            active_call.0.unshare_project(project, cx)?;
 3172                        }
 3173                        Ok::<_, anyhow::Error>(())
 3174                    });
 3175                }
 3176            }
 3177
 3178            let save_result = this
 3179                .update_in(cx, |this, window, cx| {
 3180                    this.save_all_internal(SaveIntent::Close, window, cx)
 3181                })?
 3182                .await;
 3183
 3184            // If we're not quitting, but closing, we remove the workspace from
 3185            // the current session.
 3186            if close_intent != CloseIntent::Quit
 3187                && !save_last_workspace
 3188                && save_result.as_ref().is_ok_and(|&res| res)
 3189            {
 3190                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3191                    .await;
 3192            }
 3193
 3194            save_result
 3195        })
 3196    }
 3197
 3198    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3199        self.save_all_internal(
 3200            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3201            window,
 3202            cx,
 3203        )
 3204        .detach_and_log_err(cx);
 3205    }
 3206
 3207    fn send_keystrokes(
 3208        &mut self,
 3209        action: &SendKeystrokes,
 3210        window: &mut Window,
 3211        cx: &mut Context<Self>,
 3212    ) {
 3213        let keystrokes: Vec<Keystroke> = action
 3214            .0
 3215            .split(' ')
 3216            .flat_map(|k| Keystroke::parse(k).log_err())
 3217            .map(|k| {
 3218                cx.keyboard_mapper()
 3219                    .map_key_equivalent(k, false)
 3220                    .inner()
 3221                    .clone()
 3222            })
 3223            .collect();
 3224        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3225    }
 3226
 3227    pub fn send_keystrokes_impl(
 3228        &mut self,
 3229        keystrokes: Vec<Keystroke>,
 3230        window: &mut Window,
 3231        cx: &mut Context<Self>,
 3232    ) -> Shared<Task<()>> {
 3233        let mut state = self.dispatching_keystrokes.borrow_mut();
 3234        if !state.dispatched.insert(keystrokes.clone()) {
 3235            cx.propagate();
 3236            return state.task.clone().unwrap();
 3237        }
 3238
 3239        state.queue.extend(keystrokes);
 3240
 3241        let keystrokes = self.dispatching_keystrokes.clone();
 3242        if state.task.is_none() {
 3243            state.task = Some(
 3244                window
 3245                    .spawn(cx, async move |cx| {
 3246                        // limit to 100 keystrokes to avoid infinite recursion.
 3247                        for _ in 0..100 {
 3248                            let keystroke = {
 3249                                let mut state = keystrokes.borrow_mut();
 3250                                let Some(keystroke) = state.queue.pop_front() else {
 3251                                    state.dispatched.clear();
 3252                                    state.task.take();
 3253                                    return;
 3254                                };
 3255                                keystroke
 3256                            };
 3257                            cx.update(|window, cx| {
 3258                                let focused = window.focused(cx);
 3259                                window.dispatch_keystroke(keystroke.clone(), cx);
 3260                                if window.focused(cx) != focused {
 3261                                    // dispatch_keystroke may cause the focus to change.
 3262                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3263                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3264                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3265                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3266                                    // )
 3267                                    window.draw(cx).clear();
 3268                                }
 3269                            })
 3270                            .ok();
 3271
 3272                            // Yield between synthetic keystrokes so deferred focus and
 3273                            // other effects can settle before dispatching the next key.
 3274                            yield_now().await;
 3275                        }
 3276
 3277                        *keystrokes.borrow_mut() = Default::default();
 3278                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3279                    })
 3280                    .shared(),
 3281            );
 3282        }
 3283        state.task.clone().unwrap()
 3284    }
 3285
 3286    fn save_all_internal(
 3287        &mut self,
 3288        mut save_intent: SaveIntent,
 3289        window: &mut Window,
 3290        cx: &mut Context<Self>,
 3291    ) -> Task<Result<bool>> {
 3292        if self.project.read(cx).is_disconnected(cx) {
 3293            return Task::ready(Ok(true));
 3294        }
 3295        let dirty_items = self
 3296            .panes
 3297            .iter()
 3298            .flat_map(|pane| {
 3299                pane.read(cx).items().filter_map(|item| {
 3300                    if item.is_dirty(cx) {
 3301                        item.tab_content_text(0, cx);
 3302                        Some((pane.downgrade(), item.boxed_clone()))
 3303                    } else {
 3304                        None
 3305                    }
 3306                })
 3307            })
 3308            .collect::<Vec<_>>();
 3309
 3310        let project = self.project.clone();
 3311        cx.spawn_in(window, async move |workspace, cx| {
 3312            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3313                let (serialize_tasks, remaining_dirty_items) =
 3314                    workspace.update_in(cx, |workspace, window, cx| {
 3315                        let mut remaining_dirty_items = Vec::new();
 3316                        let mut serialize_tasks = Vec::new();
 3317                        for (pane, item) in dirty_items {
 3318                            if let Some(task) = item
 3319                                .to_serializable_item_handle(cx)
 3320                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3321                            {
 3322                                serialize_tasks.push(task);
 3323                            } else {
 3324                                remaining_dirty_items.push((pane, item));
 3325                            }
 3326                        }
 3327                        (serialize_tasks, remaining_dirty_items)
 3328                    })?;
 3329
 3330                futures::future::try_join_all(serialize_tasks).await?;
 3331
 3332                if !remaining_dirty_items.is_empty() {
 3333                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3334                }
 3335
 3336                if remaining_dirty_items.len() > 1 {
 3337                    let answer = workspace.update_in(cx, |_, window, cx| {
 3338                        let detail = Pane::file_names_for_prompt(
 3339                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3340                            cx,
 3341                        );
 3342                        window.prompt(
 3343                            PromptLevel::Warning,
 3344                            "Do you want to save all changes in the following files?",
 3345                            Some(&detail),
 3346                            &["Save all", "Discard all", "Cancel"],
 3347                            cx,
 3348                        )
 3349                    })?;
 3350                    match answer.await.log_err() {
 3351                        Some(0) => save_intent = SaveIntent::SaveAll,
 3352                        Some(1) => save_intent = SaveIntent::Skip,
 3353                        Some(2) => return Ok(false),
 3354                        _ => {}
 3355                    }
 3356                }
 3357
 3358                remaining_dirty_items
 3359            } else {
 3360                dirty_items
 3361            };
 3362
 3363            for (pane, item) in dirty_items {
 3364                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3365                    (
 3366                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3367                        item.project_entry_ids(cx),
 3368                    )
 3369                })?;
 3370                if (singleton || !project_entry_ids.is_empty())
 3371                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3372                {
 3373                    return Ok(false);
 3374                }
 3375            }
 3376            Ok(true)
 3377        })
 3378    }
 3379
 3380    pub fn open_workspace_for_paths(
 3381        &mut self,
 3382        // replace_current_window: bool,
 3383        mut open_mode: OpenMode,
 3384        paths: Vec<PathBuf>,
 3385        window: &mut Window,
 3386        cx: &mut Context<Self>,
 3387    ) -> Task<Result<Entity<Workspace>>> {
 3388        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3389        let is_remote = self.project.read(cx).is_via_collab();
 3390        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3391        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3392
 3393        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3394        if workspace_is_empty {
 3395            open_mode = OpenMode::Replace;
 3396        }
 3397
 3398        let app_state = self.app_state.clone();
 3399
 3400        cx.spawn(async move |_, cx| {
 3401            let OpenResult { workspace, .. } = cx
 3402                .update(|cx| {
 3403                    open_paths(
 3404                        &paths,
 3405                        app_state,
 3406                        OpenOptions {
 3407                            requesting_window,
 3408                            open_mode,
 3409                            ..Default::default()
 3410                        },
 3411                        cx,
 3412                    )
 3413                })
 3414                .await?;
 3415            Ok(workspace)
 3416        })
 3417    }
 3418
 3419    #[allow(clippy::type_complexity)]
 3420    pub fn open_paths(
 3421        &mut self,
 3422        mut abs_paths: Vec<PathBuf>,
 3423        options: OpenOptions,
 3424        pane: Option<WeakEntity<Pane>>,
 3425        window: &mut Window,
 3426        cx: &mut Context<Self>,
 3427    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3428        let fs = self.app_state.fs.clone();
 3429
 3430        let caller_ordered_abs_paths = abs_paths.clone();
 3431
 3432        // Sort the paths to ensure we add worktrees for parents before their children.
 3433        abs_paths.sort_unstable();
 3434        cx.spawn_in(window, async move |this, cx| {
 3435            let mut tasks = Vec::with_capacity(abs_paths.len());
 3436
 3437            for abs_path in &abs_paths {
 3438                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3439                    OpenVisible::All => Some(true),
 3440                    OpenVisible::None => Some(false),
 3441                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3442                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3443                        Some(None) => Some(true),
 3444                        None => None,
 3445                    },
 3446                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3447                        Some(Some(metadata)) => Some(metadata.is_dir),
 3448                        Some(None) => Some(false),
 3449                        None => None,
 3450                    },
 3451                };
 3452                let project_path = match visible {
 3453                    Some(visible) => match this
 3454                        .update(cx, |this, cx| {
 3455                            Workspace::project_path_for_path(
 3456                                this.project.clone(),
 3457                                abs_path,
 3458                                visible,
 3459                                cx,
 3460                            )
 3461                        })
 3462                        .log_err()
 3463                    {
 3464                        Some(project_path) => project_path.await.log_err(),
 3465                        None => None,
 3466                    },
 3467                    None => None,
 3468                };
 3469
 3470                let this = this.clone();
 3471                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3472                let fs = fs.clone();
 3473                let pane = pane.clone();
 3474                let task = cx.spawn(async move |cx| {
 3475                    let (_worktree, project_path) = project_path?;
 3476                    if fs.is_dir(&abs_path).await {
 3477                        // Opening a directory should not race to update the active entry.
 3478                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3479                        None
 3480                    } else {
 3481                        Some(
 3482                            this.update_in(cx, |this, window, cx| {
 3483                                this.open_path(
 3484                                    project_path,
 3485                                    pane,
 3486                                    options.focus.unwrap_or(true),
 3487                                    window,
 3488                                    cx,
 3489                                )
 3490                            })
 3491                            .ok()?
 3492                            .await,
 3493                        )
 3494                    }
 3495                });
 3496                tasks.push(task);
 3497            }
 3498
 3499            let results = futures::future::join_all(tasks).await;
 3500
 3501            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3502            let mut winner: Option<(PathBuf, bool)> = None;
 3503            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3504                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3505                    if !metadata.is_dir {
 3506                        winner = Some((abs_path, false));
 3507                        break;
 3508                    }
 3509                    if winner.is_none() {
 3510                        winner = Some((abs_path, true));
 3511                    }
 3512                } else if winner.is_none() {
 3513                    winner = Some((abs_path, false));
 3514                }
 3515            }
 3516
 3517            // Compute the winner entry id on the foreground thread and emit once, after all
 3518            // paths finish opening. This avoids races between concurrently-opening paths
 3519            // (directories in particular) and makes the resulting project panel selection
 3520            // deterministic.
 3521            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3522                'emit_winner: {
 3523                    let winner_abs_path: Arc<Path> =
 3524                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3525
 3526                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3527                        OpenVisible::All => true,
 3528                        OpenVisible::None => false,
 3529                        OpenVisible::OnlyFiles => !winner_is_dir,
 3530                        OpenVisible::OnlyDirectories => winner_is_dir,
 3531                    };
 3532
 3533                    let Some(worktree_task) = this
 3534                        .update(cx, |workspace, cx| {
 3535                            workspace.project.update(cx, |project, cx| {
 3536                                project.find_or_create_worktree(
 3537                                    winner_abs_path.as_ref(),
 3538                                    visible,
 3539                                    cx,
 3540                                )
 3541                            })
 3542                        })
 3543                        .ok()
 3544                    else {
 3545                        break 'emit_winner;
 3546                    };
 3547
 3548                    let Ok((worktree, _)) = worktree_task.await else {
 3549                        break 'emit_winner;
 3550                    };
 3551
 3552                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3553                        let worktree = worktree.read(cx);
 3554                        let worktree_abs_path = worktree.abs_path();
 3555                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3556                            worktree.root_entry()
 3557                        } else {
 3558                            winner_abs_path
 3559                                .strip_prefix(worktree_abs_path.as_ref())
 3560                                .ok()
 3561                                .and_then(|relative_path| {
 3562                                    let relative_path =
 3563                                        RelPath::new(relative_path, PathStyle::local())
 3564                                            .log_err()?;
 3565                                    worktree.entry_for_path(&relative_path)
 3566                                })
 3567                        }?;
 3568                        Some(entry.id)
 3569                    }) else {
 3570                        break 'emit_winner;
 3571                    };
 3572
 3573                    this.update(cx, |workspace, cx| {
 3574                        workspace.project.update(cx, |_, cx| {
 3575                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3576                        });
 3577                    })
 3578                    .ok();
 3579                }
 3580            }
 3581
 3582            results
 3583        })
 3584    }
 3585
 3586    pub fn open_resolved_path(
 3587        &mut self,
 3588        path: ResolvedPath,
 3589        window: &mut Window,
 3590        cx: &mut Context<Self>,
 3591    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3592        match path {
 3593            ResolvedPath::ProjectPath { project_path, .. } => {
 3594                self.open_path(project_path, None, true, window, cx)
 3595            }
 3596            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3597                PathBuf::from(path),
 3598                OpenOptions {
 3599                    visible: Some(OpenVisible::None),
 3600                    ..Default::default()
 3601                },
 3602                window,
 3603                cx,
 3604            ),
 3605        }
 3606    }
 3607
 3608    pub fn absolute_path_of_worktree(
 3609        &self,
 3610        worktree_id: WorktreeId,
 3611        cx: &mut Context<Self>,
 3612    ) -> Option<PathBuf> {
 3613        self.project
 3614            .read(cx)
 3615            .worktree_for_id(worktree_id, cx)
 3616            // TODO: use `abs_path` or `root_dir`
 3617            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3618    }
 3619
 3620    pub fn add_folder_to_project(
 3621        &mut self,
 3622        _: &AddFolderToProject,
 3623        window: &mut Window,
 3624        cx: &mut Context<Self>,
 3625    ) {
 3626        let project = self.project.read(cx);
 3627        if project.is_via_collab() {
 3628            self.show_error(
 3629                &anyhow!("You cannot add folders to someone else's project"),
 3630                cx,
 3631            );
 3632            return;
 3633        }
 3634        let paths = self.prompt_for_open_path(
 3635            PathPromptOptions {
 3636                files: false,
 3637                directories: true,
 3638                multiple: true,
 3639                prompt: None,
 3640            },
 3641            DirectoryLister::Project(self.project.clone()),
 3642            window,
 3643            cx,
 3644        );
 3645        cx.spawn_in(window, async move |this, cx| {
 3646            if let Some(paths) = paths.await.log_err().flatten() {
 3647                let results = this
 3648                    .update_in(cx, |this, window, cx| {
 3649                        this.open_paths(
 3650                            paths,
 3651                            OpenOptions {
 3652                                visible: Some(OpenVisible::All),
 3653                                ..Default::default()
 3654                            },
 3655                            None,
 3656                            window,
 3657                            cx,
 3658                        )
 3659                    })?
 3660                    .await;
 3661                for result in results.into_iter().flatten() {
 3662                    result.log_err();
 3663                }
 3664            }
 3665            anyhow::Ok(())
 3666        })
 3667        .detach_and_log_err(cx);
 3668    }
 3669
 3670    pub fn project_path_for_path(
 3671        project: Entity<Project>,
 3672        abs_path: &Path,
 3673        visible: bool,
 3674        cx: &mut App,
 3675    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3676        let entry = project.update(cx, |project, cx| {
 3677            project.find_or_create_worktree(abs_path, visible, cx)
 3678        });
 3679        cx.spawn(async move |cx| {
 3680            let (worktree, path) = entry.await?;
 3681            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3682            Ok((worktree, ProjectPath { worktree_id, path }))
 3683        })
 3684    }
 3685
 3686    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3687        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3688    }
 3689
 3690    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3691        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3692    }
 3693
 3694    pub fn items_of_type<'a, T: Item>(
 3695        &'a self,
 3696        cx: &'a App,
 3697    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3698        self.panes
 3699            .iter()
 3700            .flat_map(|pane| pane.read(cx).items_of_type())
 3701    }
 3702
 3703    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3704        self.active_pane().read(cx).active_item()
 3705    }
 3706
 3707    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3708        let item = self.active_item(cx)?;
 3709        item.to_any_view().downcast::<I>().ok()
 3710    }
 3711
 3712    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3713        self.active_item(cx).and_then(|item| item.project_path(cx))
 3714    }
 3715
 3716    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3717        self.recent_navigation_history_iter(cx)
 3718            .filter_map(|(path, abs_path)| {
 3719                let worktree = self
 3720                    .project
 3721                    .read(cx)
 3722                    .worktree_for_id(path.worktree_id, cx)?;
 3723                if worktree.read(cx).is_visible() {
 3724                    abs_path
 3725                } else {
 3726                    None
 3727                }
 3728            })
 3729            .next()
 3730    }
 3731
 3732    pub fn save_active_item(
 3733        &mut self,
 3734        save_intent: SaveIntent,
 3735        window: &mut Window,
 3736        cx: &mut App,
 3737    ) -> Task<Result<()>> {
 3738        let project = self.project.clone();
 3739        let pane = self.active_pane();
 3740        let item = pane.read(cx).active_item();
 3741        let pane = pane.downgrade();
 3742
 3743        window.spawn(cx, async move |cx| {
 3744            if let Some(item) = item {
 3745                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3746                    .await
 3747                    .map(|_| ())
 3748            } else {
 3749                Ok(())
 3750            }
 3751        })
 3752    }
 3753
 3754    pub fn close_inactive_items_and_panes(
 3755        &mut self,
 3756        action: &CloseInactiveTabsAndPanes,
 3757        window: &mut Window,
 3758        cx: &mut Context<Self>,
 3759    ) {
 3760        if let Some(task) = self.close_all_internal(
 3761            true,
 3762            action.save_intent.unwrap_or(SaveIntent::Close),
 3763            window,
 3764            cx,
 3765        ) {
 3766            task.detach_and_log_err(cx)
 3767        }
 3768    }
 3769
 3770    pub fn close_all_items_and_panes(
 3771        &mut self,
 3772        action: &CloseAllItemsAndPanes,
 3773        window: &mut Window,
 3774        cx: &mut Context<Self>,
 3775    ) {
 3776        if let Some(task) = self.close_all_internal(
 3777            false,
 3778            action.save_intent.unwrap_or(SaveIntent::Close),
 3779            window,
 3780            cx,
 3781        ) {
 3782            task.detach_and_log_err(cx)
 3783        }
 3784    }
 3785
 3786    /// Closes the active item across all panes.
 3787    pub fn close_item_in_all_panes(
 3788        &mut self,
 3789        action: &CloseItemInAllPanes,
 3790        window: &mut Window,
 3791        cx: &mut Context<Self>,
 3792    ) {
 3793        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3794            return;
 3795        };
 3796
 3797        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3798        let close_pinned = action.close_pinned;
 3799
 3800        if let Some(project_path) = active_item.project_path(cx) {
 3801            self.close_items_with_project_path(
 3802                &project_path,
 3803                save_intent,
 3804                close_pinned,
 3805                window,
 3806                cx,
 3807            );
 3808        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3809            let item_id = active_item.item_id();
 3810            self.active_pane().update(cx, |pane, cx| {
 3811                pane.close_item_by_id(item_id, save_intent, window, cx)
 3812                    .detach_and_log_err(cx);
 3813            });
 3814        }
 3815    }
 3816
 3817    /// Closes all items with the given project path across all panes.
 3818    pub fn close_items_with_project_path(
 3819        &mut self,
 3820        project_path: &ProjectPath,
 3821        save_intent: SaveIntent,
 3822        close_pinned: bool,
 3823        window: &mut Window,
 3824        cx: &mut Context<Self>,
 3825    ) {
 3826        let panes = self.panes().to_vec();
 3827        for pane in panes {
 3828            pane.update(cx, |pane, cx| {
 3829                pane.close_items_for_project_path(
 3830                    project_path,
 3831                    save_intent,
 3832                    close_pinned,
 3833                    window,
 3834                    cx,
 3835                )
 3836                .detach_and_log_err(cx);
 3837            });
 3838        }
 3839    }
 3840
 3841    fn close_all_internal(
 3842        &mut self,
 3843        retain_active_pane: bool,
 3844        save_intent: SaveIntent,
 3845        window: &mut Window,
 3846        cx: &mut Context<Self>,
 3847    ) -> Option<Task<Result<()>>> {
 3848        let current_pane = self.active_pane();
 3849
 3850        let mut tasks = Vec::new();
 3851
 3852        if retain_active_pane {
 3853            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3854                pane.close_other_items(
 3855                    &CloseOtherItems {
 3856                        save_intent: None,
 3857                        close_pinned: false,
 3858                    },
 3859                    None,
 3860                    window,
 3861                    cx,
 3862                )
 3863            });
 3864
 3865            tasks.push(current_pane_close);
 3866        }
 3867
 3868        for pane in self.panes() {
 3869            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3870                continue;
 3871            }
 3872
 3873            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3874                pane.close_all_items(
 3875                    &CloseAllItems {
 3876                        save_intent: Some(save_intent),
 3877                        close_pinned: false,
 3878                    },
 3879                    window,
 3880                    cx,
 3881                )
 3882            });
 3883
 3884            tasks.push(close_pane_items)
 3885        }
 3886
 3887        if tasks.is_empty() {
 3888            None
 3889        } else {
 3890            Some(cx.spawn_in(window, async move |_, _| {
 3891                for task in tasks {
 3892                    task.await?
 3893                }
 3894                Ok(())
 3895            }))
 3896        }
 3897    }
 3898
 3899    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3900        self.dock_at_position(position).read(cx).is_open()
 3901    }
 3902
 3903    pub fn toggle_dock(
 3904        &mut self,
 3905        dock_side: DockPosition,
 3906        window: &mut Window,
 3907        cx: &mut Context<Self>,
 3908    ) {
 3909        let mut focus_center = false;
 3910        let mut reveal_dock = false;
 3911
 3912        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3913        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3914
 3915        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3916            telemetry::event!(
 3917                "Panel Button Clicked",
 3918                name = panel.persistent_name(),
 3919                toggle_state = !was_visible
 3920            );
 3921        }
 3922        if was_visible {
 3923            self.save_open_dock_positions(cx);
 3924        }
 3925
 3926        let dock = self.dock_at_position(dock_side);
 3927        dock.update(cx, |dock, cx| {
 3928            dock.set_open(!was_visible, window, cx);
 3929
 3930            if dock.active_panel().is_none() {
 3931                let Some(panel_ix) = dock
 3932                    .first_enabled_panel_idx(cx)
 3933                    .log_with_level(log::Level::Info)
 3934                else {
 3935                    return;
 3936                };
 3937                dock.activate_panel(panel_ix, window, cx);
 3938            }
 3939
 3940            if let Some(active_panel) = dock.active_panel() {
 3941                if was_visible {
 3942                    if active_panel
 3943                        .panel_focus_handle(cx)
 3944                        .contains_focused(window, cx)
 3945                    {
 3946                        focus_center = true;
 3947                    }
 3948                } else {
 3949                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3950                    window.focus(focus_handle, cx);
 3951                    reveal_dock = true;
 3952                }
 3953            }
 3954        });
 3955
 3956        if reveal_dock {
 3957            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3958        }
 3959
 3960        if focus_center {
 3961            self.active_pane
 3962                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3963        }
 3964
 3965        cx.notify();
 3966        self.serialize_workspace(window, cx);
 3967    }
 3968
 3969    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3970        self.all_docks().into_iter().find(|&dock| {
 3971            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3972        })
 3973    }
 3974
 3975    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3976        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3977            self.save_open_dock_positions(cx);
 3978            dock.update(cx, |dock, cx| {
 3979                dock.set_open(false, window, cx);
 3980            });
 3981            return true;
 3982        }
 3983        false
 3984    }
 3985
 3986    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3987        self.save_open_dock_positions(cx);
 3988        for dock in self.all_docks() {
 3989            dock.update(cx, |dock, cx| {
 3990                dock.set_open(false, window, cx);
 3991            });
 3992        }
 3993
 3994        cx.focus_self(window);
 3995        cx.notify();
 3996        self.serialize_workspace(window, cx);
 3997    }
 3998
 3999    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4000        self.all_docks()
 4001            .into_iter()
 4002            .filter_map(|dock| {
 4003                let dock_ref = dock.read(cx);
 4004                if dock_ref.is_open() {
 4005                    Some(dock_ref.position())
 4006                } else {
 4007                    None
 4008                }
 4009            })
 4010            .collect()
 4011    }
 4012
 4013    /// Saves the positions of currently open docks.
 4014    ///
 4015    /// Updates `last_open_dock_positions` with positions of all currently open
 4016    /// docks, to later be restored by the 'Toggle All Docks' action.
 4017    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4018        let open_dock_positions = self.get_open_dock_positions(cx);
 4019        if !open_dock_positions.is_empty() {
 4020            self.last_open_dock_positions = open_dock_positions;
 4021        }
 4022    }
 4023
 4024    /// Toggles all docks between open and closed states.
 4025    ///
 4026    /// If any docks are open, closes all and remembers their positions. If all
 4027    /// docks are closed, restores the last remembered dock configuration.
 4028    fn toggle_all_docks(
 4029        &mut self,
 4030        _: &ToggleAllDocks,
 4031        window: &mut Window,
 4032        cx: &mut Context<Self>,
 4033    ) {
 4034        let open_dock_positions = self.get_open_dock_positions(cx);
 4035
 4036        if !open_dock_positions.is_empty() {
 4037            self.close_all_docks(window, cx);
 4038        } else if !self.last_open_dock_positions.is_empty() {
 4039            self.restore_last_open_docks(window, cx);
 4040        }
 4041    }
 4042
 4043    /// Reopens docks from the most recently remembered configuration.
 4044    ///
 4045    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4046    /// and clears the stored positions.
 4047    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4048        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4049
 4050        for position in positions_to_open {
 4051            let dock = self.dock_at_position(position);
 4052            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4053        }
 4054
 4055        cx.focus_self(window);
 4056        cx.notify();
 4057        self.serialize_workspace(window, cx);
 4058    }
 4059
 4060    /// Transfer focus to the panel of the given type.
 4061    pub fn focus_panel<T: Panel>(
 4062        &mut self,
 4063        window: &mut Window,
 4064        cx: &mut Context<Self>,
 4065    ) -> Option<Entity<T>> {
 4066        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4067        panel.to_any().downcast().ok()
 4068    }
 4069
 4070    /// Focus the panel of the given type if it isn't already focused. If it is
 4071    /// already focused, then transfer focus back to the workspace center.
 4072    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4073    /// panel when transferring focus back to the center.
 4074    pub fn toggle_panel_focus<T: Panel>(
 4075        &mut self,
 4076        window: &mut Window,
 4077        cx: &mut Context<Self>,
 4078    ) -> bool {
 4079        let mut did_focus_panel = false;
 4080        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4081            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4082            did_focus_panel
 4083        });
 4084
 4085        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4086            self.close_panel::<T>(window, cx);
 4087        }
 4088
 4089        telemetry::event!(
 4090            "Panel Button Clicked",
 4091            name = T::persistent_name(),
 4092            toggle_state = did_focus_panel
 4093        );
 4094
 4095        did_focus_panel
 4096    }
 4097
 4098    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4099        if let Some(item) = self.active_item(cx) {
 4100            item.item_focus_handle(cx).focus(window, cx);
 4101        } else {
 4102            log::error!("Could not find a focus target when switching focus to the center panes",);
 4103        }
 4104    }
 4105
 4106    pub fn activate_panel_for_proto_id(
 4107        &mut self,
 4108        panel_id: PanelId,
 4109        window: &mut Window,
 4110        cx: &mut Context<Self>,
 4111    ) -> Option<Arc<dyn PanelHandle>> {
 4112        let mut panel = None;
 4113        for dock in self.all_docks() {
 4114            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4115                panel = dock.update(cx, |dock, cx| {
 4116                    dock.activate_panel(panel_index, window, cx);
 4117                    dock.set_open(true, window, cx);
 4118                    dock.active_panel().cloned()
 4119                });
 4120                break;
 4121            }
 4122        }
 4123
 4124        if panel.is_some() {
 4125            cx.notify();
 4126            self.serialize_workspace(window, cx);
 4127        }
 4128
 4129        panel
 4130    }
 4131
 4132    /// Focus or unfocus the given panel type, depending on the given callback.
 4133    fn focus_or_unfocus_panel<T: Panel>(
 4134        &mut self,
 4135        window: &mut Window,
 4136        cx: &mut Context<Self>,
 4137        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4138    ) -> Option<Arc<dyn PanelHandle>> {
 4139        let mut result_panel = None;
 4140        let mut serialize = false;
 4141        for dock in self.all_docks() {
 4142            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4143                let mut focus_center = false;
 4144                let panel = dock.update(cx, |dock, cx| {
 4145                    dock.activate_panel(panel_index, window, cx);
 4146
 4147                    let panel = dock.active_panel().cloned();
 4148                    if let Some(panel) = panel.as_ref() {
 4149                        if should_focus(&**panel, window, cx) {
 4150                            dock.set_open(true, window, cx);
 4151                            panel.panel_focus_handle(cx).focus(window, cx);
 4152                        } else {
 4153                            focus_center = true;
 4154                        }
 4155                    }
 4156                    panel
 4157                });
 4158
 4159                if focus_center {
 4160                    self.active_pane
 4161                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4162                }
 4163
 4164                result_panel = panel;
 4165                serialize = true;
 4166                break;
 4167            }
 4168        }
 4169
 4170        if serialize {
 4171            self.serialize_workspace(window, cx);
 4172        }
 4173
 4174        cx.notify();
 4175        result_panel
 4176    }
 4177
 4178    /// Open the panel of the given type
 4179    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4180        for dock in self.all_docks() {
 4181            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4182                dock.update(cx, |dock, cx| {
 4183                    dock.activate_panel(panel_index, window, cx);
 4184                    dock.set_open(true, window, cx);
 4185                });
 4186            }
 4187        }
 4188    }
 4189
 4190    /// Open the panel of the given type, dismissing any zoomed items that
 4191    /// would obscure it (e.g. a zoomed terminal).
 4192    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4193        let dock_position = self.all_docks().iter().find_map(|dock| {
 4194            let dock = dock.read(cx);
 4195            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4196        });
 4197        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4198        self.open_panel::<T>(window, cx);
 4199    }
 4200
 4201    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4202        for dock in self.all_docks().iter() {
 4203            dock.update(cx, |dock, cx| {
 4204                if dock.panel::<T>().is_some() {
 4205                    dock.set_open(false, window, cx)
 4206                }
 4207            })
 4208        }
 4209    }
 4210
 4211    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4212        self.all_docks()
 4213            .iter()
 4214            .find_map(|dock| dock.read(cx).panel::<T>())
 4215    }
 4216
 4217    fn dismiss_zoomed_items_to_reveal(
 4218        &mut self,
 4219        dock_to_reveal: Option<DockPosition>,
 4220        window: &mut Window,
 4221        cx: &mut Context<Self>,
 4222    ) {
 4223        // If a center pane is zoomed, unzoom it.
 4224        for pane in &self.panes {
 4225            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4226                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4227            }
 4228        }
 4229
 4230        // If another dock is zoomed, hide it.
 4231        let mut focus_center = false;
 4232        for dock in self.all_docks() {
 4233            dock.update(cx, |dock, cx| {
 4234                if Some(dock.position()) != dock_to_reveal
 4235                    && let Some(panel) = dock.active_panel()
 4236                    && panel.is_zoomed(window, cx)
 4237                {
 4238                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4239                    dock.set_open(false, window, cx);
 4240                }
 4241            });
 4242        }
 4243
 4244        if focus_center {
 4245            self.active_pane
 4246                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4247        }
 4248
 4249        if self.zoomed_position != dock_to_reveal {
 4250            self.zoomed = None;
 4251            self.zoomed_position = None;
 4252            cx.emit(Event::ZoomChanged);
 4253        }
 4254
 4255        cx.notify();
 4256    }
 4257
 4258    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4259        let pane = cx.new(|cx| {
 4260            let mut pane = Pane::new(
 4261                self.weak_handle(),
 4262                self.project.clone(),
 4263                self.pane_history_timestamp.clone(),
 4264                None,
 4265                NewFile.boxed_clone(),
 4266                true,
 4267                window,
 4268                cx,
 4269            );
 4270            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4271            pane
 4272        });
 4273        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4274            .detach();
 4275        self.panes.push(pane.clone());
 4276
 4277        window.focus(&pane.focus_handle(cx), cx);
 4278
 4279        cx.emit(Event::PaneAdded(pane.clone()));
 4280        pane
 4281    }
 4282
 4283    pub fn add_item_to_center(
 4284        &mut self,
 4285        item: Box<dyn ItemHandle>,
 4286        window: &mut Window,
 4287        cx: &mut Context<Self>,
 4288    ) -> bool {
 4289        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4290            if let Some(center_pane) = center_pane.upgrade() {
 4291                center_pane.update(cx, |pane, cx| {
 4292                    pane.add_item(item, true, true, None, window, cx)
 4293                });
 4294                true
 4295            } else {
 4296                false
 4297            }
 4298        } else {
 4299            false
 4300        }
 4301    }
 4302
 4303    pub fn add_item_to_active_pane(
 4304        &mut self,
 4305        item: Box<dyn ItemHandle>,
 4306        destination_index: Option<usize>,
 4307        focus_item: bool,
 4308        window: &mut Window,
 4309        cx: &mut App,
 4310    ) {
 4311        self.add_item(
 4312            self.active_pane.clone(),
 4313            item,
 4314            destination_index,
 4315            false,
 4316            focus_item,
 4317            window,
 4318            cx,
 4319        )
 4320    }
 4321
 4322    pub fn add_item(
 4323        &mut self,
 4324        pane: Entity<Pane>,
 4325        item: Box<dyn ItemHandle>,
 4326        destination_index: Option<usize>,
 4327        activate_pane: bool,
 4328        focus_item: bool,
 4329        window: &mut Window,
 4330        cx: &mut App,
 4331    ) {
 4332        pane.update(cx, |pane, cx| {
 4333            pane.add_item(
 4334                item,
 4335                activate_pane,
 4336                focus_item,
 4337                destination_index,
 4338                window,
 4339                cx,
 4340            )
 4341        });
 4342    }
 4343
 4344    pub fn split_item(
 4345        &mut self,
 4346        split_direction: SplitDirection,
 4347        item: Box<dyn ItemHandle>,
 4348        window: &mut Window,
 4349        cx: &mut Context<Self>,
 4350    ) {
 4351        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4352        self.add_item(new_pane, item, None, true, true, window, cx);
 4353    }
 4354
 4355    pub fn open_abs_path(
 4356        &mut self,
 4357        abs_path: PathBuf,
 4358        options: OpenOptions,
 4359        window: &mut Window,
 4360        cx: &mut Context<Self>,
 4361    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4362        cx.spawn_in(window, async move |workspace, cx| {
 4363            let open_paths_task_result = workspace
 4364                .update_in(cx, |workspace, window, cx| {
 4365                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4366                })
 4367                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4368                .await;
 4369            anyhow::ensure!(
 4370                open_paths_task_result.len() == 1,
 4371                "open abs path {abs_path:?} task returned incorrect number of results"
 4372            );
 4373            match open_paths_task_result
 4374                .into_iter()
 4375                .next()
 4376                .expect("ensured single task result")
 4377            {
 4378                Some(open_result) => {
 4379                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4380                }
 4381                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4382            }
 4383        })
 4384    }
 4385
 4386    pub fn split_abs_path(
 4387        &mut self,
 4388        abs_path: PathBuf,
 4389        visible: bool,
 4390        window: &mut Window,
 4391        cx: &mut Context<Self>,
 4392    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4393        let project_path_task =
 4394            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4395        cx.spawn_in(window, async move |this, cx| {
 4396            let (_, path) = project_path_task.await?;
 4397            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4398                .await
 4399        })
 4400    }
 4401
 4402    pub fn open_path(
 4403        &mut self,
 4404        path: impl Into<ProjectPath>,
 4405        pane: Option<WeakEntity<Pane>>,
 4406        focus_item: bool,
 4407        window: &mut Window,
 4408        cx: &mut App,
 4409    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4410        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4411    }
 4412
 4413    pub fn open_path_preview(
 4414        &mut self,
 4415        path: impl Into<ProjectPath>,
 4416        pane: Option<WeakEntity<Pane>>,
 4417        focus_item: bool,
 4418        allow_preview: bool,
 4419        activate: bool,
 4420        window: &mut Window,
 4421        cx: &mut App,
 4422    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4423        let pane = pane.unwrap_or_else(|| {
 4424            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
 4432        let project_path = path.into();
 4433        let task = self.load_path(project_path.clone(), window, cx);
 4434        window.spawn(cx, async move |cx| {
 4435            let (project_entry_id, build_item) = task.await?;
 4436
 4437            pane.update_in(cx, |pane, window, cx| {
 4438                pane.open_item(
 4439                    project_entry_id,
 4440                    project_path,
 4441                    focus_item,
 4442                    allow_preview,
 4443                    activate,
 4444                    None,
 4445                    window,
 4446                    cx,
 4447                    build_item,
 4448                )
 4449            })
 4450        })
 4451    }
 4452
 4453    pub fn split_path(
 4454        &mut self,
 4455        path: impl Into<ProjectPath>,
 4456        window: &mut Window,
 4457        cx: &mut Context<Self>,
 4458    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4459        self.split_path_preview(path, false, None, window, cx)
 4460    }
 4461
 4462    pub fn split_path_preview(
 4463        &mut self,
 4464        path: impl Into<ProjectPath>,
 4465        allow_preview: bool,
 4466        split_direction: Option<SplitDirection>,
 4467        window: &mut Window,
 4468        cx: &mut Context<Self>,
 4469    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4470        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4471            self.panes
 4472                .first()
 4473                .expect("There must be an active pane")
 4474                .downgrade()
 4475        });
 4476
 4477        if let Member::Pane(center_pane) = &self.center.root
 4478            && center_pane.read(cx).items_len() == 0
 4479        {
 4480            return self.open_path(path, Some(pane), true, window, cx);
 4481        }
 4482
 4483        let project_path = path.into();
 4484        let task = self.load_path(project_path.clone(), window, cx);
 4485        cx.spawn_in(window, async move |this, cx| {
 4486            let (project_entry_id, build_item) = task.await?;
 4487            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4488                let pane = pane.upgrade()?;
 4489                let new_pane = this.split_pane(
 4490                    pane,
 4491                    split_direction.unwrap_or(SplitDirection::Right),
 4492                    window,
 4493                    cx,
 4494                );
 4495                new_pane.update(cx, |new_pane, cx| {
 4496                    Some(new_pane.open_item(
 4497                        project_entry_id,
 4498                        project_path,
 4499                        true,
 4500                        allow_preview,
 4501                        true,
 4502                        None,
 4503                        window,
 4504                        cx,
 4505                        build_item,
 4506                    ))
 4507                })
 4508            })
 4509            .map(|option| option.context("pane was dropped"))?
 4510        })
 4511    }
 4512
 4513    fn load_path(
 4514        &mut self,
 4515        path: ProjectPath,
 4516        window: &mut Window,
 4517        cx: &mut App,
 4518    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4519        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4520        registry.open_path(self.project(), &path, window, cx)
 4521    }
 4522
 4523    pub fn find_project_item<T>(
 4524        &self,
 4525        pane: &Entity<Pane>,
 4526        project_item: &Entity<T::Item>,
 4527        cx: &App,
 4528    ) -> Option<Entity<T>>
 4529    where
 4530        T: ProjectItem,
 4531    {
 4532        use project::ProjectItem as _;
 4533        let project_item = project_item.read(cx);
 4534        let entry_id = project_item.entry_id(cx);
 4535        let project_path = project_item.project_path(cx);
 4536
 4537        let mut item = None;
 4538        if let Some(entry_id) = entry_id {
 4539            item = pane.read(cx).item_for_entry(entry_id, cx);
 4540        }
 4541        if item.is_none()
 4542            && let Some(project_path) = project_path
 4543        {
 4544            item = pane.read(cx).item_for_path(project_path, cx);
 4545        }
 4546
 4547        item.and_then(|item| item.downcast::<T>())
 4548    }
 4549
 4550    pub fn is_project_item_open<T>(
 4551        &self,
 4552        pane: &Entity<Pane>,
 4553        project_item: &Entity<T::Item>,
 4554        cx: &App,
 4555    ) -> bool
 4556    where
 4557        T: ProjectItem,
 4558    {
 4559        self.find_project_item::<T>(pane, project_item, cx)
 4560            .is_some()
 4561    }
 4562
 4563    pub fn open_project_item<T>(
 4564        &mut self,
 4565        pane: Entity<Pane>,
 4566        project_item: Entity<T::Item>,
 4567        activate_pane: bool,
 4568        focus_item: bool,
 4569        keep_old_preview: bool,
 4570        allow_new_preview: bool,
 4571        window: &mut Window,
 4572        cx: &mut Context<Self>,
 4573    ) -> Entity<T>
 4574    where
 4575        T: ProjectItem,
 4576    {
 4577        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4578
 4579        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4580            if !keep_old_preview
 4581                && let Some(old_id) = old_item_id
 4582                && old_id != item.item_id()
 4583            {
 4584                // switching to a different item, so unpreview old active item
 4585                pane.update(cx, |pane, _| {
 4586                    pane.unpreview_item_if_preview(old_id);
 4587                });
 4588            }
 4589
 4590            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4591            if !allow_new_preview {
 4592                pane.update(cx, |pane, _| {
 4593                    pane.unpreview_item_if_preview(item.item_id());
 4594                });
 4595            }
 4596            return item;
 4597        }
 4598
 4599        let item = pane.update(cx, |pane, cx| {
 4600            cx.new(|cx| {
 4601                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4602            })
 4603        });
 4604        let mut destination_index = None;
 4605        pane.update(cx, |pane, cx| {
 4606            if !keep_old_preview && let Some(old_id) = old_item_id {
 4607                pane.unpreview_item_if_preview(old_id);
 4608            }
 4609            if allow_new_preview {
 4610                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4611            }
 4612        });
 4613
 4614        self.add_item(
 4615            pane,
 4616            Box::new(item.clone()),
 4617            destination_index,
 4618            activate_pane,
 4619            focus_item,
 4620            window,
 4621            cx,
 4622        );
 4623        item
 4624    }
 4625
 4626    pub fn open_shared_screen(
 4627        &mut self,
 4628        peer_id: PeerId,
 4629        window: &mut Window,
 4630        cx: &mut Context<Self>,
 4631    ) {
 4632        if let Some(shared_screen) =
 4633            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4634        {
 4635            self.active_pane.update(cx, |pane, cx| {
 4636                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4637            });
 4638        }
 4639    }
 4640
 4641    pub fn activate_item(
 4642        &mut self,
 4643        item: &dyn ItemHandle,
 4644        activate_pane: bool,
 4645        focus_item: bool,
 4646        window: &mut Window,
 4647        cx: &mut App,
 4648    ) -> bool {
 4649        let result = self.panes.iter().find_map(|pane| {
 4650            pane.read(cx)
 4651                .index_for_item(item)
 4652                .map(|ix| (pane.clone(), ix))
 4653        });
 4654        if let Some((pane, ix)) = result {
 4655            pane.update(cx, |pane, cx| {
 4656                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4657            });
 4658            true
 4659        } else {
 4660            false
 4661        }
 4662    }
 4663
 4664    fn activate_pane_at_index(
 4665        &mut self,
 4666        action: &ActivatePane,
 4667        window: &mut Window,
 4668        cx: &mut Context<Self>,
 4669    ) {
 4670        let panes = self.center.panes();
 4671        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4672            window.focus(&pane.focus_handle(cx), cx);
 4673        } else {
 4674            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4675                .detach();
 4676        }
 4677    }
 4678
 4679    fn move_item_to_pane_at_index(
 4680        &mut self,
 4681        action: &MoveItemToPane,
 4682        window: &mut Window,
 4683        cx: &mut Context<Self>,
 4684    ) {
 4685        let panes = self.center.panes();
 4686        let destination = match panes.get(action.destination) {
 4687            Some(&destination) => destination.clone(),
 4688            None => {
 4689                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4690                    return;
 4691                }
 4692                let direction = SplitDirection::Right;
 4693                let split_off_pane = self
 4694                    .find_pane_in_direction(direction, cx)
 4695                    .unwrap_or_else(|| self.active_pane.clone());
 4696                let new_pane = self.add_pane(window, cx);
 4697                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4698                new_pane
 4699            }
 4700        };
 4701
 4702        if action.clone {
 4703            if self
 4704                .active_pane
 4705                .read(cx)
 4706                .active_item()
 4707                .is_some_and(|item| item.can_split(cx))
 4708            {
 4709                clone_active_item(
 4710                    self.database_id(),
 4711                    &self.active_pane,
 4712                    &destination,
 4713                    action.focus,
 4714                    window,
 4715                    cx,
 4716                );
 4717                return;
 4718            }
 4719        }
 4720        move_active_item(
 4721            &self.active_pane,
 4722            &destination,
 4723            action.focus,
 4724            true,
 4725            window,
 4726            cx,
 4727        )
 4728    }
 4729
 4730    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4731        let panes = self.center.panes();
 4732        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4733            let next_ix = (ix + 1) % panes.len();
 4734            let next_pane = panes[next_ix].clone();
 4735            window.focus(&next_pane.focus_handle(cx), cx);
 4736        }
 4737    }
 4738
 4739    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4740        let panes = self.center.panes();
 4741        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4742            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4743            let prev_pane = panes[prev_ix].clone();
 4744            window.focus(&prev_pane.focus_handle(cx), cx);
 4745        }
 4746    }
 4747
 4748    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4749        let last_pane = self.center.last_pane();
 4750        window.focus(&last_pane.focus_handle(cx), cx);
 4751    }
 4752
 4753    pub fn activate_pane_in_direction(
 4754        &mut self,
 4755        direction: SplitDirection,
 4756        window: &mut Window,
 4757        cx: &mut App,
 4758    ) {
 4759        use ActivateInDirectionTarget as Target;
 4760        enum Origin {
 4761            Sidebar,
 4762            LeftDock,
 4763            RightDock,
 4764            BottomDock,
 4765            Center,
 4766        }
 4767
 4768        let origin: Origin = if self
 4769            .sidebar_focus_handle
 4770            .as_ref()
 4771            .is_some_and(|h| h.contains_focused(window, cx))
 4772        {
 4773            Origin::Sidebar
 4774        } else {
 4775            [
 4776                (&self.left_dock, Origin::LeftDock),
 4777                (&self.right_dock, Origin::RightDock),
 4778                (&self.bottom_dock, Origin::BottomDock),
 4779            ]
 4780            .into_iter()
 4781            .find_map(|(dock, origin)| {
 4782                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4783                    Some(origin)
 4784                } else {
 4785                    None
 4786                }
 4787            })
 4788            .unwrap_or(Origin::Center)
 4789        };
 4790
 4791        let get_last_active_pane = || {
 4792            let pane = self
 4793                .last_active_center_pane
 4794                .clone()
 4795                .unwrap_or_else(|| {
 4796                    self.panes
 4797                        .first()
 4798                        .expect("There must be an active pane")
 4799                        .downgrade()
 4800                })
 4801                .upgrade()?;
 4802            (pane.read(cx).items_len() != 0).then_some(pane)
 4803        };
 4804
 4805        let try_dock =
 4806            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4807
 4808        let sidebar_target = self
 4809            .sidebar_focus_handle
 4810            .as_ref()
 4811            .map(|h| Target::Sidebar(h.clone()));
 4812
 4813        let target = match (origin, direction) {
 4814            // From the sidebar, only Right navigates into the workspace.
 4815            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4816                .or_else(|| get_last_active_pane().map(Target::Pane))
 4817                .or_else(|| try_dock(&self.bottom_dock))
 4818                .or_else(|| try_dock(&self.right_dock)),
 4819
 4820            (Origin::Sidebar, _) => None,
 4821
 4822            // We're in the center, so we first try to go to a different pane,
 4823            // otherwise try to go to a dock.
 4824            (Origin::Center, direction) => {
 4825                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4826                    Some(Target::Pane(pane))
 4827                } else {
 4828                    match direction {
 4829                        SplitDirection::Up => None,
 4830                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4831                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4832                        SplitDirection::Right => try_dock(&self.right_dock),
 4833                    }
 4834                }
 4835            }
 4836
 4837            (Origin::LeftDock, SplitDirection::Right) => {
 4838                if let Some(last_active_pane) = get_last_active_pane() {
 4839                    Some(Target::Pane(last_active_pane))
 4840                } else {
 4841                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4842                }
 4843            }
 4844
 4845            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4846
 4847            (Origin::LeftDock, SplitDirection::Down)
 4848            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4849
 4850            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4851            (Origin::BottomDock, SplitDirection::Left) => {
 4852                try_dock(&self.left_dock).or(sidebar_target)
 4853            }
 4854            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4855
 4856            (Origin::RightDock, SplitDirection::Left) => {
 4857                if let Some(last_active_pane) = get_last_active_pane() {
 4858                    Some(Target::Pane(last_active_pane))
 4859                } else {
 4860                    try_dock(&self.bottom_dock)
 4861                        .or_else(|| try_dock(&self.left_dock))
 4862                        .or(sidebar_target)
 4863                }
 4864            }
 4865
 4866            _ => None,
 4867        };
 4868
 4869        match target {
 4870            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4871                let pane = pane.read(cx);
 4872                if let Some(item) = pane.active_item() {
 4873                    item.item_focus_handle(cx).focus(window, cx);
 4874                } else {
 4875                    log::error!(
 4876                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4877                    );
 4878                }
 4879            }
 4880            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4881                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4882                window.defer(cx, move |window, cx| {
 4883                    let dock = dock.read(cx);
 4884                    if let Some(panel) = dock.active_panel() {
 4885                        panel.panel_focus_handle(cx).focus(window, cx);
 4886                    } else {
 4887                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4888                    }
 4889                })
 4890            }
 4891            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4892                focus_handle.focus(window, cx);
 4893            }
 4894            None => {}
 4895        }
 4896    }
 4897
 4898    pub fn move_item_to_pane_in_direction(
 4899        &mut self,
 4900        action: &MoveItemToPaneInDirection,
 4901        window: &mut Window,
 4902        cx: &mut Context<Self>,
 4903    ) {
 4904        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4905            Some(destination) => destination,
 4906            None => {
 4907                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4908                    return;
 4909                }
 4910                let new_pane = self.add_pane(window, cx);
 4911                self.center
 4912                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4913                new_pane
 4914            }
 4915        };
 4916
 4917        if action.clone {
 4918            if self
 4919                .active_pane
 4920                .read(cx)
 4921                .active_item()
 4922                .is_some_and(|item| item.can_split(cx))
 4923            {
 4924                clone_active_item(
 4925                    self.database_id(),
 4926                    &self.active_pane,
 4927                    &destination,
 4928                    action.focus,
 4929                    window,
 4930                    cx,
 4931                );
 4932                return;
 4933            }
 4934        }
 4935        move_active_item(
 4936            &self.active_pane,
 4937            &destination,
 4938            action.focus,
 4939            true,
 4940            window,
 4941            cx,
 4942        );
 4943    }
 4944
 4945    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4946        self.center.bounding_box_for_pane(pane)
 4947    }
 4948
 4949    pub fn find_pane_in_direction(
 4950        &mut self,
 4951        direction: SplitDirection,
 4952        cx: &App,
 4953    ) -> Option<Entity<Pane>> {
 4954        self.center
 4955            .find_pane_in_direction(&self.active_pane, direction, cx)
 4956            .cloned()
 4957    }
 4958
 4959    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4960        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4961            self.center.swap(&self.active_pane, &to, cx);
 4962            cx.notify();
 4963        }
 4964    }
 4965
 4966    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4967        if self
 4968            .center
 4969            .move_to_border(&self.active_pane, direction, cx)
 4970            .unwrap()
 4971        {
 4972            cx.notify();
 4973        }
 4974    }
 4975
 4976    pub fn resize_pane(
 4977        &mut self,
 4978        axis: gpui::Axis,
 4979        amount: Pixels,
 4980        window: &mut Window,
 4981        cx: &mut Context<Self>,
 4982    ) {
 4983        let docks = self.all_docks();
 4984        let active_dock = docks
 4985            .into_iter()
 4986            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4987
 4988        if let Some(dock_entity) = active_dock {
 4989            let dock = dock_entity.read(cx);
 4990            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 4991                return;
 4992            };
 4993            match dock.position() {
 4994                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4995                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4996                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4997            }
 4998        } else {
 4999            self.center
 5000                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5001        }
 5002        cx.notify();
 5003    }
 5004
 5005    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5006        self.center.reset_pane_sizes(cx);
 5007        cx.notify();
 5008    }
 5009
 5010    fn handle_pane_focused(
 5011        &mut self,
 5012        pane: Entity<Pane>,
 5013        window: &mut Window,
 5014        cx: &mut Context<Self>,
 5015    ) {
 5016        // This is explicitly hoisted out of the following check for pane identity as
 5017        // terminal panel panes are not registered as a center panes.
 5018        self.status_bar.update(cx, |status_bar, cx| {
 5019            status_bar.set_active_pane(&pane, window, cx);
 5020        });
 5021        if self.active_pane != pane {
 5022            self.set_active_pane(&pane, window, cx);
 5023        }
 5024
 5025        if self.last_active_center_pane.is_none() {
 5026            self.last_active_center_pane = Some(pane.downgrade());
 5027        }
 5028
 5029        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5030        // This prevents the dock from closing when focus events fire during window activation.
 5031        // We also preserve any dock whose active panel itself has focus — this covers
 5032        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5033        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5034            let dock_read = dock.read(cx);
 5035            if let Some(panel) = dock_read.active_panel() {
 5036                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5037                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5038                {
 5039                    return Some(dock_read.position());
 5040                }
 5041            }
 5042            None
 5043        });
 5044
 5045        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5046        if pane.read(cx).is_zoomed() {
 5047            self.zoomed = Some(pane.downgrade().into());
 5048        } else {
 5049            self.zoomed = None;
 5050        }
 5051        self.zoomed_position = None;
 5052        cx.emit(Event::ZoomChanged);
 5053        self.update_active_view_for_followers(window, cx);
 5054        pane.update(cx, |pane, _| {
 5055            pane.track_alternate_file_items();
 5056        });
 5057
 5058        cx.notify();
 5059    }
 5060
 5061    fn set_active_pane(
 5062        &mut self,
 5063        pane: &Entity<Pane>,
 5064        window: &mut Window,
 5065        cx: &mut Context<Self>,
 5066    ) {
 5067        self.active_pane = pane.clone();
 5068        self.active_item_path_changed(true, window, cx);
 5069        self.last_active_center_pane = Some(pane.downgrade());
 5070    }
 5071
 5072    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5073        self.update_active_view_for_followers(window, cx);
 5074    }
 5075
 5076    fn handle_pane_event(
 5077        &mut self,
 5078        pane: &Entity<Pane>,
 5079        event: &pane::Event,
 5080        window: &mut Window,
 5081        cx: &mut Context<Self>,
 5082    ) {
 5083        let mut serialize_workspace = true;
 5084        match event {
 5085            pane::Event::AddItem { item } => {
 5086                item.added_to_pane(self, pane.clone(), window, cx);
 5087                cx.emit(Event::ItemAdded {
 5088                    item: item.boxed_clone(),
 5089                });
 5090            }
 5091            pane::Event::Split { direction, mode } => {
 5092                match mode {
 5093                    SplitMode::ClonePane => {
 5094                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5095                            .detach();
 5096                    }
 5097                    SplitMode::EmptyPane => {
 5098                        self.split_pane(pane.clone(), *direction, window, cx);
 5099                    }
 5100                    SplitMode::MovePane => {
 5101                        self.split_and_move(pane.clone(), *direction, window, cx);
 5102                    }
 5103                };
 5104            }
 5105            pane::Event::JoinIntoNext => {
 5106                self.join_pane_into_next(pane.clone(), window, cx);
 5107            }
 5108            pane::Event::JoinAll => {
 5109                self.join_all_panes(window, cx);
 5110            }
 5111            pane::Event::Remove { focus_on_pane } => {
 5112                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5113            }
 5114            pane::Event::ActivateItem {
 5115                local,
 5116                focus_changed,
 5117            } => {
 5118                window.invalidate_character_coordinates();
 5119
 5120                pane.update(cx, |pane, _| {
 5121                    pane.track_alternate_file_items();
 5122                });
 5123                if *local {
 5124                    self.unfollow_in_pane(pane, window, cx);
 5125                }
 5126                serialize_workspace = *focus_changed || pane != self.active_pane();
 5127                if pane == self.active_pane() {
 5128                    self.active_item_path_changed(*focus_changed, window, cx);
 5129                    self.update_active_view_for_followers(window, cx);
 5130                } else if *local {
 5131                    self.set_active_pane(pane, window, cx);
 5132                }
 5133            }
 5134            pane::Event::UserSavedItem { item, save_intent } => {
 5135                cx.emit(Event::UserSavedItem {
 5136                    pane: pane.downgrade(),
 5137                    item: item.boxed_clone(),
 5138                    save_intent: *save_intent,
 5139                });
 5140                serialize_workspace = false;
 5141            }
 5142            pane::Event::ChangeItemTitle => {
 5143                if *pane == self.active_pane {
 5144                    self.active_item_path_changed(false, window, cx);
 5145                }
 5146                serialize_workspace = false;
 5147            }
 5148            pane::Event::RemovedItem { item } => {
 5149                cx.emit(Event::ActiveItemChanged);
 5150                self.update_window_edited(window, cx);
 5151                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5152                    && entry.get().entity_id() == pane.entity_id()
 5153                {
 5154                    entry.remove();
 5155                }
 5156                cx.emit(Event::ItemRemoved {
 5157                    item_id: item.item_id(),
 5158                });
 5159            }
 5160            pane::Event::Focus => {
 5161                window.invalidate_character_coordinates();
 5162                self.handle_pane_focused(pane.clone(), window, cx);
 5163            }
 5164            pane::Event::ZoomIn => {
 5165                if *pane == self.active_pane {
 5166                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5167                    if pane.read(cx).has_focus(window, cx) {
 5168                        self.zoomed = Some(pane.downgrade().into());
 5169                        self.zoomed_position = None;
 5170                        cx.emit(Event::ZoomChanged);
 5171                    }
 5172                    cx.notify();
 5173                }
 5174            }
 5175            pane::Event::ZoomOut => {
 5176                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5177                if self.zoomed_position.is_none() {
 5178                    self.zoomed = None;
 5179                    cx.emit(Event::ZoomChanged);
 5180                }
 5181                cx.notify();
 5182            }
 5183            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5184        }
 5185
 5186        if serialize_workspace {
 5187            self.serialize_workspace(window, cx);
 5188        }
 5189    }
 5190
 5191    pub fn unfollow_in_pane(
 5192        &mut self,
 5193        pane: &Entity<Pane>,
 5194        window: &mut Window,
 5195        cx: &mut Context<Workspace>,
 5196    ) -> Option<CollaboratorId> {
 5197        let leader_id = self.leader_for_pane(pane)?;
 5198        self.unfollow(leader_id, window, cx);
 5199        Some(leader_id)
 5200    }
 5201
 5202    pub fn split_pane(
 5203        &mut self,
 5204        pane_to_split: Entity<Pane>,
 5205        split_direction: SplitDirection,
 5206        window: &mut Window,
 5207        cx: &mut Context<Self>,
 5208    ) -> Entity<Pane> {
 5209        let new_pane = self.add_pane(window, cx);
 5210        self.center
 5211            .split(&pane_to_split, &new_pane, split_direction, cx);
 5212        cx.notify();
 5213        new_pane
 5214    }
 5215
 5216    pub fn split_and_move(
 5217        &mut self,
 5218        pane: Entity<Pane>,
 5219        direction: SplitDirection,
 5220        window: &mut Window,
 5221        cx: &mut Context<Self>,
 5222    ) {
 5223        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5224            return;
 5225        };
 5226        let new_pane = self.add_pane(window, cx);
 5227        new_pane.update(cx, |pane, cx| {
 5228            pane.add_item(item, true, true, None, window, cx)
 5229        });
 5230        self.center.split(&pane, &new_pane, direction, cx);
 5231        cx.notify();
 5232    }
 5233
 5234    pub fn split_and_clone(
 5235        &mut self,
 5236        pane: Entity<Pane>,
 5237        direction: SplitDirection,
 5238        window: &mut Window,
 5239        cx: &mut Context<Self>,
 5240    ) -> Task<Option<Entity<Pane>>> {
 5241        let Some(item) = pane.read(cx).active_item() else {
 5242            return Task::ready(None);
 5243        };
 5244        if !item.can_split(cx) {
 5245            return Task::ready(None);
 5246        }
 5247        let task = item.clone_on_split(self.database_id(), window, cx);
 5248        cx.spawn_in(window, async move |this, cx| {
 5249            if let Some(clone) = task.await {
 5250                this.update_in(cx, |this, window, cx| {
 5251                    let new_pane = this.add_pane(window, cx);
 5252                    let nav_history = pane.read(cx).fork_nav_history();
 5253                    new_pane.update(cx, |pane, cx| {
 5254                        pane.set_nav_history(nav_history, cx);
 5255                        pane.add_item(clone, true, true, None, window, cx)
 5256                    });
 5257                    this.center.split(&pane, &new_pane, direction, cx);
 5258                    cx.notify();
 5259                    new_pane
 5260                })
 5261                .ok()
 5262            } else {
 5263                None
 5264            }
 5265        })
 5266    }
 5267
 5268    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5269        let active_item = self.active_pane.read(cx).active_item();
 5270        for pane in &self.panes {
 5271            join_pane_into_active(&self.active_pane, pane, window, cx);
 5272        }
 5273        if let Some(active_item) = active_item {
 5274            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5275        }
 5276        cx.notify();
 5277    }
 5278
 5279    pub fn join_pane_into_next(
 5280        &mut self,
 5281        pane: Entity<Pane>,
 5282        window: &mut Window,
 5283        cx: &mut Context<Self>,
 5284    ) {
 5285        let next_pane = self
 5286            .find_pane_in_direction(SplitDirection::Right, cx)
 5287            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5288            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5289            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5290        let Some(next_pane) = next_pane else {
 5291            return;
 5292        };
 5293        move_all_items(&pane, &next_pane, window, cx);
 5294        cx.notify();
 5295    }
 5296
 5297    fn remove_pane(
 5298        &mut self,
 5299        pane: Entity<Pane>,
 5300        focus_on: Option<Entity<Pane>>,
 5301        window: &mut Window,
 5302        cx: &mut Context<Self>,
 5303    ) {
 5304        if self.center.remove(&pane, cx).unwrap() {
 5305            self.force_remove_pane(&pane, &focus_on, window, cx);
 5306            self.unfollow_in_pane(&pane, window, cx);
 5307            self.last_leaders_by_pane.remove(&pane.downgrade());
 5308            for removed_item in pane.read(cx).items() {
 5309                self.panes_by_item.remove(&removed_item.item_id());
 5310            }
 5311
 5312            cx.notify();
 5313        } else {
 5314            self.active_item_path_changed(true, window, cx);
 5315        }
 5316        cx.emit(Event::PaneRemoved);
 5317    }
 5318
 5319    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5320        &mut self.panes
 5321    }
 5322
 5323    pub fn panes(&self) -> &[Entity<Pane>] {
 5324        &self.panes
 5325    }
 5326
 5327    pub fn active_pane(&self) -> &Entity<Pane> {
 5328        &self.active_pane
 5329    }
 5330
 5331    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5332        for dock in self.all_docks() {
 5333            if dock.focus_handle(cx).contains_focused(window, cx)
 5334                && let Some(pane) = dock
 5335                    .read(cx)
 5336                    .active_panel()
 5337                    .and_then(|panel| panel.pane(cx))
 5338            {
 5339                return pane;
 5340            }
 5341        }
 5342        self.active_pane().clone()
 5343    }
 5344
 5345    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5346        self.find_pane_in_direction(SplitDirection::Right, cx)
 5347            .unwrap_or_else(|| {
 5348                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5349            })
 5350    }
 5351
 5352    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5353        self.pane_for_item_id(handle.item_id())
 5354    }
 5355
 5356    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5357        let weak_pane = self.panes_by_item.get(&item_id)?;
 5358        weak_pane.upgrade()
 5359    }
 5360
 5361    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5362        self.panes
 5363            .iter()
 5364            .find(|pane| pane.entity_id() == entity_id)
 5365            .cloned()
 5366    }
 5367
 5368    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5369        self.follower_states.retain(|leader_id, state| {
 5370            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5371                for item in state.items_by_leader_view_id.values() {
 5372                    item.view.set_leader_id(None, window, cx);
 5373                }
 5374                false
 5375            } else {
 5376                true
 5377            }
 5378        });
 5379        cx.notify();
 5380    }
 5381
 5382    pub fn start_following(
 5383        &mut self,
 5384        leader_id: impl Into<CollaboratorId>,
 5385        window: &mut Window,
 5386        cx: &mut Context<Self>,
 5387    ) -> Option<Task<Result<()>>> {
 5388        let leader_id = leader_id.into();
 5389        let pane = self.active_pane().clone();
 5390
 5391        self.last_leaders_by_pane
 5392            .insert(pane.downgrade(), leader_id);
 5393        self.unfollow(leader_id, window, cx);
 5394        self.unfollow_in_pane(&pane, window, cx);
 5395        self.follower_states.insert(
 5396            leader_id,
 5397            FollowerState {
 5398                center_pane: pane.clone(),
 5399                dock_pane: None,
 5400                active_view_id: None,
 5401                items_by_leader_view_id: Default::default(),
 5402            },
 5403        );
 5404        cx.notify();
 5405
 5406        match leader_id {
 5407            CollaboratorId::PeerId(leader_peer_id) => {
 5408                let room_id = self.active_call()?.room_id(cx)?;
 5409                let project_id = self.project.read(cx).remote_id();
 5410                let request = self.app_state.client.request(proto::Follow {
 5411                    room_id,
 5412                    project_id,
 5413                    leader_id: Some(leader_peer_id),
 5414                });
 5415
 5416                Some(cx.spawn_in(window, async move |this, cx| {
 5417                    let response = request.await?;
 5418                    this.update(cx, |this, _| {
 5419                        let state = this
 5420                            .follower_states
 5421                            .get_mut(&leader_id)
 5422                            .context("following interrupted")?;
 5423                        state.active_view_id = response
 5424                            .active_view
 5425                            .as_ref()
 5426                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5427                        anyhow::Ok(())
 5428                    })??;
 5429                    if let Some(view) = response.active_view {
 5430                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5431                    }
 5432                    this.update_in(cx, |this, window, cx| {
 5433                        this.leader_updated(leader_id, window, cx)
 5434                    })?;
 5435                    Ok(())
 5436                }))
 5437            }
 5438            CollaboratorId::Agent => {
 5439                self.leader_updated(leader_id, window, cx)?;
 5440                Some(Task::ready(Ok(())))
 5441            }
 5442        }
 5443    }
 5444
 5445    pub fn follow_next_collaborator(
 5446        &mut self,
 5447        _: &FollowNextCollaborator,
 5448        window: &mut Window,
 5449        cx: &mut Context<Self>,
 5450    ) {
 5451        let collaborators = self.project.read(cx).collaborators();
 5452        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5453            let mut collaborators = collaborators.keys().copied();
 5454            for peer_id in collaborators.by_ref() {
 5455                if CollaboratorId::PeerId(peer_id) == leader_id {
 5456                    break;
 5457                }
 5458            }
 5459            collaborators.next().map(CollaboratorId::PeerId)
 5460        } else if let Some(last_leader_id) =
 5461            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5462        {
 5463            match last_leader_id {
 5464                CollaboratorId::PeerId(peer_id) => {
 5465                    if collaborators.contains_key(peer_id) {
 5466                        Some(*last_leader_id)
 5467                    } else {
 5468                        None
 5469                    }
 5470                }
 5471                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5472            }
 5473        } else {
 5474            None
 5475        };
 5476
 5477        let pane = self.active_pane.clone();
 5478        let Some(leader_id) = next_leader_id.or_else(|| {
 5479            Some(CollaboratorId::PeerId(
 5480                collaborators.keys().copied().next()?,
 5481            ))
 5482        }) else {
 5483            return;
 5484        };
 5485        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5486            return;
 5487        }
 5488        if let Some(task) = self.start_following(leader_id, window, cx) {
 5489            task.detach_and_log_err(cx)
 5490        }
 5491    }
 5492
 5493    pub fn follow(
 5494        &mut self,
 5495        leader_id: impl Into<CollaboratorId>,
 5496        window: &mut Window,
 5497        cx: &mut Context<Self>,
 5498    ) {
 5499        let leader_id = leader_id.into();
 5500
 5501        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5502            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5503                return;
 5504            };
 5505            let Some(remote_participant) =
 5506                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5507            else {
 5508                return;
 5509            };
 5510
 5511            let project = self.project.read(cx);
 5512
 5513            let other_project_id = match remote_participant.location {
 5514                ParticipantLocation::External => None,
 5515                ParticipantLocation::UnsharedProject => None,
 5516                ParticipantLocation::SharedProject { project_id } => {
 5517                    if Some(project_id) == project.remote_id() {
 5518                        None
 5519                    } else {
 5520                        Some(project_id)
 5521                    }
 5522                }
 5523            };
 5524
 5525            // if they are active in another project, follow there.
 5526            if let Some(project_id) = other_project_id {
 5527                let app_state = self.app_state.clone();
 5528                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5529                    .detach_and_log_err(cx);
 5530            }
 5531        }
 5532
 5533        // if you're already following, find the right pane and focus it.
 5534        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5535            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5536
 5537            return;
 5538        }
 5539
 5540        // Otherwise, follow.
 5541        if let Some(task) = self.start_following(leader_id, window, cx) {
 5542            task.detach_and_log_err(cx)
 5543        }
 5544    }
 5545
 5546    pub fn unfollow(
 5547        &mut self,
 5548        leader_id: impl Into<CollaboratorId>,
 5549        window: &mut Window,
 5550        cx: &mut Context<Self>,
 5551    ) -> Option<()> {
 5552        cx.notify();
 5553
 5554        let leader_id = leader_id.into();
 5555        let state = self.follower_states.remove(&leader_id)?;
 5556        for (_, item) in state.items_by_leader_view_id {
 5557            item.view.set_leader_id(None, window, cx);
 5558        }
 5559
 5560        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5561            let project_id = self.project.read(cx).remote_id();
 5562            let room_id = self.active_call()?.room_id(cx)?;
 5563            self.app_state
 5564                .client
 5565                .send(proto::Unfollow {
 5566                    room_id,
 5567                    project_id,
 5568                    leader_id: Some(leader_peer_id),
 5569                })
 5570                .log_err();
 5571        }
 5572
 5573        Some(())
 5574    }
 5575
 5576    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5577        self.follower_states.contains_key(&id.into())
 5578    }
 5579
 5580    fn active_item_path_changed(
 5581        &mut self,
 5582        focus_changed: bool,
 5583        window: &mut Window,
 5584        cx: &mut Context<Self>,
 5585    ) {
 5586        cx.emit(Event::ActiveItemChanged);
 5587        let active_entry = self.active_project_path(cx);
 5588        self.project.update(cx, |project, cx| {
 5589            project.set_active_path(active_entry.clone(), cx)
 5590        });
 5591
 5592        if focus_changed && let Some(project_path) = &active_entry {
 5593            let git_store_entity = self.project.read(cx).git_store().clone();
 5594            git_store_entity.update(cx, |git_store, cx| {
 5595                git_store.set_active_repo_for_path(project_path, cx);
 5596            });
 5597        }
 5598
 5599        self.update_window_title(window, cx);
 5600    }
 5601
 5602    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5603        let project = self.project().read(cx);
 5604        let mut title = String::new();
 5605
 5606        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5607            let name = {
 5608                let settings_location = SettingsLocation {
 5609                    worktree_id: worktree.read(cx).id(),
 5610                    path: RelPath::empty(),
 5611                };
 5612
 5613                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5614                match &settings.project_name {
 5615                    Some(name) => name.as_str(),
 5616                    None => worktree.read(cx).root_name_str(),
 5617                }
 5618            };
 5619            if i > 0 {
 5620                title.push_str(", ");
 5621            }
 5622            title.push_str(name);
 5623        }
 5624
 5625        if title.is_empty() {
 5626            title = "empty project".to_string();
 5627        }
 5628
 5629        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5630            let filename = path.path.file_name().or_else(|| {
 5631                Some(
 5632                    project
 5633                        .worktree_for_id(path.worktree_id, cx)?
 5634                        .read(cx)
 5635                        .root_name_str(),
 5636                )
 5637            });
 5638
 5639            if let Some(filename) = filename {
 5640                title.push_str("");
 5641                title.push_str(filename.as_ref());
 5642            }
 5643        }
 5644
 5645        if project.is_via_collab() {
 5646            title.push_str("");
 5647        } else if project.is_shared() {
 5648            title.push_str("");
 5649        }
 5650
 5651        if let Some(last_title) = self.last_window_title.as_ref()
 5652            && &title == last_title
 5653        {
 5654            return;
 5655        }
 5656        window.set_window_title(&title);
 5657        SystemWindowTabController::update_tab_title(
 5658            cx,
 5659            window.window_handle().window_id(),
 5660            SharedString::from(&title),
 5661        );
 5662        self.last_window_title = Some(title);
 5663    }
 5664
 5665    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5666        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5667        if is_edited != self.window_edited {
 5668            self.window_edited = is_edited;
 5669            window.set_window_edited(self.window_edited)
 5670        }
 5671    }
 5672
 5673    fn update_item_dirty_state(
 5674        &mut self,
 5675        item: &dyn ItemHandle,
 5676        window: &mut Window,
 5677        cx: &mut App,
 5678    ) {
 5679        let is_dirty = item.is_dirty(cx);
 5680        let item_id = item.item_id();
 5681        let was_dirty = self.dirty_items.contains_key(&item_id);
 5682        if is_dirty == was_dirty {
 5683            return;
 5684        }
 5685        if was_dirty {
 5686            self.dirty_items.remove(&item_id);
 5687            self.update_window_edited(window, cx);
 5688            return;
 5689        }
 5690
 5691        let workspace = self.weak_handle();
 5692        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5693            return;
 5694        };
 5695        let on_release_callback = Box::new(move |cx: &mut App| {
 5696            window_handle
 5697                .update(cx, |_, window, cx| {
 5698                    workspace
 5699                        .update(cx, |workspace, cx| {
 5700                            workspace.dirty_items.remove(&item_id);
 5701                            workspace.update_window_edited(window, cx)
 5702                        })
 5703                        .ok();
 5704                })
 5705                .ok();
 5706        });
 5707
 5708        let s = item.on_release(cx, on_release_callback);
 5709        self.dirty_items.insert(item_id, s);
 5710        self.update_window_edited(window, cx);
 5711    }
 5712
 5713    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5714        if self.notifications.is_empty() {
 5715            None
 5716        } else {
 5717            Some(
 5718                div()
 5719                    .absolute()
 5720                    .right_3()
 5721                    .bottom_3()
 5722                    .w_112()
 5723                    .h_full()
 5724                    .flex()
 5725                    .flex_col()
 5726                    .justify_end()
 5727                    .gap_2()
 5728                    .children(
 5729                        self.notifications
 5730                            .iter()
 5731                            .map(|(_, notification)| notification.clone().into_any()),
 5732                    ),
 5733            )
 5734        }
 5735    }
 5736
 5737    // RPC handlers
 5738
 5739    fn active_view_for_follower(
 5740        &self,
 5741        follower_project_id: Option<u64>,
 5742        window: &mut Window,
 5743        cx: &mut Context<Self>,
 5744    ) -> Option<proto::View> {
 5745        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5746        let item = item?;
 5747        let leader_id = self
 5748            .pane_for(&*item)
 5749            .and_then(|pane| self.leader_for_pane(&pane));
 5750        let leader_peer_id = match leader_id {
 5751            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5752            Some(CollaboratorId::Agent) | None => None,
 5753        };
 5754
 5755        let item_handle = item.to_followable_item_handle(cx)?;
 5756        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5757        let variant = item_handle.to_state_proto(window, cx)?;
 5758
 5759        if item_handle.is_project_item(window, cx)
 5760            && (follower_project_id.is_none()
 5761                || follower_project_id != self.project.read(cx).remote_id())
 5762        {
 5763            return None;
 5764        }
 5765
 5766        Some(proto::View {
 5767            id: id.to_proto(),
 5768            leader_id: leader_peer_id,
 5769            variant: Some(variant),
 5770            panel_id: panel_id.map(|id| id as i32),
 5771        })
 5772    }
 5773
 5774    fn handle_follow(
 5775        &mut self,
 5776        follower_project_id: Option<u64>,
 5777        window: &mut Window,
 5778        cx: &mut Context<Self>,
 5779    ) -> proto::FollowResponse {
 5780        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5781
 5782        cx.notify();
 5783        proto::FollowResponse {
 5784            views: active_view.iter().cloned().collect(),
 5785            active_view,
 5786        }
 5787    }
 5788
 5789    fn handle_update_followers(
 5790        &mut self,
 5791        leader_id: PeerId,
 5792        message: proto::UpdateFollowers,
 5793        _window: &mut Window,
 5794        _cx: &mut Context<Self>,
 5795    ) {
 5796        self.leader_updates_tx
 5797            .unbounded_send((leader_id, message))
 5798            .ok();
 5799    }
 5800
 5801    async fn process_leader_update(
 5802        this: &WeakEntity<Self>,
 5803        leader_id: PeerId,
 5804        update: proto::UpdateFollowers,
 5805        cx: &mut AsyncWindowContext,
 5806    ) -> Result<()> {
 5807        match update.variant.context("invalid update")? {
 5808            proto::update_followers::Variant::CreateView(view) => {
 5809                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5810                let should_add_view = this.update(cx, |this, _| {
 5811                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5812                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5813                    } else {
 5814                        anyhow::Ok(false)
 5815                    }
 5816                })??;
 5817
 5818                if should_add_view {
 5819                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5820                }
 5821            }
 5822            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5823                let should_add_view = this.update(cx, |this, _| {
 5824                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5825                        state.active_view_id = update_active_view
 5826                            .view
 5827                            .as_ref()
 5828                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5829
 5830                        if state.active_view_id.is_some_and(|view_id| {
 5831                            !state.items_by_leader_view_id.contains_key(&view_id)
 5832                        }) {
 5833                            anyhow::Ok(true)
 5834                        } else {
 5835                            anyhow::Ok(false)
 5836                        }
 5837                    } else {
 5838                        anyhow::Ok(false)
 5839                    }
 5840                })??;
 5841
 5842                if should_add_view && let Some(view) = update_active_view.view {
 5843                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5844                }
 5845            }
 5846            proto::update_followers::Variant::UpdateView(update_view) => {
 5847                let variant = update_view.variant.context("missing update view variant")?;
 5848                let id = update_view.id.context("missing update view id")?;
 5849                let mut tasks = Vec::new();
 5850                this.update_in(cx, |this, window, cx| {
 5851                    let project = this.project.clone();
 5852                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5853                        let view_id = ViewId::from_proto(id.clone())?;
 5854                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5855                            tasks.push(item.view.apply_update_proto(
 5856                                &project,
 5857                                variant.clone(),
 5858                                window,
 5859                                cx,
 5860                            ));
 5861                        }
 5862                    }
 5863                    anyhow::Ok(())
 5864                })??;
 5865                try_join_all(tasks).await.log_err();
 5866            }
 5867        }
 5868        this.update_in(cx, |this, window, cx| {
 5869            this.leader_updated(leader_id, window, cx)
 5870        })?;
 5871        Ok(())
 5872    }
 5873
 5874    async fn add_view_from_leader(
 5875        this: WeakEntity<Self>,
 5876        leader_id: PeerId,
 5877        view: &proto::View,
 5878        cx: &mut AsyncWindowContext,
 5879    ) -> Result<()> {
 5880        let this = this.upgrade().context("workspace dropped")?;
 5881
 5882        let Some(id) = view.id.clone() else {
 5883            anyhow::bail!("no id for view");
 5884        };
 5885        let id = ViewId::from_proto(id)?;
 5886        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5887
 5888        let pane = this.update(cx, |this, _cx| {
 5889            let state = this
 5890                .follower_states
 5891                .get(&leader_id.into())
 5892                .context("stopped following")?;
 5893            anyhow::Ok(state.pane().clone())
 5894        })?;
 5895        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5896            let client = this.read(cx).client().clone();
 5897            pane.items().find_map(|item| {
 5898                let item = item.to_followable_item_handle(cx)?;
 5899                if item.remote_id(&client, window, cx) == Some(id) {
 5900                    Some(item)
 5901                } else {
 5902                    None
 5903                }
 5904            })
 5905        })?;
 5906        let item = if let Some(existing_item) = existing_item {
 5907            existing_item
 5908        } else {
 5909            let variant = view.variant.clone();
 5910            anyhow::ensure!(variant.is_some(), "missing view variant");
 5911
 5912            let task = cx.update(|window, cx| {
 5913                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5914            })?;
 5915
 5916            let Some(task) = task else {
 5917                anyhow::bail!(
 5918                    "failed to construct view from leader (maybe from a different version of zed?)"
 5919                );
 5920            };
 5921
 5922            let mut new_item = task.await?;
 5923            pane.update_in(cx, |pane, window, cx| {
 5924                let mut item_to_remove = None;
 5925                for (ix, item) in pane.items().enumerate() {
 5926                    if let Some(item) = item.to_followable_item_handle(cx) {
 5927                        match new_item.dedup(item.as_ref(), window, cx) {
 5928                            Some(item::Dedup::KeepExisting) => {
 5929                                new_item =
 5930                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5931                                break;
 5932                            }
 5933                            Some(item::Dedup::ReplaceExisting) => {
 5934                                item_to_remove = Some((ix, item.item_id()));
 5935                                break;
 5936                            }
 5937                            None => {}
 5938                        }
 5939                    }
 5940                }
 5941
 5942                if let Some((ix, id)) = item_to_remove {
 5943                    pane.remove_item(id, false, false, window, cx);
 5944                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5945                }
 5946            })?;
 5947
 5948            new_item
 5949        };
 5950
 5951        this.update_in(cx, |this, window, cx| {
 5952            let state = this.follower_states.get_mut(&leader_id.into())?;
 5953            item.set_leader_id(Some(leader_id.into()), window, cx);
 5954            state.items_by_leader_view_id.insert(
 5955                id,
 5956                FollowerView {
 5957                    view: item,
 5958                    location: panel_id,
 5959                },
 5960            );
 5961
 5962            Some(())
 5963        })
 5964        .context("no follower state")?;
 5965
 5966        Ok(())
 5967    }
 5968
 5969    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5970        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5971            return;
 5972        };
 5973
 5974        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5975            let buffer_entity_id = agent_location.buffer.entity_id();
 5976            let view_id = ViewId {
 5977                creator: CollaboratorId::Agent,
 5978                id: buffer_entity_id.as_u64(),
 5979            };
 5980            follower_state.active_view_id = Some(view_id);
 5981
 5982            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5983                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5984                hash_map::Entry::Vacant(entry) => {
 5985                    let existing_view =
 5986                        follower_state
 5987                            .center_pane
 5988                            .read(cx)
 5989                            .items()
 5990                            .find_map(|item| {
 5991                                let item = item.to_followable_item_handle(cx)?;
 5992                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5993                                    && item.project_item_model_ids(cx).as_slice()
 5994                                        == [buffer_entity_id]
 5995                                {
 5996                                    Some(item)
 5997                                } else {
 5998                                    None
 5999                                }
 6000                            });
 6001                    let view = existing_view.or_else(|| {
 6002                        agent_location.buffer.upgrade().and_then(|buffer| {
 6003                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6004                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6005                            })?
 6006                            .to_followable_item_handle(cx)
 6007                        })
 6008                    });
 6009
 6010                    view.map(|view| {
 6011                        entry.insert(FollowerView {
 6012                            view,
 6013                            location: None,
 6014                        })
 6015                    })
 6016                }
 6017            };
 6018
 6019            if let Some(item) = item {
 6020                item.view
 6021                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6022                item.view
 6023                    .update_agent_location(agent_location.position, window, cx);
 6024            }
 6025        } else {
 6026            follower_state.active_view_id = None;
 6027        }
 6028
 6029        self.leader_updated(CollaboratorId::Agent, window, cx);
 6030    }
 6031
 6032    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6033        let mut is_project_item = true;
 6034        let mut update = proto::UpdateActiveView::default();
 6035        if window.is_window_active() {
 6036            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6037
 6038            if let Some(item) = active_item
 6039                && item.item_focus_handle(cx).contains_focused(window, cx)
 6040            {
 6041                let leader_id = self
 6042                    .pane_for(&*item)
 6043                    .and_then(|pane| self.leader_for_pane(&pane));
 6044                let leader_peer_id = match leader_id {
 6045                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6046                    Some(CollaboratorId::Agent) | None => None,
 6047                };
 6048
 6049                if let Some(item) = item.to_followable_item_handle(cx) {
 6050                    let id = item
 6051                        .remote_id(&self.app_state.client, window, cx)
 6052                        .map(|id| id.to_proto());
 6053
 6054                    if let Some(id) = id
 6055                        && let Some(variant) = item.to_state_proto(window, cx)
 6056                    {
 6057                        let view = Some(proto::View {
 6058                            id,
 6059                            leader_id: leader_peer_id,
 6060                            variant: Some(variant),
 6061                            panel_id: panel_id.map(|id| id as i32),
 6062                        });
 6063
 6064                        is_project_item = item.is_project_item(window, cx);
 6065                        update = proto::UpdateActiveView { view };
 6066                    };
 6067                }
 6068            }
 6069        }
 6070
 6071        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6072        if active_view_id != self.last_active_view_id.as_ref() {
 6073            self.last_active_view_id = active_view_id.cloned();
 6074            self.update_followers(
 6075                is_project_item,
 6076                proto::update_followers::Variant::UpdateActiveView(update),
 6077                window,
 6078                cx,
 6079            );
 6080        }
 6081    }
 6082
 6083    fn active_item_for_followers(
 6084        &self,
 6085        window: &mut Window,
 6086        cx: &mut App,
 6087    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6088        let mut active_item = None;
 6089        let mut panel_id = None;
 6090        for dock in self.all_docks() {
 6091            if dock.focus_handle(cx).contains_focused(window, cx)
 6092                && let Some(panel) = dock.read(cx).active_panel()
 6093                && let Some(pane) = panel.pane(cx)
 6094                && let Some(item) = pane.read(cx).active_item()
 6095            {
 6096                active_item = Some(item);
 6097                panel_id = panel.remote_id();
 6098                break;
 6099            }
 6100        }
 6101
 6102        if active_item.is_none() {
 6103            active_item = self.active_pane().read(cx).active_item();
 6104        }
 6105        (active_item, panel_id)
 6106    }
 6107
 6108    fn update_followers(
 6109        &self,
 6110        project_only: bool,
 6111        update: proto::update_followers::Variant,
 6112        _: &mut Window,
 6113        cx: &mut App,
 6114    ) -> Option<()> {
 6115        // If this update only applies to for followers in the current project,
 6116        // then skip it unless this project is shared. If it applies to all
 6117        // followers, regardless of project, then set `project_id` to none,
 6118        // indicating that it goes to all followers.
 6119        let project_id = if project_only {
 6120            Some(self.project.read(cx).remote_id()?)
 6121        } else {
 6122            None
 6123        };
 6124        self.app_state().workspace_store.update(cx, |store, cx| {
 6125            store.update_followers(project_id, update, cx)
 6126        })
 6127    }
 6128
 6129    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6130        self.follower_states.iter().find_map(|(leader_id, state)| {
 6131            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6132                Some(*leader_id)
 6133            } else {
 6134                None
 6135            }
 6136        })
 6137    }
 6138
 6139    fn leader_updated(
 6140        &mut self,
 6141        leader_id: impl Into<CollaboratorId>,
 6142        window: &mut Window,
 6143        cx: &mut Context<Self>,
 6144    ) -> Option<Box<dyn ItemHandle>> {
 6145        cx.notify();
 6146
 6147        let leader_id = leader_id.into();
 6148        let (panel_id, item) = match leader_id {
 6149            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6150            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6151        };
 6152
 6153        let state = self.follower_states.get(&leader_id)?;
 6154        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6155        let pane;
 6156        if let Some(panel_id) = panel_id {
 6157            pane = self
 6158                .activate_panel_for_proto_id(panel_id, window, cx)?
 6159                .pane(cx)?;
 6160            let state = self.follower_states.get_mut(&leader_id)?;
 6161            state.dock_pane = Some(pane.clone());
 6162        } else {
 6163            pane = state.center_pane.clone();
 6164            let state = self.follower_states.get_mut(&leader_id)?;
 6165            if let Some(dock_pane) = state.dock_pane.take() {
 6166                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6167            }
 6168        }
 6169
 6170        pane.update(cx, |pane, cx| {
 6171            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6172            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6173                pane.activate_item(index, false, false, window, cx);
 6174            } else {
 6175                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6176            }
 6177
 6178            if focus_active_item {
 6179                pane.focus_active_item(window, cx)
 6180            }
 6181        });
 6182
 6183        Some(item)
 6184    }
 6185
 6186    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6187        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6188        let active_view_id = state.active_view_id?;
 6189        Some(
 6190            state
 6191                .items_by_leader_view_id
 6192                .get(&active_view_id)?
 6193                .view
 6194                .boxed_clone(),
 6195        )
 6196    }
 6197
 6198    fn active_item_for_peer(
 6199        &self,
 6200        peer_id: PeerId,
 6201        window: &mut Window,
 6202        cx: &mut Context<Self>,
 6203    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6204        let call = self.active_call()?;
 6205        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6206        let leader_in_this_app;
 6207        let leader_in_this_project;
 6208        match participant.location {
 6209            ParticipantLocation::SharedProject { project_id } => {
 6210                leader_in_this_app = true;
 6211                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6212            }
 6213            ParticipantLocation::UnsharedProject => {
 6214                leader_in_this_app = true;
 6215                leader_in_this_project = false;
 6216            }
 6217            ParticipantLocation::External => {
 6218                leader_in_this_app = false;
 6219                leader_in_this_project = false;
 6220            }
 6221        };
 6222        let state = self.follower_states.get(&peer_id.into())?;
 6223        let mut item_to_activate = None;
 6224        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6225            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6226                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6227            {
 6228                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6229            }
 6230        } else if let Some(shared_screen) =
 6231            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6232        {
 6233            item_to_activate = Some((None, Box::new(shared_screen)));
 6234        }
 6235        item_to_activate
 6236    }
 6237
 6238    fn shared_screen_for_peer(
 6239        &self,
 6240        peer_id: PeerId,
 6241        pane: &Entity<Pane>,
 6242        window: &mut Window,
 6243        cx: &mut App,
 6244    ) -> Option<Entity<SharedScreen>> {
 6245        self.active_call()?
 6246            .create_shared_screen(peer_id, pane, window, cx)
 6247    }
 6248
 6249    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6250        if window.is_window_active() {
 6251            self.update_active_view_for_followers(window, cx);
 6252
 6253            if let Some(database_id) = self.database_id {
 6254                let db = WorkspaceDb::global(cx);
 6255                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6256                    .detach();
 6257            }
 6258        } else {
 6259            for pane in &self.panes {
 6260                pane.update(cx, |pane, cx| {
 6261                    if let Some(item) = pane.active_item() {
 6262                        item.workspace_deactivated(window, cx);
 6263                    }
 6264                    for item in pane.items() {
 6265                        if matches!(
 6266                            item.workspace_settings(cx).autosave,
 6267                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6268                        ) {
 6269                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6270                                .detach_and_log_err(cx);
 6271                        }
 6272                    }
 6273                });
 6274            }
 6275        }
 6276    }
 6277
 6278    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6279        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6280    }
 6281
 6282    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6283        self.active_call.as_ref().map(|(call, _)| call.clone())
 6284    }
 6285
 6286    fn on_active_call_event(
 6287        &mut self,
 6288        event: &ActiveCallEvent,
 6289        window: &mut Window,
 6290        cx: &mut Context<Self>,
 6291    ) {
 6292        match event {
 6293            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6294            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6295                self.leader_updated(participant_id, window, cx);
 6296            }
 6297        }
 6298    }
 6299
 6300    pub fn database_id(&self) -> Option<WorkspaceId> {
 6301        self.database_id
 6302    }
 6303
 6304    #[cfg(any(test, feature = "test-support"))]
 6305    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6306        self.database_id = Some(id);
 6307    }
 6308
 6309    pub fn session_id(&self) -> Option<String> {
 6310        self.session_id.clone()
 6311    }
 6312
 6313    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6314        let Some(display) = window.display(cx) else {
 6315            return Task::ready(());
 6316        };
 6317        let Ok(display_uuid) = display.uuid() else {
 6318            return Task::ready(());
 6319        };
 6320
 6321        let window_bounds = window.inner_window_bounds();
 6322        let database_id = self.database_id;
 6323        let has_paths = !self.root_paths(cx).is_empty();
 6324        let db = WorkspaceDb::global(cx);
 6325        let kvp = db::kvp::KeyValueStore::global(cx);
 6326
 6327        cx.background_executor().spawn(async move {
 6328            if !has_paths {
 6329                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6330                    .await
 6331                    .log_err();
 6332            }
 6333            if let Some(database_id) = database_id {
 6334                db.set_window_open_status(
 6335                    database_id,
 6336                    SerializedWindowBounds(window_bounds),
 6337                    display_uuid,
 6338                )
 6339                .await
 6340                .log_err();
 6341            } else {
 6342                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6343                    .await
 6344                    .log_err();
 6345            }
 6346        })
 6347    }
 6348
 6349    /// Bypass the 200ms serialization throttle and write workspace state to
 6350    /// the DB immediately. Returns a task the caller can await to ensure the
 6351    /// write completes. Used by the quit handler so the most recent state
 6352    /// isn't lost to a pending throttle timer when the process exits.
 6353    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6354        self._schedule_serialize_workspace.take();
 6355        self._serialize_workspace_task.take();
 6356        self.bounds_save_task_queued.take();
 6357
 6358        let bounds_task = self.save_window_bounds(window, cx);
 6359        let serialize_task = self.serialize_workspace_internal(window, cx);
 6360        cx.spawn(async move |_| {
 6361            bounds_task.await;
 6362            serialize_task.await;
 6363        })
 6364    }
 6365
 6366    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6367        let project = self.project().read(cx);
 6368        project
 6369            .visible_worktrees(cx)
 6370            .map(|worktree| worktree.read(cx).abs_path())
 6371            .collect::<Vec<_>>()
 6372    }
 6373
 6374    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6375        match member {
 6376            Member::Axis(PaneAxis { members, .. }) => {
 6377                for child in members.iter() {
 6378                    self.remove_panes(child.clone(), window, cx)
 6379                }
 6380            }
 6381            Member::Pane(pane) => {
 6382                self.force_remove_pane(&pane, &None, window, cx);
 6383            }
 6384        }
 6385    }
 6386
 6387    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6388        self.session_id.take();
 6389        self.serialize_workspace_internal(window, cx)
 6390    }
 6391
 6392    fn force_remove_pane(
 6393        &mut self,
 6394        pane: &Entity<Pane>,
 6395        focus_on: &Option<Entity<Pane>>,
 6396        window: &mut Window,
 6397        cx: &mut Context<Workspace>,
 6398    ) {
 6399        self.panes.retain(|p| p != pane);
 6400        if let Some(focus_on) = focus_on {
 6401            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6402        } else if self.active_pane() == pane {
 6403            self.panes
 6404                .last()
 6405                .unwrap()
 6406                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6407        }
 6408        if self.last_active_center_pane == Some(pane.downgrade()) {
 6409            self.last_active_center_pane = None;
 6410        }
 6411        cx.notify();
 6412    }
 6413
 6414    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6415        if self._schedule_serialize_workspace.is_none() {
 6416            self._schedule_serialize_workspace =
 6417                Some(cx.spawn_in(window, async move |this, cx| {
 6418                    cx.background_executor()
 6419                        .timer(SERIALIZATION_THROTTLE_TIME)
 6420                        .await;
 6421                    this.update_in(cx, |this, window, cx| {
 6422                        this._serialize_workspace_task =
 6423                            Some(this.serialize_workspace_internal(window, cx));
 6424                        this._schedule_serialize_workspace.take();
 6425                    })
 6426                    .log_err();
 6427                }));
 6428        }
 6429    }
 6430
 6431    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6432        let Some(database_id) = self.database_id() else {
 6433            return Task::ready(());
 6434        };
 6435
 6436        fn serialize_pane_handle(
 6437            pane_handle: &Entity<Pane>,
 6438            window: &mut Window,
 6439            cx: &mut App,
 6440        ) -> SerializedPane {
 6441            let (items, active, pinned_count) = {
 6442                let pane = pane_handle.read(cx);
 6443                let active_item_id = pane.active_item().map(|item| item.item_id());
 6444                (
 6445                    pane.items()
 6446                        .filter_map(|handle| {
 6447                            let handle = handle.to_serializable_item_handle(cx)?;
 6448
 6449                            Some(SerializedItem {
 6450                                kind: Arc::from(handle.serialized_item_kind()),
 6451                                item_id: handle.item_id().as_u64(),
 6452                                active: Some(handle.item_id()) == active_item_id,
 6453                                preview: pane.is_active_preview_item(handle.item_id()),
 6454                            })
 6455                        })
 6456                        .collect::<Vec<_>>(),
 6457                    pane.has_focus(window, cx),
 6458                    pane.pinned_count(),
 6459                )
 6460            };
 6461
 6462            SerializedPane::new(items, active, pinned_count)
 6463        }
 6464
 6465        fn build_serialized_pane_group(
 6466            pane_group: &Member,
 6467            window: &mut Window,
 6468            cx: &mut App,
 6469        ) -> SerializedPaneGroup {
 6470            match pane_group {
 6471                Member::Axis(PaneAxis {
 6472                    axis,
 6473                    members,
 6474                    flexes,
 6475                    bounding_boxes: _,
 6476                }) => SerializedPaneGroup::Group {
 6477                    axis: SerializedAxis(*axis),
 6478                    children: members
 6479                        .iter()
 6480                        .map(|member| build_serialized_pane_group(member, window, cx))
 6481                        .collect::<Vec<_>>(),
 6482                    flexes: Some(flexes.lock().clone()),
 6483                },
 6484                Member::Pane(pane_handle) => {
 6485                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6486                }
 6487            }
 6488        }
 6489
 6490        fn build_serialized_docks(
 6491            this: &Workspace,
 6492            window: &mut Window,
 6493            cx: &mut App,
 6494        ) -> DockStructure {
 6495            this.capture_dock_state(window, cx)
 6496        }
 6497
 6498        match self.workspace_location(cx) {
 6499            WorkspaceLocation::Location(location, paths) => {
 6500                let breakpoints = self.project.update(cx, |project, cx| {
 6501                    project
 6502                        .breakpoint_store()
 6503                        .read(cx)
 6504                        .all_source_breakpoints(cx)
 6505                });
 6506                let user_toolchains = self
 6507                    .project
 6508                    .read(cx)
 6509                    .user_toolchains(cx)
 6510                    .unwrap_or_default();
 6511
 6512                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6513                let docks = build_serialized_docks(self, window, cx);
 6514                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6515
 6516                let serialized_workspace = SerializedWorkspace {
 6517                    id: database_id,
 6518                    location,
 6519                    paths,
 6520                    center_group,
 6521                    window_bounds,
 6522                    display: Default::default(),
 6523                    docks,
 6524                    centered_layout: self.centered_layout,
 6525                    session_id: self.session_id.clone(),
 6526                    breakpoints,
 6527                    window_id: Some(window.window_handle().window_id().as_u64()),
 6528                    user_toolchains,
 6529                };
 6530
 6531                let db = WorkspaceDb::global(cx);
 6532                window.spawn(cx, async move |_| {
 6533                    db.save_workspace(serialized_workspace).await;
 6534                })
 6535            }
 6536            WorkspaceLocation::DetachFromSession => {
 6537                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6538                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6539                // Save dock state for empty local workspaces
 6540                let docks = build_serialized_docks(self, window, cx);
 6541                let db = WorkspaceDb::global(cx);
 6542                let kvp = db::kvp::KeyValueStore::global(cx);
 6543                window.spawn(cx, async move |_| {
 6544                    db.set_window_open_status(
 6545                        database_id,
 6546                        window_bounds,
 6547                        display.unwrap_or_default(),
 6548                    )
 6549                    .await
 6550                    .log_err();
 6551                    db.set_session_id(database_id, None).await.log_err();
 6552                    persistence::write_default_dock_state(&kvp, docks)
 6553                        .await
 6554                        .log_err();
 6555                })
 6556            }
 6557            WorkspaceLocation::None => {
 6558                // Save dock state for empty non-local workspaces
 6559                let docks = build_serialized_docks(self, window, cx);
 6560                let kvp = db::kvp::KeyValueStore::global(cx);
 6561                window.spawn(cx, async move |_| {
 6562                    persistence::write_default_dock_state(&kvp, docks)
 6563                        .await
 6564                        .log_err();
 6565                })
 6566            }
 6567        }
 6568    }
 6569
 6570    fn has_any_items_open(&self, cx: &App) -> bool {
 6571        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6572    }
 6573
 6574    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6575        let paths = PathList::new(&self.root_paths(cx));
 6576        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6577            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6578        } else if self.project.read(cx).is_local() {
 6579            if !paths.is_empty() || self.has_any_items_open(cx) {
 6580                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6581            } else {
 6582                WorkspaceLocation::DetachFromSession
 6583            }
 6584        } else {
 6585            WorkspaceLocation::None
 6586        }
 6587    }
 6588
 6589    fn update_history(&self, cx: &mut App) {
 6590        let Some(id) = self.database_id() else {
 6591            return;
 6592        };
 6593        if !self.project.read(cx).is_local() {
 6594            return;
 6595        }
 6596        if let Some(manager) = HistoryManager::global(cx) {
 6597            let paths = PathList::new(&self.root_paths(cx));
 6598            manager.update(cx, |this, cx| {
 6599                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6600            });
 6601        }
 6602    }
 6603
 6604    async fn serialize_items(
 6605        this: &WeakEntity<Self>,
 6606        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6607        cx: &mut AsyncWindowContext,
 6608    ) -> Result<()> {
 6609        const CHUNK_SIZE: usize = 200;
 6610
 6611        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6612
 6613        while let Some(items_received) = serializable_items.next().await {
 6614            let unique_items =
 6615                items_received
 6616                    .into_iter()
 6617                    .fold(HashMap::default(), |mut acc, item| {
 6618                        acc.entry(item.item_id()).or_insert(item);
 6619                        acc
 6620                    });
 6621
 6622            // We use into_iter() here so that the references to the items are moved into
 6623            // the tasks and not kept alive while we're sleeping.
 6624            for (_, item) in unique_items.into_iter() {
 6625                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6626                    item.serialize(workspace, false, window, cx)
 6627                }) {
 6628                    cx.background_spawn(async move { task.await.log_err() })
 6629                        .detach();
 6630                }
 6631            }
 6632
 6633            cx.background_executor()
 6634                .timer(SERIALIZATION_THROTTLE_TIME)
 6635                .await;
 6636        }
 6637
 6638        Ok(())
 6639    }
 6640
 6641    pub(crate) fn enqueue_item_serialization(
 6642        &mut self,
 6643        item: Box<dyn SerializableItemHandle>,
 6644    ) -> Result<()> {
 6645        self.serializable_items_tx
 6646            .unbounded_send(item)
 6647            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6648    }
 6649
 6650    pub(crate) fn load_workspace(
 6651        serialized_workspace: SerializedWorkspace,
 6652        paths_to_open: Vec<Option<ProjectPath>>,
 6653        window: &mut Window,
 6654        cx: &mut Context<Workspace>,
 6655    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6656        cx.spawn_in(window, async move |workspace, cx| {
 6657            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6658
 6659            let mut center_group = None;
 6660            let mut center_items = None;
 6661
 6662            // Traverse the splits tree and add to things
 6663            if let Some((group, active_pane, items)) = serialized_workspace
 6664                .center_group
 6665                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6666                .await
 6667            {
 6668                center_items = Some(items);
 6669                center_group = Some((group, active_pane))
 6670            }
 6671
 6672            let mut items_by_project_path = HashMap::default();
 6673            let mut item_ids_by_kind = HashMap::default();
 6674            let mut all_deserialized_items = Vec::default();
 6675            cx.update(|_, cx| {
 6676                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6677                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6678                        item_ids_by_kind
 6679                            .entry(serializable_item_handle.serialized_item_kind())
 6680                            .or_insert(Vec::new())
 6681                            .push(item.item_id().as_u64() as ItemId);
 6682                    }
 6683
 6684                    if let Some(project_path) = item.project_path(cx) {
 6685                        items_by_project_path.insert(project_path, item.clone());
 6686                    }
 6687                    all_deserialized_items.push(item);
 6688                }
 6689            })?;
 6690
 6691            let opened_items = paths_to_open
 6692                .into_iter()
 6693                .map(|path_to_open| {
 6694                    path_to_open
 6695                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6696                })
 6697                .collect::<Vec<_>>();
 6698
 6699            // Remove old panes from workspace panes list
 6700            workspace.update_in(cx, |workspace, window, cx| {
 6701                if let Some((center_group, active_pane)) = center_group {
 6702                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6703
 6704                    // Swap workspace center group
 6705                    workspace.center = PaneGroup::with_root(center_group);
 6706                    workspace.center.set_is_center(true);
 6707                    workspace.center.mark_positions(cx);
 6708
 6709                    if let Some(active_pane) = active_pane {
 6710                        workspace.set_active_pane(&active_pane, window, cx);
 6711                        cx.focus_self(window);
 6712                    } else {
 6713                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6714                    }
 6715                }
 6716
 6717                let docks = serialized_workspace.docks;
 6718
 6719                for (dock, serialized_dock) in [
 6720                    (&mut workspace.right_dock, docks.right),
 6721                    (&mut workspace.left_dock, docks.left),
 6722                    (&mut workspace.bottom_dock, docks.bottom),
 6723                ]
 6724                .iter_mut()
 6725                {
 6726                    dock.update(cx, |dock, cx| {
 6727                        dock.serialized_dock = Some(serialized_dock.clone());
 6728                        dock.restore_state(window, cx);
 6729                    });
 6730                }
 6731
 6732                cx.notify();
 6733            })?;
 6734
 6735            let _ = project
 6736                .update(cx, |project, cx| {
 6737                    project
 6738                        .breakpoint_store()
 6739                        .update(cx, |breakpoint_store, cx| {
 6740                            breakpoint_store
 6741                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6742                        })
 6743                })
 6744                .await;
 6745
 6746            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6747            // after loading the items, we might have different items and in order to avoid
 6748            // the database filling up, we delete items that haven't been loaded now.
 6749            //
 6750            // The items that have been loaded, have been saved after they've been added to the workspace.
 6751            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6752                item_ids_by_kind
 6753                    .into_iter()
 6754                    .map(|(item_kind, loaded_items)| {
 6755                        SerializableItemRegistry::cleanup(
 6756                            item_kind,
 6757                            serialized_workspace.id,
 6758                            loaded_items,
 6759                            window,
 6760                            cx,
 6761                        )
 6762                        .log_err()
 6763                    })
 6764                    .collect::<Vec<_>>()
 6765            })?;
 6766
 6767            futures::future::join_all(clean_up_tasks).await;
 6768
 6769            workspace
 6770                .update_in(cx, |workspace, window, cx| {
 6771                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6772                    workspace.serialize_workspace_internal(window, cx).detach();
 6773
 6774                    // Ensure that we mark the window as edited if we did load dirty items
 6775                    workspace.update_window_edited(window, cx);
 6776                })
 6777                .ok();
 6778
 6779            Ok(opened_items)
 6780        })
 6781    }
 6782
 6783    pub fn key_context(&self, cx: &App) -> KeyContext {
 6784        let mut context = KeyContext::new_with_defaults();
 6785        context.add("Workspace");
 6786        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6787        if let Some(status) = self
 6788            .debugger_provider
 6789            .as_ref()
 6790            .and_then(|provider| provider.active_thread_state(cx))
 6791        {
 6792            match status {
 6793                ThreadStatus::Running | ThreadStatus::Stepping => {
 6794                    context.add("debugger_running");
 6795                }
 6796                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6797                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6798            }
 6799        }
 6800
 6801        if self.left_dock.read(cx).is_open() {
 6802            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6803                context.set("left_dock", active_panel.panel_key());
 6804            }
 6805        }
 6806
 6807        if self.right_dock.read(cx).is_open() {
 6808            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6809                context.set("right_dock", active_panel.panel_key());
 6810            }
 6811        }
 6812
 6813        if self.bottom_dock.read(cx).is_open() {
 6814            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6815                context.set("bottom_dock", active_panel.panel_key());
 6816            }
 6817        }
 6818
 6819        context
 6820    }
 6821
 6822    /// Multiworkspace uses this to add workspace action handling to itself
 6823    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6824        self.add_workspace_actions_listeners(div, window, cx)
 6825            .on_action(cx.listener(
 6826                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6827                    for action in &action_sequence.0 {
 6828                        window.dispatch_action(action.boxed_clone(), cx);
 6829                    }
 6830                },
 6831            ))
 6832            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6833            .on_action(cx.listener(Self::close_all_items_and_panes))
 6834            .on_action(cx.listener(Self::close_item_in_all_panes))
 6835            .on_action(cx.listener(Self::save_all))
 6836            .on_action(cx.listener(Self::send_keystrokes))
 6837            .on_action(cx.listener(Self::add_folder_to_project))
 6838            .on_action(cx.listener(Self::follow_next_collaborator))
 6839            .on_action(cx.listener(Self::activate_pane_at_index))
 6840            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6841            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6842            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6843            .on_action(cx.listener(Self::toggle_theme_mode))
 6844            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6845                let pane = workspace.active_pane().clone();
 6846                workspace.unfollow_in_pane(&pane, window, cx);
 6847            }))
 6848            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6849                workspace
 6850                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6851                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6852            }))
 6853            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6854                workspace
 6855                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6856                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6857            }))
 6858            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6859                workspace
 6860                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6861                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6862            }))
 6863            .on_action(
 6864                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6865                    workspace.activate_previous_pane(window, cx)
 6866                }),
 6867            )
 6868            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6869                workspace.activate_next_pane(window, cx)
 6870            }))
 6871            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6872                workspace.activate_last_pane(window, cx)
 6873            }))
 6874            .on_action(
 6875                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6876                    workspace.activate_next_window(cx)
 6877                }),
 6878            )
 6879            .on_action(
 6880                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6881                    workspace.activate_previous_window(cx)
 6882                }),
 6883            )
 6884            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6885                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6886            }))
 6887            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6888                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6889            }))
 6890            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6891                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6892            }))
 6893            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6894                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6895            }))
 6896            .on_action(cx.listener(
 6897                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6898                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6899                },
 6900            ))
 6901            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6902                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6903            }))
 6904            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6905                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6906            }))
 6907            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6908                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6909            }))
 6910            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6911                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6912            }))
 6913            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6914                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6915                    SplitDirection::Down,
 6916                    SplitDirection::Up,
 6917                    SplitDirection::Right,
 6918                    SplitDirection::Left,
 6919                ];
 6920                for dir in DIRECTION_PRIORITY {
 6921                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6922                        workspace.swap_pane_in_direction(dir, cx);
 6923                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6924                        break;
 6925                    }
 6926                }
 6927            }))
 6928            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6929                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6930            }))
 6931            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6932                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6933            }))
 6934            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6935                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6936            }))
 6937            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6938                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6939            }))
 6940            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6941                this.toggle_dock(DockPosition::Left, window, cx);
 6942            }))
 6943            .on_action(cx.listener(
 6944                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6945                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6946                },
 6947            ))
 6948            .on_action(cx.listener(
 6949                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6950                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6951                },
 6952            ))
 6953            .on_action(cx.listener(
 6954                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6955                    if !workspace.close_active_dock(window, cx) {
 6956                        cx.propagate();
 6957                    }
 6958                },
 6959            ))
 6960            .on_action(
 6961                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6962                    workspace.close_all_docks(window, cx);
 6963                }),
 6964            )
 6965            .on_action(cx.listener(Self::toggle_all_docks))
 6966            .on_action(cx.listener(
 6967                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6968                    workspace.clear_all_notifications(cx);
 6969                },
 6970            ))
 6971            .on_action(cx.listener(
 6972                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6973                    workspace.clear_navigation_history(window, cx);
 6974                },
 6975            ))
 6976            .on_action(cx.listener(
 6977                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6978                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6979                        workspace.suppress_notification(&notification_id, cx);
 6980                    }
 6981                },
 6982            ))
 6983            .on_action(cx.listener(
 6984                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6985                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6986                },
 6987            ))
 6988            .on_action(
 6989                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6990                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6991                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6992                            trusted_worktrees.clear_trusted_paths()
 6993                        });
 6994                        let db = WorkspaceDb::global(cx);
 6995                        cx.spawn(async move |_, cx| {
 6996                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6997                                cx.update(|cx| reload(cx));
 6998                            }
 6999                        })
 7000                        .detach();
 7001                    }
 7002                }),
 7003            )
 7004            .on_action(cx.listener(
 7005                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7006                    workspace.reopen_closed_item(window, cx).detach();
 7007                },
 7008            ))
 7009            .on_action(cx.listener(
 7010                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7011                    for dock in workspace.all_docks() {
 7012                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7013                            let panel = dock.read(cx).active_panel().cloned();
 7014                            if let Some(panel) = panel {
 7015                                dock.update(cx, |dock, cx| {
 7016                                    dock.set_panel_size_state(
 7017                                        panel.as_ref(),
 7018                                        dock::PanelSizeState::default(),
 7019                                        cx,
 7020                                    );
 7021                                });
 7022                            }
 7023                            return;
 7024                        }
 7025                    }
 7026                },
 7027            ))
 7028            .on_action(cx.listener(
 7029                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7030                    for dock in workspace.all_docks() {
 7031                        let panel = dock.read(cx).visible_panel().cloned();
 7032                        if let Some(panel) = panel {
 7033                            dock.update(cx, |dock, cx| {
 7034                                dock.set_panel_size_state(
 7035                                    panel.as_ref(),
 7036                                    dock::PanelSizeState::default(),
 7037                                    cx,
 7038                                );
 7039                            });
 7040                        }
 7041                    }
 7042                },
 7043            ))
 7044            .on_action(cx.listener(
 7045                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7046                    adjust_active_dock_size_by_px(
 7047                        px_with_ui_font_fallback(act.px, cx),
 7048                        workspace,
 7049                        window,
 7050                        cx,
 7051                    );
 7052                },
 7053            ))
 7054            .on_action(cx.listener(
 7055                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7056                    adjust_active_dock_size_by_px(
 7057                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7058                        workspace,
 7059                        window,
 7060                        cx,
 7061                    );
 7062                },
 7063            ))
 7064            .on_action(cx.listener(
 7065                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7066                    adjust_open_docks_size_by_px(
 7067                        px_with_ui_font_fallback(act.px, cx),
 7068                        workspace,
 7069                        window,
 7070                        cx,
 7071                    );
 7072                },
 7073            ))
 7074            .on_action(cx.listener(
 7075                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7076                    adjust_open_docks_size_by_px(
 7077                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7078                        workspace,
 7079                        window,
 7080                        cx,
 7081                    );
 7082                },
 7083            ))
 7084            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7085            .on_action(cx.listener(
 7086                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7087                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7088                        let dock = active_dock.read(cx);
 7089                        if let Some(active_panel) = dock.active_panel() {
 7090                            if active_panel.pane(cx).is_none() {
 7091                                let mut recent_pane: Option<Entity<Pane>> = None;
 7092                                let mut recent_timestamp = 0;
 7093                                for pane_handle in workspace.panes() {
 7094                                    let pane = pane_handle.read(cx);
 7095                                    for entry in pane.activation_history() {
 7096                                        if entry.timestamp > recent_timestamp {
 7097                                            recent_timestamp = entry.timestamp;
 7098                                            recent_pane = Some(pane_handle.clone());
 7099                                        }
 7100                                    }
 7101                                }
 7102
 7103                                if let Some(pane) = recent_pane {
 7104                                    let wrap_around = action.wrap_around;
 7105                                    pane.update(cx, |pane, cx| {
 7106                                        let current_index = pane.active_item_index();
 7107                                        let items_len = pane.items_len();
 7108                                        if items_len > 0 {
 7109                                            let next_index = if current_index + 1 < items_len {
 7110                                                current_index + 1
 7111                                            } else if wrap_around {
 7112                                                0
 7113                                            } else {
 7114                                                return;
 7115                                            };
 7116                                            pane.activate_item(
 7117                                                next_index, false, false, window, cx,
 7118                                            );
 7119                                        }
 7120                                    });
 7121                                    return;
 7122                                }
 7123                            }
 7124                        }
 7125                    }
 7126                    cx.propagate();
 7127                },
 7128            ))
 7129            .on_action(cx.listener(
 7130                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7131                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7132                        let dock = active_dock.read(cx);
 7133                        if let Some(active_panel) = dock.active_panel() {
 7134                            if active_panel.pane(cx).is_none() {
 7135                                let mut recent_pane: Option<Entity<Pane>> = None;
 7136                                let mut recent_timestamp = 0;
 7137                                for pane_handle in workspace.panes() {
 7138                                    let pane = pane_handle.read(cx);
 7139                                    for entry in pane.activation_history() {
 7140                                        if entry.timestamp > recent_timestamp {
 7141                                            recent_timestamp = entry.timestamp;
 7142                                            recent_pane = Some(pane_handle.clone());
 7143                                        }
 7144                                    }
 7145                                }
 7146
 7147                                if let Some(pane) = recent_pane {
 7148                                    let wrap_around = action.wrap_around;
 7149                                    pane.update(cx, |pane, cx| {
 7150                                        let current_index = pane.active_item_index();
 7151                                        let items_len = pane.items_len();
 7152                                        if items_len > 0 {
 7153                                            let prev_index = if current_index > 0 {
 7154                                                current_index - 1
 7155                                            } else if wrap_around {
 7156                                                items_len.saturating_sub(1)
 7157                                            } else {
 7158                                                return;
 7159                                            };
 7160                                            pane.activate_item(
 7161                                                prev_index, false, false, window, cx,
 7162                                            );
 7163                                        }
 7164                                    });
 7165                                    return;
 7166                                }
 7167                            }
 7168                        }
 7169                    }
 7170                    cx.propagate();
 7171                },
 7172            ))
 7173            .on_action(cx.listener(
 7174                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7175                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7176                        let dock = active_dock.read(cx);
 7177                        if let Some(active_panel) = dock.active_panel() {
 7178                            if active_panel.pane(cx).is_none() {
 7179                                let active_pane = workspace.active_pane().clone();
 7180                                active_pane.update(cx, |pane, cx| {
 7181                                    pane.close_active_item(action, window, cx)
 7182                                        .detach_and_log_err(cx);
 7183                                });
 7184                                return;
 7185                            }
 7186                        }
 7187                    }
 7188                    cx.propagate();
 7189                },
 7190            ))
 7191            .on_action(
 7192                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7193                    let pane = workspace.active_pane().clone();
 7194                    if let Some(item) = pane.read(cx).active_item() {
 7195                        item.toggle_read_only(window, cx);
 7196                    }
 7197                }),
 7198            )
 7199            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7200                workspace.focus_center_pane(window, cx);
 7201            }))
 7202            .on_action(cx.listener(Workspace::cancel))
 7203    }
 7204
 7205    #[cfg(any(test, feature = "test-support"))]
 7206    pub fn set_random_database_id(&mut self) {
 7207        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7208    }
 7209
 7210    #[cfg(any(test, feature = "test-support"))]
 7211    pub(crate) fn test_new(
 7212        project: Entity<Project>,
 7213        window: &mut Window,
 7214        cx: &mut Context<Self>,
 7215    ) -> Self {
 7216        use node_runtime::NodeRuntime;
 7217        use session::Session;
 7218
 7219        let client = project.read(cx).client();
 7220        let user_store = project.read(cx).user_store();
 7221        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7222        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7223        window.activate_window();
 7224        let app_state = Arc::new(AppState {
 7225            languages: project.read(cx).languages().clone(),
 7226            workspace_store,
 7227            client,
 7228            user_store,
 7229            fs: project.read(cx).fs().clone(),
 7230            build_window_options: |_, _| Default::default(),
 7231            node_runtime: NodeRuntime::unavailable(),
 7232            session,
 7233        });
 7234        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7235        workspace
 7236            .active_pane
 7237            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7238        workspace
 7239    }
 7240
 7241    pub fn register_action<A: Action>(
 7242        &mut self,
 7243        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7244    ) -> &mut Self {
 7245        let callback = Arc::new(callback);
 7246
 7247        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7248            let callback = callback.clone();
 7249            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7250                (callback)(workspace, event, window, cx)
 7251            }))
 7252        }));
 7253        self
 7254    }
 7255    pub fn register_action_renderer(
 7256        &mut self,
 7257        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7258    ) -> &mut Self {
 7259        self.workspace_actions.push(Box::new(callback));
 7260        self
 7261    }
 7262
 7263    fn add_workspace_actions_listeners(
 7264        &self,
 7265        mut div: Div,
 7266        window: &mut Window,
 7267        cx: &mut Context<Self>,
 7268    ) -> Div {
 7269        for action in self.workspace_actions.iter() {
 7270            div = (action)(div, self, window, cx)
 7271        }
 7272        div
 7273    }
 7274
 7275    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7276        self.modal_layer.read(cx).has_active_modal()
 7277    }
 7278
 7279    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7280        self.modal_layer
 7281            .read(cx)
 7282            .is_active_modal_command_palette(cx)
 7283    }
 7284
 7285    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7286        self.modal_layer.read(cx).active_modal()
 7287    }
 7288
 7289    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7290    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7291    /// If no modal is active, the new modal will be shown.
 7292    ///
 7293    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7294    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7295    /// will not be shown.
 7296    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7297    where
 7298        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7299    {
 7300        self.modal_layer.update(cx, |modal_layer, cx| {
 7301            modal_layer.toggle_modal(window, cx, build)
 7302        })
 7303    }
 7304
 7305    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7306        self.modal_layer
 7307            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7308    }
 7309
 7310    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7311        self.toast_layer
 7312            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7313    }
 7314
 7315    pub fn toggle_centered_layout(
 7316        &mut self,
 7317        _: &ToggleCenteredLayout,
 7318        _: &mut Window,
 7319        cx: &mut Context<Self>,
 7320    ) {
 7321        self.centered_layout = !self.centered_layout;
 7322        if let Some(database_id) = self.database_id() {
 7323            let db = WorkspaceDb::global(cx);
 7324            let centered_layout = self.centered_layout;
 7325            cx.background_spawn(async move {
 7326                db.set_centered_layout(database_id, centered_layout).await
 7327            })
 7328            .detach_and_log_err(cx);
 7329        }
 7330        cx.notify();
 7331    }
 7332
 7333    fn adjust_padding(padding: Option<f32>) -> f32 {
 7334        padding
 7335            .unwrap_or(CenteredPaddingSettings::default().0)
 7336            .clamp(
 7337                CenteredPaddingSettings::MIN_PADDING,
 7338                CenteredPaddingSettings::MAX_PADDING,
 7339            )
 7340    }
 7341
 7342    fn render_dock(
 7343        &self,
 7344        position: DockPosition,
 7345        dock: &Entity<Dock>,
 7346        window: &mut Window,
 7347        cx: &mut App,
 7348    ) -> Option<Div> {
 7349        if self.zoomed_position == Some(position) {
 7350            return None;
 7351        }
 7352
 7353        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7354            let pane = panel.pane(cx)?;
 7355            let follower_states = &self.follower_states;
 7356            leader_border_for_pane(follower_states, &pane, window, cx)
 7357        });
 7358
 7359        let mut container = div()
 7360            .flex()
 7361            .overflow_hidden()
 7362            .flex_none()
 7363            .child(dock.clone())
 7364            .children(leader_border);
 7365
 7366        // Apply sizing only when the dock is open. When closed the dock is still
 7367        // included in the element tree so its focus handle remains mounted — without
 7368        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7369        let dock = dock.read(cx);
 7370        if let Some(panel) = dock.visible_panel() {
 7371            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7372            if position.axis() == Axis::Horizontal {
 7373                let use_flexible = panel.has_flexible_size(window, cx);
 7374                let flex_grow = if use_flexible {
 7375                    size_state
 7376                        .and_then(|state| state.flex)
 7377                        .or_else(|| self.default_dock_flex(position))
 7378                } else {
 7379                    None
 7380                };
 7381                if let Some(grow) = flex_grow {
 7382                    let grow = grow.max(0.001);
 7383                    let style = container.style();
 7384                    style.flex_grow = Some(grow);
 7385                    style.flex_shrink = Some(1.0);
 7386                    style.flex_basis = Some(relative(0.).into());
 7387                } else {
 7388                    let size = size_state
 7389                        .and_then(|state| state.size)
 7390                        .unwrap_or_else(|| panel.default_size(window, cx));
 7391                    container = container.w(size);
 7392                }
 7393            } else {
 7394                let size = size_state
 7395                    .and_then(|state| state.size)
 7396                    .unwrap_or_else(|| panel.default_size(window, cx));
 7397                container = container.h(size);
 7398            }
 7399        }
 7400
 7401        Some(container)
 7402    }
 7403
 7404    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7405        window
 7406            .root::<MultiWorkspace>()
 7407            .flatten()
 7408            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7409    }
 7410
 7411    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7412        self.zoomed.as_ref()
 7413    }
 7414
 7415    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7416        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7417            return;
 7418        };
 7419        let windows = cx.windows();
 7420        let next_window =
 7421            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7422                || {
 7423                    windows
 7424                        .iter()
 7425                        .cycle()
 7426                        .skip_while(|window| window.window_id() != current_window_id)
 7427                        .nth(1)
 7428                },
 7429            );
 7430
 7431        if let Some(window) = next_window {
 7432            window
 7433                .update(cx, |_, window, _| window.activate_window())
 7434                .ok();
 7435        }
 7436    }
 7437
 7438    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7439        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7440            return;
 7441        };
 7442        let windows = cx.windows();
 7443        let prev_window =
 7444            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7445                || {
 7446                    windows
 7447                        .iter()
 7448                        .rev()
 7449                        .cycle()
 7450                        .skip_while(|window| window.window_id() != current_window_id)
 7451                        .nth(1)
 7452                },
 7453            );
 7454
 7455        if let Some(window) = prev_window {
 7456            window
 7457                .update(cx, |_, window, _| window.activate_window())
 7458                .ok();
 7459        }
 7460    }
 7461
 7462    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7463        if cx.stop_active_drag(window) {
 7464        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7465            dismiss_app_notification(&notification_id, cx);
 7466        } else {
 7467            cx.propagate();
 7468        }
 7469    }
 7470
 7471    fn resize_dock(
 7472        &mut self,
 7473        dock_pos: DockPosition,
 7474        new_size: Pixels,
 7475        window: &mut Window,
 7476        cx: &mut Context<Self>,
 7477    ) {
 7478        match dock_pos {
 7479            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7480            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7481            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7482        }
 7483    }
 7484
 7485    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7486        let workspace_width = self.bounds.size.width;
 7487        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7488
 7489        self.right_dock.read_with(cx, |right_dock, cx| {
 7490            let right_dock_size = right_dock
 7491                .stored_active_panel_size(window, cx)
 7492                .unwrap_or(Pixels::ZERO);
 7493            if right_dock_size + size > workspace_width {
 7494                size = workspace_width - right_dock_size
 7495            }
 7496        });
 7497
 7498        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7499        self.left_dock.update(cx, |left_dock, cx| {
 7500            if WorkspaceSettings::get_global(cx)
 7501                .resize_all_panels_in_dock
 7502                .contains(&DockPosition::Left)
 7503            {
 7504                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7505            } else {
 7506                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7507            }
 7508        });
 7509    }
 7510
 7511    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7512        let workspace_width = self.bounds.size.width;
 7513        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7514        self.left_dock.read_with(cx, |left_dock, cx| {
 7515            let left_dock_size = left_dock
 7516                .stored_active_panel_size(window, cx)
 7517                .unwrap_or(Pixels::ZERO);
 7518            if left_dock_size + size > workspace_width {
 7519                size = workspace_width - left_dock_size
 7520            }
 7521        });
 7522        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7523        self.right_dock.update(cx, |right_dock, cx| {
 7524            if WorkspaceSettings::get_global(cx)
 7525                .resize_all_panels_in_dock
 7526                .contains(&DockPosition::Right)
 7527            {
 7528                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7529            } else {
 7530                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7531            }
 7532        });
 7533    }
 7534
 7535    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7536        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7537        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7538            if WorkspaceSettings::get_global(cx)
 7539                .resize_all_panels_in_dock
 7540                .contains(&DockPosition::Bottom)
 7541            {
 7542                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7543            } else {
 7544                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7545            }
 7546        });
 7547    }
 7548
 7549    fn toggle_edit_predictions_all_files(
 7550        &mut self,
 7551        _: &ToggleEditPrediction,
 7552        _window: &mut Window,
 7553        cx: &mut Context<Self>,
 7554    ) {
 7555        let fs = self.project().read(cx).fs().clone();
 7556        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7557        update_settings_file(fs, cx, move |file, _| {
 7558            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7559        });
 7560    }
 7561
 7562    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7563        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7564        let next_mode = match current_mode {
 7565            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7566                theme_settings::ThemeAppearanceMode::Dark
 7567            }
 7568            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7569                theme_settings::ThemeAppearanceMode::Light
 7570            }
 7571            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7572                match cx.theme().appearance() {
 7573                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7574                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7575                }
 7576            }
 7577        };
 7578
 7579        let fs = self.project().read(cx).fs().clone();
 7580        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7581            theme_settings::set_mode(settings, next_mode);
 7582        });
 7583    }
 7584
 7585    pub fn show_worktree_trust_security_modal(
 7586        &mut self,
 7587        toggle: bool,
 7588        window: &mut Window,
 7589        cx: &mut Context<Self>,
 7590    ) {
 7591        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7592            if toggle {
 7593                security_modal.update(cx, |security_modal, cx| {
 7594                    security_modal.dismiss(cx);
 7595                })
 7596            } else {
 7597                security_modal.update(cx, |security_modal, cx| {
 7598                    security_modal.refresh_restricted_paths(cx);
 7599                });
 7600            }
 7601        } else {
 7602            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7603                .map(|trusted_worktrees| {
 7604                    trusted_worktrees
 7605                        .read(cx)
 7606                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7607                })
 7608                .unwrap_or(false);
 7609            if has_restricted_worktrees {
 7610                let project = self.project().read(cx);
 7611                let remote_host = project
 7612                    .remote_connection_options(cx)
 7613                    .map(RemoteHostLocation::from);
 7614                let worktree_store = project.worktree_store().downgrade();
 7615                self.toggle_modal(window, cx, |_, cx| {
 7616                    SecurityModal::new(worktree_store, remote_host, cx)
 7617                });
 7618            }
 7619        }
 7620    }
 7621}
 7622
 7623pub trait AnyActiveCall {
 7624    fn entity(&self) -> AnyEntity;
 7625    fn is_in_room(&self, _: &App) -> bool;
 7626    fn room_id(&self, _: &App) -> Option<u64>;
 7627    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7628    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7629    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7630    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7631    fn is_sharing_project(&self, _: &App) -> bool;
 7632    fn has_remote_participants(&self, _: &App) -> bool;
 7633    fn local_participant_is_guest(&self, _: &App) -> bool;
 7634    fn client(&self, _: &App) -> Arc<Client>;
 7635    fn share_on_join(&self, _: &App) -> bool;
 7636    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7637    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7638    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7639    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7640    fn join_project(
 7641        &self,
 7642        _: u64,
 7643        _: Arc<LanguageRegistry>,
 7644        _: Arc<dyn Fs>,
 7645        _: &mut App,
 7646    ) -> Task<Result<Entity<Project>>>;
 7647    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7648    fn subscribe(
 7649        &self,
 7650        _: &mut Window,
 7651        _: &mut Context<Workspace>,
 7652        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7653    ) -> Subscription;
 7654    fn create_shared_screen(
 7655        &self,
 7656        _: PeerId,
 7657        _: &Entity<Pane>,
 7658        _: &mut Window,
 7659        _: &mut App,
 7660    ) -> Option<Entity<SharedScreen>>;
 7661}
 7662
 7663#[derive(Clone)]
 7664pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7665impl Global for GlobalAnyActiveCall {}
 7666
 7667impl GlobalAnyActiveCall {
 7668    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7669        cx.try_global()
 7670    }
 7671
 7672    pub(crate) fn global(cx: &App) -> &Self {
 7673        cx.global()
 7674    }
 7675}
 7676
 7677pub fn merge_conflict_notification_id() -> NotificationId {
 7678    struct MergeConflictNotification;
 7679    NotificationId::unique::<MergeConflictNotification>()
 7680}
 7681
 7682/// Workspace-local view of a remote participant's location.
 7683#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7684pub enum ParticipantLocation {
 7685    SharedProject { project_id: u64 },
 7686    UnsharedProject,
 7687    External,
 7688}
 7689
 7690impl ParticipantLocation {
 7691    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7692        match location
 7693            .and_then(|l| l.variant)
 7694            .context("participant location was not provided")?
 7695        {
 7696            proto::participant_location::Variant::SharedProject(project) => {
 7697                Ok(Self::SharedProject {
 7698                    project_id: project.id,
 7699                })
 7700            }
 7701            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7702            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7703        }
 7704    }
 7705}
 7706/// Workspace-local view of a remote collaborator's state.
 7707/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7708#[derive(Clone)]
 7709pub struct RemoteCollaborator {
 7710    pub user: Arc<User>,
 7711    pub peer_id: PeerId,
 7712    pub location: ParticipantLocation,
 7713    pub participant_index: ParticipantIndex,
 7714}
 7715
 7716pub enum ActiveCallEvent {
 7717    ParticipantLocationChanged { participant_id: PeerId },
 7718    RemoteVideoTracksChanged { participant_id: PeerId },
 7719}
 7720
 7721fn leader_border_for_pane(
 7722    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7723    pane: &Entity<Pane>,
 7724    _: &Window,
 7725    cx: &App,
 7726) -> Option<Div> {
 7727    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7728        if state.pane() == pane {
 7729            Some((*leader_id, state))
 7730        } else {
 7731            None
 7732        }
 7733    })?;
 7734
 7735    let mut leader_color = match leader_id {
 7736        CollaboratorId::PeerId(leader_peer_id) => {
 7737            let leader = GlobalAnyActiveCall::try_global(cx)?
 7738                .0
 7739                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7740
 7741            cx.theme()
 7742                .players()
 7743                .color_for_participant(leader.participant_index.0)
 7744                .cursor
 7745        }
 7746        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7747    };
 7748    leader_color.fade_out(0.3);
 7749    Some(
 7750        div()
 7751            .absolute()
 7752            .size_full()
 7753            .left_0()
 7754            .top_0()
 7755            .border_2()
 7756            .border_color(leader_color),
 7757    )
 7758}
 7759
 7760fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7761    ZED_WINDOW_POSITION
 7762        .zip(*ZED_WINDOW_SIZE)
 7763        .map(|(position, size)| Bounds {
 7764            origin: position,
 7765            size,
 7766        })
 7767}
 7768
 7769fn open_items(
 7770    serialized_workspace: Option<SerializedWorkspace>,
 7771    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7772    window: &mut Window,
 7773    cx: &mut Context<Workspace>,
 7774) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7775    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7776        Workspace::load_workspace(
 7777            serialized_workspace,
 7778            project_paths_to_open
 7779                .iter()
 7780                .map(|(_, project_path)| project_path)
 7781                .cloned()
 7782                .collect(),
 7783            window,
 7784            cx,
 7785        )
 7786    });
 7787
 7788    cx.spawn_in(window, async move |workspace, cx| {
 7789        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7790
 7791        if let Some(restored_items) = restored_items {
 7792            let restored_items = restored_items.await?;
 7793
 7794            let restored_project_paths = restored_items
 7795                .iter()
 7796                .filter_map(|item| {
 7797                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7798                        .ok()
 7799                        .flatten()
 7800                })
 7801                .collect::<HashSet<_>>();
 7802
 7803            for restored_item in restored_items {
 7804                opened_items.push(restored_item.map(Ok));
 7805            }
 7806
 7807            project_paths_to_open
 7808                .iter_mut()
 7809                .for_each(|(_, project_path)| {
 7810                    if let Some(project_path_to_open) = project_path
 7811                        && restored_project_paths.contains(project_path_to_open)
 7812                    {
 7813                        *project_path = None;
 7814                    }
 7815                });
 7816        } else {
 7817            for _ in 0..project_paths_to_open.len() {
 7818                opened_items.push(None);
 7819            }
 7820        }
 7821        assert!(opened_items.len() == project_paths_to_open.len());
 7822
 7823        let tasks =
 7824            project_paths_to_open
 7825                .into_iter()
 7826                .enumerate()
 7827                .map(|(ix, (abs_path, project_path))| {
 7828                    let workspace = workspace.clone();
 7829                    cx.spawn(async move |cx| {
 7830                        let file_project_path = project_path?;
 7831                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7832                            workspace.project().update(cx, |project, cx| {
 7833                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7834                            })
 7835                        });
 7836
 7837                        // We only want to open file paths here. If one of the items
 7838                        // here is a directory, it was already opened further above
 7839                        // with a `find_or_create_worktree`.
 7840                        if let Ok(task) = abs_path_task
 7841                            && task.await.is_none_or(|p| p.is_file())
 7842                        {
 7843                            return Some((
 7844                                ix,
 7845                                workspace
 7846                                    .update_in(cx, |workspace, window, cx| {
 7847                                        workspace.open_path(
 7848                                            file_project_path,
 7849                                            None,
 7850                                            true,
 7851                                            window,
 7852                                            cx,
 7853                                        )
 7854                                    })
 7855                                    .log_err()?
 7856                                    .await,
 7857                            ));
 7858                        }
 7859                        None
 7860                    })
 7861                });
 7862
 7863        let tasks = tasks.collect::<Vec<_>>();
 7864
 7865        let tasks = futures::future::join_all(tasks);
 7866        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7867            opened_items[ix] = Some(path_open_result);
 7868        }
 7869
 7870        Ok(opened_items)
 7871    })
 7872}
 7873
 7874#[derive(Clone)]
 7875enum ActivateInDirectionTarget {
 7876    Pane(Entity<Pane>),
 7877    Dock(Entity<Dock>),
 7878    Sidebar(FocusHandle),
 7879}
 7880
 7881fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7882    window
 7883        .update(cx, |multi_workspace, _, cx| {
 7884            let workspace = multi_workspace.workspace().clone();
 7885            workspace.update(cx, |workspace, cx| {
 7886                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7887                    struct DatabaseFailedNotification;
 7888
 7889                    workspace.show_notification(
 7890                        NotificationId::unique::<DatabaseFailedNotification>(),
 7891                        cx,
 7892                        |cx| {
 7893                            cx.new(|cx| {
 7894                                MessageNotification::new("Failed to load the database file.", cx)
 7895                                    .primary_message("File an Issue")
 7896                                    .primary_icon(IconName::Plus)
 7897                                    .primary_on_click(|window, cx| {
 7898                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7899                                    })
 7900                            })
 7901                        },
 7902                    );
 7903                }
 7904            });
 7905        })
 7906        .log_err();
 7907}
 7908
 7909fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7910    if val == 0 {
 7911        ThemeSettings::get_global(cx).ui_font_size(cx)
 7912    } else {
 7913        px(val as f32)
 7914    }
 7915}
 7916
 7917fn adjust_active_dock_size_by_px(
 7918    px: Pixels,
 7919    workspace: &mut Workspace,
 7920    window: &mut Window,
 7921    cx: &mut Context<Workspace>,
 7922) {
 7923    let Some(active_dock) = workspace
 7924        .all_docks()
 7925        .into_iter()
 7926        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7927    else {
 7928        return;
 7929    };
 7930    let dock = active_dock.read(cx);
 7931    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7932        return;
 7933    };
 7934    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7935}
 7936
 7937fn adjust_open_docks_size_by_px(
 7938    px: Pixels,
 7939    workspace: &mut Workspace,
 7940    window: &mut Window,
 7941    cx: &mut Context<Workspace>,
 7942) {
 7943    let docks = workspace
 7944        .all_docks()
 7945        .into_iter()
 7946        .filter_map(|dock_entity| {
 7947            let dock = dock_entity.read(cx);
 7948            if dock.is_open() {
 7949                let dock_pos = dock.position();
 7950                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7951                Some((dock_pos, panel_size + px))
 7952            } else {
 7953                None
 7954            }
 7955        })
 7956        .collect::<Vec<_>>();
 7957
 7958    for (position, new_size) in docks {
 7959        workspace.resize_dock(position, new_size, window, cx);
 7960    }
 7961}
 7962
 7963impl Focusable for Workspace {
 7964    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7965        self.active_pane.focus_handle(cx)
 7966    }
 7967}
 7968
 7969#[derive(Clone)]
 7970struct DraggedDock(DockPosition);
 7971
 7972impl Render for DraggedDock {
 7973    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7974        gpui::Empty
 7975    }
 7976}
 7977
 7978impl Render for Workspace {
 7979    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7980        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7981        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7982            log::info!("Rendered first frame");
 7983        }
 7984
 7985        let centered_layout = self.centered_layout
 7986            && self.center.panes().len() == 1
 7987            && self.active_item(cx).is_some();
 7988        let render_padding = |size| {
 7989            (size > 0.0).then(|| {
 7990                div()
 7991                    .h_full()
 7992                    .w(relative(size))
 7993                    .bg(cx.theme().colors().editor_background)
 7994                    .border_color(cx.theme().colors().pane_group_border)
 7995            })
 7996        };
 7997        let paddings = if centered_layout {
 7998            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7999            (
 8000                render_padding(Self::adjust_padding(
 8001                    settings.left_padding.map(|padding| padding.0),
 8002                )),
 8003                render_padding(Self::adjust_padding(
 8004                    settings.right_padding.map(|padding| padding.0),
 8005                )),
 8006            )
 8007        } else {
 8008            (None, None)
 8009        };
 8010        let ui_font = theme_settings::setup_ui_font(window, cx);
 8011
 8012        let theme = cx.theme().clone();
 8013        let colors = theme.colors();
 8014        let notification_entities = self
 8015            .notifications
 8016            .iter()
 8017            .map(|(_, notification)| notification.entity_id())
 8018            .collect::<Vec<_>>();
 8019        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8020
 8021        div()
 8022            .relative()
 8023            .size_full()
 8024            .flex()
 8025            .flex_col()
 8026            .font(ui_font)
 8027            .gap_0()
 8028                .justify_start()
 8029                .items_start()
 8030                .text_color(colors.text)
 8031                .overflow_hidden()
 8032                .children(self.titlebar_item.clone())
 8033                .on_modifiers_changed(move |_, _, cx| {
 8034                    for &id in &notification_entities {
 8035                        cx.notify(id);
 8036                    }
 8037                })
 8038                .child(
 8039                    div()
 8040                        .size_full()
 8041                        .relative()
 8042                        .flex_1()
 8043                        .flex()
 8044                        .flex_col()
 8045                        .child(
 8046                            div()
 8047                                .id("workspace")
 8048                                .bg(colors.background)
 8049                                .relative()
 8050                                .flex_1()
 8051                                .w_full()
 8052                                .flex()
 8053                                .flex_col()
 8054                                .overflow_hidden()
 8055                                .border_t_1()
 8056                                .border_b_1()
 8057                                .border_color(colors.border)
 8058                                .child({
 8059                                    let this = cx.entity();
 8060                                    canvas(
 8061                                        move |bounds, window, cx| {
 8062                                            this.update(cx, |this, cx| {
 8063                                                let bounds_changed = this.bounds != bounds;
 8064                                                this.bounds = bounds;
 8065
 8066                                                if bounds_changed {
 8067                                                    this.left_dock.update(cx, |dock, cx| {
 8068                                                        dock.clamp_panel_size(
 8069                                                            bounds.size.width,
 8070                                                            window,
 8071                                                            cx,
 8072                                                        )
 8073                                                    });
 8074
 8075                                                    this.right_dock.update(cx, |dock, cx| {
 8076                                                        dock.clamp_panel_size(
 8077                                                            bounds.size.width,
 8078                                                            window,
 8079                                                            cx,
 8080                                                        )
 8081                                                    });
 8082
 8083                                                    this.bottom_dock.update(cx, |dock, cx| {
 8084                                                        dock.clamp_panel_size(
 8085                                                            bounds.size.height,
 8086                                                            window,
 8087                                                            cx,
 8088                                                        )
 8089                                                    });
 8090                                                }
 8091                                            })
 8092                                        },
 8093                                        |_, _, _, _| {},
 8094                                    )
 8095                                    .absolute()
 8096                                    .size_full()
 8097                                })
 8098                                .when(self.zoomed.is_none(), |this| {
 8099                                    this.on_drag_move(cx.listener(
 8100                                        move |workspace,
 8101                                              e: &DragMoveEvent<DraggedDock>,
 8102                                              window,
 8103                                              cx| {
 8104                                            if workspace.previous_dock_drag_coordinates
 8105                                                != Some(e.event.position)
 8106                                            {
 8107                                                workspace.previous_dock_drag_coordinates =
 8108                                                    Some(e.event.position);
 8109
 8110                                                match e.drag(cx).0 {
 8111                                                    DockPosition::Left => {
 8112                                                        workspace.resize_left_dock(
 8113                                                            e.event.position.x
 8114                                                                - workspace.bounds.left(),
 8115                                                            window,
 8116                                                            cx,
 8117                                                        );
 8118                                                    }
 8119                                                    DockPosition::Right => {
 8120                                                        workspace.resize_right_dock(
 8121                                                            workspace.bounds.right()
 8122                                                                - e.event.position.x,
 8123                                                            window,
 8124                                                            cx,
 8125                                                        );
 8126                                                    }
 8127                                                    DockPosition::Bottom => {
 8128                                                        workspace.resize_bottom_dock(
 8129                                                            workspace.bounds.bottom()
 8130                                                                - e.event.position.y,
 8131                                                            window,
 8132                                                            cx,
 8133                                                        );
 8134                                                    }
 8135                                                };
 8136                                                workspace.serialize_workspace(window, cx);
 8137                                            }
 8138                                        },
 8139                                    ))
 8140
 8141                                })
 8142                                .child({
 8143                                    match bottom_dock_layout {
 8144                                        BottomDockLayout::Full => div()
 8145                                            .flex()
 8146                                            .flex_col()
 8147                                            .h_full()
 8148                                            .child(
 8149                                                div()
 8150                                                    .flex()
 8151                                                    .flex_row()
 8152                                                    .flex_1()
 8153                                                    .overflow_hidden()
 8154                                                    .children(self.render_dock(
 8155                                                        DockPosition::Left,
 8156                                                        &self.left_dock,
 8157                                                        window,
 8158                                                        cx,
 8159                                                    ))
 8160
 8161                                                    .child(
 8162                                                        div()
 8163                                                            .flex()
 8164                                                            .flex_col()
 8165                                                            .flex_1()
 8166                                                            .overflow_hidden()
 8167                                                            .child(
 8168                                                                h_flex()
 8169                                                                    .flex_1()
 8170                                                                    .when_some(
 8171                                                                        paddings.0,
 8172                                                                        |this, p| {
 8173                                                                            this.child(
 8174                                                                                p.border_r_1(),
 8175                                                                            )
 8176                                                                        },
 8177                                                                    )
 8178                                                                    .child(self.center.render(
 8179                                                                        self.zoomed.as_ref(),
 8180                                                                        &PaneRenderContext {
 8181                                                                            follower_states:
 8182                                                                                &self.follower_states,
 8183                                                                            active_call: self.active_call(),
 8184                                                                            active_pane: &self.active_pane,
 8185                                                                            app_state: &self.app_state,
 8186                                                                            project: &self.project,
 8187                                                                            workspace: &self.weak_self,
 8188                                                                        },
 8189                                                                        window,
 8190                                                                        cx,
 8191                                                                    ))
 8192                                                                    .when_some(
 8193                                                                        paddings.1,
 8194                                                                        |this, p| {
 8195                                                                            this.child(
 8196                                                                                p.border_l_1(),
 8197                                                                            )
 8198                                                                        },
 8199                                                                    ),
 8200                                                            ),
 8201                                                    )
 8202
 8203                                                    .children(self.render_dock(
 8204                                                        DockPosition::Right,
 8205                                                        &self.right_dock,
 8206                                                        window,
 8207                                                        cx,
 8208                                                    )),
 8209                                            )
 8210                                            .child(div().w_full().children(self.render_dock(
 8211                                                DockPosition::Bottom,
 8212                                                &self.bottom_dock,
 8213                                                window,
 8214                                                cx
 8215                                            ))),
 8216
 8217                                        BottomDockLayout::LeftAligned => div()
 8218                                            .flex()
 8219                                            .flex_row()
 8220                                            .h_full()
 8221                                            .child(
 8222                                                div()
 8223                                                    .flex()
 8224                                                    .flex_col()
 8225                                                    .flex_1()
 8226                                                    .h_full()
 8227                                                    .child(
 8228                                                        div()
 8229                                                            .flex()
 8230                                                            .flex_row()
 8231                                                            .flex_1()
 8232                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8233
 8234                                                            .child(
 8235                                                                div()
 8236                                                                    .flex()
 8237                                                                    .flex_col()
 8238                                                                    .flex_1()
 8239                                                                    .overflow_hidden()
 8240                                                                    .child(
 8241                                                                        h_flex()
 8242                                                                            .flex_1()
 8243                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8244                                                                            .child(self.center.render(
 8245                                                                                self.zoomed.as_ref(),
 8246                                                                                &PaneRenderContext {
 8247                                                                                    follower_states:
 8248                                                                                        &self.follower_states,
 8249                                                                                    active_call: self.active_call(),
 8250                                                                                    active_pane: &self.active_pane,
 8251                                                                                    app_state: &self.app_state,
 8252                                                                                    project: &self.project,
 8253                                                                                    workspace: &self.weak_self,
 8254                                                                                },
 8255                                                                                window,
 8256                                                                                cx,
 8257                                                                            ))
 8258                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8259                                                                    )
 8260                                                            )
 8261
 8262                                                    )
 8263                                                    .child(
 8264                                                        div()
 8265                                                            .w_full()
 8266                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8267                                                    ),
 8268                                            )
 8269                                            .children(self.render_dock(
 8270                                                DockPosition::Right,
 8271                                                &self.right_dock,
 8272                                                window,
 8273                                                cx,
 8274                                            )),
 8275                                        BottomDockLayout::RightAligned => div()
 8276                                            .flex()
 8277                                            .flex_row()
 8278                                            .h_full()
 8279                                            .children(self.render_dock(
 8280                                                DockPosition::Left,
 8281                                                &self.left_dock,
 8282                                                window,
 8283                                                cx,
 8284                                            ))
 8285
 8286                                            .child(
 8287                                                div()
 8288                                                    .flex()
 8289                                                    .flex_col()
 8290                                                    .flex_1()
 8291                                                    .h_full()
 8292                                                    .child(
 8293                                                        div()
 8294                                                            .flex()
 8295                                                            .flex_row()
 8296                                                            .flex_1()
 8297                                                            .child(
 8298                                                                div()
 8299                                                                    .flex()
 8300                                                                    .flex_col()
 8301                                                                    .flex_1()
 8302                                                                    .overflow_hidden()
 8303                                                                    .child(
 8304                                                                        h_flex()
 8305                                                                            .flex_1()
 8306                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8307                                                                            .child(self.center.render(
 8308                                                                                self.zoomed.as_ref(),
 8309                                                                                &PaneRenderContext {
 8310                                                                                    follower_states:
 8311                                                                                        &self.follower_states,
 8312                                                                                    active_call: self.active_call(),
 8313                                                                                    active_pane: &self.active_pane,
 8314                                                                                    app_state: &self.app_state,
 8315                                                                                    project: &self.project,
 8316                                                                                    workspace: &self.weak_self,
 8317                                                                                },
 8318                                                                                window,
 8319                                                                                cx,
 8320                                                                            ))
 8321                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8322                                                                    )
 8323                                                            )
 8324
 8325                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8326                                                    )
 8327                                                    .child(
 8328                                                        div()
 8329                                                            .w_full()
 8330                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8331                                                    ),
 8332                                            ),
 8333                                        BottomDockLayout::Contained => div()
 8334                                            .flex()
 8335                                            .flex_row()
 8336                                            .h_full()
 8337                                            .children(self.render_dock(
 8338                                                DockPosition::Left,
 8339                                                &self.left_dock,
 8340                                                window,
 8341                                                cx,
 8342                                            ))
 8343
 8344                                            .child(
 8345                                                div()
 8346                                                    .flex()
 8347                                                    .flex_col()
 8348                                                    .flex_1()
 8349                                                    .overflow_hidden()
 8350                                                    .child(
 8351                                                        h_flex()
 8352                                                            .flex_1()
 8353                                                            .when_some(paddings.0, |this, p| {
 8354                                                                this.child(p.border_r_1())
 8355                                                            })
 8356                                                            .child(self.center.render(
 8357                                                                self.zoomed.as_ref(),
 8358                                                                &PaneRenderContext {
 8359                                                                    follower_states:
 8360                                                                        &self.follower_states,
 8361                                                                    active_call: self.active_call(),
 8362                                                                    active_pane: &self.active_pane,
 8363                                                                    app_state: &self.app_state,
 8364                                                                    project: &self.project,
 8365                                                                    workspace: &self.weak_self,
 8366                                                                },
 8367                                                                window,
 8368                                                                cx,
 8369                                                            ))
 8370                                                            .when_some(paddings.1, |this, p| {
 8371                                                                this.child(p.border_l_1())
 8372                                                            }),
 8373                                                    )
 8374                                                    .children(self.render_dock(
 8375                                                        DockPosition::Bottom,
 8376                                                        &self.bottom_dock,
 8377                                                        window,
 8378                                                        cx,
 8379                                                    )),
 8380                                            )
 8381
 8382                                            .children(self.render_dock(
 8383                                                DockPosition::Right,
 8384                                                &self.right_dock,
 8385                                                window,
 8386                                                cx,
 8387                                            )),
 8388                                    }
 8389                                })
 8390                                .children(self.zoomed.as_ref().and_then(|view| {
 8391                                    let zoomed_view = view.upgrade()?;
 8392                                    let div = div()
 8393                                        .occlude()
 8394                                        .absolute()
 8395                                        .overflow_hidden()
 8396                                        .border_color(colors.border)
 8397                                        .bg(colors.background)
 8398                                        .child(zoomed_view)
 8399                                        .inset_0()
 8400                                        .shadow_lg();
 8401
 8402                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8403                                       return Some(div);
 8404                                    }
 8405
 8406                                    Some(match self.zoomed_position {
 8407                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8408                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8409                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8410                                        None => {
 8411                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8412                                        }
 8413                                    })
 8414                                }))
 8415                                .children(self.render_notifications(window, cx)),
 8416                        )
 8417                        .when(self.status_bar_visible(cx), |parent| {
 8418                            parent.child(self.status_bar.clone())
 8419                        })
 8420                        .child(self.toast_layer.clone()),
 8421                )
 8422    }
 8423}
 8424
 8425impl WorkspaceStore {
 8426    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8427        Self {
 8428            workspaces: Default::default(),
 8429            _subscriptions: vec![
 8430                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8431                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8432            ],
 8433            client,
 8434        }
 8435    }
 8436
 8437    pub fn update_followers(
 8438        &self,
 8439        project_id: Option<u64>,
 8440        update: proto::update_followers::Variant,
 8441        cx: &App,
 8442    ) -> Option<()> {
 8443        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8444        let room_id = active_call.0.room_id(cx)?;
 8445        self.client
 8446            .send(proto::UpdateFollowers {
 8447                room_id,
 8448                project_id,
 8449                variant: Some(update),
 8450            })
 8451            .log_err()
 8452    }
 8453
 8454    pub async fn handle_follow(
 8455        this: Entity<Self>,
 8456        envelope: TypedEnvelope<proto::Follow>,
 8457        mut cx: AsyncApp,
 8458    ) -> Result<proto::FollowResponse> {
 8459        this.update(&mut cx, |this, cx| {
 8460            let follower = Follower {
 8461                project_id: envelope.payload.project_id,
 8462                peer_id: envelope.original_sender_id()?,
 8463            };
 8464
 8465            let mut response = proto::FollowResponse::default();
 8466
 8467            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8468                let Some(workspace) = weak_workspace.upgrade() else {
 8469                    return false;
 8470                };
 8471                window_handle
 8472                    .update(cx, |_, window, cx| {
 8473                        workspace.update(cx, |workspace, cx| {
 8474                            let handler_response =
 8475                                workspace.handle_follow(follower.project_id, window, cx);
 8476                            if let Some(active_view) = handler_response.active_view
 8477                                && workspace.project.read(cx).remote_id() == follower.project_id
 8478                            {
 8479                                response.active_view = Some(active_view)
 8480                            }
 8481                        });
 8482                    })
 8483                    .is_ok()
 8484            });
 8485
 8486            Ok(response)
 8487        })
 8488    }
 8489
 8490    async fn handle_update_followers(
 8491        this: Entity<Self>,
 8492        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8493        mut cx: AsyncApp,
 8494    ) -> Result<()> {
 8495        let leader_id = envelope.original_sender_id()?;
 8496        let update = envelope.payload;
 8497
 8498        this.update(&mut cx, |this, cx| {
 8499            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8500                let Some(workspace) = weak_workspace.upgrade() else {
 8501                    return false;
 8502                };
 8503                window_handle
 8504                    .update(cx, |_, window, cx| {
 8505                        workspace.update(cx, |workspace, cx| {
 8506                            let project_id = workspace.project.read(cx).remote_id();
 8507                            if update.project_id != project_id && update.project_id.is_some() {
 8508                                return;
 8509                            }
 8510                            workspace.handle_update_followers(
 8511                                leader_id,
 8512                                update.clone(),
 8513                                window,
 8514                                cx,
 8515                            );
 8516                        });
 8517                    })
 8518                    .is_ok()
 8519            });
 8520            Ok(())
 8521        })
 8522    }
 8523
 8524    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8525        self.workspaces.iter().map(|(_, weak)| weak)
 8526    }
 8527
 8528    pub fn workspaces_with_windows(
 8529        &self,
 8530    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8531        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8532    }
 8533}
 8534
 8535impl ViewId {
 8536    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8537        Ok(Self {
 8538            creator: message
 8539                .creator
 8540                .map(CollaboratorId::PeerId)
 8541                .context("creator is missing")?,
 8542            id: message.id,
 8543        })
 8544    }
 8545
 8546    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8547        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8548            Some(proto::ViewId {
 8549                creator: Some(peer_id),
 8550                id: self.id,
 8551            })
 8552        } else {
 8553            None
 8554        }
 8555    }
 8556}
 8557
 8558impl FollowerState {
 8559    fn pane(&self) -> &Entity<Pane> {
 8560        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8561    }
 8562}
 8563
 8564pub trait WorkspaceHandle {
 8565    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8566}
 8567
 8568impl WorkspaceHandle for Entity<Workspace> {
 8569    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8570        self.read(cx)
 8571            .worktrees(cx)
 8572            .flat_map(|worktree| {
 8573                let worktree_id = worktree.read(cx).id();
 8574                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8575                    worktree_id,
 8576                    path: f.path.clone(),
 8577                })
 8578            })
 8579            .collect::<Vec<_>>()
 8580    }
 8581}
 8582
 8583pub async fn last_opened_workspace_location(
 8584    db: &WorkspaceDb,
 8585    fs: &dyn fs::Fs,
 8586) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8587    db.last_workspace(fs)
 8588        .await
 8589        .log_err()
 8590        .flatten()
 8591        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8592}
 8593
 8594pub async fn last_session_workspace_locations(
 8595    db: &WorkspaceDb,
 8596    last_session_id: &str,
 8597    last_session_window_stack: Option<Vec<WindowId>>,
 8598    fs: &dyn fs::Fs,
 8599) -> Option<Vec<SessionWorkspace>> {
 8600    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8601        .await
 8602        .log_err()
 8603}
 8604
 8605pub struct MultiWorkspaceRestoreResult {
 8606    pub window_handle: WindowHandle<MultiWorkspace>,
 8607    pub errors: Vec<anyhow::Error>,
 8608}
 8609
 8610pub async fn restore_multiworkspace(
 8611    multi_workspace: SerializedMultiWorkspace,
 8612    app_state: Arc<AppState>,
 8613    cx: &mut AsyncApp,
 8614) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8615    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8616    let mut group_iter = workspaces.into_iter();
 8617    let first = group_iter
 8618        .next()
 8619        .context("window group must not be empty")?;
 8620
 8621    let window_handle = if first.paths.is_empty() {
 8622        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8623            .await?
 8624    } else {
 8625        let OpenResult { window, .. } = cx
 8626            .update(|cx| {
 8627                Workspace::new_local(
 8628                    first.paths.paths().to_vec(),
 8629                    app_state.clone(),
 8630                    None,
 8631                    None,
 8632                    None,
 8633                    OpenMode::Activate,
 8634                    cx,
 8635                )
 8636            })
 8637            .await?;
 8638        window
 8639    };
 8640
 8641    let mut errors = Vec::new();
 8642
 8643    for session_workspace in group_iter {
 8644        let error = if session_workspace.paths.is_empty() {
 8645            cx.update(|cx| {
 8646                open_workspace_by_id(
 8647                    session_workspace.workspace_id,
 8648                    app_state.clone(),
 8649                    Some(window_handle),
 8650                    cx,
 8651                )
 8652            })
 8653            .await
 8654            .err()
 8655        } else {
 8656            cx.update(|cx| {
 8657                Workspace::new_local(
 8658                    session_workspace.paths.paths().to_vec(),
 8659                    app_state.clone(),
 8660                    Some(window_handle),
 8661                    None,
 8662                    None,
 8663                    OpenMode::Add,
 8664                    cx,
 8665                )
 8666            })
 8667            .await
 8668            .err()
 8669        };
 8670
 8671        if let Some(error) = error {
 8672            errors.push(error);
 8673        }
 8674    }
 8675
 8676    if let Some(target_id) = state.active_workspace_id {
 8677        window_handle
 8678            .update(cx, |multi_workspace, window, cx| {
 8679                let target_index = multi_workspace
 8680                    .workspaces()
 8681                    .iter()
 8682                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8683                let index = target_index.unwrap_or(0);
 8684                if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
 8685                    multi_workspace.activate(workspace, window, cx);
 8686                }
 8687            })
 8688            .ok();
 8689    } else {
 8690        window_handle
 8691            .update(cx, |multi_workspace, window, cx| {
 8692                if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
 8693                    multi_workspace.activate(workspace, window, cx);
 8694                }
 8695            })
 8696            .ok();
 8697    }
 8698
 8699    if state.sidebar_open {
 8700        window_handle
 8701            .update(cx, |multi_workspace, _, cx| {
 8702                multi_workspace.open_sidebar(cx);
 8703            })
 8704            .ok();
 8705    }
 8706
 8707    if let Some(sidebar_state) = &state.sidebar_state {
 8708        let sidebar_state = sidebar_state.clone();
 8709        window_handle
 8710            .update(cx, |multi_workspace, window, cx| {
 8711                if let Some(sidebar) = multi_workspace.sidebar() {
 8712                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8713                }
 8714                multi_workspace.serialize(cx);
 8715            })
 8716            .ok();
 8717    }
 8718
 8719    window_handle
 8720        .update(cx, |_, window, _cx| {
 8721            window.activate_window();
 8722        })
 8723        .ok();
 8724
 8725    Ok(MultiWorkspaceRestoreResult {
 8726        window_handle,
 8727        errors,
 8728    })
 8729}
 8730
 8731actions!(
 8732    collab,
 8733    [
 8734        /// Opens the channel notes for the current call.
 8735        ///
 8736        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8737        /// channel in the collab panel.
 8738        ///
 8739        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8740        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8741        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8742        OpenChannelNotes,
 8743        /// Mutes your microphone.
 8744        Mute,
 8745        /// Deafens yourself (mute both microphone and speakers).
 8746        Deafen,
 8747        /// Leaves the current call.
 8748        LeaveCall,
 8749        /// Shares the current project with collaborators.
 8750        ShareProject,
 8751        /// Shares your screen with collaborators.
 8752        ScreenShare,
 8753        /// Copies the current room name and session id for debugging purposes.
 8754        CopyRoomId,
 8755    ]
 8756);
 8757
 8758/// Opens the channel notes for a specific channel by its ID.
 8759#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8760#[action(namespace = collab)]
 8761#[serde(deny_unknown_fields)]
 8762pub struct OpenChannelNotesById {
 8763    pub channel_id: u64,
 8764}
 8765
 8766actions!(
 8767    zed,
 8768    [
 8769        /// Opens the Zed log file.
 8770        OpenLog,
 8771        /// Reveals the Zed log file in the system file manager.
 8772        RevealLogInFileManager
 8773    ]
 8774);
 8775
 8776async fn join_channel_internal(
 8777    channel_id: ChannelId,
 8778    app_state: &Arc<AppState>,
 8779    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8780    requesting_workspace: Option<WeakEntity<Workspace>>,
 8781    active_call: &dyn AnyActiveCall,
 8782    cx: &mut AsyncApp,
 8783) -> Result<bool> {
 8784    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8785        if !active_call.is_in_room(cx) {
 8786            return (false, false);
 8787        }
 8788
 8789        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8790        let should_prompt = active_call.is_sharing_project(cx)
 8791            && active_call.has_remote_participants(cx)
 8792            && !already_in_channel;
 8793        (should_prompt, already_in_channel)
 8794    });
 8795
 8796    if already_in_channel {
 8797        let task = cx.update(|cx| {
 8798            if let Some((project, host)) = active_call.most_active_project(cx) {
 8799                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8800            } else {
 8801                None
 8802            }
 8803        });
 8804        if let Some(task) = task {
 8805            task.await?;
 8806        }
 8807        return anyhow::Ok(true);
 8808    }
 8809
 8810    if should_prompt {
 8811        if let Some(multi_workspace) = requesting_window {
 8812            let answer = multi_workspace
 8813                .update(cx, |_, window, cx| {
 8814                    window.prompt(
 8815                        PromptLevel::Warning,
 8816                        "Do you want to switch channels?",
 8817                        Some("Leaving this call will unshare your current project."),
 8818                        &["Yes, Join Channel", "Cancel"],
 8819                        cx,
 8820                    )
 8821                })?
 8822                .await;
 8823
 8824            if answer == Ok(1) {
 8825                return Ok(false);
 8826            }
 8827        } else {
 8828            return Ok(false);
 8829        }
 8830    }
 8831
 8832    let client = cx.update(|cx| active_call.client(cx));
 8833
 8834    let mut client_status = client.status();
 8835
 8836    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8837    'outer: loop {
 8838        let Some(status) = client_status.recv().await else {
 8839            anyhow::bail!("error connecting");
 8840        };
 8841
 8842        match status {
 8843            Status::Connecting
 8844            | Status::Authenticating
 8845            | Status::Authenticated
 8846            | Status::Reconnecting
 8847            | Status::Reauthenticating
 8848            | Status::Reauthenticated => continue,
 8849            Status::Connected { .. } => break 'outer,
 8850            Status::SignedOut | Status::AuthenticationError => {
 8851                return Err(ErrorCode::SignedOut.into());
 8852            }
 8853            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8854            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8855                return Err(ErrorCode::Disconnected.into());
 8856            }
 8857        }
 8858    }
 8859
 8860    let joined = cx
 8861        .update(|cx| active_call.join_channel(channel_id, cx))
 8862        .await?;
 8863
 8864    if !joined {
 8865        return anyhow::Ok(true);
 8866    }
 8867
 8868    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8869
 8870    let task = cx.update(|cx| {
 8871        if let Some((project, host)) = active_call.most_active_project(cx) {
 8872            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8873        }
 8874
 8875        // If you are the first to join a channel, see if you should share your project.
 8876        if !active_call.has_remote_participants(cx)
 8877            && !active_call.local_participant_is_guest(cx)
 8878            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8879        {
 8880            let project = workspace.update(cx, |workspace, cx| {
 8881                let project = workspace.project.read(cx);
 8882
 8883                if !active_call.share_on_join(cx) {
 8884                    return None;
 8885                }
 8886
 8887                if (project.is_local() || project.is_via_remote_server())
 8888                    && project.visible_worktrees(cx).any(|tree| {
 8889                        tree.read(cx)
 8890                            .root_entry()
 8891                            .is_some_and(|entry| entry.is_dir())
 8892                    })
 8893                {
 8894                    Some(workspace.project.clone())
 8895                } else {
 8896                    None
 8897                }
 8898            });
 8899            if let Some(project) = project {
 8900                let share_task = active_call.share_project(project, cx);
 8901                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8902                    share_task.await?;
 8903                    Ok(())
 8904                }));
 8905            }
 8906        }
 8907
 8908        None
 8909    });
 8910    if let Some(task) = task {
 8911        task.await?;
 8912        return anyhow::Ok(true);
 8913    }
 8914    anyhow::Ok(false)
 8915}
 8916
 8917pub fn join_channel(
 8918    channel_id: ChannelId,
 8919    app_state: Arc<AppState>,
 8920    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8921    requesting_workspace: Option<WeakEntity<Workspace>>,
 8922    cx: &mut App,
 8923) -> Task<Result<()>> {
 8924    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8925    cx.spawn(async move |cx| {
 8926        let result = join_channel_internal(
 8927            channel_id,
 8928            &app_state,
 8929            requesting_window,
 8930            requesting_workspace,
 8931            &*active_call.0,
 8932            cx,
 8933        )
 8934        .await;
 8935
 8936        // join channel succeeded, and opened a window
 8937        if matches!(result, Ok(true)) {
 8938            return anyhow::Ok(());
 8939        }
 8940
 8941        // find an existing workspace to focus and show call controls
 8942        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8943        if active_window.is_none() {
 8944            // no open workspaces, make one to show the error in (blergh)
 8945            let OpenResult {
 8946                window: window_handle,
 8947                ..
 8948            } = cx
 8949                .update(|cx| {
 8950                    Workspace::new_local(
 8951                        vec![],
 8952                        app_state.clone(),
 8953                        requesting_window,
 8954                        None,
 8955                        None,
 8956                        OpenMode::Activate,
 8957                        cx,
 8958                    )
 8959                })
 8960                .await?;
 8961
 8962            window_handle
 8963                .update(cx, |_, window, _cx| {
 8964                    window.activate_window();
 8965                })
 8966                .ok();
 8967
 8968            if result.is_ok() {
 8969                cx.update(|cx| {
 8970                    cx.dispatch_action(&OpenChannelNotes);
 8971                });
 8972            }
 8973
 8974            active_window = Some(window_handle);
 8975        }
 8976
 8977        if let Err(err) = result {
 8978            log::error!("failed to join channel: {}", err);
 8979            if let Some(active_window) = active_window {
 8980                active_window
 8981                    .update(cx, |_, window, cx| {
 8982                        let detail: SharedString = match err.error_code() {
 8983                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8984                            ErrorCode::UpgradeRequired => concat!(
 8985                                "Your are running an unsupported version of Zed. ",
 8986                                "Please update to continue."
 8987                            )
 8988                            .into(),
 8989                            ErrorCode::NoSuchChannel => concat!(
 8990                                "No matching channel was found. ",
 8991                                "Please check the link and try again."
 8992                            )
 8993                            .into(),
 8994                            ErrorCode::Forbidden => concat!(
 8995                                "This channel is private, and you do not have access. ",
 8996                                "Please ask someone to add you and try again."
 8997                            )
 8998                            .into(),
 8999                            ErrorCode::Disconnected => {
 9000                                "Please check your internet connection and try again.".into()
 9001                            }
 9002                            _ => format!("{}\n\nPlease try again.", err).into(),
 9003                        };
 9004                        window.prompt(
 9005                            PromptLevel::Critical,
 9006                            "Failed to join channel",
 9007                            Some(&detail),
 9008                            &["Ok"],
 9009                            cx,
 9010                        )
 9011                    })?
 9012                    .await
 9013                    .ok();
 9014            }
 9015        }
 9016
 9017        // return ok, we showed the error to the user.
 9018        anyhow::Ok(())
 9019    })
 9020}
 9021
 9022pub async fn get_any_active_multi_workspace(
 9023    app_state: Arc<AppState>,
 9024    mut cx: AsyncApp,
 9025) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9026    // find an existing workspace to focus and show call controls
 9027    let active_window = activate_any_workspace_window(&mut cx);
 9028    if active_window.is_none() {
 9029        cx.update(|cx| {
 9030            Workspace::new_local(
 9031                vec![],
 9032                app_state.clone(),
 9033                None,
 9034                None,
 9035                None,
 9036                OpenMode::Activate,
 9037                cx,
 9038            )
 9039        })
 9040        .await?;
 9041    }
 9042    activate_any_workspace_window(&mut cx).context("could not open zed")
 9043}
 9044
 9045fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9046    cx.update(|cx| {
 9047        if let Some(workspace_window) = cx
 9048            .active_window()
 9049            .and_then(|window| window.downcast::<MultiWorkspace>())
 9050        {
 9051            return Some(workspace_window);
 9052        }
 9053
 9054        for window in cx.windows() {
 9055            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9056                workspace_window
 9057                    .update(cx, |_, window, _| window.activate_window())
 9058                    .ok();
 9059                return Some(workspace_window);
 9060            }
 9061        }
 9062        None
 9063    })
 9064}
 9065
 9066pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9067    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9068}
 9069
 9070pub fn workspace_windows_for_location(
 9071    serialized_location: &SerializedWorkspaceLocation,
 9072    cx: &App,
 9073) -> Vec<WindowHandle<MultiWorkspace>> {
 9074    cx.windows()
 9075        .into_iter()
 9076        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9077        .filter(|multi_workspace| {
 9078            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9079                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9080                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9081                }
 9082                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9083                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9084                    a.distro_name == b.distro_name
 9085                }
 9086                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9087                    a.container_id == b.container_id
 9088                }
 9089                #[cfg(any(test, feature = "test-support"))]
 9090                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9091                    a.id == b.id
 9092                }
 9093                _ => false,
 9094            };
 9095
 9096            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9097                multi_workspace.workspaces().iter().any(|workspace| {
 9098                    match workspace.read(cx).workspace_location(cx) {
 9099                        WorkspaceLocation::Location(location, _) => {
 9100                            match (&location, serialized_location) {
 9101                                (
 9102                                    SerializedWorkspaceLocation::Local,
 9103                                    SerializedWorkspaceLocation::Local,
 9104                                ) => true,
 9105                                (
 9106                                    SerializedWorkspaceLocation::Remote(a),
 9107                                    SerializedWorkspaceLocation::Remote(b),
 9108                                ) => same_host(a, b),
 9109                                _ => false,
 9110                            }
 9111                        }
 9112                        _ => false,
 9113                    }
 9114                })
 9115            })
 9116        })
 9117        .collect()
 9118}
 9119
 9120pub async fn find_existing_workspace(
 9121    abs_paths: &[PathBuf],
 9122    open_options: &OpenOptions,
 9123    location: &SerializedWorkspaceLocation,
 9124    cx: &mut AsyncApp,
 9125) -> (
 9126    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9127    OpenVisible,
 9128) {
 9129    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9130    let mut open_visible = OpenVisible::All;
 9131    let mut best_match = None;
 9132
 9133    if open_options.open_new_workspace != Some(true) {
 9134        cx.update(|cx| {
 9135            for window in workspace_windows_for_location(location, cx) {
 9136                if let Ok(multi_workspace) = window.read(cx) {
 9137                    for workspace in multi_workspace.workspaces() {
 9138                        let project = workspace.read(cx).project.read(cx);
 9139                        let m = project.visibility_for_paths(
 9140                            abs_paths,
 9141                            open_options.open_new_workspace == None,
 9142                            cx,
 9143                        );
 9144                        if m > best_match {
 9145                            existing = Some((window, workspace.clone()));
 9146                            best_match = m;
 9147                        } else if best_match.is_none()
 9148                            && open_options.open_new_workspace == Some(false)
 9149                        {
 9150                            existing = Some((window, workspace.clone()))
 9151                        }
 9152                    }
 9153                }
 9154            }
 9155        });
 9156
 9157        let all_paths_are_files = existing
 9158            .as_ref()
 9159            .and_then(|(_, target_workspace)| {
 9160                cx.update(|cx| {
 9161                    let workspace = target_workspace.read(cx);
 9162                    let project = workspace.project.read(cx);
 9163                    let path_style = workspace.path_style(cx);
 9164                    Some(!abs_paths.iter().any(|path| {
 9165                        let path = util::paths::SanitizedPath::new(path);
 9166                        project.worktrees(cx).any(|worktree| {
 9167                            let worktree = worktree.read(cx);
 9168                            let abs_path = worktree.abs_path();
 9169                            path_style
 9170                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9171                                .and_then(|rel| worktree.entry_for_path(&rel))
 9172                                .is_some_and(|e| e.is_dir())
 9173                        })
 9174                    }))
 9175                })
 9176            })
 9177            .unwrap_or(false);
 9178
 9179        if open_options.open_new_workspace.is_none()
 9180            && existing.is_some()
 9181            && open_options.wait
 9182            && all_paths_are_files
 9183        {
 9184            cx.update(|cx| {
 9185                let windows = workspace_windows_for_location(location, cx);
 9186                let window = cx
 9187                    .active_window()
 9188                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9189                    .filter(|window| windows.contains(window))
 9190                    .or_else(|| windows.into_iter().next());
 9191                if let Some(window) = window {
 9192                    if let Ok(multi_workspace) = window.read(cx) {
 9193                        let active_workspace = multi_workspace.workspace().clone();
 9194                        existing = Some((window, active_workspace));
 9195                        open_visible = OpenVisible::None;
 9196                    }
 9197                }
 9198            });
 9199        }
 9200    }
 9201    (existing, open_visible)
 9202}
 9203
 9204#[derive(Default, Clone)]
 9205pub struct OpenOptions {
 9206    pub visible: Option<OpenVisible>,
 9207    pub focus: Option<bool>,
 9208    pub open_new_workspace: Option<bool>,
 9209    pub wait: bool,
 9210    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9211    pub open_mode: OpenMode,
 9212    pub env: Option<HashMap<String, String>>,
 9213}
 9214
 9215/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9216/// or [`Workspace::open_workspace_for_paths`].
 9217pub struct OpenResult {
 9218    pub window: WindowHandle<MultiWorkspace>,
 9219    pub workspace: Entity<Workspace>,
 9220    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9221}
 9222
 9223/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9224pub fn open_workspace_by_id(
 9225    workspace_id: WorkspaceId,
 9226    app_state: Arc<AppState>,
 9227    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9228    cx: &mut App,
 9229) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9230    let project_handle = Project::local(
 9231        app_state.client.clone(),
 9232        app_state.node_runtime.clone(),
 9233        app_state.user_store.clone(),
 9234        app_state.languages.clone(),
 9235        app_state.fs.clone(),
 9236        None,
 9237        project::LocalProjectFlags {
 9238            init_worktree_trust: true,
 9239            ..project::LocalProjectFlags::default()
 9240        },
 9241        cx,
 9242    );
 9243
 9244    let db = WorkspaceDb::global(cx);
 9245    let kvp = db::kvp::KeyValueStore::global(cx);
 9246    cx.spawn(async move |cx| {
 9247        let serialized_workspace = db
 9248            .workspace_for_id(workspace_id)
 9249            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9250
 9251        let centered_layout = serialized_workspace.centered_layout;
 9252
 9253        let (window, workspace) = if let Some(window) = requesting_window {
 9254            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9255                let workspace = cx.new(|cx| {
 9256                    let mut workspace = Workspace::new(
 9257                        Some(workspace_id),
 9258                        project_handle.clone(),
 9259                        app_state.clone(),
 9260                        window,
 9261                        cx,
 9262                    );
 9263                    workspace.centered_layout = centered_layout;
 9264                    workspace
 9265                });
 9266                multi_workspace.add(workspace.clone(), &*window, cx);
 9267                workspace
 9268            })?;
 9269            (window, workspace)
 9270        } else {
 9271            let window_bounds_override = window_bounds_env_override();
 9272
 9273            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9274                (Some(WindowBounds::Windowed(bounds)), None)
 9275            } else if let Some(display) = serialized_workspace.display
 9276                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9277            {
 9278                (Some(bounds.0), Some(display))
 9279            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9280                (Some(bounds), Some(display))
 9281            } else {
 9282                (None, None)
 9283            };
 9284
 9285            let options = cx.update(|cx| {
 9286                let mut options = (app_state.build_window_options)(display, cx);
 9287                options.window_bounds = window_bounds;
 9288                options
 9289            });
 9290
 9291            let window = cx.open_window(options, {
 9292                let app_state = app_state.clone();
 9293                let project_handle = project_handle.clone();
 9294                move |window, cx| {
 9295                    let workspace = cx.new(|cx| {
 9296                        let mut workspace = Workspace::new(
 9297                            Some(workspace_id),
 9298                            project_handle,
 9299                            app_state,
 9300                            window,
 9301                            cx,
 9302                        );
 9303                        workspace.centered_layout = centered_layout;
 9304                        workspace
 9305                    });
 9306                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9307                }
 9308            })?;
 9309
 9310            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9311                multi_workspace.workspace().clone()
 9312            })?;
 9313
 9314            (window, workspace)
 9315        };
 9316
 9317        notify_if_database_failed(window, cx);
 9318
 9319        // Restore items from the serialized workspace
 9320        window
 9321            .update(cx, |_, window, cx| {
 9322                workspace.update(cx, |_workspace, cx| {
 9323                    open_items(Some(serialized_workspace), vec![], window, cx)
 9324                })
 9325            })?
 9326            .await?;
 9327
 9328        window.update(cx, |_, window, cx| {
 9329            workspace.update(cx, |workspace, cx| {
 9330                workspace.serialize_workspace(window, cx);
 9331            });
 9332        })?;
 9333
 9334        Ok(window)
 9335    })
 9336}
 9337
 9338#[allow(clippy::type_complexity)]
 9339pub fn open_paths(
 9340    abs_paths: &[PathBuf],
 9341    app_state: Arc<AppState>,
 9342    open_options: OpenOptions,
 9343    cx: &mut App,
 9344) -> Task<anyhow::Result<OpenResult>> {
 9345    let abs_paths = abs_paths.to_vec();
 9346    #[cfg(target_os = "windows")]
 9347    let wsl_path = abs_paths
 9348        .iter()
 9349        .find_map(|p| util::paths::WslPath::from_path(p));
 9350
 9351    cx.spawn(async move |cx| {
 9352        let (mut existing, mut open_visible) = find_existing_workspace(
 9353            &abs_paths,
 9354            &open_options,
 9355            &SerializedWorkspaceLocation::Local,
 9356            cx,
 9357        )
 9358        .await;
 9359
 9360        // Fallback: if no workspace contains the paths and all paths are files,
 9361        // prefer an existing local workspace window (active window first).
 9362        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9363            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9364            let all_metadatas = futures::future::join_all(all_paths)
 9365                .await
 9366                .into_iter()
 9367                .filter_map(|result| result.ok().flatten())
 9368                .collect::<Vec<_>>();
 9369
 9370            if all_metadatas.iter().all(|file| !file.is_dir) {
 9371                cx.update(|cx| {
 9372                    let windows = workspace_windows_for_location(
 9373                        &SerializedWorkspaceLocation::Local,
 9374                        cx,
 9375                    );
 9376                    let window = cx
 9377                        .active_window()
 9378                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9379                        .filter(|window| windows.contains(window))
 9380                        .or_else(|| windows.into_iter().next());
 9381                    if let Some(window) = window {
 9382                        if let Ok(multi_workspace) = window.read(cx) {
 9383                            let active_workspace = multi_workspace.workspace().clone();
 9384                            existing = Some((window, active_workspace));
 9385                            open_visible = OpenVisible::None;
 9386                        }
 9387                    }
 9388                });
 9389            }
 9390        }
 9391
 9392        let result = if let Some((existing, target_workspace)) = existing {
 9393            let open_task = existing
 9394                .update(cx, |multi_workspace, window, cx| {
 9395                    window.activate_window();
 9396                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9397                    target_workspace.update(cx, |workspace, cx| {
 9398                        workspace.open_paths(
 9399                            abs_paths,
 9400                            OpenOptions {
 9401                                visible: Some(open_visible),
 9402                                ..Default::default()
 9403                            },
 9404                            None,
 9405                            window,
 9406                            cx,
 9407                        )
 9408                    })
 9409                })?
 9410                .await;
 9411
 9412            _ = existing.update(cx, |multi_workspace, _, cx| {
 9413                let workspace = multi_workspace.workspace().clone();
 9414                workspace.update(cx, |workspace, cx| {
 9415                    for item in open_task.iter().flatten() {
 9416                        if let Err(e) = item {
 9417                            workspace.show_error(&e, cx);
 9418                        }
 9419                    }
 9420                });
 9421            });
 9422
 9423            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9424        } else {
 9425            let result = cx
 9426                .update(move |cx| {
 9427                    Workspace::new_local(
 9428                        abs_paths,
 9429                        app_state.clone(),
 9430                        open_options.requesting_window,
 9431                        open_options.env,
 9432                        None,
 9433                        open_options.open_mode,
 9434                        cx,
 9435                    )
 9436                })
 9437                .await;
 9438
 9439            if let Ok(ref result) = result {
 9440                result.window
 9441                    .update(cx, |_, window, _cx| {
 9442                        window.activate_window();
 9443                    })
 9444                    .log_err();
 9445            }
 9446
 9447            result
 9448        };
 9449
 9450        #[cfg(target_os = "windows")]
 9451        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9452            && let Ok(ref result) = result
 9453        {
 9454            result.window
 9455                .update(cx, move |multi_workspace, _window, cx| {
 9456                    struct OpenInWsl;
 9457                    let workspace = multi_workspace.workspace().clone();
 9458                    workspace.update(cx, |workspace, cx| {
 9459                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9460                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9461                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9462                            cx.new(move |cx| {
 9463                                MessageNotification::new(msg, cx)
 9464                                    .primary_message("Open in WSL")
 9465                                    .primary_icon(IconName::FolderOpen)
 9466                                    .primary_on_click(move |window, cx| {
 9467                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9468                                                distro: remote::WslConnectionOptions {
 9469                                                        distro_name: distro.clone(),
 9470                                                    user: None,
 9471                                                },
 9472                                                paths: vec![path.clone().into()],
 9473                                            }), cx)
 9474                                    })
 9475                            })
 9476                        });
 9477                    });
 9478                })
 9479                .unwrap();
 9480        };
 9481        result
 9482    })
 9483}
 9484
 9485pub fn open_new(
 9486    open_options: OpenOptions,
 9487    app_state: Arc<AppState>,
 9488    cx: &mut App,
 9489    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9490) -> Task<anyhow::Result<()>> {
 9491    let addition = open_options.open_mode;
 9492    let task = Workspace::new_local(
 9493        Vec::new(),
 9494        app_state,
 9495        open_options.requesting_window,
 9496        open_options.env,
 9497        Some(Box::new(init)),
 9498        addition,
 9499        cx,
 9500    );
 9501    cx.spawn(async move |cx| {
 9502        let OpenResult { window, .. } = task.await?;
 9503        window
 9504            .update(cx, |_, window, _cx| {
 9505                window.activate_window();
 9506            })
 9507            .ok();
 9508        Ok(())
 9509    })
 9510}
 9511
 9512pub fn create_and_open_local_file(
 9513    path: &'static Path,
 9514    window: &mut Window,
 9515    cx: &mut Context<Workspace>,
 9516    default_content: impl 'static + Send + FnOnce() -> Rope,
 9517) -> Task<Result<Box<dyn ItemHandle>>> {
 9518    cx.spawn_in(window, async move |workspace, cx| {
 9519        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9520        if !fs.is_file(path).await {
 9521            fs.create_file(path, Default::default()).await?;
 9522            fs.save(path, &default_content(), Default::default())
 9523                .await?;
 9524        }
 9525
 9526        workspace
 9527            .update_in(cx, |workspace, window, cx| {
 9528                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9529                    let path = workspace
 9530                        .project
 9531                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9532                    cx.spawn_in(window, async move |workspace, cx| {
 9533                        let path = path.await?;
 9534
 9535                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9536
 9537                        let mut items = workspace
 9538                            .update_in(cx, |workspace, window, cx| {
 9539                                workspace.open_paths(
 9540                                    vec![path.to_path_buf()],
 9541                                    OpenOptions {
 9542                                        visible: Some(OpenVisible::None),
 9543                                        ..Default::default()
 9544                                    },
 9545                                    None,
 9546                                    window,
 9547                                    cx,
 9548                                )
 9549                            })?
 9550                            .await;
 9551                        let item = items.pop().flatten();
 9552                        item.with_context(|| format!("path {path:?} is not a file"))?
 9553                    })
 9554                })
 9555            })?
 9556            .await?
 9557            .await
 9558    })
 9559}
 9560
 9561pub fn open_remote_project_with_new_connection(
 9562    window: WindowHandle<MultiWorkspace>,
 9563    remote_connection: Arc<dyn RemoteConnection>,
 9564    cancel_rx: oneshot::Receiver<()>,
 9565    delegate: Arc<dyn RemoteClientDelegate>,
 9566    app_state: Arc<AppState>,
 9567    paths: Vec<PathBuf>,
 9568    cx: &mut App,
 9569) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9570    cx.spawn(async move |cx| {
 9571        let (workspace_id, serialized_workspace) =
 9572            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9573                .await?;
 9574
 9575        let session = match cx
 9576            .update(|cx| {
 9577                remote::RemoteClient::new(
 9578                    ConnectionIdentifier::Workspace(workspace_id.0),
 9579                    remote_connection,
 9580                    cancel_rx,
 9581                    delegate,
 9582                    cx,
 9583                )
 9584            })
 9585            .await?
 9586        {
 9587            Some(result) => result,
 9588            None => return Ok(Vec::new()),
 9589        };
 9590
 9591        let project = cx.update(|cx| {
 9592            project::Project::remote(
 9593                session,
 9594                app_state.client.clone(),
 9595                app_state.node_runtime.clone(),
 9596                app_state.user_store.clone(),
 9597                app_state.languages.clone(),
 9598                app_state.fs.clone(),
 9599                true,
 9600                cx,
 9601            )
 9602        });
 9603
 9604        open_remote_project_inner(
 9605            project,
 9606            paths,
 9607            workspace_id,
 9608            serialized_workspace,
 9609            app_state,
 9610            window,
 9611            cx,
 9612        )
 9613        .await
 9614    })
 9615}
 9616
 9617pub fn open_remote_project_with_existing_connection(
 9618    connection_options: RemoteConnectionOptions,
 9619    project: Entity<Project>,
 9620    paths: Vec<PathBuf>,
 9621    app_state: Arc<AppState>,
 9622    window: WindowHandle<MultiWorkspace>,
 9623    cx: &mut AsyncApp,
 9624) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9625    cx.spawn(async move |cx| {
 9626        let (workspace_id, serialized_workspace) =
 9627            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9628
 9629        open_remote_project_inner(
 9630            project,
 9631            paths,
 9632            workspace_id,
 9633            serialized_workspace,
 9634            app_state,
 9635            window,
 9636            cx,
 9637        )
 9638        .await
 9639    })
 9640}
 9641
 9642async fn open_remote_project_inner(
 9643    project: Entity<Project>,
 9644    paths: Vec<PathBuf>,
 9645    workspace_id: WorkspaceId,
 9646    serialized_workspace: Option<SerializedWorkspace>,
 9647    app_state: Arc<AppState>,
 9648    window: WindowHandle<MultiWorkspace>,
 9649    cx: &mut AsyncApp,
 9650) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9651    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9652    let toolchains = db.toolchains(workspace_id).await?;
 9653    for (toolchain, worktree_path, path) in toolchains {
 9654        project
 9655            .update(cx, |this, cx| {
 9656                let Some(worktree_id) =
 9657                    this.find_worktree(&worktree_path, cx)
 9658                        .and_then(|(worktree, rel_path)| {
 9659                            if rel_path.is_empty() {
 9660                                Some(worktree.read(cx).id())
 9661                            } else {
 9662                                None
 9663                            }
 9664                        })
 9665                else {
 9666                    return Task::ready(None);
 9667                };
 9668
 9669                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9670            })
 9671            .await;
 9672    }
 9673    let mut project_paths_to_open = vec![];
 9674    let mut project_path_errors = vec![];
 9675
 9676    for path in paths {
 9677        let result = cx
 9678            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9679            .await;
 9680        match result {
 9681            Ok((_, project_path)) => {
 9682                project_paths_to_open.push((path.clone(), Some(project_path)));
 9683            }
 9684            Err(error) => {
 9685                project_path_errors.push(error);
 9686            }
 9687        };
 9688    }
 9689
 9690    if project_paths_to_open.is_empty() {
 9691        return Err(project_path_errors.pop().context("no paths given")?);
 9692    }
 9693
 9694    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9695        telemetry::event!("SSH Project Opened");
 9696
 9697        let new_workspace = cx.new(|cx| {
 9698            let mut workspace =
 9699                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9700            workspace.update_history(cx);
 9701
 9702            if let Some(ref serialized) = serialized_workspace {
 9703                workspace.centered_layout = serialized.centered_layout;
 9704            }
 9705
 9706            workspace
 9707        });
 9708
 9709        multi_workspace.activate(new_workspace.clone(), window, cx);
 9710        new_workspace
 9711    })?;
 9712
 9713    let items = window
 9714        .update(cx, |_, window, cx| {
 9715            window.activate_window();
 9716            workspace.update(cx, |_workspace, cx| {
 9717                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9718            })
 9719        })?
 9720        .await?;
 9721
 9722    workspace.update(cx, |workspace, cx| {
 9723        for error in project_path_errors {
 9724            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9725                if let Some(path) = error.error_tag("path") {
 9726                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9727                }
 9728            } else {
 9729                workspace.show_error(&error, cx)
 9730            }
 9731        }
 9732    });
 9733
 9734    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9735}
 9736
 9737fn deserialize_remote_project(
 9738    connection_options: RemoteConnectionOptions,
 9739    paths: Vec<PathBuf>,
 9740    cx: &AsyncApp,
 9741) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9742    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9743    cx.background_spawn(async move {
 9744        let remote_connection_id = db
 9745            .get_or_create_remote_connection(connection_options)
 9746            .await?;
 9747
 9748        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9749
 9750        let workspace_id = if let Some(workspace_id) =
 9751            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9752        {
 9753            workspace_id
 9754        } else {
 9755            db.next_id().await?
 9756        };
 9757
 9758        Ok((workspace_id, serialized_workspace))
 9759    })
 9760}
 9761
 9762pub fn join_in_room_project(
 9763    project_id: u64,
 9764    follow_user_id: u64,
 9765    app_state: Arc<AppState>,
 9766    cx: &mut App,
 9767) -> Task<Result<()>> {
 9768    let windows = cx.windows();
 9769    cx.spawn(async move |cx| {
 9770        let existing_window_and_workspace: Option<(
 9771            WindowHandle<MultiWorkspace>,
 9772            Entity<Workspace>,
 9773        )> = windows.into_iter().find_map(|window_handle| {
 9774            window_handle
 9775                .downcast::<MultiWorkspace>()
 9776                .and_then(|window_handle| {
 9777                    window_handle
 9778                        .update(cx, |multi_workspace, _window, cx| {
 9779                            for workspace in multi_workspace.workspaces() {
 9780                                if workspace.read(cx).project().read(cx).remote_id()
 9781                                    == Some(project_id)
 9782                                {
 9783                                    return Some((window_handle, workspace.clone()));
 9784                                }
 9785                            }
 9786                            None
 9787                        })
 9788                        .unwrap_or(None)
 9789                })
 9790        });
 9791
 9792        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9793            existing_window_and_workspace
 9794        {
 9795            existing_window
 9796                .update(cx, |multi_workspace, window, cx| {
 9797                    multi_workspace.activate(target_workspace, window, cx);
 9798                })
 9799                .ok();
 9800            existing_window
 9801        } else {
 9802            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9803            let project = cx
 9804                .update(|cx| {
 9805                    active_call.0.join_project(
 9806                        project_id,
 9807                        app_state.languages.clone(),
 9808                        app_state.fs.clone(),
 9809                        cx,
 9810                    )
 9811                })
 9812                .await?;
 9813
 9814            let window_bounds_override = window_bounds_env_override();
 9815            cx.update(|cx| {
 9816                let mut options = (app_state.build_window_options)(None, cx);
 9817                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9818                cx.open_window(options, |window, cx| {
 9819                    let workspace = cx.new(|cx| {
 9820                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9821                    });
 9822                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9823                })
 9824            })?
 9825        };
 9826
 9827        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9828            cx.activate(true);
 9829            window.activate_window();
 9830
 9831            // We set the active workspace above, so this is the correct workspace.
 9832            let workspace = multi_workspace.workspace().clone();
 9833            workspace.update(cx, |workspace, cx| {
 9834                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9835                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9836                    .or_else(|| {
 9837                        // If we couldn't follow the given user, follow the host instead.
 9838                        let collaborator = workspace
 9839                            .project()
 9840                            .read(cx)
 9841                            .collaborators()
 9842                            .values()
 9843                            .find(|collaborator| collaborator.is_host)?;
 9844                        Some(collaborator.peer_id)
 9845                    });
 9846
 9847                if let Some(follow_peer_id) = follow_peer_id {
 9848                    workspace.follow(follow_peer_id, window, cx);
 9849                }
 9850            });
 9851        })?;
 9852
 9853        anyhow::Ok(())
 9854    })
 9855}
 9856
 9857pub fn reload(cx: &mut App) {
 9858    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9859    let mut workspace_windows = cx
 9860        .windows()
 9861        .into_iter()
 9862        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9863        .collect::<Vec<_>>();
 9864
 9865    // If multiple windows have unsaved changes, and need a save prompt,
 9866    // prompt in the active window before switching to a different window.
 9867    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9868
 9869    let mut prompt = None;
 9870    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9871        prompt = window
 9872            .update(cx, |_, window, cx| {
 9873                window.prompt(
 9874                    PromptLevel::Info,
 9875                    "Are you sure you want to restart?",
 9876                    None,
 9877                    &["Restart", "Cancel"],
 9878                    cx,
 9879                )
 9880            })
 9881            .ok();
 9882    }
 9883
 9884    cx.spawn(async move |cx| {
 9885        if let Some(prompt) = prompt {
 9886            let answer = prompt.await?;
 9887            if answer != 0 {
 9888                return anyhow::Ok(());
 9889            }
 9890        }
 9891
 9892        // If the user cancels any save prompt, then keep the app open.
 9893        for window in workspace_windows {
 9894            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9895                let workspace = multi_workspace.workspace().clone();
 9896                workspace.update(cx, |workspace, cx| {
 9897                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9898                })
 9899            }) && !should_close.await?
 9900            {
 9901                return anyhow::Ok(());
 9902            }
 9903        }
 9904        cx.update(|cx| cx.restart());
 9905        anyhow::Ok(())
 9906    })
 9907    .detach_and_log_err(cx);
 9908}
 9909
 9910fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9911    let mut parts = value.split(',');
 9912    let x: usize = parts.next()?.parse().ok()?;
 9913    let y: usize = parts.next()?.parse().ok()?;
 9914    Some(point(px(x as f32), px(y as f32)))
 9915}
 9916
 9917fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9918    let mut parts = value.split(',');
 9919    let width: usize = parts.next()?.parse().ok()?;
 9920    let height: usize = parts.next()?.parse().ok()?;
 9921    Some(size(px(width as f32), px(height as f32)))
 9922}
 9923
 9924/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9925/// appropriate.
 9926///
 9927/// The `border_radius_tiling` parameter allows overriding which corners get
 9928/// rounded, independently of the actual window tiling state. This is used
 9929/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9930/// we want square corners on the left (so the sidebar appears flush with the
 9931/// window edge) but we still need the shadow padding for proper visual
 9932/// appearance. Unlike actual window tiling, this only affects border radius -
 9933/// not padding or shadows.
 9934pub fn client_side_decorations(
 9935    element: impl IntoElement,
 9936    window: &mut Window,
 9937    cx: &mut App,
 9938    border_radius_tiling: Tiling,
 9939) -> Stateful<Div> {
 9940    const BORDER_SIZE: Pixels = px(1.0);
 9941    let decorations = window.window_decorations();
 9942    let tiling = match decorations {
 9943        Decorations::Server => Tiling::default(),
 9944        Decorations::Client { tiling } => tiling,
 9945    };
 9946
 9947    match decorations {
 9948        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9949        Decorations::Server => window.set_client_inset(px(0.0)),
 9950    }
 9951
 9952    struct GlobalResizeEdge(ResizeEdge);
 9953    impl Global for GlobalResizeEdge {}
 9954
 9955    div()
 9956        .id("window-backdrop")
 9957        .bg(transparent_black())
 9958        .map(|div| match decorations {
 9959            Decorations::Server => div,
 9960            Decorations::Client { .. } => div
 9961                .when(
 9962                    !(tiling.top
 9963                        || tiling.right
 9964                        || border_radius_tiling.top
 9965                        || border_radius_tiling.right),
 9966                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9967                )
 9968                .when(
 9969                    !(tiling.top
 9970                        || tiling.left
 9971                        || border_radius_tiling.top
 9972                        || border_radius_tiling.left),
 9973                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9974                )
 9975                .when(
 9976                    !(tiling.bottom
 9977                        || tiling.right
 9978                        || border_radius_tiling.bottom
 9979                        || border_radius_tiling.right),
 9980                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9981                )
 9982                .when(
 9983                    !(tiling.bottom
 9984                        || tiling.left
 9985                        || border_radius_tiling.bottom
 9986                        || border_radius_tiling.left),
 9987                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9988                )
 9989                .when(!tiling.top, |div| {
 9990                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9991                })
 9992                .when(!tiling.bottom, |div| {
 9993                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9994                })
 9995                .when(!tiling.left, |div| {
 9996                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9997                })
 9998                .when(!tiling.right, |div| {
 9999                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10000                })
10001                .on_mouse_move(move |e, window, cx| {
10002                    let size = window.window_bounds().get_bounds().size;
10003                    let pos = e.position;
10004
10005                    let new_edge =
10006                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10007
10008                    let edge = cx.try_global::<GlobalResizeEdge>();
10009                    if new_edge != edge.map(|edge| edge.0) {
10010                        window
10011                            .window_handle()
10012                            .update(cx, |workspace, _, cx| {
10013                                cx.notify(workspace.entity_id());
10014                            })
10015                            .ok();
10016                    }
10017                })
10018                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10019                    let size = window.window_bounds().get_bounds().size;
10020                    let pos = e.position;
10021
10022                    let edge = match resize_edge(
10023                        pos,
10024                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10025                        size,
10026                        tiling,
10027                    ) {
10028                        Some(value) => value,
10029                        None => return,
10030                    };
10031
10032                    window.start_window_resize(edge);
10033                }),
10034        })
10035        .size_full()
10036        .child(
10037            div()
10038                .cursor(CursorStyle::Arrow)
10039                .map(|div| match decorations {
10040                    Decorations::Server => div,
10041                    Decorations::Client { .. } => div
10042                        .border_color(cx.theme().colors().border)
10043                        .when(
10044                            !(tiling.top
10045                                || tiling.right
10046                                || border_radius_tiling.top
10047                                || border_radius_tiling.right),
10048                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10049                        )
10050                        .when(
10051                            !(tiling.top
10052                                || tiling.left
10053                                || border_radius_tiling.top
10054                                || border_radius_tiling.left),
10055                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10056                        )
10057                        .when(
10058                            !(tiling.bottom
10059                                || tiling.right
10060                                || border_radius_tiling.bottom
10061                                || border_radius_tiling.right),
10062                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10063                        )
10064                        .when(
10065                            !(tiling.bottom
10066                                || tiling.left
10067                                || border_radius_tiling.bottom
10068                                || border_radius_tiling.left),
10069                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10070                        )
10071                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10072                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10073                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10074                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10075                        .when(!tiling.is_tiled(), |div| {
10076                            div.shadow(vec![gpui::BoxShadow {
10077                                color: Hsla {
10078                                    h: 0.,
10079                                    s: 0.,
10080                                    l: 0.,
10081                                    a: 0.4,
10082                                },
10083                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10084                                spread_radius: px(0.),
10085                                offset: point(px(0.0), px(0.0)),
10086                            }])
10087                        }),
10088                })
10089                .on_mouse_move(|_e, _, cx| {
10090                    cx.stop_propagation();
10091                })
10092                .size_full()
10093                .child(element),
10094        )
10095        .map(|div| match decorations {
10096            Decorations::Server => div,
10097            Decorations::Client { tiling, .. } => div.child(
10098                canvas(
10099                    |_bounds, window, _| {
10100                        window.insert_hitbox(
10101                            Bounds::new(
10102                                point(px(0.0), px(0.0)),
10103                                window.window_bounds().get_bounds().size,
10104                            ),
10105                            HitboxBehavior::Normal,
10106                        )
10107                    },
10108                    move |_bounds, hitbox, window, cx| {
10109                        let mouse = window.mouse_position();
10110                        let size = window.window_bounds().get_bounds().size;
10111                        let Some(edge) =
10112                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10113                        else {
10114                            return;
10115                        };
10116                        cx.set_global(GlobalResizeEdge(edge));
10117                        window.set_cursor_style(
10118                            match edge {
10119                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10120                                ResizeEdge::Left | ResizeEdge::Right => {
10121                                    CursorStyle::ResizeLeftRight
10122                                }
10123                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10124                                    CursorStyle::ResizeUpLeftDownRight
10125                                }
10126                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10127                                    CursorStyle::ResizeUpRightDownLeft
10128                                }
10129                            },
10130                            &hitbox,
10131                        );
10132                    },
10133                )
10134                .size_full()
10135                .absolute(),
10136            ),
10137        })
10138}
10139
10140fn resize_edge(
10141    pos: Point<Pixels>,
10142    shadow_size: Pixels,
10143    window_size: Size<Pixels>,
10144    tiling: Tiling,
10145) -> Option<ResizeEdge> {
10146    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10147    if bounds.contains(&pos) {
10148        return None;
10149    }
10150
10151    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10152    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10153    if !tiling.top && top_left_bounds.contains(&pos) {
10154        return Some(ResizeEdge::TopLeft);
10155    }
10156
10157    let top_right_bounds = Bounds::new(
10158        Point::new(window_size.width - corner_size.width, px(0.)),
10159        corner_size,
10160    );
10161    if !tiling.top && top_right_bounds.contains(&pos) {
10162        return Some(ResizeEdge::TopRight);
10163    }
10164
10165    let bottom_left_bounds = Bounds::new(
10166        Point::new(px(0.), window_size.height - corner_size.height),
10167        corner_size,
10168    );
10169    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10170        return Some(ResizeEdge::BottomLeft);
10171    }
10172
10173    let bottom_right_bounds = Bounds::new(
10174        Point::new(
10175            window_size.width - corner_size.width,
10176            window_size.height - corner_size.height,
10177        ),
10178        corner_size,
10179    );
10180    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10181        return Some(ResizeEdge::BottomRight);
10182    }
10183
10184    if !tiling.top && pos.y < shadow_size {
10185        Some(ResizeEdge::Top)
10186    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10187        Some(ResizeEdge::Bottom)
10188    } else if !tiling.left && pos.x < shadow_size {
10189        Some(ResizeEdge::Left)
10190    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10191        Some(ResizeEdge::Right)
10192    } else {
10193        None
10194    }
10195}
10196
10197fn join_pane_into_active(
10198    active_pane: &Entity<Pane>,
10199    pane: &Entity<Pane>,
10200    window: &mut Window,
10201    cx: &mut App,
10202) {
10203    if pane == active_pane {
10204    } else if pane.read(cx).items_len() == 0 {
10205        pane.update(cx, |_, cx| {
10206            cx.emit(pane::Event::Remove {
10207                focus_on_pane: None,
10208            });
10209        })
10210    } else {
10211        move_all_items(pane, active_pane, window, cx);
10212    }
10213}
10214
10215fn move_all_items(
10216    from_pane: &Entity<Pane>,
10217    to_pane: &Entity<Pane>,
10218    window: &mut Window,
10219    cx: &mut App,
10220) {
10221    let destination_is_different = from_pane != to_pane;
10222    let mut moved_items = 0;
10223    for (item_ix, item_handle) in from_pane
10224        .read(cx)
10225        .items()
10226        .enumerate()
10227        .map(|(ix, item)| (ix, item.clone()))
10228        .collect::<Vec<_>>()
10229    {
10230        let ix = item_ix - moved_items;
10231        if destination_is_different {
10232            // Close item from previous pane
10233            from_pane.update(cx, |source, cx| {
10234                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10235            });
10236            moved_items += 1;
10237        }
10238
10239        // This automatically removes duplicate items in the pane
10240        to_pane.update(cx, |destination, cx| {
10241            destination.add_item(item_handle, true, true, None, window, cx);
10242            window.focus(&destination.focus_handle(cx), cx)
10243        });
10244    }
10245}
10246
10247pub fn move_item(
10248    source: &Entity<Pane>,
10249    destination: &Entity<Pane>,
10250    item_id_to_move: EntityId,
10251    destination_index: usize,
10252    activate: bool,
10253    window: &mut Window,
10254    cx: &mut App,
10255) {
10256    let Some((item_ix, item_handle)) = source
10257        .read(cx)
10258        .items()
10259        .enumerate()
10260        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10261        .map(|(ix, item)| (ix, item.clone()))
10262    else {
10263        // Tab was closed during drag
10264        return;
10265    };
10266
10267    if source != destination {
10268        // Close item from previous pane
10269        source.update(cx, |source, cx| {
10270            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10271        });
10272    }
10273
10274    // This automatically removes duplicate items in the pane
10275    destination.update(cx, |destination, cx| {
10276        destination.add_item_inner(
10277            item_handle,
10278            activate,
10279            activate,
10280            activate,
10281            Some(destination_index),
10282            window,
10283            cx,
10284        );
10285        if activate {
10286            window.focus(&destination.focus_handle(cx), cx)
10287        }
10288    });
10289}
10290
10291pub fn move_active_item(
10292    source: &Entity<Pane>,
10293    destination: &Entity<Pane>,
10294    focus_destination: bool,
10295    close_if_empty: bool,
10296    window: &mut Window,
10297    cx: &mut App,
10298) {
10299    if source == destination {
10300        return;
10301    }
10302    let Some(active_item) = source.read(cx).active_item() else {
10303        return;
10304    };
10305    source.update(cx, |source_pane, cx| {
10306        let item_id = active_item.item_id();
10307        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10308        destination.update(cx, |target_pane, cx| {
10309            target_pane.add_item(
10310                active_item,
10311                focus_destination,
10312                focus_destination,
10313                Some(target_pane.items_len()),
10314                window,
10315                cx,
10316            );
10317        });
10318    });
10319}
10320
10321pub fn clone_active_item(
10322    workspace_id: Option<WorkspaceId>,
10323    source: &Entity<Pane>,
10324    destination: &Entity<Pane>,
10325    focus_destination: bool,
10326    window: &mut Window,
10327    cx: &mut App,
10328) {
10329    if source == destination {
10330        return;
10331    }
10332    let Some(active_item) = source.read(cx).active_item() else {
10333        return;
10334    };
10335    if !active_item.can_split(cx) {
10336        return;
10337    }
10338    let destination = destination.downgrade();
10339    let task = active_item.clone_on_split(workspace_id, window, cx);
10340    window
10341        .spawn(cx, async move |cx| {
10342            let Some(clone) = task.await else {
10343                return;
10344            };
10345            destination
10346                .update_in(cx, |target_pane, window, cx| {
10347                    target_pane.add_item(
10348                        clone,
10349                        focus_destination,
10350                        focus_destination,
10351                        Some(target_pane.items_len()),
10352                        window,
10353                        cx,
10354                    );
10355                })
10356                .log_err();
10357        })
10358        .detach();
10359}
10360
10361#[derive(Debug)]
10362pub struct WorkspacePosition {
10363    pub window_bounds: Option<WindowBounds>,
10364    pub display: Option<Uuid>,
10365    pub centered_layout: bool,
10366}
10367
10368pub fn remote_workspace_position_from_db(
10369    connection_options: RemoteConnectionOptions,
10370    paths_to_open: &[PathBuf],
10371    cx: &App,
10372) -> Task<Result<WorkspacePosition>> {
10373    let paths = paths_to_open.to_vec();
10374    let db = WorkspaceDb::global(cx);
10375    let kvp = db::kvp::KeyValueStore::global(cx);
10376
10377    cx.background_spawn(async move {
10378        let remote_connection_id = db
10379            .get_or_create_remote_connection(connection_options)
10380            .await
10381            .context("fetching serialized ssh project")?;
10382        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10383
10384        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10385            (Some(WindowBounds::Windowed(bounds)), None)
10386        } else {
10387            let restorable_bounds = serialized_workspace
10388                .as_ref()
10389                .and_then(|workspace| {
10390                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10391                })
10392                .or_else(|| persistence::read_default_window_bounds(&kvp));
10393
10394            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10395                (Some(serialized_bounds), Some(serialized_display))
10396            } else {
10397                (None, None)
10398            }
10399        };
10400
10401        let centered_layout = serialized_workspace
10402            .as_ref()
10403            .map(|w| w.centered_layout)
10404            .unwrap_or(false);
10405
10406        Ok(WorkspacePosition {
10407            window_bounds,
10408            display,
10409            centered_layout,
10410        })
10411    })
10412}
10413
10414pub fn with_active_or_new_workspace(
10415    cx: &mut App,
10416    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10417) {
10418    match cx
10419        .active_window()
10420        .and_then(|w| w.downcast::<MultiWorkspace>())
10421    {
10422        Some(multi_workspace) => {
10423            cx.defer(move |cx| {
10424                multi_workspace
10425                    .update(cx, |multi_workspace, window, cx| {
10426                        let workspace = multi_workspace.workspace().clone();
10427                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10428                    })
10429                    .log_err();
10430            });
10431        }
10432        None => {
10433            let app_state = AppState::global(cx);
10434            open_new(
10435                OpenOptions::default(),
10436                app_state,
10437                cx,
10438                move |workspace, window, cx| f(workspace, window, cx),
10439            )
10440            .detach_and_log_err(cx);
10441        }
10442    }
10443}
10444
10445/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10446/// key. This migration path only runs once per panel per workspace.
10447fn load_legacy_panel_size(
10448    panel_key: &str,
10449    dock_position: DockPosition,
10450    workspace: &Workspace,
10451    cx: &mut App,
10452) -> Option<Pixels> {
10453    #[derive(Deserialize)]
10454    struct LegacyPanelState {
10455        #[serde(default)]
10456        width: Option<Pixels>,
10457        #[serde(default)]
10458        height: Option<Pixels>,
10459    }
10460
10461    let workspace_id = workspace
10462        .database_id()
10463        .map(|id| i64::from(id).to_string())
10464        .or_else(|| workspace.session_id())?;
10465
10466    let legacy_key = match panel_key {
10467        "ProjectPanel" => {
10468            format!("{}-{:?}", "ProjectPanel", workspace_id)
10469        }
10470        "OutlinePanel" => {
10471            format!("{}-{:?}", "OutlinePanel", workspace_id)
10472        }
10473        "GitPanel" => {
10474            format!("{}-{:?}", "GitPanel", workspace_id)
10475        }
10476        "TerminalPanel" => {
10477            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10478        }
10479        _ => return None,
10480    };
10481
10482    let kvp = db::kvp::KeyValueStore::global(cx);
10483    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10484    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10485    let size = match dock_position {
10486        DockPosition::Bottom => state.height,
10487        DockPosition::Left | DockPosition::Right => state.width,
10488    }?;
10489
10490    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10491        .detach_and_log_err(cx);
10492
10493    Some(size)
10494}
10495
10496#[cfg(test)]
10497mod tests {
10498    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10499
10500    use super::*;
10501    use crate::{
10502        dock::{PanelEvent, test::TestPanel},
10503        item::{
10504            ItemBufferKind, ItemEvent,
10505            test::{TestItem, TestProjectItem},
10506        },
10507    };
10508    use fs::FakeFs;
10509    use gpui::{
10510        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10511        UpdateGlobal, VisualTestContext, px,
10512    };
10513    use project::{Project, ProjectEntryId};
10514    use serde_json::json;
10515    use settings::SettingsStore;
10516    use util::path;
10517    use util::rel_path::rel_path;
10518
10519    #[gpui::test]
10520    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10521        init_test(cx);
10522
10523        let fs = FakeFs::new(cx.executor());
10524        let project = Project::test(fs, [], cx).await;
10525        let (workspace, cx) =
10526            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10527
10528        // Adding an item with no ambiguity renders the tab without detail.
10529        let item1 = cx.new(|cx| {
10530            let mut item = TestItem::new(cx);
10531            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10532            item
10533        });
10534        workspace.update_in(cx, |workspace, window, cx| {
10535            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10536        });
10537        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10538
10539        // Adding an item that creates ambiguity increases the level of detail on
10540        // both tabs.
10541        let item2 = cx.new_window_entity(|_window, cx| {
10542            let mut item = TestItem::new(cx);
10543            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10544            item
10545        });
10546        workspace.update_in(cx, |workspace, window, cx| {
10547            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10548        });
10549        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10550        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10551
10552        // Adding an item that creates ambiguity increases the level of detail only
10553        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10554        // we stop at the highest detail available.
10555        let item3 = cx.new(|cx| {
10556            let mut item = TestItem::new(cx);
10557            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10558            item
10559        });
10560        workspace.update_in(cx, |workspace, window, cx| {
10561            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10562        });
10563        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10564        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10565        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10566    }
10567
10568    #[gpui::test]
10569    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10570        init_test(cx);
10571
10572        let fs = FakeFs::new(cx.executor());
10573        fs.insert_tree(
10574            "/root1",
10575            json!({
10576                "one.txt": "",
10577                "two.txt": "",
10578            }),
10579        )
10580        .await;
10581        fs.insert_tree(
10582            "/root2",
10583            json!({
10584                "three.txt": "",
10585            }),
10586        )
10587        .await;
10588
10589        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10590        let (workspace, cx) =
10591            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10592        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10593        let worktree_id = project.update(cx, |project, cx| {
10594            project.worktrees(cx).next().unwrap().read(cx).id()
10595        });
10596
10597        let item1 = cx.new(|cx| {
10598            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10599        });
10600        let item2 = cx.new(|cx| {
10601            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10602        });
10603
10604        // Add an item to an empty pane
10605        workspace.update_in(cx, |workspace, window, cx| {
10606            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10607        });
10608        project.update(cx, |project, cx| {
10609            assert_eq!(
10610                project.active_entry(),
10611                project
10612                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10613                    .map(|e| e.id)
10614            );
10615        });
10616        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10617
10618        // Add a second item to a non-empty pane
10619        workspace.update_in(cx, |workspace, window, cx| {
10620            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10621        });
10622        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10623        project.update(cx, |project, cx| {
10624            assert_eq!(
10625                project.active_entry(),
10626                project
10627                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10628                    .map(|e| e.id)
10629            );
10630        });
10631
10632        // Close the active item
10633        pane.update_in(cx, |pane, window, cx| {
10634            pane.close_active_item(&Default::default(), window, cx)
10635        })
10636        .await
10637        .unwrap();
10638        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10639        project.update(cx, |project, cx| {
10640            assert_eq!(
10641                project.active_entry(),
10642                project
10643                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10644                    .map(|e| e.id)
10645            );
10646        });
10647
10648        // Add a project folder
10649        project
10650            .update(cx, |project, cx| {
10651                project.find_or_create_worktree("root2", true, cx)
10652            })
10653            .await
10654            .unwrap();
10655        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10656
10657        // Remove a project folder
10658        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10659        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10660    }
10661
10662    #[gpui::test]
10663    async fn test_close_window(cx: &mut TestAppContext) {
10664        init_test(cx);
10665
10666        let fs = FakeFs::new(cx.executor());
10667        fs.insert_tree("/root", json!({ "one": "" })).await;
10668
10669        let project = Project::test(fs, ["root".as_ref()], cx).await;
10670        let (workspace, cx) =
10671            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10672
10673        // When there are no dirty items, there's nothing to do.
10674        let item1 = cx.new(TestItem::new);
10675        workspace.update_in(cx, |w, window, cx| {
10676            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10677        });
10678        let task = workspace.update_in(cx, |w, window, cx| {
10679            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10680        });
10681        assert!(task.await.unwrap());
10682
10683        // When there are dirty untitled items, prompt to save each one. If the user
10684        // cancels any prompt, then abort.
10685        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10686        let item3 = cx.new(|cx| {
10687            TestItem::new(cx)
10688                .with_dirty(true)
10689                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10690        });
10691        workspace.update_in(cx, |w, window, cx| {
10692            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10693            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10694        });
10695        let task = workspace.update_in(cx, |w, window, cx| {
10696            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10697        });
10698        cx.executor().run_until_parked();
10699        cx.simulate_prompt_answer("Cancel"); // cancel save all
10700        cx.executor().run_until_parked();
10701        assert!(!cx.has_pending_prompt());
10702        assert!(!task.await.unwrap());
10703    }
10704
10705    #[gpui::test]
10706    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10707        init_test(cx);
10708
10709        let fs = FakeFs::new(cx.executor());
10710        fs.insert_tree("/root", json!({ "one": "" })).await;
10711
10712        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10713        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10714        let multi_workspace_handle =
10715            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10716        cx.run_until_parked();
10717
10718        let workspace_a = multi_workspace_handle
10719            .read_with(cx, |mw, _| mw.workspace().clone())
10720            .unwrap();
10721
10722        let workspace_b = multi_workspace_handle
10723            .update(cx, |mw, window, cx| {
10724                mw.test_add_workspace(project_b, window, cx)
10725            })
10726            .unwrap();
10727
10728        // Activate workspace A
10729        multi_workspace_handle
10730            .update(cx, |mw, window, cx| {
10731                let workspace = mw.workspaces()[0].clone();
10732                mw.activate(workspace, window, cx);
10733            })
10734            .unwrap();
10735
10736        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10737
10738        // Workspace A has a clean item
10739        let item_a = cx.new(TestItem::new);
10740        workspace_a.update_in(cx, |w, window, cx| {
10741            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10742        });
10743
10744        // Workspace B has a dirty item
10745        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10746        workspace_b.update_in(cx, |w, window, cx| {
10747            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10748        });
10749
10750        // Verify workspace A is active
10751        multi_workspace_handle
10752            .read_with(cx, |mw, _| {
10753                assert_eq!(mw.active_workspace_index(), 0);
10754            })
10755            .unwrap();
10756
10757        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10758        multi_workspace_handle
10759            .update(cx, |mw, window, cx| {
10760                mw.close_window(&CloseWindow, window, cx);
10761            })
10762            .unwrap();
10763        cx.run_until_parked();
10764
10765        // Workspace B should now be active since it has dirty items that need attention
10766        multi_workspace_handle
10767            .read_with(cx, |mw, _| {
10768                assert_eq!(
10769                    mw.active_workspace_index(),
10770                    1,
10771                    "workspace B should be activated when it prompts"
10772                );
10773            })
10774            .unwrap();
10775
10776        // User cancels the save prompt from workspace B
10777        cx.simulate_prompt_answer("Cancel");
10778        cx.run_until_parked();
10779
10780        // Window should still exist because workspace B's close was cancelled
10781        assert!(
10782            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10783            "window should still exist after cancelling one workspace's close"
10784        );
10785    }
10786
10787    #[gpui::test]
10788    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10789        init_test(cx);
10790
10791        // Register TestItem as a serializable item
10792        cx.update(|cx| {
10793            register_serializable_item::<TestItem>(cx);
10794        });
10795
10796        let fs = FakeFs::new(cx.executor());
10797        fs.insert_tree("/root", json!({ "one": "" })).await;
10798
10799        let project = Project::test(fs, ["root".as_ref()], cx).await;
10800        let (workspace, cx) =
10801            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10802
10803        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10804        let item1 = cx.new(|cx| {
10805            TestItem::new(cx)
10806                .with_dirty(true)
10807                .with_serialize(|| Some(Task::ready(Ok(()))))
10808        });
10809        let item2 = cx.new(|cx| {
10810            TestItem::new(cx)
10811                .with_dirty(true)
10812                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10813                .with_serialize(|| Some(Task::ready(Ok(()))))
10814        });
10815        workspace.update_in(cx, |w, window, cx| {
10816            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10817            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10818        });
10819        let task = workspace.update_in(cx, |w, window, cx| {
10820            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10821        });
10822        assert!(task.await.unwrap());
10823    }
10824
10825    #[gpui::test]
10826    async fn test_close_pane_items(cx: &mut TestAppContext) {
10827        init_test(cx);
10828
10829        let fs = FakeFs::new(cx.executor());
10830
10831        let project = Project::test(fs, None, cx).await;
10832        let (workspace, cx) =
10833            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10834
10835        let item1 = cx.new(|cx| {
10836            TestItem::new(cx)
10837                .with_dirty(true)
10838                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10839        });
10840        let item2 = cx.new(|cx| {
10841            TestItem::new(cx)
10842                .with_dirty(true)
10843                .with_conflict(true)
10844                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10845        });
10846        let item3 = cx.new(|cx| {
10847            TestItem::new(cx)
10848                .with_dirty(true)
10849                .with_conflict(true)
10850                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10851        });
10852        let item4 = cx.new(|cx| {
10853            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10854                let project_item = TestProjectItem::new_untitled(cx);
10855                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10856                project_item
10857            }])
10858        });
10859        let pane = workspace.update_in(cx, |workspace, window, cx| {
10860            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10861            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10862            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10863            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10864            workspace.active_pane().clone()
10865        });
10866
10867        let close_items = pane.update_in(cx, |pane, window, cx| {
10868            pane.activate_item(1, true, true, window, cx);
10869            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10870            let item1_id = item1.item_id();
10871            let item3_id = item3.item_id();
10872            let item4_id = item4.item_id();
10873            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10874                [item1_id, item3_id, item4_id].contains(&id)
10875            })
10876        });
10877        cx.executor().run_until_parked();
10878
10879        assert!(cx.has_pending_prompt());
10880        cx.simulate_prompt_answer("Save all");
10881
10882        cx.executor().run_until_parked();
10883
10884        // Item 1 is saved. There's a prompt to save item 3.
10885        pane.update(cx, |pane, cx| {
10886            assert_eq!(item1.read(cx).save_count, 1);
10887            assert_eq!(item1.read(cx).save_as_count, 0);
10888            assert_eq!(item1.read(cx).reload_count, 0);
10889            assert_eq!(pane.items_len(), 3);
10890            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10891        });
10892        assert!(cx.has_pending_prompt());
10893
10894        // Cancel saving item 3.
10895        cx.simulate_prompt_answer("Discard");
10896        cx.executor().run_until_parked();
10897
10898        // Item 3 is reloaded. There's a prompt to save item 4.
10899        pane.update(cx, |pane, cx| {
10900            assert_eq!(item3.read(cx).save_count, 0);
10901            assert_eq!(item3.read(cx).save_as_count, 0);
10902            assert_eq!(item3.read(cx).reload_count, 1);
10903            assert_eq!(pane.items_len(), 2);
10904            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10905        });
10906
10907        // There's a prompt for a path for item 4.
10908        cx.simulate_new_path_selection(|_| Some(Default::default()));
10909        close_items.await.unwrap();
10910
10911        // The requested items are closed.
10912        pane.update(cx, |pane, cx| {
10913            assert_eq!(item4.read(cx).save_count, 0);
10914            assert_eq!(item4.read(cx).save_as_count, 1);
10915            assert_eq!(item4.read(cx).reload_count, 0);
10916            assert_eq!(pane.items_len(), 1);
10917            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10918        });
10919    }
10920
10921    #[gpui::test]
10922    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10923        init_test(cx);
10924
10925        let fs = FakeFs::new(cx.executor());
10926        let project = Project::test(fs, [], cx).await;
10927        let (workspace, cx) =
10928            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10929
10930        // Create several workspace items with single project entries, and two
10931        // workspace items with multiple project entries.
10932        let single_entry_items = (0..=4)
10933            .map(|project_entry_id| {
10934                cx.new(|cx| {
10935                    TestItem::new(cx)
10936                        .with_dirty(true)
10937                        .with_project_items(&[dirty_project_item(
10938                            project_entry_id,
10939                            &format!("{project_entry_id}.txt"),
10940                            cx,
10941                        )])
10942                })
10943            })
10944            .collect::<Vec<_>>();
10945        let item_2_3 = cx.new(|cx| {
10946            TestItem::new(cx)
10947                .with_dirty(true)
10948                .with_buffer_kind(ItemBufferKind::Multibuffer)
10949                .with_project_items(&[
10950                    single_entry_items[2].read(cx).project_items[0].clone(),
10951                    single_entry_items[3].read(cx).project_items[0].clone(),
10952                ])
10953        });
10954        let item_3_4 = cx.new(|cx| {
10955            TestItem::new(cx)
10956                .with_dirty(true)
10957                .with_buffer_kind(ItemBufferKind::Multibuffer)
10958                .with_project_items(&[
10959                    single_entry_items[3].read(cx).project_items[0].clone(),
10960                    single_entry_items[4].read(cx).project_items[0].clone(),
10961                ])
10962        });
10963
10964        // Create two panes that contain the following project entries:
10965        //   left pane:
10966        //     multi-entry items:   (2, 3)
10967        //     single-entry items:  0, 2, 3, 4
10968        //   right pane:
10969        //     single-entry items:  4, 1
10970        //     multi-entry items:   (3, 4)
10971        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10972            let left_pane = workspace.active_pane().clone();
10973            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10974            workspace.add_item_to_active_pane(
10975                single_entry_items[0].boxed_clone(),
10976                None,
10977                true,
10978                window,
10979                cx,
10980            );
10981            workspace.add_item_to_active_pane(
10982                single_entry_items[2].boxed_clone(),
10983                None,
10984                true,
10985                window,
10986                cx,
10987            );
10988            workspace.add_item_to_active_pane(
10989                single_entry_items[3].boxed_clone(),
10990                None,
10991                true,
10992                window,
10993                cx,
10994            );
10995            workspace.add_item_to_active_pane(
10996                single_entry_items[4].boxed_clone(),
10997                None,
10998                true,
10999                window,
11000                cx,
11001            );
11002
11003            let right_pane =
11004                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11005
11006            let boxed_clone = single_entry_items[1].boxed_clone();
11007            let right_pane = window.spawn(cx, async move |cx| {
11008                right_pane.await.inspect(|right_pane| {
11009                    right_pane
11010                        .update_in(cx, |pane, window, cx| {
11011                            pane.add_item(boxed_clone, true, true, None, window, cx);
11012                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11013                        })
11014                        .unwrap();
11015                })
11016            });
11017
11018            (left_pane, right_pane)
11019        });
11020        let right_pane = right_pane.await.unwrap();
11021        cx.focus(&right_pane);
11022
11023        let close = right_pane.update_in(cx, |pane, window, cx| {
11024            pane.close_all_items(&CloseAllItems::default(), window, cx)
11025                .unwrap()
11026        });
11027        cx.executor().run_until_parked();
11028
11029        let msg = cx.pending_prompt().unwrap().0;
11030        assert!(msg.contains("1.txt"));
11031        assert!(!msg.contains("2.txt"));
11032        assert!(!msg.contains("3.txt"));
11033        assert!(!msg.contains("4.txt"));
11034
11035        // With best-effort close, cancelling item 1 keeps it open but items 4
11036        // and (3,4) still close since their entries exist in left pane.
11037        cx.simulate_prompt_answer("Cancel");
11038        close.await;
11039
11040        right_pane.read_with(cx, |pane, _| {
11041            assert_eq!(pane.items_len(), 1);
11042        });
11043
11044        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11045        left_pane
11046            .update_in(cx, |left_pane, window, cx| {
11047                left_pane.close_item_by_id(
11048                    single_entry_items[3].entity_id(),
11049                    SaveIntent::Skip,
11050                    window,
11051                    cx,
11052                )
11053            })
11054            .await
11055            .unwrap();
11056
11057        let close = left_pane.update_in(cx, |pane, window, cx| {
11058            pane.close_all_items(&CloseAllItems::default(), window, cx)
11059                .unwrap()
11060        });
11061        cx.executor().run_until_parked();
11062
11063        let details = cx.pending_prompt().unwrap().1;
11064        assert!(details.contains("0.txt"));
11065        assert!(details.contains("3.txt"));
11066        assert!(details.contains("4.txt"));
11067        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11068        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11069        // assert!(!details.contains("2.txt"));
11070
11071        cx.simulate_prompt_answer("Save all");
11072        cx.executor().run_until_parked();
11073        close.await;
11074
11075        left_pane.read_with(cx, |pane, _| {
11076            assert_eq!(pane.items_len(), 0);
11077        });
11078    }
11079
11080    #[gpui::test]
11081    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11082        init_test(cx);
11083
11084        let fs = FakeFs::new(cx.executor());
11085        let project = Project::test(fs, [], cx).await;
11086        let (workspace, cx) =
11087            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11088        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11089
11090        let item = cx.new(|cx| {
11091            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11092        });
11093        let item_id = item.entity_id();
11094        workspace.update_in(cx, |workspace, window, cx| {
11095            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11096        });
11097
11098        // Autosave on window change.
11099        item.update(cx, |item, cx| {
11100            SettingsStore::update_global(cx, |settings, cx| {
11101                settings.update_user_settings(cx, |settings| {
11102                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11103                })
11104            });
11105            item.is_dirty = true;
11106        });
11107
11108        // Deactivating the window saves the file.
11109        cx.deactivate_window();
11110        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11111
11112        // Re-activating the window doesn't save the file.
11113        cx.update(|window, _| window.activate_window());
11114        cx.executor().run_until_parked();
11115        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11116
11117        // Autosave on focus change.
11118        item.update_in(cx, |item, window, cx| {
11119            cx.focus_self(window);
11120            SettingsStore::update_global(cx, |settings, cx| {
11121                settings.update_user_settings(cx, |settings| {
11122                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11123                })
11124            });
11125            item.is_dirty = true;
11126        });
11127        // Blurring the item saves the file.
11128        item.update_in(cx, |_, window, _| window.blur());
11129        cx.executor().run_until_parked();
11130        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11131
11132        // Deactivating the window still saves the file.
11133        item.update_in(cx, |item, window, cx| {
11134            cx.focus_self(window);
11135            item.is_dirty = true;
11136        });
11137        cx.deactivate_window();
11138        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11139
11140        // Autosave after delay.
11141        item.update(cx, |item, cx| {
11142            SettingsStore::update_global(cx, |settings, cx| {
11143                settings.update_user_settings(cx, |settings| {
11144                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11145                        milliseconds: 500.into(),
11146                    });
11147                })
11148            });
11149            item.is_dirty = true;
11150            cx.emit(ItemEvent::Edit);
11151        });
11152
11153        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11154        cx.executor().advance_clock(Duration::from_millis(250));
11155        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11156
11157        // After delay expires, the file is saved.
11158        cx.executor().advance_clock(Duration::from_millis(250));
11159        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11160
11161        // Autosave after delay, should save earlier than delay if tab is closed
11162        item.update(cx, |item, cx| {
11163            item.is_dirty = true;
11164            cx.emit(ItemEvent::Edit);
11165        });
11166        cx.executor().advance_clock(Duration::from_millis(250));
11167        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11168
11169        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11170        pane.update_in(cx, |pane, window, cx| {
11171            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11172        })
11173        .await
11174        .unwrap();
11175        assert!(!cx.has_pending_prompt());
11176        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11177
11178        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11179        workspace.update_in(cx, |workspace, window, cx| {
11180            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11181        });
11182        item.update_in(cx, |item, _window, cx| {
11183            item.is_dirty = true;
11184            for project_item in &mut item.project_items {
11185                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11186            }
11187        });
11188        cx.run_until_parked();
11189        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11190
11191        // Autosave on focus change, ensuring closing the tab counts as such.
11192        item.update(cx, |item, cx| {
11193            SettingsStore::update_global(cx, |settings, cx| {
11194                settings.update_user_settings(cx, |settings| {
11195                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11196                })
11197            });
11198            item.is_dirty = true;
11199            for project_item in &mut item.project_items {
11200                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11201            }
11202        });
11203
11204        pane.update_in(cx, |pane, window, cx| {
11205            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11206        })
11207        .await
11208        .unwrap();
11209        assert!(!cx.has_pending_prompt());
11210        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11211
11212        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11213        workspace.update_in(cx, |workspace, window, cx| {
11214            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11215        });
11216        item.update_in(cx, |item, window, cx| {
11217            item.project_items[0].update(cx, |item, _| {
11218                item.entry_id = None;
11219            });
11220            item.is_dirty = true;
11221            window.blur();
11222        });
11223        cx.run_until_parked();
11224        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11225
11226        // Ensure autosave is prevented for deleted files also when closing the buffer.
11227        let _close_items = pane.update_in(cx, |pane, window, cx| {
11228            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11229        });
11230        cx.run_until_parked();
11231        assert!(cx.has_pending_prompt());
11232        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11233    }
11234
11235    #[gpui::test]
11236    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11237        init_test(cx);
11238
11239        let fs = FakeFs::new(cx.executor());
11240        let project = Project::test(fs, [], cx).await;
11241        let (workspace, cx) =
11242            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11243
11244        // Create a multibuffer-like item with two child focus handles,
11245        // simulating individual buffer editors within a multibuffer.
11246        let item = cx.new(|cx| {
11247            TestItem::new(cx)
11248                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11249                .with_child_focus_handles(2, cx)
11250        });
11251        workspace.update_in(cx, |workspace, window, cx| {
11252            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11253        });
11254
11255        // Set autosave to OnFocusChange and focus the first child handle,
11256        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11257        item.update_in(cx, |item, window, cx| {
11258            SettingsStore::update_global(cx, |settings, cx| {
11259                settings.update_user_settings(cx, |settings| {
11260                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11261                })
11262            });
11263            item.is_dirty = true;
11264            window.focus(&item.child_focus_handles[0], cx);
11265        });
11266        cx.executor().run_until_parked();
11267        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11268
11269        // Moving focus from one child to another within the same item should
11270        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11271        item.update_in(cx, |item, window, cx| {
11272            window.focus(&item.child_focus_handles[1], cx);
11273        });
11274        cx.executor().run_until_parked();
11275        item.read_with(cx, |item, _| {
11276            assert_eq!(
11277                item.save_count, 0,
11278                "Switching focus between children within the same item should not autosave"
11279            );
11280        });
11281
11282        // Blurring the item saves the file. This is the core regression scenario:
11283        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11284        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11285        // the leaf is always a child focus handle, so `on_blur` never detected
11286        // focus leaving the item.
11287        item.update_in(cx, |_, window, _| window.blur());
11288        cx.executor().run_until_parked();
11289        item.read_with(cx, |item, _| {
11290            assert_eq!(
11291                item.save_count, 1,
11292                "Blurring should trigger autosave when focus was on a child of the item"
11293            );
11294        });
11295
11296        // Deactivating the window should also trigger autosave when a child of
11297        // the multibuffer item currently owns focus.
11298        item.update_in(cx, |item, window, cx| {
11299            item.is_dirty = true;
11300            window.focus(&item.child_focus_handles[0], cx);
11301        });
11302        cx.executor().run_until_parked();
11303        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11304
11305        cx.deactivate_window();
11306        item.read_with(cx, |item, _| {
11307            assert_eq!(
11308                item.save_count, 2,
11309                "Deactivating window should trigger autosave when focus was on a child"
11310            );
11311        });
11312    }
11313
11314    #[gpui::test]
11315    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11316        init_test(cx);
11317
11318        let fs = FakeFs::new(cx.executor());
11319
11320        let project = Project::test(fs, [], cx).await;
11321        let (workspace, cx) =
11322            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11323
11324        let item = cx.new(|cx| {
11325            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11326        });
11327        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11328        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11329        let toolbar_notify_count = Rc::new(RefCell::new(0));
11330
11331        workspace.update_in(cx, |workspace, window, cx| {
11332            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11333            let toolbar_notification_count = toolbar_notify_count.clone();
11334            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11335                *toolbar_notification_count.borrow_mut() += 1
11336            })
11337            .detach();
11338        });
11339
11340        pane.read_with(cx, |pane, _| {
11341            assert!(!pane.can_navigate_backward());
11342            assert!(!pane.can_navigate_forward());
11343        });
11344
11345        item.update_in(cx, |item, _, cx| {
11346            item.set_state("one".to_string(), cx);
11347        });
11348
11349        // Toolbar must be notified to re-render the navigation buttons
11350        assert_eq!(*toolbar_notify_count.borrow(), 1);
11351
11352        pane.read_with(cx, |pane, _| {
11353            assert!(pane.can_navigate_backward());
11354            assert!(!pane.can_navigate_forward());
11355        });
11356
11357        workspace
11358            .update_in(cx, |workspace, window, cx| {
11359                workspace.go_back(pane.downgrade(), window, cx)
11360            })
11361            .await
11362            .unwrap();
11363
11364        assert_eq!(*toolbar_notify_count.borrow(), 2);
11365        pane.read_with(cx, |pane, _| {
11366            assert!(!pane.can_navigate_backward());
11367            assert!(pane.can_navigate_forward());
11368        });
11369    }
11370
11371    /// Tests that the navigation history deduplicates entries for the same item.
11372    ///
11373    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11374    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11375    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11376    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11377    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11378    ///
11379    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11380    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11381    #[gpui::test]
11382    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11383        init_test(cx);
11384
11385        let fs = FakeFs::new(cx.executor());
11386        let project = Project::test(fs, [], cx).await;
11387        let (workspace, cx) =
11388            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11389
11390        let item_a = cx.new(|cx| {
11391            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11392        });
11393        let item_b = cx.new(|cx| {
11394            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11395        });
11396        let item_c = cx.new(|cx| {
11397            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11398        });
11399
11400        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11401
11402        workspace.update_in(cx, |workspace, window, cx| {
11403            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11404            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11405            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11406        });
11407
11408        workspace.update_in(cx, |workspace, window, cx| {
11409            workspace.activate_item(&item_a, false, false, window, cx);
11410        });
11411        cx.run_until_parked();
11412
11413        workspace.update_in(cx, |workspace, window, cx| {
11414            workspace.activate_item(&item_b, false, false, window, cx);
11415        });
11416        cx.run_until_parked();
11417
11418        workspace.update_in(cx, |workspace, window, cx| {
11419            workspace.activate_item(&item_a, false, false, window, cx);
11420        });
11421        cx.run_until_parked();
11422
11423        workspace.update_in(cx, |workspace, window, cx| {
11424            workspace.activate_item(&item_b, false, false, window, cx);
11425        });
11426        cx.run_until_parked();
11427
11428        workspace.update_in(cx, |workspace, window, cx| {
11429            workspace.activate_item(&item_a, false, false, window, cx);
11430        });
11431        cx.run_until_parked();
11432
11433        workspace.update_in(cx, |workspace, window, cx| {
11434            workspace.activate_item(&item_b, false, false, window, cx);
11435        });
11436        cx.run_until_parked();
11437
11438        workspace.update_in(cx, |workspace, window, cx| {
11439            workspace.activate_item(&item_c, false, false, window, cx);
11440        });
11441        cx.run_until_parked();
11442
11443        let backward_count = pane.read_with(cx, |pane, cx| {
11444            let mut count = 0;
11445            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11446                count += 1;
11447            });
11448            count
11449        });
11450        assert!(
11451            backward_count <= 4,
11452            "Should have at most 4 entries, got {}",
11453            backward_count
11454        );
11455
11456        workspace
11457            .update_in(cx, |workspace, window, cx| {
11458                workspace.go_back(pane.downgrade(), window, cx)
11459            })
11460            .await
11461            .unwrap();
11462
11463        let active_item = workspace.read_with(cx, |workspace, cx| {
11464            workspace.active_item(cx).unwrap().item_id()
11465        });
11466        assert_eq!(
11467            active_item,
11468            item_b.entity_id(),
11469            "After first go_back, should be at item B"
11470        );
11471
11472        workspace
11473            .update_in(cx, |workspace, window, cx| {
11474                workspace.go_back(pane.downgrade(), window, cx)
11475            })
11476            .await
11477            .unwrap();
11478
11479        let active_item = workspace.read_with(cx, |workspace, cx| {
11480            workspace.active_item(cx).unwrap().item_id()
11481        });
11482        assert_eq!(
11483            active_item,
11484            item_a.entity_id(),
11485            "After second go_back, should be at item A"
11486        );
11487
11488        pane.read_with(cx, |pane, _| {
11489            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11490        });
11491    }
11492
11493    #[gpui::test]
11494    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11495        init_test(cx);
11496        let fs = FakeFs::new(cx.executor());
11497        let project = Project::test(fs, [], cx).await;
11498        let (multi_workspace, cx) =
11499            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11500        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11501
11502        workspace.update_in(cx, |workspace, window, cx| {
11503            let first_item = cx.new(|cx| {
11504                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11505            });
11506            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11507            workspace.split_pane(
11508                workspace.active_pane().clone(),
11509                SplitDirection::Right,
11510                window,
11511                cx,
11512            );
11513            workspace.split_pane(
11514                workspace.active_pane().clone(),
11515                SplitDirection::Right,
11516                window,
11517                cx,
11518            );
11519        });
11520
11521        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11522            let panes = workspace.center.panes();
11523            assert!(panes.len() >= 2);
11524            (
11525                panes.first().expect("at least one pane").entity_id(),
11526                panes.last().expect("at least one pane").entity_id(),
11527            )
11528        });
11529
11530        workspace.update_in(cx, |workspace, window, cx| {
11531            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11532        });
11533        workspace.update(cx, |workspace, _| {
11534            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11535            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11536        });
11537
11538        cx.dispatch_action(ActivateLastPane);
11539
11540        workspace.update(cx, |workspace, _| {
11541            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11542        });
11543    }
11544
11545    #[gpui::test]
11546    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11547        init_test(cx);
11548        let fs = FakeFs::new(cx.executor());
11549
11550        let project = Project::test(fs, [], cx).await;
11551        let (workspace, cx) =
11552            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11553
11554        let panel = workspace.update_in(cx, |workspace, window, cx| {
11555            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11556            workspace.add_panel(panel.clone(), window, cx);
11557
11558            workspace
11559                .right_dock()
11560                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11561
11562            panel
11563        });
11564
11565        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11566        pane.update_in(cx, |pane, window, cx| {
11567            let item = cx.new(TestItem::new);
11568            pane.add_item(Box::new(item), true, true, None, window, cx);
11569        });
11570
11571        // Transfer focus from center to panel
11572        workspace.update_in(cx, |workspace, window, cx| {
11573            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11574        });
11575
11576        workspace.update_in(cx, |workspace, window, cx| {
11577            assert!(workspace.right_dock().read(cx).is_open());
11578            assert!(!panel.is_zoomed(window, cx));
11579            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11580        });
11581
11582        // Transfer focus from panel to center
11583        workspace.update_in(cx, |workspace, window, cx| {
11584            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11585        });
11586
11587        workspace.update_in(cx, |workspace, window, cx| {
11588            assert!(workspace.right_dock().read(cx).is_open());
11589            assert!(!panel.is_zoomed(window, cx));
11590            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11591            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11592        });
11593
11594        // Close the dock
11595        workspace.update_in(cx, |workspace, window, cx| {
11596            workspace.toggle_dock(DockPosition::Right, window, cx);
11597        });
11598
11599        workspace.update_in(cx, |workspace, window, cx| {
11600            assert!(!workspace.right_dock().read(cx).is_open());
11601            assert!(!panel.is_zoomed(window, cx));
11602            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11603            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11604        });
11605
11606        // Open the dock
11607        workspace.update_in(cx, |workspace, window, cx| {
11608            workspace.toggle_dock(DockPosition::Right, window, cx);
11609        });
11610
11611        workspace.update_in(cx, |workspace, window, cx| {
11612            assert!(workspace.right_dock().read(cx).is_open());
11613            assert!(!panel.is_zoomed(window, cx));
11614            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11615        });
11616
11617        // Focus and zoom panel
11618        panel.update_in(cx, |panel, window, cx| {
11619            cx.focus_self(window);
11620            panel.set_zoomed(true, window, cx)
11621        });
11622
11623        workspace.update_in(cx, |workspace, window, cx| {
11624            assert!(workspace.right_dock().read(cx).is_open());
11625            assert!(panel.is_zoomed(window, cx));
11626            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11627        });
11628
11629        // Transfer focus to the center closes the dock
11630        workspace.update_in(cx, |workspace, window, cx| {
11631            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11632        });
11633
11634        workspace.update_in(cx, |workspace, window, cx| {
11635            assert!(!workspace.right_dock().read(cx).is_open());
11636            assert!(panel.is_zoomed(window, cx));
11637            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11638        });
11639
11640        // Transferring focus back to the panel keeps it zoomed
11641        workspace.update_in(cx, |workspace, window, cx| {
11642            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11643        });
11644
11645        workspace.update_in(cx, |workspace, window, cx| {
11646            assert!(workspace.right_dock().read(cx).is_open());
11647            assert!(panel.is_zoomed(window, cx));
11648            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11649        });
11650
11651        // Close the dock while it is zoomed
11652        workspace.update_in(cx, |workspace, window, cx| {
11653            workspace.toggle_dock(DockPosition::Right, window, cx)
11654        });
11655
11656        workspace.update_in(cx, |workspace, window, cx| {
11657            assert!(!workspace.right_dock().read(cx).is_open());
11658            assert!(panel.is_zoomed(window, cx));
11659            assert!(workspace.zoomed.is_none());
11660            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11661        });
11662
11663        // Opening the dock, when it's zoomed, retains focus
11664        workspace.update_in(cx, |workspace, window, cx| {
11665            workspace.toggle_dock(DockPosition::Right, window, cx)
11666        });
11667
11668        workspace.update_in(cx, |workspace, window, cx| {
11669            assert!(workspace.right_dock().read(cx).is_open());
11670            assert!(panel.is_zoomed(window, cx));
11671            assert!(workspace.zoomed.is_some());
11672            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11673        });
11674
11675        // Unzoom and close the panel, zoom the active pane.
11676        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11677        workspace.update_in(cx, |workspace, window, cx| {
11678            workspace.toggle_dock(DockPosition::Right, window, cx)
11679        });
11680        pane.update_in(cx, |pane, window, cx| {
11681            pane.toggle_zoom(&Default::default(), window, cx)
11682        });
11683
11684        // Opening a dock unzooms the pane.
11685        workspace.update_in(cx, |workspace, window, cx| {
11686            workspace.toggle_dock(DockPosition::Right, window, cx)
11687        });
11688        workspace.update_in(cx, |workspace, window, cx| {
11689            let pane = pane.read(cx);
11690            assert!(!pane.is_zoomed());
11691            assert!(!pane.focus_handle(cx).is_focused(window));
11692            assert!(workspace.right_dock().read(cx).is_open());
11693            assert!(workspace.zoomed.is_none());
11694        });
11695    }
11696
11697    #[gpui::test]
11698    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11699        init_test(cx);
11700        let fs = FakeFs::new(cx.executor());
11701
11702        let project = Project::test(fs, [], cx).await;
11703        let (workspace, cx) =
11704            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11705
11706        let panel = workspace.update_in(cx, |workspace, window, cx| {
11707            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11708            workspace.add_panel(panel.clone(), window, cx);
11709            panel
11710        });
11711
11712        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11713        pane.update_in(cx, |pane, window, cx| {
11714            let item = cx.new(TestItem::new);
11715            pane.add_item(Box::new(item), true, true, None, window, cx);
11716        });
11717
11718        // Enable close_panel_on_toggle
11719        cx.update_global(|store: &mut SettingsStore, cx| {
11720            store.update_user_settings(cx, |settings| {
11721                settings.workspace.close_panel_on_toggle = Some(true);
11722            });
11723        });
11724
11725        // Panel starts closed. Toggling should open and focus it.
11726        workspace.update_in(cx, |workspace, window, cx| {
11727            assert!(!workspace.right_dock().read(cx).is_open());
11728            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11729        });
11730
11731        workspace.update_in(cx, |workspace, window, cx| {
11732            assert!(
11733                workspace.right_dock().read(cx).is_open(),
11734                "Dock should be open after toggling from center"
11735            );
11736            assert!(
11737                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11738                "Panel should be focused after toggling from center"
11739            );
11740        });
11741
11742        // Panel is open and focused. Toggling should close the panel and
11743        // return focus to the center.
11744        workspace.update_in(cx, |workspace, window, cx| {
11745            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11746        });
11747
11748        workspace.update_in(cx, |workspace, window, cx| {
11749            assert!(
11750                !workspace.right_dock().read(cx).is_open(),
11751                "Dock should be closed after toggling from focused panel"
11752            );
11753            assert!(
11754                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11755                "Panel should not be focused after toggling from focused panel"
11756            );
11757        });
11758
11759        // Open the dock and focus something else so the panel is open but not
11760        // focused. Toggling should focus the panel (not close it).
11761        workspace.update_in(cx, |workspace, window, cx| {
11762            workspace
11763                .right_dock()
11764                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11765            window.focus(&pane.read(cx).focus_handle(cx), cx);
11766        });
11767
11768        workspace.update_in(cx, |workspace, window, cx| {
11769            assert!(workspace.right_dock().read(cx).is_open());
11770            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11771            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11772        });
11773
11774        workspace.update_in(cx, |workspace, window, cx| {
11775            assert!(
11776                workspace.right_dock().read(cx).is_open(),
11777                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11778            );
11779            assert!(
11780                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11781                "Panel should be focused after toggling an open-but-unfocused panel"
11782            );
11783        });
11784
11785        // Now disable the setting and verify the original behavior: toggling
11786        // from a focused panel moves focus to center but leaves the dock open.
11787        cx.update_global(|store: &mut SettingsStore, cx| {
11788            store.update_user_settings(cx, |settings| {
11789                settings.workspace.close_panel_on_toggle = Some(false);
11790            });
11791        });
11792
11793        workspace.update_in(cx, |workspace, window, cx| {
11794            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11795        });
11796
11797        workspace.update_in(cx, |workspace, window, cx| {
11798            assert!(
11799                workspace.right_dock().read(cx).is_open(),
11800                "Dock should remain open when setting is disabled"
11801            );
11802            assert!(
11803                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11804                "Panel should not be focused after toggling with setting disabled"
11805            );
11806        });
11807    }
11808
11809    #[gpui::test]
11810    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11811        init_test(cx);
11812        let fs = FakeFs::new(cx.executor());
11813
11814        let project = Project::test(fs, [], cx).await;
11815        let (workspace, cx) =
11816            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11817
11818        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11819            workspace.active_pane().clone()
11820        });
11821
11822        // Add an item to the pane so it can be zoomed
11823        workspace.update_in(cx, |workspace, window, cx| {
11824            let item = cx.new(TestItem::new);
11825            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11826        });
11827
11828        // Initially not zoomed
11829        workspace.update_in(cx, |workspace, _window, cx| {
11830            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11831            assert!(
11832                workspace.zoomed.is_none(),
11833                "Workspace should track no zoomed pane"
11834            );
11835            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11836        });
11837
11838        // Zoom In
11839        pane.update_in(cx, |pane, window, cx| {
11840            pane.zoom_in(&crate::ZoomIn, window, cx);
11841        });
11842
11843        workspace.update_in(cx, |workspace, window, cx| {
11844            assert!(
11845                pane.read(cx).is_zoomed(),
11846                "Pane should be zoomed after ZoomIn"
11847            );
11848            assert!(
11849                workspace.zoomed.is_some(),
11850                "Workspace should track the zoomed pane"
11851            );
11852            assert!(
11853                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11854                "ZoomIn should focus the pane"
11855            );
11856        });
11857
11858        // Zoom In again is a no-op
11859        pane.update_in(cx, |pane, window, cx| {
11860            pane.zoom_in(&crate::ZoomIn, window, cx);
11861        });
11862
11863        workspace.update_in(cx, |workspace, window, cx| {
11864            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11865            assert!(
11866                workspace.zoomed.is_some(),
11867                "Workspace still tracks zoomed pane"
11868            );
11869            assert!(
11870                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11871                "Pane remains focused after repeated ZoomIn"
11872            );
11873        });
11874
11875        // Zoom Out
11876        pane.update_in(cx, |pane, window, cx| {
11877            pane.zoom_out(&crate::ZoomOut, window, cx);
11878        });
11879
11880        workspace.update_in(cx, |workspace, _window, cx| {
11881            assert!(
11882                !pane.read(cx).is_zoomed(),
11883                "Pane should unzoom after ZoomOut"
11884            );
11885            assert!(
11886                workspace.zoomed.is_none(),
11887                "Workspace clears zoom tracking after ZoomOut"
11888            );
11889        });
11890
11891        // Zoom Out again is a no-op
11892        pane.update_in(cx, |pane, window, cx| {
11893            pane.zoom_out(&crate::ZoomOut, window, cx);
11894        });
11895
11896        workspace.update_in(cx, |workspace, _window, cx| {
11897            assert!(
11898                !pane.read(cx).is_zoomed(),
11899                "Second ZoomOut keeps pane unzoomed"
11900            );
11901            assert!(
11902                workspace.zoomed.is_none(),
11903                "Workspace remains without zoomed pane"
11904            );
11905        });
11906    }
11907
11908    #[gpui::test]
11909    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11910        init_test(cx);
11911        let fs = FakeFs::new(cx.executor());
11912
11913        let project = Project::test(fs, [], cx).await;
11914        let (workspace, cx) =
11915            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11916        workspace.update_in(cx, |workspace, window, cx| {
11917            // Open two docks
11918            let left_dock = workspace.dock_at_position(DockPosition::Left);
11919            let right_dock = workspace.dock_at_position(DockPosition::Right);
11920
11921            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11922            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11923
11924            assert!(left_dock.read(cx).is_open());
11925            assert!(right_dock.read(cx).is_open());
11926        });
11927
11928        workspace.update_in(cx, |workspace, window, cx| {
11929            // Toggle all docks - should close both
11930            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11931
11932            let left_dock = workspace.dock_at_position(DockPosition::Left);
11933            let right_dock = workspace.dock_at_position(DockPosition::Right);
11934            assert!(!left_dock.read(cx).is_open());
11935            assert!(!right_dock.read(cx).is_open());
11936        });
11937
11938        workspace.update_in(cx, |workspace, window, cx| {
11939            // Toggle again - should reopen both
11940            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11941
11942            let left_dock = workspace.dock_at_position(DockPosition::Left);
11943            let right_dock = workspace.dock_at_position(DockPosition::Right);
11944            assert!(left_dock.read(cx).is_open());
11945            assert!(right_dock.read(cx).is_open());
11946        });
11947    }
11948
11949    #[gpui::test]
11950    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11951        init_test(cx);
11952        let fs = FakeFs::new(cx.executor());
11953
11954        let project = Project::test(fs, [], cx).await;
11955        let (workspace, cx) =
11956            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11957        workspace.update_in(cx, |workspace, window, cx| {
11958            // Open two docks
11959            let left_dock = workspace.dock_at_position(DockPosition::Left);
11960            let right_dock = workspace.dock_at_position(DockPosition::Right);
11961
11962            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11963            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11964
11965            assert!(left_dock.read(cx).is_open());
11966            assert!(right_dock.read(cx).is_open());
11967        });
11968
11969        workspace.update_in(cx, |workspace, window, cx| {
11970            // Close them manually
11971            workspace.toggle_dock(DockPosition::Left, window, cx);
11972            workspace.toggle_dock(DockPosition::Right, window, cx);
11973
11974            let left_dock = workspace.dock_at_position(DockPosition::Left);
11975            let right_dock = workspace.dock_at_position(DockPosition::Right);
11976            assert!(!left_dock.read(cx).is_open());
11977            assert!(!right_dock.read(cx).is_open());
11978        });
11979
11980        workspace.update_in(cx, |workspace, window, cx| {
11981            // Toggle all docks - only last closed (right dock) should reopen
11982            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11983
11984            let left_dock = workspace.dock_at_position(DockPosition::Left);
11985            let right_dock = workspace.dock_at_position(DockPosition::Right);
11986            assert!(!left_dock.read(cx).is_open());
11987            assert!(right_dock.read(cx).is_open());
11988        });
11989    }
11990
11991    #[gpui::test]
11992    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11993        init_test(cx);
11994        let fs = FakeFs::new(cx.executor());
11995        let project = Project::test(fs, [], cx).await;
11996        let (multi_workspace, cx) =
11997            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11998        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11999
12000        // Open two docks (left and right) with one panel each
12001        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12002            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12003            workspace.add_panel(left_panel.clone(), window, cx);
12004
12005            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12006            workspace.add_panel(right_panel.clone(), window, cx);
12007
12008            workspace.toggle_dock(DockPosition::Left, window, cx);
12009            workspace.toggle_dock(DockPosition::Right, window, cx);
12010
12011            // Verify initial state
12012            assert!(
12013                workspace.left_dock().read(cx).is_open(),
12014                "Left dock should be open"
12015            );
12016            assert_eq!(
12017                workspace
12018                    .left_dock()
12019                    .read(cx)
12020                    .visible_panel()
12021                    .unwrap()
12022                    .panel_id(),
12023                left_panel.panel_id(),
12024                "Left panel should be visible in left dock"
12025            );
12026            assert!(
12027                workspace.right_dock().read(cx).is_open(),
12028                "Right dock should be open"
12029            );
12030            assert_eq!(
12031                workspace
12032                    .right_dock()
12033                    .read(cx)
12034                    .visible_panel()
12035                    .unwrap()
12036                    .panel_id(),
12037                right_panel.panel_id(),
12038                "Right panel should be visible in right dock"
12039            );
12040            assert!(
12041                !workspace.bottom_dock().read(cx).is_open(),
12042                "Bottom dock should be closed"
12043            );
12044
12045            (left_panel, right_panel)
12046        });
12047
12048        // Focus the left panel and move it to the next position (bottom dock)
12049        workspace.update_in(cx, |workspace, window, cx| {
12050            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12051            assert!(
12052                left_panel.read(cx).focus_handle(cx).is_focused(window),
12053                "Left panel should be focused"
12054            );
12055        });
12056
12057        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12058
12059        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12060        workspace.update(cx, |workspace, cx| {
12061            assert!(
12062                !workspace.left_dock().read(cx).is_open(),
12063                "Left dock should be closed"
12064            );
12065            assert!(
12066                workspace.bottom_dock().read(cx).is_open(),
12067                "Bottom dock should now be open"
12068            );
12069            assert_eq!(
12070                left_panel.read(cx).position,
12071                DockPosition::Bottom,
12072                "Left panel should now be in the bottom dock"
12073            );
12074            assert_eq!(
12075                workspace
12076                    .bottom_dock()
12077                    .read(cx)
12078                    .visible_panel()
12079                    .unwrap()
12080                    .panel_id(),
12081                left_panel.panel_id(),
12082                "Left panel should be the visible panel in the bottom dock"
12083            );
12084        });
12085
12086        // Toggle all docks off
12087        workspace.update_in(cx, |workspace, window, cx| {
12088            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12089            assert!(
12090                !workspace.left_dock().read(cx).is_open(),
12091                "Left dock should be closed"
12092            );
12093            assert!(
12094                !workspace.right_dock().read(cx).is_open(),
12095                "Right dock should be closed"
12096            );
12097            assert!(
12098                !workspace.bottom_dock().read(cx).is_open(),
12099                "Bottom dock should be closed"
12100            );
12101        });
12102
12103        // Toggle all docks back on and verify positions are restored
12104        workspace.update_in(cx, |workspace, window, cx| {
12105            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12106            assert!(
12107                !workspace.left_dock().read(cx).is_open(),
12108                "Left dock should remain closed"
12109            );
12110            assert!(
12111                workspace.right_dock().read(cx).is_open(),
12112                "Right dock should remain open"
12113            );
12114            assert!(
12115                workspace.bottom_dock().read(cx).is_open(),
12116                "Bottom dock should remain open"
12117            );
12118            assert_eq!(
12119                left_panel.read(cx).position,
12120                DockPosition::Bottom,
12121                "Left panel should remain in the bottom dock"
12122            );
12123            assert_eq!(
12124                right_panel.read(cx).position,
12125                DockPosition::Right,
12126                "Right panel should remain in the right dock"
12127            );
12128            assert_eq!(
12129                workspace
12130                    .bottom_dock()
12131                    .read(cx)
12132                    .visible_panel()
12133                    .unwrap()
12134                    .panel_id(),
12135                left_panel.panel_id(),
12136                "Left panel should be the visible panel in the right dock"
12137            );
12138        });
12139    }
12140
12141    #[gpui::test]
12142    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12143        init_test(cx);
12144
12145        let fs = FakeFs::new(cx.executor());
12146
12147        let project = Project::test(fs, None, cx).await;
12148        let (workspace, cx) =
12149            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12150
12151        // Let's arrange the panes like this:
12152        //
12153        // +-----------------------+
12154        // |         top           |
12155        // +------+--------+-------+
12156        // | left | center | right |
12157        // +------+--------+-------+
12158        // |        bottom         |
12159        // +-----------------------+
12160
12161        let top_item = cx.new(|cx| {
12162            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12163        });
12164        let bottom_item = cx.new(|cx| {
12165            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12166        });
12167        let left_item = cx.new(|cx| {
12168            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12169        });
12170        let right_item = cx.new(|cx| {
12171            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12172        });
12173        let center_item = cx.new(|cx| {
12174            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12175        });
12176
12177        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12178            let top_pane_id = workspace.active_pane().entity_id();
12179            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12180            workspace.split_pane(
12181                workspace.active_pane().clone(),
12182                SplitDirection::Down,
12183                window,
12184                cx,
12185            );
12186            top_pane_id
12187        });
12188        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12189            let bottom_pane_id = workspace.active_pane().entity_id();
12190            workspace.add_item_to_active_pane(
12191                Box::new(bottom_item.clone()),
12192                None,
12193                false,
12194                window,
12195                cx,
12196            );
12197            workspace.split_pane(
12198                workspace.active_pane().clone(),
12199                SplitDirection::Up,
12200                window,
12201                cx,
12202            );
12203            bottom_pane_id
12204        });
12205        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12206            let left_pane_id = workspace.active_pane().entity_id();
12207            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12208            workspace.split_pane(
12209                workspace.active_pane().clone(),
12210                SplitDirection::Right,
12211                window,
12212                cx,
12213            );
12214            left_pane_id
12215        });
12216        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12217            let right_pane_id = workspace.active_pane().entity_id();
12218            workspace.add_item_to_active_pane(
12219                Box::new(right_item.clone()),
12220                None,
12221                false,
12222                window,
12223                cx,
12224            );
12225            workspace.split_pane(
12226                workspace.active_pane().clone(),
12227                SplitDirection::Left,
12228                window,
12229                cx,
12230            );
12231            right_pane_id
12232        });
12233        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12234            let center_pane_id = workspace.active_pane().entity_id();
12235            workspace.add_item_to_active_pane(
12236                Box::new(center_item.clone()),
12237                None,
12238                false,
12239                window,
12240                cx,
12241            );
12242            center_pane_id
12243        });
12244        cx.executor().run_until_parked();
12245
12246        workspace.update_in(cx, |workspace, window, cx| {
12247            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12248
12249            // Join into next from center pane into right
12250            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12251        });
12252
12253        workspace.update_in(cx, |workspace, window, cx| {
12254            let active_pane = workspace.active_pane();
12255            assert_eq!(right_pane_id, active_pane.entity_id());
12256            assert_eq!(2, active_pane.read(cx).items_len());
12257            let item_ids_in_pane =
12258                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12259            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12260            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12261
12262            // Join into next from right pane into bottom
12263            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12264        });
12265
12266        workspace.update_in(cx, |workspace, window, cx| {
12267            let active_pane = workspace.active_pane();
12268            assert_eq!(bottom_pane_id, active_pane.entity_id());
12269            assert_eq!(3, active_pane.read(cx).items_len());
12270            let item_ids_in_pane =
12271                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12272            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12273            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12274            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12275
12276            // Join into next from bottom pane into left
12277            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12278        });
12279
12280        workspace.update_in(cx, |workspace, window, cx| {
12281            let active_pane = workspace.active_pane();
12282            assert_eq!(left_pane_id, active_pane.entity_id());
12283            assert_eq!(4, active_pane.read(cx).items_len());
12284            let item_ids_in_pane =
12285                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12286            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12287            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12288            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12289            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12290
12291            // Join into next from left pane into top
12292            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12293        });
12294
12295        workspace.update_in(cx, |workspace, window, cx| {
12296            let active_pane = workspace.active_pane();
12297            assert_eq!(top_pane_id, active_pane.entity_id());
12298            assert_eq!(5, active_pane.read(cx).items_len());
12299            let item_ids_in_pane =
12300                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12301            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12302            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12303            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12304            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12305            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12306
12307            // Single pane left: no-op
12308            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12309        });
12310
12311        workspace.update(cx, |workspace, _cx| {
12312            let active_pane = workspace.active_pane();
12313            assert_eq!(top_pane_id, active_pane.entity_id());
12314        });
12315    }
12316
12317    fn add_an_item_to_active_pane(
12318        cx: &mut VisualTestContext,
12319        workspace: &Entity<Workspace>,
12320        item_id: u64,
12321    ) -> Entity<TestItem> {
12322        let item = cx.new(|cx| {
12323            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12324                item_id,
12325                "item{item_id}.txt",
12326                cx,
12327            )])
12328        });
12329        workspace.update_in(cx, |workspace, window, cx| {
12330            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12331        });
12332        item
12333    }
12334
12335    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12336        workspace.update_in(cx, |workspace, window, cx| {
12337            workspace.split_pane(
12338                workspace.active_pane().clone(),
12339                SplitDirection::Right,
12340                window,
12341                cx,
12342            )
12343        })
12344    }
12345
12346    #[gpui::test]
12347    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12348        init_test(cx);
12349        let fs = FakeFs::new(cx.executor());
12350        let project = Project::test(fs, None, cx).await;
12351        let (workspace, cx) =
12352            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12353
12354        add_an_item_to_active_pane(cx, &workspace, 1);
12355        split_pane(cx, &workspace);
12356        add_an_item_to_active_pane(cx, &workspace, 2);
12357        split_pane(cx, &workspace); // empty pane
12358        split_pane(cx, &workspace);
12359        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12360
12361        cx.executor().run_until_parked();
12362
12363        workspace.update(cx, |workspace, cx| {
12364            let num_panes = workspace.panes().len();
12365            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12366            let active_item = workspace
12367                .active_pane()
12368                .read(cx)
12369                .active_item()
12370                .expect("item is in focus");
12371
12372            assert_eq!(num_panes, 4);
12373            assert_eq!(num_items_in_current_pane, 1);
12374            assert_eq!(active_item.item_id(), last_item.item_id());
12375        });
12376
12377        workspace.update_in(cx, |workspace, window, cx| {
12378            workspace.join_all_panes(window, cx);
12379        });
12380
12381        workspace.update(cx, |workspace, cx| {
12382            let num_panes = workspace.panes().len();
12383            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12384            let active_item = workspace
12385                .active_pane()
12386                .read(cx)
12387                .active_item()
12388                .expect("item is in focus");
12389
12390            assert_eq!(num_panes, 1);
12391            assert_eq!(num_items_in_current_pane, 3);
12392            assert_eq!(active_item.item_id(), last_item.item_id());
12393        });
12394    }
12395
12396    #[gpui::test]
12397    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12398        init_test(cx);
12399        let fs = FakeFs::new(cx.executor());
12400
12401        let project = Project::test(fs, [], cx).await;
12402        let (multi_workspace, cx) =
12403            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12404        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12405
12406        workspace.update(cx, |workspace, _cx| {
12407            workspace.bounds.size.width = px(800.);
12408        });
12409
12410        workspace.update_in(cx, |workspace, window, cx| {
12411            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12412            workspace.add_panel(panel, window, cx);
12413            workspace.toggle_dock(DockPosition::Right, window, cx);
12414        });
12415
12416        let (panel, resized_width, ratio_basis_width) =
12417            workspace.update_in(cx, |workspace, window, cx| {
12418                let item = cx.new(|cx| {
12419                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12420                });
12421                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12422
12423                let dock = workspace.right_dock().read(cx);
12424                let workspace_width = workspace.bounds.size.width;
12425                let initial_width = workspace
12426                    .dock_size(&dock, window, cx)
12427                    .expect("flexible dock should have an initial width");
12428
12429                assert_eq!(initial_width, workspace_width / 2.);
12430
12431                workspace.resize_right_dock(px(300.), window, cx);
12432
12433                let dock = workspace.right_dock().read(cx);
12434                let resized_width = workspace
12435                    .dock_size(&dock, window, cx)
12436                    .expect("flexible dock should keep its resized width");
12437
12438                assert_eq!(resized_width, px(300.));
12439
12440                let panel = workspace
12441                    .right_dock()
12442                    .read(cx)
12443                    .visible_panel()
12444                    .expect("flexible dock should have a visible panel")
12445                    .panel_id();
12446
12447                (panel, resized_width, workspace_width)
12448            });
12449
12450        workspace.update_in(cx, |workspace, window, cx| {
12451            workspace.toggle_dock(DockPosition::Right, window, cx);
12452            workspace.toggle_dock(DockPosition::Right, window, cx);
12453
12454            let dock = workspace.right_dock().read(cx);
12455            let reopened_width = workspace
12456                .dock_size(&dock, window, cx)
12457                .expect("flexible dock should restore when reopened");
12458
12459            assert_eq!(reopened_width, resized_width);
12460
12461            let right_dock = workspace.right_dock().read(cx);
12462            let flexible_panel = right_dock
12463                .visible_panel()
12464                .expect("flexible dock should still have a visible panel");
12465            assert_eq!(flexible_panel.panel_id(), panel);
12466            assert_eq!(
12467                right_dock
12468                    .stored_panel_size_state(flexible_panel.as_ref())
12469                    .and_then(|size_state| size_state.flex),
12470                Some(
12471                    resized_width.to_f64() as f32
12472                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12473                )
12474            );
12475        });
12476
12477        workspace.update_in(cx, |workspace, window, cx| {
12478            workspace.split_pane(
12479                workspace.active_pane().clone(),
12480                SplitDirection::Right,
12481                window,
12482                cx,
12483            );
12484
12485            let dock = workspace.right_dock().read(cx);
12486            let split_width = workspace
12487                .dock_size(&dock, window, cx)
12488                .expect("flexible dock should keep its user-resized proportion");
12489
12490            assert_eq!(split_width, px(300.));
12491
12492            workspace.bounds.size.width = px(1600.);
12493
12494            let dock = workspace.right_dock().read(cx);
12495            let resized_window_width = workspace
12496                .dock_size(&dock, window, cx)
12497                .expect("flexible dock should preserve proportional size on window resize");
12498
12499            assert_eq!(
12500                resized_window_width,
12501                workspace.bounds.size.width
12502                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12503            );
12504        });
12505    }
12506
12507    #[gpui::test]
12508    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12509        init_test(cx);
12510        let fs = FakeFs::new(cx.executor());
12511
12512        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12513        {
12514            let project = Project::test(fs.clone(), [], cx).await;
12515            let (multi_workspace, cx) =
12516                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12517            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12518
12519            workspace.update(cx, |workspace, _cx| {
12520                workspace.set_random_database_id();
12521                workspace.bounds.size.width = px(800.);
12522            });
12523
12524            let panel = workspace.update_in(cx, |workspace, window, cx| {
12525                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12526                workspace.add_panel(panel.clone(), window, cx);
12527                workspace.toggle_dock(DockPosition::Left, window, cx);
12528                panel
12529            });
12530
12531            workspace.update_in(cx, |workspace, window, cx| {
12532                workspace.resize_left_dock(px(350.), window, cx);
12533            });
12534
12535            cx.run_until_parked();
12536
12537            let persisted = workspace.read_with(cx, |workspace, cx| {
12538                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12539            });
12540            assert_eq!(
12541                persisted.and_then(|s| s.size),
12542                Some(px(350.)),
12543                "fixed-width panel size should be persisted to KVP"
12544            );
12545
12546            // Remove the panel and re-add a fresh instance with the same key.
12547            // The new instance should have its size state restored from KVP.
12548            workspace.update_in(cx, |workspace, window, cx| {
12549                workspace.remove_panel(&panel, window, cx);
12550            });
12551
12552            workspace.update_in(cx, |workspace, window, cx| {
12553                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12554                workspace.add_panel(new_panel, window, cx);
12555
12556                let left_dock = workspace.left_dock().read(cx);
12557                let size_state = left_dock
12558                    .panel::<TestPanel>()
12559                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12560                assert_eq!(
12561                    size_state.and_then(|s| s.size),
12562                    Some(px(350.)),
12563                    "re-added fixed-width panel should restore persisted size from KVP"
12564                );
12565            });
12566        }
12567
12568        // Flexible panel: both pixel size and ratio are persisted and restored.
12569        {
12570            let project = Project::test(fs.clone(), [], cx).await;
12571            let (multi_workspace, cx) =
12572                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12573            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12574
12575            workspace.update(cx, |workspace, _cx| {
12576                workspace.set_random_database_id();
12577                workspace.bounds.size.width = px(800.);
12578            });
12579
12580            let panel = workspace.update_in(cx, |workspace, window, cx| {
12581                let item = cx.new(|cx| {
12582                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12583                });
12584                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12585
12586                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12587                workspace.add_panel(panel.clone(), window, cx);
12588                workspace.toggle_dock(DockPosition::Right, window, cx);
12589                panel
12590            });
12591
12592            workspace.update_in(cx, |workspace, window, cx| {
12593                workspace.resize_right_dock(px(300.), window, cx);
12594            });
12595
12596            cx.run_until_parked();
12597
12598            let persisted = workspace
12599                .read_with(cx, |workspace, cx| {
12600                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12601                })
12602                .expect("flexible panel state should be persisted to KVP");
12603            assert_eq!(
12604                persisted.size, None,
12605                "flexible panel should not persist a redundant pixel size"
12606            );
12607            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12608
12609            // Remove the panel and re-add: both size and ratio should be restored.
12610            workspace.update_in(cx, |workspace, window, cx| {
12611                workspace.remove_panel(&panel, window, cx);
12612            });
12613
12614            workspace.update_in(cx, |workspace, window, cx| {
12615                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12616                workspace.add_panel(new_panel, window, cx);
12617
12618                let right_dock = workspace.right_dock().read(cx);
12619                let size_state = right_dock
12620                    .panel::<TestPanel>()
12621                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12622                    .expect("re-added flexible panel should have restored size state from KVP");
12623                assert_eq!(
12624                    size_state.size, None,
12625                    "re-added flexible panel should not have a persisted pixel size"
12626                );
12627                assert_eq!(
12628                    size_state.flex,
12629                    Some(original_ratio),
12630                    "re-added flexible panel should restore persisted flex"
12631                );
12632            });
12633        }
12634    }
12635
12636    #[gpui::test]
12637    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12638        init_test(cx);
12639        let fs = FakeFs::new(cx.executor());
12640
12641        let project = Project::test(fs, [], cx).await;
12642        let (multi_workspace, cx) =
12643            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12644        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12645
12646        workspace.update(cx, |workspace, _cx| {
12647            workspace.bounds.size.width = px(900.);
12648        });
12649
12650        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12651        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12652        // and the center pane each take half the workspace width.
12653        workspace.update_in(cx, |workspace, window, cx| {
12654            let item = cx.new(|cx| {
12655                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12656            });
12657            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12658
12659            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12660            workspace.add_panel(panel, window, cx);
12661            workspace.toggle_dock(DockPosition::Left, window, cx);
12662
12663            let left_dock = workspace.left_dock().read(cx);
12664            let left_width = workspace
12665                .dock_size(&left_dock, window, cx)
12666                .expect("left dock should have an active panel");
12667
12668            assert_eq!(
12669                left_width,
12670                workspace.bounds.size.width / 2.,
12671                "flexible left panel should split evenly with the center pane"
12672            );
12673        });
12674
12675        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12676        // change horizontal width fractions, so the flexible panel stays at the same
12677        // width as each half of the split.
12678        workspace.update_in(cx, |workspace, window, cx| {
12679            workspace.split_pane(
12680                workspace.active_pane().clone(),
12681                SplitDirection::Down,
12682                window,
12683                cx,
12684            );
12685
12686            let left_dock = workspace.left_dock().read(cx);
12687            let left_width = workspace
12688                .dock_size(&left_dock, window, cx)
12689                .expect("left dock should still have an active panel after vertical split");
12690
12691            assert_eq!(
12692                left_width,
12693                workspace.bounds.size.width / 2.,
12694                "flexible left panel width should match each vertically-split pane"
12695            );
12696        });
12697
12698        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12699        // size reduces the available width, so the flexible left panel and the center
12700        // panes all shrink proportionally to accommodate it.
12701        workspace.update_in(cx, |workspace, window, cx| {
12702            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12703            workspace.add_panel(panel, window, cx);
12704            workspace.toggle_dock(DockPosition::Right, window, cx);
12705
12706            let right_dock = workspace.right_dock().read(cx);
12707            let right_width = workspace
12708                .dock_size(&right_dock, window, cx)
12709                .expect("right dock should have an active panel");
12710
12711            let left_dock = workspace.left_dock().read(cx);
12712            let left_width = workspace
12713                .dock_size(&left_dock, window, cx)
12714                .expect("left dock should still have an active panel");
12715
12716            let available_width = workspace.bounds.size.width - right_width;
12717            assert_eq!(
12718                left_width,
12719                available_width / 2.,
12720                "flexible left panel should shrink proportionally as the right dock takes space"
12721            );
12722        });
12723
12724        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12725        // flex sizing and the workspace width is divided among left-flex, center
12726        // (implicit flex 1.0), and right-flex.
12727        workspace.update_in(cx, |workspace, window, cx| {
12728            let right_dock = workspace.right_dock().clone();
12729            let right_panel = right_dock
12730                .read(cx)
12731                .visible_panel()
12732                .expect("right dock should have a visible panel")
12733                .clone();
12734            workspace.toggle_dock_panel_flexible_size(
12735                &right_dock,
12736                right_panel.as_ref(),
12737                window,
12738                cx,
12739            );
12740
12741            let right_dock = right_dock.read(cx);
12742            let right_panel = right_dock
12743                .visible_panel()
12744                .expect("right dock should still have a visible panel");
12745            assert!(
12746                right_panel.has_flexible_size(window, cx),
12747                "right panel should now be flexible"
12748            );
12749
12750            let right_size_state = right_dock
12751                .stored_panel_size_state(right_panel.as_ref())
12752                .expect("right panel should have a stored size state after toggling");
12753            let right_flex = right_size_state
12754                .flex
12755                .expect("right panel should have a flex value after toggling");
12756
12757            let left_dock = workspace.left_dock().read(cx);
12758            let left_width = workspace
12759                .dock_size(&left_dock, window, cx)
12760                .expect("left dock should still have an active panel");
12761            let right_width = workspace
12762                .dock_size(&right_dock, window, cx)
12763                .expect("right dock should still have an active panel");
12764
12765            let left_flex = workspace
12766                .default_dock_flex(DockPosition::Left)
12767                .expect("left dock should have a default flex");
12768
12769            let total_flex = left_flex + 1.0 + right_flex;
12770            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12771            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12772            assert_eq!(
12773                left_width, expected_left,
12774                "flexible left panel should share workspace width via flex ratios"
12775            );
12776            assert_eq!(
12777                right_width, expected_right,
12778                "flexible right panel should share workspace width via flex ratios"
12779            );
12780        });
12781    }
12782
12783    struct TestModal(FocusHandle);
12784
12785    impl TestModal {
12786        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12787            Self(cx.focus_handle())
12788        }
12789    }
12790
12791    impl EventEmitter<DismissEvent> for TestModal {}
12792
12793    impl Focusable for TestModal {
12794        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12795            self.0.clone()
12796        }
12797    }
12798
12799    impl ModalView for TestModal {}
12800
12801    impl Render for TestModal {
12802        fn render(
12803            &mut self,
12804            _window: &mut Window,
12805            _cx: &mut Context<TestModal>,
12806        ) -> impl IntoElement {
12807            div().track_focus(&self.0)
12808        }
12809    }
12810
12811    #[gpui::test]
12812    async fn test_panels(cx: &mut gpui::TestAppContext) {
12813        init_test(cx);
12814        let fs = FakeFs::new(cx.executor());
12815
12816        let project = Project::test(fs, [], cx).await;
12817        let (multi_workspace, cx) =
12818            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12819        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12820
12821        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12822            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12823            workspace.add_panel(panel_1.clone(), window, cx);
12824            workspace.toggle_dock(DockPosition::Left, window, cx);
12825            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12826            workspace.add_panel(panel_2.clone(), window, cx);
12827            workspace.toggle_dock(DockPosition::Right, window, cx);
12828
12829            let left_dock = workspace.left_dock();
12830            assert_eq!(
12831                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12832                panel_1.panel_id()
12833            );
12834            assert_eq!(
12835                workspace.dock_size(&left_dock.read(cx), window, cx),
12836                Some(px(300.))
12837            );
12838
12839            workspace.resize_left_dock(px(1337.), window, cx);
12840            assert_eq!(
12841                workspace
12842                    .right_dock()
12843                    .read(cx)
12844                    .visible_panel()
12845                    .unwrap()
12846                    .panel_id(),
12847                panel_2.panel_id(),
12848            );
12849
12850            (panel_1, panel_2)
12851        });
12852
12853        // Move panel_1 to the right
12854        panel_1.update_in(cx, |panel_1, window, cx| {
12855            panel_1.set_position(DockPosition::Right, window, cx)
12856        });
12857
12858        workspace.update_in(cx, |workspace, window, cx| {
12859            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12860            // Since it was the only panel on the left, the left dock should now be closed.
12861            assert!(!workspace.left_dock().read(cx).is_open());
12862            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12863            let right_dock = workspace.right_dock();
12864            assert_eq!(
12865                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12866                panel_1.panel_id()
12867            );
12868            assert_eq!(
12869                right_dock
12870                    .read(cx)
12871                    .active_panel_size()
12872                    .unwrap()
12873                    .size
12874                    .unwrap(),
12875                px(1337.)
12876            );
12877
12878            // Now we move panel_2 to the left
12879            panel_2.set_position(DockPosition::Left, window, cx);
12880        });
12881
12882        workspace.update(cx, |workspace, cx| {
12883            // Since panel_2 was not visible on the right, we don't open the left dock.
12884            assert!(!workspace.left_dock().read(cx).is_open());
12885            // And the right dock is unaffected in its displaying of panel_1
12886            assert!(workspace.right_dock().read(cx).is_open());
12887            assert_eq!(
12888                workspace
12889                    .right_dock()
12890                    .read(cx)
12891                    .visible_panel()
12892                    .unwrap()
12893                    .panel_id(),
12894                panel_1.panel_id(),
12895            );
12896        });
12897
12898        // Move panel_1 back to the left
12899        panel_1.update_in(cx, |panel_1, window, cx| {
12900            panel_1.set_position(DockPosition::Left, window, cx)
12901        });
12902
12903        workspace.update_in(cx, |workspace, window, cx| {
12904            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12905            let left_dock = workspace.left_dock();
12906            assert!(left_dock.read(cx).is_open());
12907            assert_eq!(
12908                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12909                panel_1.panel_id()
12910            );
12911            assert_eq!(
12912                workspace.dock_size(&left_dock.read(cx), window, cx),
12913                Some(px(1337.))
12914            );
12915            // And the right dock should be closed as it no longer has any panels.
12916            assert!(!workspace.right_dock().read(cx).is_open());
12917
12918            // Now we move panel_1 to the bottom
12919            panel_1.set_position(DockPosition::Bottom, window, cx);
12920        });
12921
12922        workspace.update_in(cx, |workspace, window, cx| {
12923            // Since panel_1 was visible on the left, we close the left dock.
12924            assert!(!workspace.left_dock().read(cx).is_open());
12925            // The bottom dock is sized based on the panel's default size,
12926            // since the panel orientation changed from vertical to horizontal.
12927            let bottom_dock = workspace.bottom_dock();
12928            assert_eq!(
12929                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12930                Some(px(300.))
12931            );
12932            // Close bottom dock and move panel_1 back to the left.
12933            bottom_dock.update(cx, |bottom_dock, cx| {
12934                bottom_dock.set_open(false, window, cx)
12935            });
12936            panel_1.set_position(DockPosition::Left, window, cx);
12937        });
12938
12939        // Emit activated event on panel 1
12940        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12941
12942        // Now the left dock is open and panel_1 is active and focused.
12943        workspace.update_in(cx, |workspace, window, cx| {
12944            let left_dock = workspace.left_dock();
12945            assert!(left_dock.read(cx).is_open());
12946            assert_eq!(
12947                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12948                panel_1.panel_id(),
12949            );
12950            assert!(panel_1.focus_handle(cx).is_focused(window));
12951        });
12952
12953        // Emit closed event on panel 2, which is not active
12954        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12955
12956        // Wo don't close the left dock, because panel_2 wasn't the active panel
12957        workspace.update(cx, |workspace, cx| {
12958            let left_dock = workspace.left_dock();
12959            assert!(left_dock.read(cx).is_open());
12960            assert_eq!(
12961                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12962                panel_1.panel_id(),
12963            );
12964        });
12965
12966        // Emitting a ZoomIn event shows the panel as zoomed.
12967        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12968        workspace.read_with(cx, |workspace, _| {
12969            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12970            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12971        });
12972
12973        // Move panel to another dock while it is zoomed
12974        panel_1.update_in(cx, |panel, window, cx| {
12975            panel.set_position(DockPosition::Right, window, cx)
12976        });
12977        workspace.read_with(cx, |workspace, _| {
12978            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12979
12980            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12981        });
12982
12983        // This is a helper for getting a:
12984        // - valid focus on an element,
12985        // - that isn't a part of the panes and panels system of the Workspace,
12986        // - and doesn't trigger the 'on_focus_lost' API.
12987        let focus_other_view = {
12988            let workspace = workspace.clone();
12989            move |cx: &mut VisualTestContext| {
12990                workspace.update_in(cx, |workspace, window, cx| {
12991                    if workspace.active_modal::<TestModal>(cx).is_some() {
12992                        workspace.toggle_modal(window, cx, TestModal::new);
12993                        workspace.toggle_modal(window, cx, TestModal::new);
12994                    } else {
12995                        workspace.toggle_modal(window, cx, TestModal::new);
12996                    }
12997                })
12998            }
12999        };
13000
13001        // If focus is transferred to another view that's not a panel or another pane, we still show
13002        // the panel as zoomed.
13003        focus_other_view(cx);
13004        workspace.read_with(cx, |workspace, _| {
13005            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13006            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13007        });
13008
13009        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13010        workspace.update_in(cx, |_workspace, window, cx| {
13011            cx.focus_self(window);
13012        });
13013        workspace.read_with(cx, |workspace, _| {
13014            assert_eq!(workspace.zoomed, None);
13015            assert_eq!(workspace.zoomed_position, None);
13016        });
13017
13018        // If focus is transferred again to another view that's not a panel or a pane, we won't
13019        // show the panel as zoomed because it wasn't zoomed before.
13020        focus_other_view(cx);
13021        workspace.read_with(cx, |workspace, _| {
13022            assert_eq!(workspace.zoomed, None);
13023            assert_eq!(workspace.zoomed_position, None);
13024        });
13025
13026        // When the panel is activated, it is zoomed again.
13027        cx.dispatch_action(ToggleRightDock);
13028        workspace.read_with(cx, |workspace, _| {
13029            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13030            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13031        });
13032
13033        // Emitting a ZoomOut event unzooms the panel.
13034        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13035        workspace.read_with(cx, |workspace, _| {
13036            assert_eq!(workspace.zoomed, None);
13037            assert_eq!(workspace.zoomed_position, None);
13038        });
13039
13040        // Emit closed event on panel 1, which is active
13041        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13042
13043        // Now the left dock is closed, because panel_1 was the active panel
13044        workspace.update(cx, |workspace, cx| {
13045            let right_dock = workspace.right_dock();
13046            assert!(!right_dock.read(cx).is_open());
13047        });
13048    }
13049
13050    #[gpui::test]
13051    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13052        init_test(cx);
13053
13054        let fs = FakeFs::new(cx.background_executor.clone());
13055        let project = Project::test(fs, [], cx).await;
13056        let (workspace, cx) =
13057            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13058        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13059
13060        let dirty_regular_buffer = cx.new(|cx| {
13061            TestItem::new(cx)
13062                .with_dirty(true)
13063                .with_label("1.txt")
13064                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13065        });
13066        let dirty_regular_buffer_2 = cx.new(|cx| {
13067            TestItem::new(cx)
13068                .with_dirty(true)
13069                .with_label("2.txt")
13070                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13071        });
13072        let dirty_multi_buffer_with_both = cx.new(|cx| {
13073            TestItem::new(cx)
13074                .with_dirty(true)
13075                .with_buffer_kind(ItemBufferKind::Multibuffer)
13076                .with_label("Fake Project Search")
13077                .with_project_items(&[
13078                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13079                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13080                ])
13081        });
13082        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13083        workspace.update_in(cx, |workspace, window, cx| {
13084            workspace.add_item(
13085                pane.clone(),
13086                Box::new(dirty_regular_buffer.clone()),
13087                None,
13088                false,
13089                false,
13090                window,
13091                cx,
13092            );
13093            workspace.add_item(
13094                pane.clone(),
13095                Box::new(dirty_regular_buffer_2.clone()),
13096                None,
13097                false,
13098                false,
13099                window,
13100                cx,
13101            );
13102            workspace.add_item(
13103                pane.clone(),
13104                Box::new(dirty_multi_buffer_with_both.clone()),
13105                None,
13106                false,
13107                false,
13108                window,
13109                cx,
13110            );
13111        });
13112
13113        pane.update_in(cx, |pane, window, cx| {
13114            pane.activate_item(2, true, true, window, cx);
13115            assert_eq!(
13116                pane.active_item().unwrap().item_id(),
13117                multi_buffer_with_both_files_id,
13118                "Should select the multi buffer in the pane"
13119            );
13120        });
13121        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13122            pane.close_other_items(
13123                &CloseOtherItems {
13124                    save_intent: Some(SaveIntent::Save),
13125                    close_pinned: true,
13126                },
13127                None,
13128                window,
13129                cx,
13130            )
13131        });
13132        cx.background_executor.run_until_parked();
13133        assert!(!cx.has_pending_prompt());
13134        close_all_but_multi_buffer_task
13135            .await
13136            .expect("Closing all buffers but the multi buffer failed");
13137        pane.update(cx, |pane, cx| {
13138            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13139            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13140            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13141            assert_eq!(pane.items_len(), 1);
13142            assert_eq!(
13143                pane.active_item().unwrap().item_id(),
13144                multi_buffer_with_both_files_id,
13145                "Should have only the multi buffer left in the pane"
13146            );
13147            assert!(
13148                dirty_multi_buffer_with_both.read(cx).is_dirty,
13149                "The multi buffer containing the unsaved buffer should still be dirty"
13150            );
13151        });
13152
13153        dirty_regular_buffer.update(cx, |buffer, cx| {
13154            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13155        });
13156
13157        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13158            pane.close_active_item(
13159                &CloseActiveItem {
13160                    save_intent: Some(SaveIntent::Close),
13161                    close_pinned: false,
13162                },
13163                window,
13164                cx,
13165            )
13166        });
13167        cx.background_executor.run_until_parked();
13168        assert!(
13169            cx.has_pending_prompt(),
13170            "Dirty multi buffer should prompt a save dialog"
13171        );
13172        cx.simulate_prompt_answer("Save");
13173        cx.background_executor.run_until_parked();
13174        close_multi_buffer_task
13175            .await
13176            .expect("Closing the multi buffer failed");
13177        pane.update(cx, |pane, cx| {
13178            assert_eq!(
13179                dirty_multi_buffer_with_both.read(cx).save_count,
13180                1,
13181                "Multi buffer item should get be saved"
13182            );
13183            // Test impl does not save inner items, so we do not assert them
13184            assert_eq!(
13185                pane.items_len(),
13186                0,
13187                "No more items should be left in the pane"
13188            );
13189            assert!(pane.active_item().is_none());
13190        });
13191    }
13192
13193    #[gpui::test]
13194    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13195        cx: &mut TestAppContext,
13196    ) {
13197        init_test(cx);
13198
13199        let fs = FakeFs::new(cx.background_executor.clone());
13200        let project = Project::test(fs, [], cx).await;
13201        let (workspace, cx) =
13202            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13203        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13204
13205        let dirty_regular_buffer = cx.new(|cx| {
13206            TestItem::new(cx)
13207                .with_dirty(true)
13208                .with_label("1.txt")
13209                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13210        });
13211        let dirty_regular_buffer_2 = cx.new(|cx| {
13212            TestItem::new(cx)
13213                .with_dirty(true)
13214                .with_label("2.txt")
13215                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13216        });
13217        let clear_regular_buffer = cx.new(|cx| {
13218            TestItem::new(cx)
13219                .with_label("3.txt")
13220                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13221        });
13222
13223        let dirty_multi_buffer_with_both = cx.new(|cx| {
13224            TestItem::new(cx)
13225                .with_dirty(true)
13226                .with_buffer_kind(ItemBufferKind::Multibuffer)
13227                .with_label("Fake Project Search")
13228                .with_project_items(&[
13229                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13230                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13231                    clear_regular_buffer.read(cx).project_items[0].clone(),
13232                ])
13233        });
13234        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13235        workspace.update_in(cx, |workspace, window, cx| {
13236            workspace.add_item(
13237                pane.clone(),
13238                Box::new(dirty_regular_buffer.clone()),
13239                None,
13240                false,
13241                false,
13242                window,
13243                cx,
13244            );
13245            workspace.add_item(
13246                pane.clone(),
13247                Box::new(dirty_multi_buffer_with_both.clone()),
13248                None,
13249                false,
13250                false,
13251                window,
13252                cx,
13253            );
13254        });
13255
13256        pane.update_in(cx, |pane, window, cx| {
13257            pane.activate_item(1, true, true, window, cx);
13258            assert_eq!(
13259                pane.active_item().unwrap().item_id(),
13260                multi_buffer_with_both_files_id,
13261                "Should select the multi buffer in the pane"
13262            );
13263        });
13264        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13265            pane.close_active_item(
13266                &CloseActiveItem {
13267                    save_intent: None,
13268                    close_pinned: false,
13269                },
13270                window,
13271                cx,
13272            )
13273        });
13274        cx.background_executor.run_until_parked();
13275        assert!(
13276            cx.has_pending_prompt(),
13277            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13278        );
13279    }
13280
13281    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13282    /// closed when they are deleted from disk.
13283    #[gpui::test]
13284    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13285        init_test(cx);
13286
13287        // Enable the close_on_disk_deletion setting
13288        cx.update_global(|store: &mut SettingsStore, cx| {
13289            store.update_user_settings(cx, |settings| {
13290                settings.workspace.close_on_file_delete = Some(true);
13291            });
13292        });
13293
13294        let fs = FakeFs::new(cx.background_executor.clone());
13295        let project = Project::test(fs, [], cx).await;
13296        let (workspace, cx) =
13297            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13298        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13299
13300        // Create a test item that simulates a file
13301        let item = cx.new(|cx| {
13302            TestItem::new(cx)
13303                .with_label("test.txt")
13304                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13305        });
13306
13307        // Add item to workspace
13308        workspace.update_in(cx, |workspace, window, cx| {
13309            workspace.add_item(
13310                pane.clone(),
13311                Box::new(item.clone()),
13312                None,
13313                false,
13314                false,
13315                window,
13316                cx,
13317            );
13318        });
13319
13320        // Verify the item is in the pane
13321        pane.read_with(cx, |pane, _| {
13322            assert_eq!(pane.items().count(), 1);
13323        });
13324
13325        // Simulate file deletion by setting the item's deleted state
13326        item.update(cx, |item, _| {
13327            item.set_has_deleted_file(true);
13328        });
13329
13330        // Emit UpdateTab event to trigger the close behavior
13331        cx.run_until_parked();
13332        item.update(cx, |_, cx| {
13333            cx.emit(ItemEvent::UpdateTab);
13334        });
13335
13336        // Allow the close operation to complete
13337        cx.run_until_parked();
13338
13339        // Verify the item was automatically closed
13340        pane.read_with(cx, |pane, _| {
13341            assert_eq!(
13342                pane.items().count(),
13343                0,
13344                "Item should be automatically closed when file is deleted"
13345            );
13346        });
13347    }
13348
13349    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13350    /// open with a strikethrough when they are deleted from disk.
13351    #[gpui::test]
13352    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13353        init_test(cx);
13354
13355        // Ensure close_on_disk_deletion is disabled (default)
13356        cx.update_global(|store: &mut SettingsStore, cx| {
13357            store.update_user_settings(cx, |settings| {
13358                settings.workspace.close_on_file_delete = Some(false);
13359            });
13360        });
13361
13362        let fs = FakeFs::new(cx.background_executor.clone());
13363        let project = Project::test(fs, [], cx).await;
13364        let (workspace, cx) =
13365            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13366        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13367
13368        // Create a test item that simulates a file
13369        let item = cx.new(|cx| {
13370            TestItem::new(cx)
13371                .with_label("test.txt")
13372                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13373        });
13374
13375        // Add item to workspace
13376        workspace.update_in(cx, |workspace, window, cx| {
13377            workspace.add_item(
13378                pane.clone(),
13379                Box::new(item.clone()),
13380                None,
13381                false,
13382                false,
13383                window,
13384                cx,
13385            );
13386        });
13387
13388        // Verify the item is in the pane
13389        pane.read_with(cx, |pane, _| {
13390            assert_eq!(pane.items().count(), 1);
13391        });
13392
13393        // Simulate file deletion
13394        item.update(cx, |item, _| {
13395            item.set_has_deleted_file(true);
13396        });
13397
13398        // Emit UpdateTab event
13399        cx.run_until_parked();
13400        item.update(cx, |_, cx| {
13401            cx.emit(ItemEvent::UpdateTab);
13402        });
13403
13404        // Allow any potential close operation to complete
13405        cx.run_until_parked();
13406
13407        // Verify the item remains open (with strikethrough)
13408        pane.read_with(cx, |pane, _| {
13409            assert_eq!(
13410                pane.items().count(),
13411                1,
13412                "Item should remain open when close_on_disk_deletion is disabled"
13413            );
13414        });
13415
13416        // Verify the item shows as deleted
13417        item.read_with(cx, |item, _| {
13418            assert!(
13419                item.has_deleted_file,
13420                "Item should be marked as having deleted file"
13421            );
13422        });
13423    }
13424
13425    /// Tests that dirty files are not automatically closed when deleted from disk,
13426    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13427    /// unsaved changes without being prompted.
13428    #[gpui::test]
13429    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13430        init_test(cx);
13431
13432        // Enable the close_on_file_delete setting
13433        cx.update_global(|store: &mut SettingsStore, cx| {
13434            store.update_user_settings(cx, |settings| {
13435                settings.workspace.close_on_file_delete = Some(true);
13436            });
13437        });
13438
13439        let fs = FakeFs::new(cx.background_executor.clone());
13440        let project = Project::test(fs, [], cx).await;
13441        let (workspace, cx) =
13442            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13443        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13444
13445        // Create a dirty test item
13446        let item = cx.new(|cx| {
13447            TestItem::new(cx)
13448                .with_dirty(true)
13449                .with_label("test.txt")
13450                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13451        });
13452
13453        // Add item to workspace
13454        workspace.update_in(cx, |workspace, window, cx| {
13455            workspace.add_item(
13456                pane.clone(),
13457                Box::new(item.clone()),
13458                None,
13459                false,
13460                false,
13461                window,
13462                cx,
13463            );
13464        });
13465
13466        // Simulate file deletion
13467        item.update(cx, |item, _| {
13468            item.set_has_deleted_file(true);
13469        });
13470
13471        // Emit UpdateTab event to trigger the close behavior
13472        cx.run_until_parked();
13473        item.update(cx, |_, cx| {
13474            cx.emit(ItemEvent::UpdateTab);
13475        });
13476
13477        // Allow any potential close operation to complete
13478        cx.run_until_parked();
13479
13480        // Verify the item remains open (dirty files are not auto-closed)
13481        pane.read_with(cx, |pane, _| {
13482            assert_eq!(
13483                pane.items().count(),
13484                1,
13485                "Dirty items should not be automatically closed even when file is deleted"
13486            );
13487        });
13488
13489        // Verify the item is marked as deleted and still dirty
13490        item.read_with(cx, |item, _| {
13491            assert!(
13492                item.has_deleted_file,
13493                "Item should be marked as having deleted file"
13494            );
13495            assert!(item.is_dirty, "Item should still be dirty");
13496        });
13497    }
13498
13499    /// Tests that navigation history is cleaned up when files are auto-closed
13500    /// due to deletion from disk.
13501    #[gpui::test]
13502    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13503        init_test(cx);
13504
13505        // Enable the close_on_file_delete setting
13506        cx.update_global(|store: &mut SettingsStore, cx| {
13507            store.update_user_settings(cx, |settings| {
13508                settings.workspace.close_on_file_delete = Some(true);
13509            });
13510        });
13511
13512        let fs = FakeFs::new(cx.background_executor.clone());
13513        let project = Project::test(fs, [], cx).await;
13514        let (workspace, cx) =
13515            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13516        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13517
13518        // Create test items
13519        let item1 = cx.new(|cx| {
13520            TestItem::new(cx)
13521                .with_label("test1.txt")
13522                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13523        });
13524        let item1_id = item1.item_id();
13525
13526        let item2 = cx.new(|cx| {
13527            TestItem::new(cx)
13528                .with_label("test2.txt")
13529                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13530        });
13531
13532        // Add items to workspace
13533        workspace.update_in(cx, |workspace, window, cx| {
13534            workspace.add_item(
13535                pane.clone(),
13536                Box::new(item1.clone()),
13537                None,
13538                false,
13539                false,
13540                window,
13541                cx,
13542            );
13543            workspace.add_item(
13544                pane.clone(),
13545                Box::new(item2.clone()),
13546                None,
13547                false,
13548                false,
13549                window,
13550                cx,
13551            );
13552        });
13553
13554        // Activate item1 to ensure it gets navigation entries
13555        pane.update_in(cx, |pane, window, cx| {
13556            pane.activate_item(0, true, true, window, cx);
13557        });
13558
13559        // Switch to item2 and back to create navigation history
13560        pane.update_in(cx, |pane, window, cx| {
13561            pane.activate_item(1, true, true, window, cx);
13562        });
13563        cx.run_until_parked();
13564
13565        pane.update_in(cx, |pane, window, cx| {
13566            pane.activate_item(0, true, true, window, cx);
13567        });
13568        cx.run_until_parked();
13569
13570        // Simulate file deletion for item1
13571        item1.update(cx, |item, _| {
13572            item.set_has_deleted_file(true);
13573        });
13574
13575        // Emit UpdateTab event to trigger the close behavior
13576        item1.update(cx, |_, cx| {
13577            cx.emit(ItemEvent::UpdateTab);
13578        });
13579        cx.run_until_parked();
13580
13581        // Verify item1 was closed
13582        pane.read_with(cx, |pane, _| {
13583            assert_eq!(
13584                pane.items().count(),
13585                1,
13586                "Should have 1 item remaining after auto-close"
13587            );
13588        });
13589
13590        // Check navigation history after close
13591        let has_item = pane.read_with(cx, |pane, cx| {
13592            let mut has_item = false;
13593            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13594                if entry.item.id() == item1_id {
13595                    has_item = true;
13596                }
13597            });
13598            has_item
13599        });
13600
13601        assert!(
13602            !has_item,
13603            "Navigation history should not contain closed item entries"
13604        );
13605    }
13606
13607    #[gpui::test]
13608    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13609        cx: &mut TestAppContext,
13610    ) {
13611        init_test(cx);
13612
13613        let fs = FakeFs::new(cx.background_executor.clone());
13614        let project = Project::test(fs, [], cx).await;
13615        let (workspace, cx) =
13616            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13617        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13618
13619        let dirty_regular_buffer = cx.new(|cx| {
13620            TestItem::new(cx)
13621                .with_dirty(true)
13622                .with_label("1.txt")
13623                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13624        });
13625        let dirty_regular_buffer_2 = cx.new(|cx| {
13626            TestItem::new(cx)
13627                .with_dirty(true)
13628                .with_label("2.txt")
13629                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13630        });
13631        let clear_regular_buffer = cx.new(|cx| {
13632            TestItem::new(cx)
13633                .with_label("3.txt")
13634                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13635        });
13636
13637        let dirty_multi_buffer = cx.new(|cx| {
13638            TestItem::new(cx)
13639                .with_dirty(true)
13640                .with_buffer_kind(ItemBufferKind::Multibuffer)
13641                .with_label("Fake Project Search")
13642                .with_project_items(&[
13643                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13644                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13645                    clear_regular_buffer.read(cx).project_items[0].clone(),
13646                ])
13647        });
13648        workspace.update_in(cx, |workspace, window, cx| {
13649            workspace.add_item(
13650                pane.clone(),
13651                Box::new(dirty_regular_buffer.clone()),
13652                None,
13653                false,
13654                false,
13655                window,
13656                cx,
13657            );
13658            workspace.add_item(
13659                pane.clone(),
13660                Box::new(dirty_regular_buffer_2.clone()),
13661                None,
13662                false,
13663                false,
13664                window,
13665                cx,
13666            );
13667            workspace.add_item(
13668                pane.clone(),
13669                Box::new(dirty_multi_buffer.clone()),
13670                None,
13671                false,
13672                false,
13673                window,
13674                cx,
13675            );
13676        });
13677
13678        pane.update_in(cx, |pane, window, cx| {
13679            pane.activate_item(2, true, true, window, cx);
13680            assert_eq!(
13681                pane.active_item().unwrap().item_id(),
13682                dirty_multi_buffer.item_id(),
13683                "Should select the multi buffer in the pane"
13684            );
13685        });
13686        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13687            pane.close_active_item(
13688                &CloseActiveItem {
13689                    save_intent: None,
13690                    close_pinned: false,
13691                },
13692                window,
13693                cx,
13694            )
13695        });
13696        cx.background_executor.run_until_parked();
13697        assert!(
13698            !cx.has_pending_prompt(),
13699            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13700        );
13701        close_multi_buffer_task
13702            .await
13703            .expect("Closing multi buffer failed");
13704        pane.update(cx, |pane, cx| {
13705            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13706            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13707            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13708            assert_eq!(
13709                pane.items()
13710                    .map(|item| item.item_id())
13711                    .sorted()
13712                    .collect::<Vec<_>>(),
13713                vec![
13714                    dirty_regular_buffer.item_id(),
13715                    dirty_regular_buffer_2.item_id(),
13716                ],
13717                "Should have no multi buffer left in the pane"
13718            );
13719            assert!(dirty_regular_buffer.read(cx).is_dirty);
13720            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13721        });
13722    }
13723
13724    #[gpui::test]
13725    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13726        init_test(cx);
13727        let fs = FakeFs::new(cx.executor());
13728        let project = Project::test(fs, [], cx).await;
13729        let (multi_workspace, cx) =
13730            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13731        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13732
13733        // Add a new panel to the right dock, opening the dock and setting the
13734        // focus to the new panel.
13735        let panel = workspace.update_in(cx, |workspace, window, cx| {
13736            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13737            workspace.add_panel(panel.clone(), window, cx);
13738
13739            workspace
13740                .right_dock()
13741                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13742
13743            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13744
13745            panel
13746        });
13747
13748        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13749        // panel to the next valid position which, in this case, is the left
13750        // dock.
13751        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13752        workspace.update(cx, |workspace, cx| {
13753            assert!(workspace.left_dock().read(cx).is_open());
13754            assert_eq!(panel.read(cx).position, DockPosition::Left);
13755        });
13756
13757        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13758        // panel to the next valid position which, in this case, is the bottom
13759        // dock.
13760        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13761        workspace.update(cx, |workspace, cx| {
13762            assert!(workspace.bottom_dock().read(cx).is_open());
13763            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13764        });
13765
13766        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13767        // around moving the panel to its initial position, the right dock.
13768        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13769        workspace.update(cx, |workspace, cx| {
13770            assert!(workspace.right_dock().read(cx).is_open());
13771            assert_eq!(panel.read(cx).position, DockPosition::Right);
13772        });
13773
13774        // Remove focus from the panel, ensuring that, if the panel is not
13775        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13776        // the panel's position, so the panel is still in the right dock.
13777        workspace.update_in(cx, |workspace, window, cx| {
13778            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13779        });
13780
13781        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13782        workspace.update(cx, |workspace, cx| {
13783            assert!(workspace.right_dock().read(cx).is_open());
13784            assert_eq!(panel.read(cx).position, DockPosition::Right);
13785        });
13786    }
13787
13788    #[gpui::test]
13789    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13790        init_test(cx);
13791
13792        let fs = FakeFs::new(cx.executor());
13793        let project = Project::test(fs, [], cx).await;
13794        let (workspace, cx) =
13795            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13796
13797        let item_1 = cx.new(|cx| {
13798            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13799        });
13800        workspace.update_in(cx, |workspace, window, cx| {
13801            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13802            workspace.move_item_to_pane_in_direction(
13803                &MoveItemToPaneInDirection {
13804                    direction: SplitDirection::Right,
13805                    focus: true,
13806                    clone: false,
13807                },
13808                window,
13809                cx,
13810            );
13811            workspace.move_item_to_pane_at_index(
13812                &MoveItemToPane {
13813                    destination: 3,
13814                    focus: true,
13815                    clone: false,
13816                },
13817                window,
13818                cx,
13819            );
13820
13821            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13822            assert_eq!(
13823                pane_items_paths(&workspace.active_pane, cx),
13824                vec!["first.txt".to_string()],
13825                "Single item was not moved anywhere"
13826            );
13827        });
13828
13829        let item_2 = cx.new(|cx| {
13830            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13831        });
13832        workspace.update_in(cx, |workspace, window, cx| {
13833            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13834            assert_eq!(
13835                pane_items_paths(&workspace.panes[0], cx),
13836                vec!["first.txt".to_string(), "second.txt".to_string()],
13837            );
13838            workspace.move_item_to_pane_in_direction(
13839                &MoveItemToPaneInDirection {
13840                    direction: SplitDirection::Right,
13841                    focus: true,
13842                    clone: false,
13843                },
13844                window,
13845                cx,
13846            );
13847
13848            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13849            assert_eq!(
13850                pane_items_paths(&workspace.panes[0], cx),
13851                vec!["first.txt".to_string()],
13852                "After moving, one item should be left in the original pane"
13853            );
13854            assert_eq!(
13855                pane_items_paths(&workspace.panes[1], cx),
13856                vec!["second.txt".to_string()],
13857                "New item should have been moved to the new pane"
13858            );
13859        });
13860
13861        let item_3 = cx.new(|cx| {
13862            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13863        });
13864        workspace.update_in(cx, |workspace, window, cx| {
13865            let original_pane = workspace.panes[0].clone();
13866            workspace.set_active_pane(&original_pane, window, cx);
13867            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13868            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13869            assert_eq!(
13870                pane_items_paths(&workspace.active_pane, cx),
13871                vec!["first.txt".to_string(), "third.txt".to_string()],
13872                "New pane should be ready to move one item out"
13873            );
13874
13875            workspace.move_item_to_pane_at_index(
13876                &MoveItemToPane {
13877                    destination: 3,
13878                    focus: true,
13879                    clone: false,
13880                },
13881                window,
13882                cx,
13883            );
13884            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13885            assert_eq!(
13886                pane_items_paths(&workspace.active_pane, cx),
13887                vec!["first.txt".to_string()],
13888                "After moving, one item should be left in the original pane"
13889            );
13890            assert_eq!(
13891                pane_items_paths(&workspace.panes[1], cx),
13892                vec!["second.txt".to_string()],
13893                "Previously created pane should be unchanged"
13894            );
13895            assert_eq!(
13896                pane_items_paths(&workspace.panes[2], cx),
13897                vec!["third.txt".to_string()],
13898                "New item should have been moved to the new pane"
13899            );
13900        });
13901    }
13902
13903    #[gpui::test]
13904    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13905        init_test(cx);
13906
13907        let fs = FakeFs::new(cx.executor());
13908        let project = Project::test(fs, [], cx).await;
13909        let (workspace, cx) =
13910            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13911
13912        let item_1 = cx.new(|cx| {
13913            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13914        });
13915        workspace.update_in(cx, |workspace, window, cx| {
13916            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13917            workspace.move_item_to_pane_in_direction(
13918                &MoveItemToPaneInDirection {
13919                    direction: SplitDirection::Right,
13920                    focus: true,
13921                    clone: true,
13922                },
13923                window,
13924                cx,
13925            );
13926        });
13927        cx.run_until_parked();
13928        workspace.update_in(cx, |workspace, window, cx| {
13929            workspace.move_item_to_pane_at_index(
13930                &MoveItemToPane {
13931                    destination: 3,
13932                    focus: true,
13933                    clone: true,
13934                },
13935                window,
13936                cx,
13937            );
13938        });
13939        cx.run_until_parked();
13940
13941        workspace.update(cx, |workspace, cx| {
13942            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13943            for pane in workspace.panes() {
13944                assert_eq!(
13945                    pane_items_paths(pane, cx),
13946                    vec!["first.txt".to_string()],
13947                    "Single item exists in all panes"
13948                );
13949            }
13950        });
13951
13952        // verify that the active pane has been updated after waiting for the
13953        // pane focus event to fire and resolve
13954        workspace.read_with(cx, |workspace, _app| {
13955            assert_eq!(
13956                workspace.active_pane(),
13957                &workspace.panes[2],
13958                "The third pane should be the active one: {:?}",
13959                workspace.panes
13960            );
13961        })
13962    }
13963
13964    #[gpui::test]
13965    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13966        init_test(cx);
13967
13968        let fs = FakeFs::new(cx.executor());
13969        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13970
13971        let project = Project::test(fs, ["root".as_ref()], cx).await;
13972        let (workspace, cx) =
13973            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13974
13975        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13976        // Add item to pane A with project path
13977        let item_a = cx.new(|cx| {
13978            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13979        });
13980        workspace.update_in(cx, |workspace, window, cx| {
13981            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13982        });
13983
13984        // Split to create pane B
13985        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13986            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13987        });
13988
13989        // Add item with SAME project path to pane B, and pin it
13990        let item_b = cx.new(|cx| {
13991            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13992        });
13993        pane_b.update_in(cx, |pane, window, cx| {
13994            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13995            pane.set_pinned_count(1);
13996        });
13997
13998        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13999        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14000
14001        // close_pinned: false should only close the unpinned copy
14002        workspace.update_in(cx, |workspace, window, cx| {
14003            workspace.close_item_in_all_panes(
14004                &CloseItemInAllPanes {
14005                    save_intent: Some(SaveIntent::Close),
14006                    close_pinned: false,
14007                },
14008                window,
14009                cx,
14010            )
14011        });
14012        cx.executor().run_until_parked();
14013
14014        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14015        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14016        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14017        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14018
14019        // Split again, seeing as closing the previous item also closed its
14020        // pane, so only pane remains, which does not allow us to properly test
14021        // that both items close when `close_pinned: true`.
14022        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14023            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14024        });
14025
14026        // Add an item with the same project path to pane C so that
14027        // close_item_in_all_panes can determine what to close across all panes
14028        // (it reads the active item from the active pane, and split_pane
14029        // creates an empty pane).
14030        let item_c = cx.new(|cx| {
14031            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14032        });
14033        pane_c.update_in(cx, |pane, window, cx| {
14034            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14035        });
14036
14037        // close_pinned: true should close the pinned copy too
14038        workspace.update_in(cx, |workspace, window, cx| {
14039            let panes_count = workspace.panes().len();
14040            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14041
14042            workspace.close_item_in_all_panes(
14043                &CloseItemInAllPanes {
14044                    save_intent: Some(SaveIntent::Close),
14045                    close_pinned: true,
14046                },
14047                window,
14048                cx,
14049            )
14050        });
14051        cx.executor().run_until_parked();
14052
14053        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14054        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14055        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14056        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14057    }
14058
14059    mod register_project_item_tests {
14060
14061        use super::*;
14062
14063        // View
14064        struct TestPngItemView {
14065            focus_handle: FocusHandle,
14066        }
14067        // Model
14068        struct TestPngItem {}
14069
14070        impl project::ProjectItem for TestPngItem {
14071            fn try_open(
14072                _project: &Entity<Project>,
14073                path: &ProjectPath,
14074                cx: &mut App,
14075            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14076                if path.path.extension().unwrap() == "png" {
14077                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14078                } else {
14079                    None
14080                }
14081            }
14082
14083            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14084                None
14085            }
14086
14087            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14088                None
14089            }
14090
14091            fn is_dirty(&self) -> bool {
14092                false
14093            }
14094        }
14095
14096        impl Item for TestPngItemView {
14097            type Event = ();
14098            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14099                "".into()
14100            }
14101        }
14102        impl EventEmitter<()> for TestPngItemView {}
14103        impl Focusable for TestPngItemView {
14104            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14105                self.focus_handle.clone()
14106            }
14107        }
14108
14109        impl Render for TestPngItemView {
14110            fn render(
14111                &mut self,
14112                _window: &mut Window,
14113                _cx: &mut Context<Self>,
14114            ) -> impl IntoElement {
14115                Empty
14116            }
14117        }
14118
14119        impl ProjectItem for TestPngItemView {
14120            type Item = TestPngItem;
14121
14122            fn for_project_item(
14123                _project: Entity<Project>,
14124                _pane: Option<&Pane>,
14125                _item: Entity<Self::Item>,
14126                _: &mut Window,
14127                cx: &mut Context<Self>,
14128            ) -> Self
14129            where
14130                Self: Sized,
14131            {
14132                Self {
14133                    focus_handle: cx.focus_handle(),
14134                }
14135            }
14136        }
14137
14138        // View
14139        struct TestIpynbItemView {
14140            focus_handle: FocusHandle,
14141        }
14142        // Model
14143        struct TestIpynbItem {}
14144
14145        impl project::ProjectItem for TestIpynbItem {
14146            fn try_open(
14147                _project: &Entity<Project>,
14148                path: &ProjectPath,
14149                cx: &mut App,
14150            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14151                if path.path.extension().unwrap() == "ipynb" {
14152                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14153                } else {
14154                    None
14155                }
14156            }
14157
14158            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14159                None
14160            }
14161
14162            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14163                None
14164            }
14165
14166            fn is_dirty(&self) -> bool {
14167                false
14168            }
14169        }
14170
14171        impl Item for TestIpynbItemView {
14172            type Event = ();
14173            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14174                "".into()
14175            }
14176        }
14177        impl EventEmitter<()> for TestIpynbItemView {}
14178        impl Focusable for TestIpynbItemView {
14179            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14180                self.focus_handle.clone()
14181            }
14182        }
14183
14184        impl Render for TestIpynbItemView {
14185            fn render(
14186                &mut self,
14187                _window: &mut Window,
14188                _cx: &mut Context<Self>,
14189            ) -> impl IntoElement {
14190                Empty
14191            }
14192        }
14193
14194        impl ProjectItem for TestIpynbItemView {
14195            type Item = TestIpynbItem;
14196
14197            fn for_project_item(
14198                _project: Entity<Project>,
14199                _pane: Option<&Pane>,
14200                _item: Entity<Self::Item>,
14201                _: &mut Window,
14202                cx: &mut Context<Self>,
14203            ) -> Self
14204            where
14205                Self: Sized,
14206            {
14207                Self {
14208                    focus_handle: cx.focus_handle(),
14209                }
14210            }
14211        }
14212
14213        struct TestAlternatePngItemView {
14214            focus_handle: FocusHandle,
14215        }
14216
14217        impl Item for TestAlternatePngItemView {
14218            type Event = ();
14219            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14220                "".into()
14221            }
14222        }
14223
14224        impl EventEmitter<()> for TestAlternatePngItemView {}
14225        impl Focusable for TestAlternatePngItemView {
14226            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14227                self.focus_handle.clone()
14228            }
14229        }
14230
14231        impl Render for TestAlternatePngItemView {
14232            fn render(
14233                &mut self,
14234                _window: &mut Window,
14235                _cx: &mut Context<Self>,
14236            ) -> impl IntoElement {
14237                Empty
14238            }
14239        }
14240
14241        impl ProjectItem for TestAlternatePngItemView {
14242            type Item = TestPngItem;
14243
14244            fn for_project_item(
14245                _project: Entity<Project>,
14246                _pane: Option<&Pane>,
14247                _item: Entity<Self::Item>,
14248                _: &mut Window,
14249                cx: &mut Context<Self>,
14250            ) -> Self
14251            where
14252                Self: Sized,
14253            {
14254                Self {
14255                    focus_handle: cx.focus_handle(),
14256                }
14257            }
14258        }
14259
14260        #[gpui::test]
14261        async fn test_register_project_item(cx: &mut TestAppContext) {
14262            init_test(cx);
14263
14264            cx.update(|cx| {
14265                register_project_item::<TestPngItemView>(cx);
14266                register_project_item::<TestIpynbItemView>(cx);
14267            });
14268
14269            let fs = FakeFs::new(cx.executor());
14270            fs.insert_tree(
14271                "/root1",
14272                json!({
14273                    "one.png": "BINARYDATAHERE",
14274                    "two.ipynb": "{ totally a notebook }",
14275                    "three.txt": "editing text, sure why not?"
14276                }),
14277            )
14278            .await;
14279
14280            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14281            let (workspace, cx) =
14282                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14283
14284            let worktree_id = project.update(cx, |project, cx| {
14285                project.worktrees(cx).next().unwrap().read(cx).id()
14286            });
14287
14288            let handle = workspace
14289                .update_in(cx, |workspace, window, cx| {
14290                    let project_path = (worktree_id, rel_path("one.png"));
14291                    workspace.open_path(project_path, None, true, window, cx)
14292                })
14293                .await
14294                .unwrap();
14295
14296            // Now we can check if the handle we got back errored or not
14297            assert_eq!(
14298                handle.to_any_view().entity_type(),
14299                TypeId::of::<TestPngItemView>()
14300            );
14301
14302            let handle = workspace
14303                .update_in(cx, |workspace, window, cx| {
14304                    let project_path = (worktree_id, rel_path("two.ipynb"));
14305                    workspace.open_path(project_path, None, true, window, cx)
14306                })
14307                .await
14308                .unwrap();
14309
14310            assert_eq!(
14311                handle.to_any_view().entity_type(),
14312                TypeId::of::<TestIpynbItemView>()
14313            );
14314
14315            let handle = workspace
14316                .update_in(cx, |workspace, window, cx| {
14317                    let project_path = (worktree_id, rel_path("three.txt"));
14318                    workspace.open_path(project_path, None, true, window, cx)
14319                })
14320                .await;
14321            assert!(handle.is_err());
14322        }
14323
14324        #[gpui::test]
14325        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14326            init_test(cx);
14327
14328            cx.update(|cx| {
14329                register_project_item::<TestPngItemView>(cx);
14330                register_project_item::<TestAlternatePngItemView>(cx);
14331            });
14332
14333            let fs = FakeFs::new(cx.executor());
14334            fs.insert_tree(
14335                "/root1",
14336                json!({
14337                    "one.png": "BINARYDATAHERE",
14338                    "two.ipynb": "{ totally a notebook }",
14339                    "three.txt": "editing text, sure why not?"
14340                }),
14341            )
14342            .await;
14343            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14344            let (workspace, cx) =
14345                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14346            let worktree_id = project.update(cx, |project, cx| {
14347                project.worktrees(cx).next().unwrap().read(cx).id()
14348            });
14349
14350            let handle = workspace
14351                .update_in(cx, |workspace, window, cx| {
14352                    let project_path = (worktree_id, rel_path("one.png"));
14353                    workspace.open_path(project_path, None, true, window, cx)
14354                })
14355                .await
14356                .unwrap();
14357
14358            // This _must_ be the second item registered
14359            assert_eq!(
14360                handle.to_any_view().entity_type(),
14361                TypeId::of::<TestAlternatePngItemView>()
14362            );
14363
14364            let handle = workspace
14365                .update_in(cx, |workspace, window, cx| {
14366                    let project_path = (worktree_id, rel_path("three.txt"));
14367                    workspace.open_path(project_path, None, true, window, cx)
14368                })
14369                .await;
14370            assert!(handle.is_err());
14371        }
14372    }
14373
14374    #[gpui::test]
14375    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14376        init_test(cx);
14377
14378        let fs = FakeFs::new(cx.executor());
14379        let project = Project::test(fs, [], cx).await;
14380        let (workspace, _cx) =
14381            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14382
14383        // Test with status bar shown (default)
14384        workspace.read_with(cx, |workspace, cx| {
14385            let visible = workspace.status_bar_visible(cx);
14386            assert!(visible, "Status bar should be visible by default");
14387        });
14388
14389        // Test with status bar hidden
14390        cx.update_global(|store: &mut SettingsStore, cx| {
14391            store.update_user_settings(cx, |settings| {
14392                settings.status_bar.get_or_insert_default().show = Some(false);
14393            });
14394        });
14395
14396        workspace.read_with(cx, |workspace, cx| {
14397            let visible = workspace.status_bar_visible(cx);
14398            assert!(!visible, "Status bar should be hidden when show is false");
14399        });
14400
14401        // Test with status bar shown explicitly
14402        cx.update_global(|store: &mut SettingsStore, cx| {
14403            store.update_user_settings(cx, |settings| {
14404                settings.status_bar.get_or_insert_default().show = Some(true);
14405            });
14406        });
14407
14408        workspace.read_with(cx, |workspace, cx| {
14409            let visible = workspace.status_bar_visible(cx);
14410            assert!(visible, "Status bar should be visible when show is true");
14411        });
14412    }
14413
14414    #[gpui::test]
14415    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14416        init_test(cx);
14417
14418        let fs = FakeFs::new(cx.executor());
14419        let project = Project::test(fs, [], cx).await;
14420        let (multi_workspace, cx) =
14421            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14422        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14423        let panel = workspace.update_in(cx, |workspace, window, cx| {
14424            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14425            workspace.add_panel(panel.clone(), window, cx);
14426
14427            workspace
14428                .right_dock()
14429                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14430
14431            panel
14432        });
14433
14434        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14435        let item_a = cx.new(TestItem::new);
14436        let item_b = cx.new(TestItem::new);
14437        let item_a_id = item_a.entity_id();
14438        let item_b_id = item_b.entity_id();
14439
14440        pane.update_in(cx, |pane, window, cx| {
14441            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14442            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14443        });
14444
14445        pane.read_with(cx, |pane, _| {
14446            assert_eq!(pane.items_len(), 2);
14447            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14448        });
14449
14450        workspace.update_in(cx, |workspace, window, cx| {
14451            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14452        });
14453
14454        workspace.update_in(cx, |_, window, cx| {
14455            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14456        });
14457
14458        // Assert that the `pane::CloseActiveItem` action is handled at the
14459        // workspace level when one of the dock panels is focused and, in that
14460        // case, the center pane's active item is closed but the focus is not
14461        // moved.
14462        cx.dispatch_action(pane::CloseActiveItem::default());
14463        cx.run_until_parked();
14464
14465        pane.read_with(cx, |pane, _| {
14466            assert_eq!(pane.items_len(), 1);
14467            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14468        });
14469
14470        workspace.update_in(cx, |workspace, window, cx| {
14471            assert!(workspace.right_dock().read(cx).is_open());
14472            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14473        });
14474    }
14475
14476    #[gpui::test]
14477    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14478        init_test(cx);
14479        let fs = FakeFs::new(cx.executor());
14480
14481        let project_a = Project::test(fs.clone(), [], cx).await;
14482        let project_b = Project::test(fs, [], cx).await;
14483
14484        let multi_workspace_handle =
14485            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14486        cx.run_until_parked();
14487
14488        let workspace_a = multi_workspace_handle
14489            .read_with(cx, |mw, _| mw.workspace().clone())
14490            .unwrap();
14491
14492        let _workspace_b = multi_workspace_handle
14493            .update(cx, |mw, window, cx| {
14494                mw.test_add_workspace(project_b, window, cx)
14495            })
14496            .unwrap();
14497
14498        // Switch to workspace A
14499        multi_workspace_handle
14500            .update(cx, |mw, window, cx| {
14501                let workspace = mw.workspaces()[0].clone();
14502                mw.activate(workspace, window, cx);
14503            })
14504            .unwrap();
14505
14506        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14507
14508        // Add a panel to workspace A's right dock and open the dock
14509        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14510            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14511            workspace.add_panel(panel.clone(), window, cx);
14512            workspace
14513                .right_dock()
14514                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14515            panel
14516        });
14517
14518        // Focus the panel through the workspace (matching existing test pattern)
14519        workspace_a.update_in(cx, |workspace, window, cx| {
14520            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14521        });
14522
14523        // Zoom the panel
14524        panel.update_in(cx, |panel, window, cx| {
14525            panel.set_zoomed(true, window, cx);
14526        });
14527
14528        // Verify the panel is zoomed and the dock is open
14529        workspace_a.update_in(cx, |workspace, window, cx| {
14530            assert!(
14531                workspace.right_dock().read(cx).is_open(),
14532                "dock should be open before switch"
14533            );
14534            assert!(
14535                panel.is_zoomed(window, cx),
14536                "panel should be zoomed before switch"
14537            );
14538            assert!(
14539                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14540                "panel should be focused before switch"
14541            );
14542        });
14543
14544        // Switch to workspace B
14545        multi_workspace_handle
14546            .update(cx, |mw, window, cx| {
14547                let workspace = mw.workspaces()[1].clone();
14548                mw.activate(workspace, window, cx);
14549            })
14550            .unwrap();
14551        cx.run_until_parked();
14552
14553        // Switch back to workspace A
14554        multi_workspace_handle
14555            .update(cx, |mw, window, cx| {
14556                let workspace = mw.workspaces()[0].clone();
14557                mw.activate(workspace, window, cx);
14558            })
14559            .unwrap();
14560        cx.run_until_parked();
14561
14562        // Verify the panel is still zoomed and the dock is still open
14563        workspace_a.update_in(cx, |workspace, window, cx| {
14564            assert!(
14565                workspace.right_dock().read(cx).is_open(),
14566                "dock should still be open after switching back"
14567            );
14568            assert!(
14569                panel.is_zoomed(window, cx),
14570                "panel should still be zoomed after switching back"
14571            );
14572        });
14573    }
14574
14575    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14576        pane.read(cx)
14577            .items()
14578            .flat_map(|item| {
14579                item.project_paths(cx)
14580                    .into_iter()
14581                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14582            })
14583            .collect()
14584    }
14585
14586    pub fn init_test(cx: &mut TestAppContext) {
14587        cx.update(|cx| {
14588            let settings_store = SettingsStore::test(cx);
14589            cx.set_global(settings_store);
14590            cx.set_global(db::AppDatabase::test_new());
14591            theme_settings::init(theme::LoadThemes::JustBase, cx);
14592        });
14593    }
14594
14595    #[gpui::test]
14596    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14597        use settings::{ThemeName, ThemeSelection};
14598        use theme::SystemAppearance;
14599        use zed_actions::theme::ToggleMode;
14600
14601        init_test(cx);
14602
14603        let fs = FakeFs::new(cx.executor());
14604        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14605
14606        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14607            .await;
14608
14609        // Build a test project and workspace view so the test can invoke
14610        // the workspace action handler the same way the UI would.
14611        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14612        let (workspace, cx) =
14613            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14614
14615        // Seed the settings file with a plain static light theme so the
14616        // first toggle always starts from a known persisted state.
14617        workspace.update_in(cx, |_workspace, _window, cx| {
14618            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14619            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14620                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14621            });
14622        });
14623        cx.executor().advance_clock(Duration::from_millis(200));
14624        cx.run_until_parked();
14625
14626        // Confirm the initial persisted settings contain the static theme
14627        // we just wrote before any toggling happens.
14628        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14629        assert!(settings_text.contains(r#""theme": "One Light""#));
14630
14631        // Toggle once. This should migrate the persisted theme settings
14632        // into light/dark slots and enable system mode.
14633        workspace.update_in(cx, |workspace, window, cx| {
14634            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14635        });
14636        cx.executor().advance_clock(Duration::from_millis(200));
14637        cx.run_until_parked();
14638
14639        // 1. Static -> Dynamic
14640        // this assertion checks theme changed from static to dynamic.
14641        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14642        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14643        assert_eq!(
14644            parsed["theme"],
14645            serde_json::json!({
14646                "mode": "system",
14647                "light": "One Light",
14648                "dark": "One Dark"
14649            })
14650        );
14651
14652        // 2. Toggle again, suppose it will change the mode to light
14653        workspace.update_in(cx, |workspace, window, cx| {
14654            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14655        });
14656        cx.executor().advance_clock(Duration::from_millis(200));
14657        cx.run_until_parked();
14658
14659        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14660        assert!(settings_text.contains(r#""mode": "light""#));
14661    }
14662
14663    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14664        let item = TestProjectItem::new(id, path, cx);
14665        item.update(cx, |item, _| {
14666            item.is_dirty = true;
14667        });
14668        item
14669    }
14670
14671    #[gpui::test]
14672    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14673        cx: &mut gpui::TestAppContext,
14674    ) {
14675        init_test(cx);
14676        let fs = FakeFs::new(cx.executor());
14677
14678        let project = Project::test(fs, [], cx).await;
14679        let (workspace, cx) =
14680            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14681
14682        let panel = workspace.update_in(cx, |workspace, window, cx| {
14683            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14684            workspace.add_panel(panel.clone(), window, cx);
14685            workspace
14686                .right_dock()
14687                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14688            panel
14689        });
14690
14691        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14692        pane.update_in(cx, |pane, window, cx| {
14693            let item = cx.new(TestItem::new);
14694            pane.add_item(Box::new(item), true, true, None, window, cx);
14695        });
14696
14697        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14698        // mirrors the real-world flow and avoids side effects from directly
14699        // focusing the panel while the center pane is active.
14700        workspace.update_in(cx, |workspace, window, cx| {
14701            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14702        });
14703
14704        panel.update_in(cx, |panel, window, cx| {
14705            panel.set_zoomed(true, window, cx);
14706        });
14707
14708        workspace.update_in(cx, |workspace, window, cx| {
14709            assert!(workspace.right_dock().read(cx).is_open());
14710            assert!(panel.is_zoomed(window, cx));
14711            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14712        });
14713
14714        // Simulate a spurious pane::Event::Focus on the center pane while the
14715        // panel still has focus. This mirrors what happens during macOS window
14716        // activation: the center pane fires a focus event even though actual
14717        // focus remains on the dock panel.
14718        pane.update_in(cx, |_, _, cx| {
14719            cx.emit(pane::Event::Focus);
14720        });
14721
14722        // The dock must remain open because the panel had focus at the time the
14723        // event was processed. Before the fix, dock_to_preserve was None for
14724        // panels that don't implement pane(), causing the dock to close.
14725        workspace.update_in(cx, |workspace, window, cx| {
14726            assert!(
14727                workspace.right_dock().read(cx).is_open(),
14728                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14729            );
14730            assert!(panel.is_zoomed(window, cx));
14731        });
14732    }
14733
14734    #[gpui::test]
14735    async fn test_panels_stay_open_after_position_change_and_settings_update(
14736        cx: &mut gpui::TestAppContext,
14737    ) {
14738        init_test(cx);
14739        let fs = FakeFs::new(cx.executor());
14740        let project = Project::test(fs, [], cx).await;
14741        let (workspace, cx) =
14742            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14743
14744        // Add two panels to the left dock and open it.
14745        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14746            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14747            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14748            workspace.add_panel(panel_a.clone(), window, cx);
14749            workspace.add_panel(panel_b.clone(), window, cx);
14750            workspace.left_dock().update(cx, |dock, cx| {
14751                dock.set_open(true, window, cx);
14752                dock.activate_panel(0, window, cx);
14753            });
14754            (panel_a, panel_b)
14755        });
14756
14757        workspace.update_in(cx, |workspace, _, cx| {
14758            assert!(workspace.left_dock().read(cx).is_open());
14759        });
14760
14761        // Simulate a feature flag changing default dock positions: both panels
14762        // move from Left to Right.
14763        workspace.update_in(cx, |_workspace, _window, cx| {
14764            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14765            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14766            cx.update_global::<SettingsStore, _>(|_, _| {});
14767        });
14768
14769        // Both panels should now be in the right dock.
14770        workspace.update_in(cx, |workspace, _, cx| {
14771            let right_dock = workspace.right_dock().read(cx);
14772            assert_eq!(right_dock.panels_len(), 2);
14773        });
14774
14775        // Open the right dock and activate panel_b (simulating the user
14776        // opening the panel after it moved).
14777        workspace.update_in(cx, |workspace, window, cx| {
14778            workspace.right_dock().update(cx, |dock, cx| {
14779                dock.set_open(true, window, cx);
14780                dock.activate_panel(1, window, cx);
14781            });
14782        });
14783
14784        // Now trigger another SettingsStore change
14785        workspace.update_in(cx, |_workspace, _window, cx| {
14786            cx.update_global::<SettingsStore, _>(|_, _| {});
14787        });
14788
14789        workspace.update_in(cx, |workspace, _, cx| {
14790            assert!(
14791                workspace.right_dock().read(cx).is_open(),
14792                "Right dock should still be open after a settings change"
14793            );
14794            assert_eq!(
14795                workspace.right_dock().read(cx).panels_len(),
14796                2,
14797                "Both panels should still be in the right dock"
14798            );
14799        });
14800    }
14801}