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;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22pub mod focus_follows_mouse;
   23mod status_bar;
   24pub mod tasks;
   25mod theme_preview;
   26mod toast_layer;
   27mod toolbar;
   28pub mod welcome;
   29mod workspace_settings;
   30
   31pub use crate::notifications::NotificationFrame;
   32pub use dock::Panel;
   33pub use multi_workspace::{
   34    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MoveWorkspaceToNewWindow,
   35    MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProjectGroup, NextThread,
   36    PreviousProjectGroup, PreviousThread, ShowFewerThreads, ShowMoreThreads, Sidebar, SidebarEvent,
   37    SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
   38    sidebar_side_context_menu,
   39};
   40pub use path_list::{PathList, SerializedPathList};
   41pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   42
   43use anyhow::{Context as _, Result, anyhow};
   44use client::{
   45    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   46    proto::{self, ErrorCode, PanelId, PeerId},
   47};
   48use collections::{HashMap, HashSet, hash_map};
   49use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   50use fs::Fs;
   51use futures::{
   52    Future, FutureExt, StreamExt,
   53    channel::{
   54        mpsc::{self, UnboundedReceiver, UnboundedSender},
   55        oneshot,
   56    },
   57    future::{Shared, try_join_all},
   58};
   59use gpui::{
   60    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   61    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   62    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   63    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   64    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   65    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   66};
   67pub use history_manager::*;
   68pub use item::{
   69    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   70    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   71};
   72use itertools::Itertools;
   73use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   74pub use modal_layer::*;
   75use node_runtime::NodeRuntime;
   76use notifications::{
   77    DetachAndPromptErr, Notifications, dismiss_app_notification,
   78    simple_message_notification::MessageNotification,
   79};
   80pub use pane::*;
   81pub use pane_group::{
   82    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   83    SplitDirection,
   84};
   85use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   86pub use persistence::{
   87    WorkspaceDb, delete_unloaded_items,
   88    model::{
   89        DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
   90        SerializedWorkspaceLocation, SessionWorkspace,
   91    },
   92    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   93};
   94use postage::stream::Stream;
   95use project::{
   96    DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
   97    WorktreeId, WorktreeSettings,
   98    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   99    project_settings::ProjectSettings,
  100    toolchain_store::ToolchainStoreEvent,
  101    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  102};
  103use remote::{
  104    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  105    remote_client::ConnectionIdentifier,
  106};
  107use schemars::JsonSchema;
  108use serde::Deserialize;
  109use session::AppSession;
  110use settings::{
  111    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  112};
  113
  114use sqlez::{
  115    bindable::{Bind, Column, StaticColumnCount},
  116    statement::Statement,
  117};
  118use status_bar::StatusBar;
  119pub use status_bar::StatusItemView;
  120use std::{
  121    any::TypeId,
  122    borrow::Cow,
  123    cell::RefCell,
  124    cmp,
  125    collections::VecDeque,
  126    env,
  127    hash::Hash,
  128    path::{Path, PathBuf},
  129    process::ExitStatus,
  130    rc::Rc,
  131    sync::{
  132        Arc, LazyLock,
  133        atomic::{AtomicBool, AtomicUsize},
  134    },
  135    time::Duration,
  136};
  137use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  138use theme::{ActiveTheme, SystemAppearance};
  139use theme_settings::ThemeSettings;
  140pub use toolbar::{
  141    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  142};
  143pub use ui;
  144use ui::{Window, prelude::*};
  145use util::{
  146    ResultExt, TryFutureExt,
  147    paths::{PathStyle, SanitizedPath},
  148    rel_path::RelPath,
  149    serde::default_true,
  150};
  151use uuid::Uuid;
  152pub use workspace_settings::{
  153    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  154    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  155};
  156use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  157
  158use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  159use crate::{
  160    persistence::{
  161        SerializedAxis,
  162        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  163    },
  164    security_modal::SecurityModal,
  165};
  166
  167pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  168
  169static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  170    env::var("ZED_WINDOW_SIZE")
  171        .ok()
  172        .as_deref()
  173        .and_then(parse_pixel_size_env_var)
  174});
  175
  176static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  177    env::var("ZED_WINDOW_POSITION")
  178        .ok()
  179        .as_deref()
  180        .and_then(parse_pixel_position_env_var)
  181});
  182
  183pub trait TerminalProvider {
  184    fn spawn(
  185        &self,
  186        task: SpawnInTerminal,
  187        window: &mut Window,
  188        cx: &mut App,
  189    ) -> Task<Option<Result<ExitStatus>>>;
  190}
  191
  192pub trait DebuggerProvider {
  193    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  194    fn start_session(
  195        &self,
  196        definition: DebugScenario,
  197        task_context: SharedTaskContext,
  198        active_buffer: Option<Entity<Buffer>>,
  199        worktree_id: Option<WorktreeId>,
  200        window: &mut Window,
  201        cx: &mut App,
  202    );
  203
  204    fn spawn_task_or_modal(
  205        &self,
  206        workspace: &mut Workspace,
  207        action: &Spawn,
  208        window: &mut Window,
  209        cx: &mut Context<Workspace>,
  210    );
  211
  212    fn task_scheduled(&self, cx: &mut App);
  213    fn debug_scenario_scheduled(&self, cx: &mut App);
  214    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  215
  216    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  217}
  218
  219/// Opens a file or directory.
  220#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  221#[action(namespace = workspace)]
  222pub struct Open {
  223    /// When true, opens in a new window. When false, adds to the current
  224    /// window as a new workspace (multi-workspace).
  225    #[serde(default = "Open::default_create_new_window")]
  226    pub create_new_window: bool,
  227}
  228
  229impl Open {
  230    pub const DEFAULT: Self = Self {
  231        create_new_window: true,
  232    };
  233
  234    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  235    /// the serde default and `Open::DEFAULT` stay in sync.
  236    fn default_create_new_window() -> bool {
  237        Self::DEFAULT.create_new_window
  238    }
  239}
  240
  241impl Default for Open {
  242    fn default() -> Self {
  243        Self::DEFAULT
  244    }
  245}
  246
  247actions!(
  248    workspace,
  249    [
  250        /// Activates the next pane in the workspace.
  251        ActivateNextPane,
  252        /// Activates the previous pane in the workspace.
  253        ActivatePreviousPane,
  254        /// Activates the last pane in the workspace.
  255        ActivateLastPane,
  256        /// Switches to the next window.
  257        ActivateNextWindow,
  258        /// Switches to the previous window.
  259        ActivatePreviousWindow,
  260        /// Adds a folder to the current project.
  261        AddFolderToProject,
  262        /// Clears all notifications.
  263        ClearAllNotifications,
  264        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  265        ClearNavigationHistory,
  266        /// Closes the active dock.
  267        CloseActiveDock,
  268        /// Closes all docks.
  269        CloseAllDocks,
  270        /// Toggles all docks.
  271        ToggleAllDocks,
  272        /// Closes the current window.
  273        CloseWindow,
  274        /// Closes the current project.
  275        CloseProject,
  276        /// Opens the feedback dialog.
  277        Feedback,
  278        /// Follows the next collaborator in the session.
  279        FollowNextCollaborator,
  280        /// Moves the focused panel to the next position.
  281        MoveFocusedPanelToNextPosition,
  282        /// Creates a new file.
  283        NewFile,
  284        /// Creates a new file in a vertical split.
  285        NewFileSplitVertical,
  286        /// Creates a new file in a horizontal split.
  287        NewFileSplitHorizontal,
  288        /// Opens a new search.
  289        NewSearch,
  290        /// Opens a new window.
  291        NewWindow,
  292        /// Opens multiple files.
  293        OpenFiles,
  294        /// Opens the current location in terminal.
  295        OpenInTerminal,
  296        /// Opens the component preview.
  297        OpenComponentPreview,
  298        /// Reloads the active item.
  299        ReloadActiveItem,
  300        /// Resets the active dock to its default size.
  301        ResetActiveDockSize,
  302        /// Resets all open docks to their default sizes.
  303        ResetOpenDocksSize,
  304        /// Reloads the application
  305        Reload,
  306        /// Saves the current file with a new name.
  307        SaveAs,
  308        /// Saves without formatting.
  309        SaveWithoutFormat,
  310        /// Shuts down all debug adapters.
  311        ShutdownDebugAdapters,
  312        /// Suppresses the current notification.
  313        SuppressNotification,
  314        /// Toggles the bottom dock.
  315        ToggleBottomDock,
  316        /// Toggles centered layout mode.
  317        ToggleCenteredLayout,
  318        /// Toggles edit prediction feature globally for all files.
  319        ToggleEditPrediction,
  320        /// Toggles the left dock.
  321        ToggleLeftDock,
  322        /// Toggles the right dock.
  323        ToggleRightDock,
  324        /// Toggles zoom on the active pane.
  325        ToggleZoom,
  326        /// Toggles read-only mode for the active item (if supported by that item).
  327        ToggleReadOnlyFile,
  328        /// Zooms in on the active pane.
  329        ZoomIn,
  330        /// Zooms out of the active pane.
  331        ZoomOut,
  332        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  333        /// If the modal is shown already, closes it without trusting any worktree.
  334        ToggleWorktreeSecurity,
  335        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  336        /// Requires restart to take effect on already opened projects.
  337        ClearTrustedWorktrees,
  338        /// Stops following a collaborator.
  339        Unfollow,
  340        /// Restores the banner.
  341        RestoreBanner,
  342        /// Toggles expansion of the selected item.
  343        ToggleExpandItem,
  344    ]
  345);
  346
  347/// Activates a specific pane by its index.
  348#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  349#[action(namespace = workspace)]
  350pub struct ActivatePane(pub usize);
  351
  352/// Moves an item to a specific pane by index.
  353#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  354#[action(namespace = workspace)]
  355#[serde(deny_unknown_fields)]
  356pub struct MoveItemToPane {
  357    #[serde(default = "default_1")]
  358    pub destination: usize,
  359    #[serde(default = "default_true")]
  360    pub focus: bool,
  361    #[serde(default)]
  362    pub clone: bool,
  363}
  364
  365fn default_1() -> usize {
  366    1
  367}
  368
  369/// Moves an item to a pane in the specified direction.
  370#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  371#[action(namespace = workspace)]
  372#[serde(deny_unknown_fields)]
  373pub struct MoveItemToPaneInDirection {
  374    #[serde(default = "default_right")]
  375    pub direction: SplitDirection,
  376    #[serde(default = "default_true")]
  377    pub focus: bool,
  378    #[serde(default)]
  379    pub clone: bool,
  380}
  381
  382/// Creates a new file in a split of the desired direction.
  383#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  384#[action(namespace = workspace)]
  385#[serde(deny_unknown_fields)]
  386pub struct NewFileSplit(pub SplitDirection);
  387
  388fn default_right() -> SplitDirection {
  389    SplitDirection::Right
  390}
  391
  392/// Saves all open files in the workspace.
  393#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  394#[action(namespace = workspace)]
  395#[serde(deny_unknown_fields)]
  396pub struct SaveAll {
  397    #[serde(default)]
  398    pub save_intent: Option<SaveIntent>,
  399}
  400
  401/// Saves the current file with the specified options.
  402#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  403#[action(namespace = workspace)]
  404#[serde(deny_unknown_fields)]
  405pub struct Save {
  406    #[serde(default)]
  407    pub save_intent: Option<SaveIntent>,
  408}
  409
  410/// Moves Focus to the central panes in the workspace.
  411#[derive(Clone, Debug, PartialEq, Eq, Action)]
  412#[action(namespace = workspace)]
  413pub struct FocusCenterPane;
  414
  415///  Closes all items and panes in the workspace.
  416#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  417#[action(namespace = workspace)]
  418#[serde(deny_unknown_fields)]
  419pub struct CloseAllItemsAndPanes {
  420    #[serde(default)]
  421    pub save_intent: Option<SaveIntent>,
  422}
  423
  424/// Closes all inactive tabs and panes in the workspace.
  425#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  426#[action(namespace = workspace)]
  427#[serde(deny_unknown_fields)]
  428pub struct CloseInactiveTabsAndPanes {
  429    #[serde(default)]
  430    pub save_intent: Option<SaveIntent>,
  431}
  432
  433/// Closes the active item across all panes.
  434#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  435#[action(namespace = workspace)]
  436#[serde(deny_unknown_fields)]
  437pub struct CloseItemInAllPanes {
  438    #[serde(default)]
  439    pub save_intent: Option<SaveIntent>,
  440    #[serde(default)]
  441    pub close_pinned: bool,
  442}
  443
  444/// Sends a sequence of keystrokes to the active element.
  445#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  446#[action(namespace = workspace)]
  447pub struct SendKeystrokes(pub String);
  448
  449actions!(
  450    project_symbols,
  451    [
  452        /// Toggles the project symbols search.
  453        #[action(name = "Toggle")]
  454        ToggleProjectSymbols
  455    ]
  456);
  457
  458/// Toggles the file finder interface.
  459#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  460#[action(namespace = file_finder, name = "Toggle")]
  461#[serde(deny_unknown_fields)]
  462pub struct ToggleFileFinder {
  463    #[serde(default)]
  464    pub separate_history: bool,
  465}
  466
  467/// Opens a new terminal in the center.
  468#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  469#[action(namespace = workspace)]
  470#[serde(deny_unknown_fields)]
  471pub struct NewCenterTerminal {
  472    /// If true, creates a local terminal even in remote projects.
  473    #[serde(default)]
  474    pub local: bool,
  475}
  476
  477/// Opens a new terminal.
  478#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  479#[action(namespace = workspace)]
  480#[serde(deny_unknown_fields)]
  481pub struct NewTerminal {
  482    /// If true, creates a local terminal even in remote projects.
  483    #[serde(default)]
  484    pub local: bool,
  485}
  486
  487/// Increases size of a currently focused dock by a given amount of pixels.
  488#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  489#[action(namespace = workspace)]
  490#[serde(deny_unknown_fields)]
  491pub struct IncreaseActiveDockSize {
  492    /// For 0px parameter, uses UI font size value.
  493    #[serde(default)]
  494    pub px: u32,
  495}
  496
  497/// Decreases size of a currently focused dock by a given amount of pixels.
  498#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  499#[action(namespace = workspace)]
  500#[serde(deny_unknown_fields)]
  501pub struct DecreaseActiveDockSize {
  502    /// For 0px parameter, uses UI font size value.
  503    #[serde(default)]
  504    pub px: u32,
  505}
  506
  507/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  508#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  509#[action(namespace = workspace)]
  510#[serde(deny_unknown_fields)]
  511pub struct IncreaseOpenDocksSize {
  512    /// For 0px parameter, uses UI font size value.
  513    #[serde(default)]
  514    pub px: u32,
  515}
  516
  517/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  518#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  519#[action(namespace = workspace)]
  520#[serde(deny_unknown_fields)]
  521pub struct DecreaseOpenDocksSize {
  522    /// For 0px parameter, uses UI font size value.
  523    #[serde(default)]
  524    pub px: u32,
  525}
  526
  527actions!(
  528    workspace,
  529    [
  530        /// Activates the pane to the left.
  531        ActivatePaneLeft,
  532        /// Activates the pane to the right.
  533        ActivatePaneRight,
  534        /// Activates the pane above.
  535        ActivatePaneUp,
  536        /// Activates the pane below.
  537        ActivatePaneDown,
  538        /// Swaps the current pane with the one to the left.
  539        SwapPaneLeft,
  540        /// Swaps the current pane with the one to the right.
  541        SwapPaneRight,
  542        /// Swaps the current pane with the one above.
  543        SwapPaneUp,
  544        /// Swaps the current pane with the one below.
  545        SwapPaneDown,
  546        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  547        SwapPaneAdjacent,
  548        /// Move the current pane to be at the far left.
  549        MovePaneLeft,
  550        /// Move the current pane to be at the far right.
  551        MovePaneRight,
  552        /// Move the current pane to be at the very top.
  553        MovePaneUp,
  554        /// Move the current pane to be at the very bottom.
  555        MovePaneDown,
  556    ]
  557);
  558
  559#[derive(PartialEq, Eq, Debug)]
  560pub enum CloseIntent {
  561    /// Quit the program entirely.
  562    Quit,
  563    /// Close a window.
  564    CloseWindow,
  565    /// Replace the workspace in an existing window.
  566    ReplaceWindow,
  567}
  568
  569#[derive(Clone)]
  570pub struct Toast {
  571    id: NotificationId,
  572    msg: Cow<'static, str>,
  573    autohide: bool,
  574    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  575}
  576
  577impl Toast {
  578    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  579        Toast {
  580            id,
  581            msg: msg.into(),
  582            on_click: None,
  583            autohide: false,
  584        }
  585    }
  586
  587    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  588    where
  589        M: Into<Cow<'static, str>>,
  590        F: Fn(&mut Window, &mut App) + 'static,
  591    {
  592        self.on_click = Some((message.into(), Arc::new(on_click)));
  593        self
  594    }
  595
  596    pub fn autohide(mut self) -> Self {
  597        self.autohide = true;
  598        self
  599    }
  600}
  601
  602impl PartialEq for Toast {
  603    fn eq(&self, other: &Self) -> bool {
  604        self.id == other.id
  605            && self.msg == other.msg
  606            && self.on_click.is_some() == other.on_click.is_some()
  607    }
  608}
  609
  610/// Opens a new terminal with the specified working directory.
  611#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  612#[action(namespace = workspace)]
  613#[serde(deny_unknown_fields)]
  614pub struct OpenTerminal {
  615    pub working_directory: PathBuf,
  616    /// If true, creates a local terminal even in remote projects.
  617    #[serde(default)]
  618    pub local: bool,
  619}
  620
  621#[derive(
  622    Clone,
  623    Copy,
  624    Debug,
  625    Default,
  626    Hash,
  627    PartialEq,
  628    Eq,
  629    PartialOrd,
  630    Ord,
  631    serde::Serialize,
  632    serde::Deserialize,
  633)]
  634pub struct WorkspaceId(i64);
  635
  636impl WorkspaceId {
  637    pub fn from_i64(value: i64) -> Self {
  638        Self(value)
  639    }
  640}
  641
  642impl StaticColumnCount for WorkspaceId {}
  643impl Bind for WorkspaceId {
  644    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  645        self.0.bind(statement, start_index)
  646    }
  647}
  648impl Column for WorkspaceId {
  649    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  650        i64::column(statement, start_index)
  651            .map(|(i, next_index)| (Self(i), next_index))
  652            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  653    }
  654}
  655impl From<WorkspaceId> for i64 {
  656    fn from(val: WorkspaceId) -> Self {
  657        val.0
  658    }
  659}
  660
  661fn prompt_and_open_paths(
  662    app_state: Arc<AppState>,
  663    options: PathPromptOptions,
  664    create_new_window: bool,
  665    cx: &mut App,
  666) {
  667    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  668        workspace_window
  669            .update(cx, |multi_workspace, window, cx| {
  670                let workspace = multi_workspace.workspace().clone();
  671                workspace.update(cx, |workspace, cx| {
  672                    prompt_for_open_path_and_open(
  673                        workspace,
  674                        app_state,
  675                        options,
  676                        create_new_window,
  677                        window,
  678                        cx,
  679                    );
  680                });
  681            })
  682            .ok();
  683    } else {
  684        let task = Workspace::new_local(
  685            Vec::new(),
  686            app_state.clone(),
  687            None,
  688            None,
  689            None,
  690            OpenMode::Activate,
  691            cx,
  692        );
  693        cx.spawn(async move |cx| {
  694            let OpenResult { window, .. } = task.await?;
  695            window.update(cx, |multi_workspace, window, cx| {
  696                window.activate_window();
  697                let workspace = multi_workspace.workspace().clone();
  698                workspace.update(cx, |workspace, cx| {
  699                    prompt_for_open_path_and_open(
  700                        workspace,
  701                        app_state,
  702                        options,
  703                        create_new_window,
  704                        window,
  705                        cx,
  706                    );
  707                });
  708            })?;
  709            anyhow::Ok(())
  710        })
  711        .detach_and_log_err(cx);
  712    }
  713}
  714
  715pub fn prompt_for_open_path_and_open(
  716    workspace: &mut Workspace,
  717    app_state: Arc<AppState>,
  718    options: PathPromptOptions,
  719    create_new_window: bool,
  720    window: &mut Window,
  721    cx: &mut Context<Workspace>,
  722) {
  723    let paths = workspace.prompt_for_open_path(
  724        options,
  725        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  726        window,
  727        cx,
  728    );
  729    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  730    cx.spawn_in(window, async move |this, cx| {
  731        let Some(paths) = paths.await.log_err().flatten() else {
  732            return;
  733        };
  734        if !create_new_window {
  735            if let Some(handle) = multi_workspace_handle {
  736                if let Some(task) = handle
  737                    .update(cx, |multi_workspace, window, cx| {
  738                        multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
  739                    })
  740                    .log_err()
  741                {
  742                    task.await.log_err();
  743                }
  744                return;
  745            }
  746        }
  747        if let Some(task) = this
  748            .update_in(cx, |this, window, cx| {
  749                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  750            })
  751            .log_err()
  752        {
  753            task.await.log_err();
  754        }
  755    })
  756    .detach();
  757}
  758
  759pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  760    component::init();
  761    theme_preview::init(cx);
  762    toast_layer::init(cx);
  763    history_manager::init(app_state.fs.clone(), cx);
  764
  765    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  766        .on_action(|_: &Reload, cx| reload(cx))
  767        .on_action(|action: &Open, cx: &mut App| {
  768            let app_state = AppState::global(cx);
  769            prompt_and_open_paths(
  770                app_state,
  771                PathPromptOptions {
  772                    files: true,
  773                    directories: true,
  774                    multiple: true,
  775                    prompt: None,
  776                },
  777                action.create_new_window,
  778                cx,
  779            );
  780        })
  781        .on_action(|_: &OpenFiles, cx: &mut App| {
  782            let directories = cx.can_select_mixed_files_and_dirs();
  783            let app_state = AppState::global(cx);
  784            prompt_and_open_paths(
  785                app_state,
  786                PathPromptOptions {
  787                    files: true,
  788                    directories,
  789                    multiple: true,
  790                    prompt: None,
  791                },
  792                true,
  793                cx,
  794            );
  795        });
  796}
  797
  798type BuildProjectItemFn =
  799    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  800
  801type BuildProjectItemForPathFn =
  802    fn(
  803        &Entity<Project>,
  804        &ProjectPath,
  805        &mut Window,
  806        &mut App,
  807    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  808
  809#[derive(Clone, Default)]
  810struct ProjectItemRegistry {
  811    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  812    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  813}
  814
  815impl ProjectItemRegistry {
  816    fn register<T: ProjectItem>(&mut self) {
  817        self.build_project_item_fns_by_type.insert(
  818            TypeId::of::<T::Item>(),
  819            |item, project, pane, window, cx| {
  820                let item = item.downcast().unwrap();
  821                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  822                    as Box<dyn ItemHandle>
  823            },
  824        );
  825        self.build_project_item_for_path_fns
  826            .push(|project, project_path, window, cx| {
  827                let project_path = project_path.clone();
  828                let is_file = project
  829                    .read(cx)
  830                    .entry_for_path(&project_path, cx)
  831                    .is_some_and(|entry| entry.is_file());
  832                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  833                let is_local = project.read(cx).is_local();
  834                let project_item =
  835                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  836                let project = project.clone();
  837                Some(window.spawn(cx, async move |cx| {
  838                    match project_item.await.with_context(|| {
  839                        format!(
  840                            "opening project path {:?}",
  841                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  842                        )
  843                    }) {
  844                        Ok(project_item) => {
  845                            let project_item = project_item;
  846                            let project_entry_id: Option<ProjectEntryId> =
  847                                project_item.read_with(cx, project::ProjectItem::entry_id);
  848                            let build_workspace_item = Box::new(
  849                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  850                                    Box::new(cx.new(|cx| {
  851                                        T::for_project_item(
  852                                            project,
  853                                            Some(pane),
  854                                            project_item,
  855                                            window,
  856                                            cx,
  857                                        )
  858                                    })) as Box<dyn ItemHandle>
  859                                },
  860                            ) as Box<_>;
  861                            Ok((project_entry_id, build_workspace_item))
  862                        }
  863                        Err(e) => {
  864                            log::warn!("Failed to open a project item: {e:#}");
  865                            if e.error_code() == ErrorCode::Internal {
  866                                if let Some(abs_path) =
  867                                    entry_abs_path.as_deref().filter(|_| is_file)
  868                                {
  869                                    if let Some(broken_project_item_view) =
  870                                        cx.update(|window, cx| {
  871                                            T::for_broken_project_item(
  872                                                abs_path, is_local, &e, window, cx,
  873                                            )
  874                                        })?
  875                                    {
  876                                        let build_workspace_item = Box::new(
  877                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  878                                                cx.new(|_| broken_project_item_view).boxed_clone()
  879                                            },
  880                                        )
  881                                        as Box<_>;
  882                                        return Ok((None, build_workspace_item));
  883                                    }
  884                                }
  885                            }
  886                            Err(e)
  887                        }
  888                    }
  889                }))
  890            });
  891    }
  892
  893    fn open_path(
  894        &self,
  895        project: &Entity<Project>,
  896        path: &ProjectPath,
  897        window: &mut Window,
  898        cx: &mut App,
  899    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  900        let Some(open_project_item) = self
  901            .build_project_item_for_path_fns
  902            .iter()
  903            .rev()
  904            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  905        else {
  906            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  907        };
  908        open_project_item
  909    }
  910
  911    fn build_item<T: project::ProjectItem>(
  912        &self,
  913        item: Entity<T>,
  914        project: Entity<Project>,
  915        pane: Option<&Pane>,
  916        window: &mut Window,
  917        cx: &mut App,
  918    ) -> Option<Box<dyn ItemHandle>> {
  919        let build = self
  920            .build_project_item_fns_by_type
  921            .get(&TypeId::of::<T>())?;
  922        Some(build(item.into_any(), project, pane, window, cx))
  923    }
  924}
  925
  926type WorkspaceItemBuilder =
  927    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  928
  929impl Global for ProjectItemRegistry {}
  930
  931/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  932/// items will get a chance to open the file, starting from the project item that
  933/// was added last.
  934pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  935    cx.default_global::<ProjectItemRegistry>().register::<I>();
  936}
  937
  938#[derive(Default)]
  939pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  940
  941struct FollowableViewDescriptor {
  942    from_state_proto: fn(
  943        Entity<Workspace>,
  944        ViewId,
  945        &mut Option<proto::view::Variant>,
  946        &mut Window,
  947        &mut App,
  948    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  949    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  950}
  951
  952impl Global for FollowableViewRegistry {}
  953
  954impl FollowableViewRegistry {
  955    pub fn register<I: FollowableItem>(cx: &mut App) {
  956        cx.default_global::<Self>().0.insert(
  957            TypeId::of::<I>(),
  958            FollowableViewDescriptor {
  959                from_state_proto: |workspace, id, state, window, cx| {
  960                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  961                        cx.foreground_executor()
  962                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  963                    })
  964                },
  965                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  966            },
  967        );
  968    }
  969
  970    pub fn from_state_proto(
  971        workspace: Entity<Workspace>,
  972        view_id: ViewId,
  973        mut state: Option<proto::view::Variant>,
  974        window: &mut Window,
  975        cx: &mut App,
  976    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  977        cx.update_default_global(|this: &mut Self, cx| {
  978            this.0.values().find_map(|descriptor| {
  979                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  980            })
  981        })
  982    }
  983
  984    pub fn to_followable_view(
  985        view: impl Into<AnyView>,
  986        cx: &App,
  987    ) -> Option<Box<dyn FollowableItemHandle>> {
  988        let this = cx.try_global::<Self>()?;
  989        let view = view.into();
  990        let descriptor = this.0.get(&view.entity_type())?;
  991        Some((descriptor.to_followable_view)(&view))
  992    }
  993}
  994
  995#[derive(Copy, Clone)]
  996struct SerializableItemDescriptor {
  997    deserialize: fn(
  998        Entity<Project>,
  999        WeakEntity<Workspace>,
 1000        WorkspaceId,
 1001        ItemId,
 1002        &mut Window,
 1003        &mut Context<Pane>,
 1004    ) -> Task<Result<Box<dyn ItemHandle>>>,
 1005    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
 1006    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
 1007}
 1008
 1009#[derive(Default)]
 1010struct SerializableItemRegistry {
 1011    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
 1012    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
 1013}
 1014
 1015impl Global for SerializableItemRegistry {}
 1016
 1017impl SerializableItemRegistry {
 1018    fn deserialize(
 1019        item_kind: &str,
 1020        project: Entity<Project>,
 1021        workspace: WeakEntity<Workspace>,
 1022        workspace_id: WorkspaceId,
 1023        item_item: ItemId,
 1024        window: &mut Window,
 1025        cx: &mut Context<Pane>,
 1026    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1027        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1028            return Task::ready(Err(anyhow!(
 1029                "cannot deserialize {}, descriptor not found",
 1030                item_kind
 1031            )));
 1032        };
 1033
 1034        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1035    }
 1036
 1037    fn cleanup(
 1038        item_kind: &str,
 1039        workspace_id: WorkspaceId,
 1040        loaded_items: Vec<ItemId>,
 1041        window: &mut Window,
 1042        cx: &mut App,
 1043    ) -> Task<Result<()>> {
 1044        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1045            return Task::ready(Err(anyhow!(
 1046                "cannot cleanup {}, descriptor not found",
 1047                item_kind
 1048            )));
 1049        };
 1050
 1051        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1052    }
 1053
 1054    fn view_to_serializable_item_handle(
 1055        view: AnyView,
 1056        cx: &App,
 1057    ) -> Option<Box<dyn SerializableItemHandle>> {
 1058        let this = cx.try_global::<Self>()?;
 1059        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1060        Some((descriptor.view_to_serializable_item)(view))
 1061    }
 1062
 1063    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1064        let this = cx.try_global::<Self>()?;
 1065        this.descriptors_by_kind.get(item_kind).copied()
 1066    }
 1067}
 1068
 1069pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1070    let serialized_item_kind = I::serialized_item_kind();
 1071
 1072    let registry = cx.default_global::<SerializableItemRegistry>();
 1073    let descriptor = SerializableItemDescriptor {
 1074        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1075            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1076            cx.foreground_executor()
 1077                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1078        },
 1079        cleanup: |workspace_id, loaded_items, window, cx| {
 1080            I::cleanup(workspace_id, loaded_items, window, cx)
 1081        },
 1082        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1083    };
 1084    registry
 1085        .descriptors_by_kind
 1086        .insert(Arc::from(serialized_item_kind), descriptor);
 1087    registry
 1088        .descriptors_by_type
 1089        .insert(TypeId::of::<I>(), descriptor);
 1090}
 1091
 1092pub struct AppState {
 1093    pub languages: Arc<LanguageRegistry>,
 1094    pub client: Arc<Client>,
 1095    pub user_store: Entity<UserStore>,
 1096    pub workspace_store: Entity<WorkspaceStore>,
 1097    pub fs: Arc<dyn fs::Fs>,
 1098    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1099    pub node_runtime: NodeRuntime,
 1100    pub session: Entity<AppSession>,
 1101}
 1102
 1103struct GlobalAppState(Arc<AppState>);
 1104
 1105impl Global for GlobalAppState {}
 1106
 1107pub struct WorkspaceStore {
 1108    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1109    client: Arc<Client>,
 1110    _subscriptions: Vec<client::Subscription>,
 1111}
 1112
 1113#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1114pub enum CollaboratorId {
 1115    PeerId(PeerId),
 1116    Agent,
 1117}
 1118
 1119impl From<PeerId> for CollaboratorId {
 1120    fn from(peer_id: PeerId) -> Self {
 1121        CollaboratorId::PeerId(peer_id)
 1122    }
 1123}
 1124
 1125impl From<&PeerId> for CollaboratorId {
 1126    fn from(peer_id: &PeerId) -> Self {
 1127        CollaboratorId::PeerId(*peer_id)
 1128    }
 1129}
 1130
 1131#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1132struct Follower {
 1133    project_id: Option<u64>,
 1134    peer_id: PeerId,
 1135}
 1136
 1137impl AppState {
 1138    #[track_caller]
 1139    pub fn global(cx: &App) -> Arc<Self> {
 1140        cx.global::<GlobalAppState>().0.clone()
 1141    }
 1142    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1143        cx.try_global::<GlobalAppState>()
 1144            .map(|state| state.0.clone())
 1145    }
 1146    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1147        cx.set_global(GlobalAppState(state));
 1148    }
 1149
 1150    #[cfg(any(test, feature = "test-support"))]
 1151    pub fn test(cx: &mut App) -> Arc<Self> {
 1152        use fs::Fs;
 1153        use node_runtime::NodeRuntime;
 1154        use session::Session;
 1155        use settings::SettingsStore;
 1156
 1157        if !cx.has_global::<SettingsStore>() {
 1158            let settings_store = SettingsStore::test(cx);
 1159            cx.set_global(settings_store);
 1160        }
 1161
 1162        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1163        <dyn Fs>::set_global(fs.clone(), cx);
 1164        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1165        let clock = Arc::new(clock::FakeSystemClock::new());
 1166        let http_client = http_client::FakeHttpClient::with_404_response();
 1167        let client = Client::new(clock, http_client, cx);
 1168        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1169        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1170        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1171
 1172        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1173        client::init(&client, cx);
 1174
 1175        Arc::new(Self {
 1176            client,
 1177            fs,
 1178            languages,
 1179            user_store,
 1180            workspace_store,
 1181            node_runtime: NodeRuntime::unavailable(),
 1182            build_window_options: |_, _| Default::default(),
 1183            session,
 1184        })
 1185    }
 1186}
 1187
 1188struct DelayedDebouncedEditAction {
 1189    task: Option<Task<()>>,
 1190    cancel_channel: Option<oneshot::Sender<()>>,
 1191}
 1192
 1193impl DelayedDebouncedEditAction {
 1194    fn new() -> DelayedDebouncedEditAction {
 1195        DelayedDebouncedEditAction {
 1196            task: None,
 1197            cancel_channel: None,
 1198        }
 1199    }
 1200
 1201    fn fire_new<F>(
 1202        &mut self,
 1203        delay: Duration,
 1204        window: &mut Window,
 1205        cx: &mut Context<Workspace>,
 1206        func: F,
 1207    ) where
 1208        F: 'static
 1209            + Send
 1210            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1211    {
 1212        if let Some(channel) = self.cancel_channel.take() {
 1213            _ = channel.send(());
 1214        }
 1215
 1216        let (sender, mut receiver) = oneshot::channel::<()>();
 1217        self.cancel_channel = Some(sender);
 1218
 1219        let previous_task = self.task.take();
 1220        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1221            let mut timer = cx.background_executor().timer(delay).fuse();
 1222            if let Some(previous_task) = previous_task {
 1223                previous_task.await;
 1224            }
 1225
 1226            futures::select_biased! {
 1227                _ = receiver => return,
 1228                    _ = timer => {}
 1229            }
 1230
 1231            if let Some(result) = workspace
 1232                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1233                .log_err()
 1234            {
 1235                result.await.log_err();
 1236            }
 1237        }));
 1238    }
 1239}
 1240
 1241pub enum Event {
 1242    PaneAdded(Entity<Pane>),
 1243    PaneRemoved,
 1244    ItemAdded {
 1245        item: Box<dyn ItemHandle>,
 1246    },
 1247    ActiveItemChanged,
 1248    ItemRemoved {
 1249        item_id: EntityId,
 1250    },
 1251    UserSavedItem {
 1252        pane: WeakEntity<Pane>,
 1253        item: Box<dyn WeakItemHandle>,
 1254        save_intent: SaveIntent,
 1255    },
 1256    ContactRequestedJoin(u64),
 1257    WorkspaceCreated(WeakEntity<Workspace>),
 1258    OpenBundledFile {
 1259        text: Cow<'static, str>,
 1260        title: &'static str,
 1261        language: &'static str,
 1262    },
 1263    ZoomChanged,
 1264    ModalOpened,
 1265    Activate,
 1266    PanelAdded(AnyView),
 1267}
 1268
 1269#[derive(Debug, Clone)]
 1270pub enum OpenVisible {
 1271    All,
 1272    None,
 1273    OnlyFiles,
 1274    OnlyDirectories,
 1275}
 1276
 1277enum WorkspaceLocation {
 1278    // Valid local paths or SSH project to serialize
 1279    Location(SerializedWorkspaceLocation, PathList),
 1280    // No valid location found hence clear session id
 1281    DetachFromSession,
 1282    // No valid location found to serialize
 1283    None,
 1284}
 1285
 1286type PromptForNewPath = Box<
 1287    dyn Fn(
 1288        &mut Workspace,
 1289        DirectoryLister,
 1290        Option<String>,
 1291        &mut Window,
 1292        &mut Context<Workspace>,
 1293    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1294>;
 1295
 1296type PromptForOpenPath = Box<
 1297    dyn Fn(
 1298        &mut Workspace,
 1299        DirectoryLister,
 1300        &mut Window,
 1301        &mut Context<Workspace>,
 1302    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1303>;
 1304
 1305#[derive(Default)]
 1306struct DispatchingKeystrokes {
 1307    dispatched: HashSet<Vec<Keystroke>>,
 1308    queue: VecDeque<Keystroke>,
 1309    task: Option<Shared<Task<()>>>,
 1310}
 1311
 1312/// Collects everything project-related for a certain window opened.
 1313/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1314///
 1315/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1316/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1317/// that can be used to register a global action to be triggered from any place in the window.
 1318pub struct Workspace {
 1319    weak_self: WeakEntity<Self>,
 1320    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1321    zoomed: Option<AnyWeakView>,
 1322    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1323    zoomed_position: Option<DockPosition>,
 1324    center: PaneGroup,
 1325    left_dock: Entity<Dock>,
 1326    bottom_dock: Entity<Dock>,
 1327    right_dock: Entity<Dock>,
 1328    panes: Vec<Entity<Pane>>,
 1329    active_worktree_override: Option<WorktreeId>,
 1330    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1331    active_pane: Entity<Pane>,
 1332    last_active_center_pane: Option<WeakEntity<Pane>>,
 1333    last_active_view_id: Option<proto::ViewId>,
 1334    status_bar: Entity<StatusBar>,
 1335    pub(crate) modal_layer: Entity<ModalLayer>,
 1336    toast_layer: Entity<ToastLayer>,
 1337    titlebar_item: Option<AnyView>,
 1338    notifications: Notifications,
 1339    suppressed_notifications: HashSet<NotificationId>,
 1340    project: Entity<Project>,
 1341    follower_states: HashMap<CollaboratorId, FollowerState>,
 1342    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1343    window_edited: bool,
 1344    last_window_title: Option<String>,
 1345    dirty_items: HashMap<EntityId, Subscription>,
 1346    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1347    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1348    database_id: Option<WorkspaceId>,
 1349    app_state: Arc<AppState>,
 1350    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1351    _subscriptions: Vec<Subscription>,
 1352    _apply_leader_updates: Task<Result<()>>,
 1353    _observe_current_user: Task<Result<()>>,
 1354    _schedule_serialize_workspace: Option<Task<()>>,
 1355    _serialize_workspace_task: Option<Task<()>>,
 1356    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1357    pane_history_timestamp: Arc<AtomicUsize>,
 1358    bounds: Bounds<Pixels>,
 1359    pub centered_layout: bool,
 1360    bounds_save_task_queued: Option<Task<()>>,
 1361    on_prompt_for_new_path: Option<PromptForNewPath>,
 1362    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1363    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1364    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1365    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1366    _items_serializer: Task<Result<()>>,
 1367    session_id: Option<String>,
 1368    scheduled_tasks: Vec<Task<()>>,
 1369    last_open_dock_positions: Vec<DockPosition>,
 1370    removing: bool,
 1371    open_in_dev_container: bool,
 1372    _dev_container_task: Option<Task<Result<()>>>,
 1373    _panels_task: Option<Task<Result<()>>>,
 1374    sidebar_focus_handle: Option<FocusHandle>,
 1375    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1376}
 1377
 1378impl EventEmitter<Event> for Workspace {}
 1379
 1380#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1381pub struct ViewId {
 1382    pub creator: CollaboratorId,
 1383    pub id: u64,
 1384}
 1385
 1386pub struct FollowerState {
 1387    center_pane: Entity<Pane>,
 1388    dock_pane: Option<Entity<Pane>>,
 1389    active_view_id: Option<ViewId>,
 1390    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1391}
 1392
 1393struct FollowerView {
 1394    view: Box<dyn FollowableItemHandle>,
 1395    location: Option<proto::PanelId>,
 1396}
 1397
 1398#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1399pub enum OpenMode {
 1400    /// Open the workspace in a new window.
 1401    NewWindow,
 1402    /// Add to the window's multi workspace without activating it (used during deserialization).
 1403    Add,
 1404    /// Add to the window's multi workspace and activate it.
 1405    #[default]
 1406    Activate,
 1407}
 1408
 1409impl Workspace {
 1410    pub fn new(
 1411        workspace_id: Option<WorkspaceId>,
 1412        project: Entity<Project>,
 1413        app_state: Arc<AppState>,
 1414        window: &mut Window,
 1415        cx: &mut Context<Self>,
 1416    ) -> Self {
 1417        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1418            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1419                if let TrustedWorktreesEvent::Trusted(..) = e {
 1420                    // Do not persist auto trusted worktrees
 1421                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1422                        worktrees_store.update(cx, |worktrees_store, cx| {
 1423                            worktrees_store.schedule_serialization(
 1424                                cx,
 1425                                |new_trusted_worktrees, cx| {
 1426                                    let timeout =
 1427                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1428                                    let db = WorkspaceDb::global(cx);
 1429                                    cx.background_spawn(async move {
 1430                                        timeout.await;
 1431                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1432                                            .await
 1433                                            .log_err();
 1434                                    })
 1435                                },
 1436                            )
 1437                        });
 1438                    }
 1439                }
 1440            })
 1441            .detach();
 1442
 1443            cx.observe_global::<SettingsStore>(|_, cx| {
 1444                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1445                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1446                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1447                            trusted_worktrees.auto_trust_all(cx);
 1448                        })
 1449                    }
 1450                }
 1451            })
 1452            .detach();
 1453        }
 1454
 1455        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1456            match event {
 1457                project::Event::RemoteIdChanged(_) => {
 1458                    this.update_window_title(window, cx);
 1459                }
 1460
 1461                project::Event::CollaboratorLeft(peer_id) => {
 1462                    this.collaborator_left(*peer_id, window, cx);
 1463                }
 1464
 1465                &project::Event::WorktreeRemoved(_) => {
 1466                    this.update_window_title(window, cx);
 1467                    this.serialize_workspace(window, cx);
 1468                    this.update_history(cx);
 1469                }
 1470
 1471                &project::Event::WorktreeAdded(id) => {
 1472                    this.update_window_title(window, cx);
 1473                    if this
 1474                        .project()
 1475                        .read(cx)
 1476                        .worktree_for_id(id, cx)
 1477                        .is_some_and(|wt| wt.read(cx).is_visible())
 1478                    {
 1479                        this.serialize_workspace(window, cx);
 1480                        this.update_history(cx);
 1481                    }
 1482                }
 1483                project::Event::WorktreeUpdatedEntries(..) => {
 1484                    this.update_window_title(window, cx);
 1485                    this.serialize_workspace(window, cx);
 1486                }
 1487
 1488                project::Event::DisconnectedFromHost => {
 1489                    this.update_window_edited(window, cx);
 1490                    let leaders_to_unfollow =
 1491                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1492                    for leader_id in leaders_to_unfollow {
 1493                        this.unfollow(leader_id, window, cx);
 1494                    }
 1495                }
 1496
 1497                project::Event::DisconnectedFromRemote {
 1498                    server_not_running: _,
 1499                } => {
 1500                    this.update_window_edited(window, cx);
 1501                }
 1502
 1503                project::Event::Closed => {
 1504                    window.remove_window();
 1505                }
 1506
 1507                project::Event::DeletedEntry(_, entry_id) => {
 1508                    for pane in this.panes.iter() {
 1509                        pane.update(cx, |pane, cx| {
 1510                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1511                        });
 1512                    }
 1513                }
 1514
 1515                project::Event::Toast {
 1516                    notification_id,
 1517                    message,
 1518                    link,
 1519                } => this.show_notification(
 1520                    NotificationId::named(notification_id.clone()),
 1521                    cx,
 1522                    |cx| {
 1523                        let mut notification = MessageNotification::new(message.clone(), cx);
 1524                        if let Some(link) = link {
 1525                            notification = notification
 1526                                .more_info_message(link.label)
 1527                                .more_info_url(link.url);
 1528                        }
 1529
 1530                        cx.new(|_| notification)
 1531                    },
 1532                ),
 1533
 1534                project::Event::HideToast { notification_id } => {
 1535                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1536                }
 1537
 1538                project::Event::LanguageServerPrompt(request) => {
 1539                    struct LanguageServerPrompt;
 1540
 1541                    this.show_notification(
 1542                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1543                        cx,
 1544                        |cx| {
 1545                            cx.new(|cx| {
 1546                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1547                            })
 1548                        },
 1549                    );
 1550                }
 1551
 1552                project::Event::AgentLocationChanged => {
 1553                    this.handle_agent_location_changed(window, cx)
 1554                }
 1555
 1556                _ => {}
 1557            }
 1558            cx.notify()
 1559        })
 1560        .detach();
 1561
 1562        cx.subscribe_in(
 1563            &project.read(cx).breakpoint_store(),
 1564            window,
 1565            |workspace, _, event, window, cx| match event {
 1566                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1567                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1568                    workspace.serialize_workspace(window, cx);
 1569                }
 1570                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1571            },
 1572        )
 1573        .detach();
 1574        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1575            cx.subscribe_in(
 1576                &toolchain_store,
 1577                window,
 1578                |workspace, _, event, window, cx| match event {
 1579                    ToolchainStoreEvent::CustomToolchainsModified => {
 1580                        workspace.serialize_workspace(window, cx);
 1581                    }
 1582                    _ => {}
 1583                },
 1584            )
 1585            .detach();
 1586        }
 1587
 1588        cx.on_focus_lost(window, |this, window, cx| {
 1589            let focus_handle = this.focus_handle(cx);
 1590            window.focus(&focus_handle, cx);
 1591        })
 1592        .detach();
 1593
 1594        let weak_handle = cx.entity().downgrade();
 1595        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1596
 1597        let center_pane = cx.new(|cx| {
 1598            let mut center_pane = Pane::new(
 1599                weak_handle.clone(),
 1600                project.clone(),
 1601                pane_history_timestamp.clone(),
 1602                None,
 1603                NewFile.boxed_clone(),
 1604                true,
 1605                window,
 1606                cx,
 1607            );
 1608            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1609            center_pane.set_should_display_welcome_page(true);
 1610            center_pane
 1611        });
 1612        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1613            .detach();
 1614
 1615        window.focus(&center_pane.focus_handle(cx), cx);
 1616
 1617        cx.emit(Event::PaneAdded(center_pane.clone()));
 1618
 1619        let any_window_handle = window.window_handle();
 1620        app_state.workspace_store.update(cx, |store, _| {
 1621            store
 1622                .workspaces
 1623                .insert((any_window_handle, weak_handle.clone()));
 1624        });
 1625
 1626        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1627        let mut connection_status = app_state.client.status();
 1628        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1629            current_user.next().await;
 1630            connection_status.next().await;
 1631            let mut stream =
 1632                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1633
 1634            while stream.recv().await.is_some() {
 1635                this.update(cx, |_, cx| cx.notify())?;
 1636            }
 1637            anyhow::Ok(())
 1638        });
 1639
 1640        // All leader updates are enqueued and then processed in a single task, so
 1641        // that each asynchronous operation can be run in order.
 1642        let (leader_updates_tx, mut leader_updates_rx) =
 1643            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1644        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1645            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1646                Self::process_leader_update(&this, leader_id, update, cx)
 1647                    .await
 1648                    .log_err();
 1649            }
 1650
 1651            Ok(())
 1652        });
 1653
 1654        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1655        let modal_layer = cx.new(|_| ModalLayer::new());
 1656        let toast_layer = cx.new(|_| ToastLayer::new());
 1657        cx.subscribe(
 1658            &modal_layer,
 1659            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1660                cx.emit(Event::ModalOpened);
 1661            },
 1662        )
 1663        .detach();
 1664
 1665        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1666        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1667        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1668        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1669        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1670        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1671        let multi_workspace = window
 1672            .root::<MultiWorkspace>()
 1673            .flatten()
 1674            .map(|mw| mw.downgrade());
 1675        let status_bar = cx.new(|cx| {
 1676            let mut status_bar =
 1677                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1678            status_bar.add_left_item(left_dock_buttons, window, cx);
 1679            status_bar.add_right_item(right_dock_buttons, window, cx);
 1680            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1681            status_bar
 1682        });
 1683
 1684        let session_id = app_state.session.read(cx).id().to_owned();
 1685
 1686        let mut active_call = None;
 1687        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1688            let subscriptions =
 1689                vec![
 1690                    call.0
 1691                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1692                ];
 1693            active_call = Some((call, subscriptions));
 1694        }
 1695
 1696        let (serializable_items_tx, serializable_items_rx) =
 1697            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1698        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1699            Self::serialize_items(&this, serializable_items_rx, cx).await
 1700        });
 1701
 1702        let subscriptions = vec![
 1703            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1704            cx.observe_window_bounds(window, move |this, window, cx| {
 1705                if this.bounds_save_task_queued.is_some() {
 1706                    return;
 1707                }
 1708                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1709                    cx.background_executor()
 1710                        .timer(Duration::from_millis(100))
 1711                        .await;
 1712                    this.update_in(cx, |this, window, cx| {
 1713                        this.save_window_bounds(window, cx).detach();
 1714                        this.bounds_save_task_queued.take();
 1715                    })
 1716                    .ok();
 1717                }));
 1718                cx.notify();
 1719            }),
 1720            cx.observe_window_appearance(window, |_, window, cx| {
 1721                let window_appearance = window.appearance();
 1722
 1723                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1724
 1725                theme_settings::reload_theme(cx);
 1726                theme_settings::reload_icon_theme(cx);
 1727            }),
 1728            cx.on_release({
 1729                let weak_handle = weak_handle.clone();
 1730                move |this, cx| {
 1731                    this.app_state.workspace_store.update(cx, move |store, _| {
 1732                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1733                    })
 1734                }
 1735            }),
 1736        ];
 1737
 1738        cx.defer_in(window, move |this, window, cx| {
 1739            this.update_window_title(window, cx);
 1740            this.show_initial_notifications(cx);
 1741        });
 1742
 1743        let mut center = PaneGroup::new(center_pane.clone());
 1744        center.set_is_center(true);
 1745        center.mark_positions(cx);
 1746
 1747        Workspace {
 1748            weak_self: weak_handle.clone(),
 1749            zoomed: None,
 1750            zoomed_position: None,
 1751            previous_dock_drag_coordinates: None,
 1752            center,
 1753            panes: vec![center_pane.clone()],
 1754            panes_by_item: Default::default(),
 1755            active_pane: center_pane.clone(),
 1756            last_active_center_pane: Some(center_pane.downgrade()),
 1757            last_active_view_id: None,
 1758            status_bar,
 1759            modal_layer,
 1760            toast_layer,
 1761            titlebar_item: None,
 1762            active_worktree_override: None,
 1763            notifications: Notifications::default(),
 1764            suppressed_notifications: HashSet::default(),
 1765            left_dock,
 1766            bottom_dock,
 1767            right_dock,
 1768            _panels_task: None,
 1769            project: project.clone(),
 1770            follower_states: Default::default(),
 1771            last_leaders_by_pane: Default::default(),
 1772            dispatching_keystrokes: Default::default(),
 1773            window_edited: false,
 1774            last_window_title: None,
 1775            dirty_items: Default::default(),
 1776            active_call,
 1777            database_id: workspace_id,
 1778            app_state,
 1779            _observe_current_user,
 1780            _apply_leader_updates,
 1781            _schedule_serialize_workspace: None,
 1782            _serialize_workspace_task: None,
 1783            _schedule_serialize_ssh_paths: None,
 1784            leader_updates_tx,
 1785            _subscriptions: subscriptions,
 1786            pane_history_timestamp,
 1787            workspace_actions: Default::default(),
 1788            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1789            bounds: Default::default(),
 1790            centered_layout: false,
 1791            bounds_save_task_queued: None,
 1792            on_prompt_for_new_path: None,
 1793            on_prompt_for_open_path: None,
 1794            terminal_provider: None,
 1795            debugger_provider: None,
 1796            serializable_items_tx,
 1797            _items_serializer,
 1798            session_id: Some(session_id),
 1799
 1800            scheduled_tasks: Vec::new(),
 1801            last_open_dock_positions: Vec::new(),
 1802            removing: false,
 1803            sidebar_focus_handle: None,
 1804            multi_workspace,
 1805            open_in_dev_container: false,
 1806            _dev_container_task: None,
 1807        }
 1808    }
 1809
 1810    pub fn new_local(
 1811        abs_paths: Vec<PathBuf>,
 1812        app_state: Arc<AppState>,
 1813        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1814        env: Option<HashMap<String, String>>,
 1815        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1816        open_mode: OpenMode,
 1817        cx: &mut App,
 1818    ) -> Task<anyhow::Result<OpenResult>> {
 1819        let project_handle = Project::local(
 1820            app_state.client.clone(),
 1821            app_state.node_runtime.clone(),
 1822            app_state.user_store.clone(),
 1823            app_state.languages.clone(),
 1824            app_state.fs.clone(),
 1825            env,
 1826            Default::default(),
 1827            cx,
 1828        );
 1829
 1830        let db = WorkspaceDb::global(cx);
 1831        let kvp = db::kvp::KeyValueStore::global(cx);
 1832        cx.spawn(async move |cx| {
 1833            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1834            for path in abs_paths.into_iter() {
 1835                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1836                    paths_to_open.push(canonical)
 1837                } else {
 1838                    paths_to_open.push(path)
 1839                }
 1840            }
 1841
 1842            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1843
 1844            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1845                paths_to_open = paths.ordered_paths().cloned().collect();
 1846                if !paths.is_lexicographically_ordered() {
 1847                    project_handle.update(cx, |project, cx| {
 1848                        project.set_worktrees_reordered(true, cx);
 1849                    });
 1850                }
 1851            }
 1852
 1853            // Get project paths for all of the abs_paths
 1854            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1855                Vec::with_capacity(paths_to_open.len());
 1856
 1857            for path in paths_to_open.into_iter() {
 1858                if let Some((_, project_entry)) = cx
 1859                    .update(|cx| {
 1860                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1861                    })
 1862                    .await
 1863                    .log_err()
 1864                {
 1865                    project_paths.push((path, Some(project_entry)));
 1866                } else {
 1867                    project_paths.push((path, None));
 1868                }
 1869            }
 1870
 1871            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1872                serialized_workspace.id
 1873            } else {
 1874                db.next_id().await.unwrap_or_else(|_| Default::default())
 1875            };
 1876
 1877            let toolchains = db.toolchains(workspace_id).await?;
 1878
 1879            for (toolchain, worktree_path, path) in toolchains {
 1880                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1881                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1882                    this.find_worktree(&worktree_path, cx)
 1883                        .and_then(|(worktree, rel_path)| {
 1884                            if rel_path.is_empty() {
 1885                                Some(worktree.read(cx).id())
 1886                            } else {
 1887                                None
 1888                            }
 1889                        })
 1890                }) else {
 1891                    // We did not find a worktree with a given path, but that's whatever.
 1892                    continue;
 1893                };
 1894                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1895                    continue;
 1896                }
 1897
 1898                project_handle
 1899                    .update(cx, |this, cx| {
 1900                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1901                    })
 1902                    .await;
 1903            }
 1904            if let Some(workspace) = serialized_workspace.as_ref() {
 1905                project_handle.update(cx, |this, cx| {
 1906                    for (scope, toolchains) in &workspace.user_toolchains {
 1907                        for toolchain in toolchains {
 1908                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1909                        }
 1910                    }
 1911                });
 1912            }
 1913
 1914            let window_to_replace = match open_mode {
 1915                OpenMode::NewWindow => None,
 1916                _ => requesting_window,
 1917            };
 1918
 1919            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1920                if let Some(window) = window_to_replace {
 1921                    let centered_layout = serialized_workspace
 1922                        .as_ref()
 1923                        .map(|w| w.centered_layout)
 1924                        .unwrap_or(false);
 1925
 1926                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1927                        let workspace = cx.new(|cx| {
 1928                            let mut workspace = Workspace::new(
 1929                                Some(workspace_id),
 1930                                project_handle.clone(),
 1931                                app_state.clone(),
 1932                                window,
 1933                                cx,
 1934                            );
 1935
 1936                            workspace.centered_layout = centered_layout;
 1937
 1938                            // Call init callback to add items before window renders
 1939                            if let Some(init) = init {
 1940                                init(&mut workspace, window, cx);
 1941                            }
 1942
 1943                            workspace
 1944                        });
 1945                        match open_mode {
 1946                            OpenMode::Activate => {
 1947                                multi_workspace.activate(workspace.clone(), window, cx);
 1948                            }
 1949                            OpenMode::Add => {
 1950                                multi_workspace.add(workspace.clone(), &*window, cx);
 1951                            }
 1952                            OpenMode::NewWindow => {
 1953                                unreachable!()
 1954                            }
 1955                        }
 1956                        workspace
 1957                    })?;
 1958                    (window, workspace)
 1959                } else {
 1960                    let window_bounds_override = window_bounds_env_override();
 1961
 1962                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1963                        (Some(WindowBounds::Windowed(bounds)), None)
 1964                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1965                        && let Some(display) = workspace.display
 1966                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1967                    {
 1968                        // Reopening an existing workspace - restore its saved bounds
 1969                        (Some(bounds.0), Some(display))
 1970                    } else if let Some((display, bounds)) =
 1971                        persistence::read_default_window_bounds(&kvp)
 1972                    {
 1973                        // New or empty workspace - use the last known window bounds
 1974                        (Some(bounds), Some(display))
 1975                    } else {
 1976                        // New window - let GPUI's default_bounds() handle cascading
 1977                        (None, None)
 1978                    };
 1979
 1980                    // Use the serialized workspace to construct the new window
 1981                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1982                    options.window_bounds = window_bounds;
 1983                    let centered_layout = serialized_workspace
 1984                        .as_ref()
 1985                        .map(|w| w.centered_layout)
 1986                        .unwrap_or(false);
 1987                    let window = cx.open_window(options, {
 1988                        let app_state = app_state.clone();
 1989                        let project_handle = project_handle.clone();
 1990                        move |window, cx| {
 1991                            let workspace = cx.new(|cx| {
 1992                                let mut workspace = Workspace::new(
 1993                                    Some(workspace_id),
 1994                                    project_handle,
 1995                                    app_state,
 1996                                    window,
 1997                                    cx,
 1998                                );
 1999                                workspace.centered_layout = centered_layout;
 2000
 2001                                // Call init callback to add items before window renders
 2002                                if let Some(init) = init {
 2003                                    init(&mut workspace, window, cx);
 2004                                }
 2005
 2006                                workspace
 2007                            });
 2008                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 2009                        }
 2010                    })?;
 2011                    let workspace =
 2012                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 2013                            multi_workspace.workspace().clone()
 2014                        })?;
 2015                    (window, workspace)
 2016                };
 2017
 2018            notify_if_database_failed(window, cx);
 2019            // Check if this is an empty workspace (no paths to open)
 2020            // An empty workspace is one where project_paths is empty
 2021            let is_empty_workspace = project_paths.is_empty();
 2022            // Check if serialized workspace has paths before it's moved
 2023            let serialized_workspace_has_paths = serialized_workspace
 2024                .as_ref()
 2025                .map(|ws| !ws.paths.is_empty())
 2026                .unwrap_or(false);
 2027
 2028            let opened_items = window
 2029                .update(cx, |_, window, cx| {
 2030                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2031                        open_items(serialized_workspace, project_paths, window, cx)
 2032                    })
 2033                })?
 2034                .await
 2035                .unwrap_or_default();
 2036
 2037            // Restore default dock state for empty workspaces
 2038            // Only restore if:
 2039            // 1. This is an empty workspace (no paths), AND
 2040            // 2. The serialized workspace either doesn't exist or has no paths
 2041            if is_empty_workspace && !serialized_workspace_has_paths {
 2042                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2043                    window
 2044                        .update(cx, |_, window, cx| {
 2045                            workspace.update(cx, |workspace, cx| {
 2046                                for (dock, serialized_dock) in [
 2047                                    (&workspace.right_dock, &default_docks.right),
 2048                                    (&workspace.left_dock, &default_docks.left),
 2049                                    (&workspace.bottom_dock, &default_docks.bottom),
 2050                                ] {
 2051                                    dock.update(cx, |dock, cx| {
 2052                                        dock.serialized_dock = Some(serialized_dock.clone());
 2053                                        dock.restore_state(window, cx);
 2054                                    });
 2055                                }
 2056                                cx.notify();
 2057                            });
 2058                        })
 2059                        .log_err();
 2060                }
 2061            }
 2062
 2063            window
 2064                .update(cx, |_, _window, cx| {
 2065                    workspace.update(cx, |this: &mut Workspace, cx| {
 2066                        this.update_history(cx);
 2067                    });
 2068                })
 2069                .log_err();
 2070            Ok(OpenResult {
 2071                window,
 2072                workspace,
 2073                opened_items,
 2074            })
 2075        })
 2076    }
 2077
 2078    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2079        self.project.read(cx).project_group_key(cx)
 2080    }
 2081
 2082    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2083        self.weak_self.clone()
 2084    }
 2085
 2086    pub fn left_dock(&self) -> &Entity<Dock> {
 2087        &self.left_dock
 2088    }
 2089
 2090    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2091        &self.bottom_dock
 2092    }
 2093
 2094    pub fn set_bottom_dock_layout(
 2095        &mut self,
 2096        layout: BottomDockLayout,
 2097        window: &mut Window,
 2098        cx: &mut Context<Self>,
 2099    ) {
 2100        let fs = self.project().read(cx).fs();
 2101        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2102            content.workspace.bottom_dock_layout = Some(layout);
 2103        });
 2104
 2105        cx.notify();
 2106        self.serialize_workspace(window, cx);
 2107    }
 2108
 2109    pub fn right_dock(&self) -> &Entity<Dock> {
 2110        &self.right_dock
 2111    }
 2112
 2113    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2114        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2115    }
 2116
 2117    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2118        let left_dock = self.left_dock.read(cx);
 2119        let left_visible = left_dock.is_open();
 2120        let left_active_panel = left_dock
 2121            .active_panel()
 2122            .map(|panel| panel.persistent_name().to_string());
 2123        // `zoomed_position` is kept in sync with individual panel zoom state
 2124        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2125        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2126
 2127        let right_dock = self.right_dock.read(cx);
 2128        let right_visible = right_dock.is_open();
 2129        let right_active_panel = right_dock
 2130            .active_panel()
 2131            .map(|panel| panel.persistent_name().to_string());
 2132        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2133
 2134        let bottom_dock = self.bottom_dock.read(cx);
 2135        let bottom_visible = bottom_dock.is_open();
 2136        let bottom_active_panel = bottom_dock
 2137            .active_panel()
 2138            .map(|panel| panel.persistent_name().to_string());
 2139        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2140
 2141        DockStructure {
 2142            left: DockData {
 2143                visible: left_visible,
 2144                active_panel: left_active_panel,
 2145                zoom: left_dock_zoom,
 2146            },
 2147            right: DockData {
 2148                visible: right_visible,
 2149                active_panel: right_active_panel,
 2150                zoom: right_dock_zoom,
 2151            },
 2152            bottom: DockData {
 2153                visible: bottom_visible,
 2154                active_panel: bottom_active_panel,
 2155                zoom: bottom_dock_zoom,
 2156            },
 2157        }
 2158    }
 2159
 2160    pub fn set_dock_structure(
 2161        &self,
 2162        docks: DockStructure,
 2163        window: &mut Window,
 2164        cx: &mut Context<Self>,
 2165    ) {
 2166        for (dock, data) in [
 2167            (&self.left_dock, docks.left),
 2168            (&self.bottom_dock, docks.bottom),
 2169            (&self.right_dock, docks.right),
 2170        ] {
 2171            dock.update(cx, |dock, cx| {
 2172                dock.serialized_dock = Some(data);
 2173                dock.restore_state(window, cx);
 2174            });
 2175        }
 2176    }
 2177
 2178    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2179        self.items(cx)
 2180            .filter_map(|item| {
 2181                let project_path = item.project_path(cx)?;
 2182                self.project.read(cx).absolute_path(&project_path, cx)
 2183            })
 2184            .collect()
 2185    }
 2186
 2187    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2188        match position {
 2189            DockPosition::Left => &self.left_dock,
 2190            DockPosition::Bottom => &self.bottom_dock,
 2191            DockPosition::Right => &self.right_dock,
 2192        }
 2193    }
 2194
 2195    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2196        self.all_docks().into_iter().find_map(|dock| {
 2197            let dock = dock.read(cx);
 2198            dock.has_agent_panel(cx).then_some(dock.position())
 2199        })
 2200    }
 2201
 2202    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2203        self.all_docks().into_iter().find_map(|dock| {
 2204            let dock = dock.read(cx);
 2205            let panel = dock.panel::<T>()?;
 2206            dock.stored_panel_size_state(&panel)
 2207        })
 2208    }
 2209
 2210    pub fn persisted_panel_size_state(
 2211        &self,
 2212        panel_key: &'static str,
 2213        cx: &App,
 2214    ) -> Option<dock::PanelSizeState> {
 2215        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2216    }
 2217
 2218    pub fn persist_panel_size_state(
 2219        &self,
 2220        panel_key: &str,
 2221        size_state: dock::PanelSizeState,
 2222        cx: &mut App,
 2223    ) {
 2224        let Some(workspace_id) = self
 2225            .database_id()
 2226            .map(|id| i64::from(id).to_string())
 2227            .or(self.session_id())
 2228        else {
 2229            return;
 2230        };
 2231
 2232        let kvp = db::kvp::KeyValueStore::global(cx);
 2233        let panel_key = panel_key.to_string();
 2234        cx.background_spawn(async move {
 2235            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2236            scope
 2237                .write(
 2238                    format!("{workspace_id}:{panel_key}"),
 2239                    serde_json::to_string(&size_state)?,
 2240                )
 2241                .await
 2242        })
 2243        .detach_and_log_err(cx);
 2244    }
 2245
 2246    pub fn set_panel_size_state<T: Panel>(
 2247        &mut self,
 2248        size_state: dock::PanelSizeState,
 2249        window: &mut Window,
 2250        cx: &mut Context<Self>,
 2251    ) -> bool {
 2252        let Some(panel) = self.panel::<T>(cx) else {
 2253            return false;
 2254        };
 2255
 2256        let dock = self.dock_at_position(panel.position(window, cx));
 2257        let did_set = dock.update(cx, |dock, cx| {
 2258            dock.set_panel_size_state(&panel, size_state, cx)
 2259        });
 2260
 2261        if did_set {
 2262            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2263        }
 2264
 2265        did_set
 2266    }
 2267
 2268    pub fn toggle_dock_panel_flexible_size(
 2269        &self,
 2270        dock: &Entity<Dock>,
 2271        panel: &dyn PanelHandle,
 2272        window: &mut Window,
 2273        cx: &mut App,
 2274    ) {
 2275        let position = dock.read(cx).position();
 2276        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2277        let current_flex =
 2278            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2279        dock.update(cx, |dock, cx| {
 2280            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2281        });
 2282    }
 2283
 2284    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2285        let panel = dock.active_panel()?;
 2286        let size_state = dock
 2287            .stored_panel_size_state(panel.as_ref())
 2288            .unwrap_or_default();
 2289        let position = dock.position();
 2290
 2291        let use_flex = panel.has_flexible_size(window, cx);
 2292
 2293        if position.axis() == Axis::Horizontal
 2294            && use_flex
 2295            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2296        {
 2297            let workspace_width = self.bounds.size.width;
 2298            if workspace_width <= Pixels::ZERO {
 2299                return None;
 2300            }
 2301            let flex = flex.max(0.001);
 2302            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2303            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2304                // Both docks are flex items sharing the full workspace width.
 2305                let total_flex = flex + 1.0 + opposite_flex;
 2306                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2307            } else {
 2308                // Opposite dock is fixed-width; flex items share (W - fixed).
 2309                let opposite_fixed = opposite
 2310                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2311                    .unwrap_or_default();
 2312                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2313                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2314            }
 2315        }
 2316
 2317        Some(
 2318            size_state
 2319                .size
 2320                .unwrap_or_else(|| panel.default_size(window, cx)),
 2321        )
 2322    }
 2323
 2324    pub fn dock_flex_for_size(
 2325        &self,
 2326        position: DockPosition,
 2327        size: Pixels,
 2328        window: &Window,
 2329        cx: &App,
 2330    ) -> Option<f32> {
 2331        if position.axis() != Axis::Horizontal {
 2332            return None;
 2333        }
 2334
 2335        let workspace_width = self.bounds.size.width;
 2336        if workspace_width <= Pixels::ZERO {
 2337            return None;
 2338        }
 2339
 2340        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2341        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2342            let size = size.clamp(px(0.), workspace_width - px(1.));
 2343            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2344        } else {
 2345            let opposite_width = opposite
 2346                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2347                .unwrap_or_default();
 2348            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2349            let remaining = (available - size).max(px(1.));
 2350            Some((size / remaining).max(0.0))
 2351        }
 2352    }
 2353
 2354    fn opposite_dock_panel_and_size_state(
 2355        &self,
 2356        position: DockPosition,
 2357        window: &Window,
 2358        cx: &App,
 2359    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2360        let opposite_position = match position {
 2361            DockPosition::Left => DockPosition::Right,
 2362            DockPosition::Right => DockPosition::Left,
 2363            DockPosition::Bottom => return None,
 2364        };
 2365
 2366        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2367        let panel = opposite_dock.visible_panel()?;
 2368        let mut size_state = opposite_dock
 2369            .stored_panel_size_state(panel.as_ref())
 2370            .unwrap_or_default();
 2371        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2372            size_state.flex = self.default_dock_flex(opposite_position);
 2373        }
 2374        Some((panel.clone(), size_state))
 2375    }
 2376
 2377    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2378        if position.axis() != Axis::Horizontal {
 2379            return None;
 2380        }
 2381
 2382        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2383        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2384    }
 2385
 2386    pub fn is_edited(&self) -> bool {
 2387        self.window_edited
 2388    }
 2389
 2390    pub fn add_panel<T: Panel>(
 2391        &mut self,
 2392        panel: Entity<T>,
 2393        window: &mut Window,
 2394        cx: &mut Context<Self>,
 2395    ) {
 2396        let focus_handle = panel.panel_focus_handle(cx);
 2397        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2398            .detach();
 2399
 2400        let dock_position = panel.position(window, cx);
 2401        let dock = self.dock_at_position(dock_position);
 2402        let any_panel = panel.to_any();
 2403        let persisted_size_state =
 2404            self.persisted_panel_size_state(T::panel_key(), cx)
 2405                .or_else(|| {
 2406                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2407                        let state = dock::PanelSizeState {
 2408                            size: Some(size),
 2409                            flex: None,
 2410                        };
 2411                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2412                        state
 2413                    })
 2414                });
 2415
 2416        dock.update(cx, |dock, cx| {
 2417            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2418            if let Some(size_state) = persisted_size_state {
 2419                dock.set_panel_size_state(&panel, size_state, cx);
 2420            }
 2421            index
 2422        });
 2423
 2424        cx.emit(Event::PanelAdded(any_panel));
 2425    }
 2426
 2427    pub fn remove_panel<T: Panel>(
 2428        &mut self,
 2429        panel: &Entity<T>,
 2430        window: &mut Window,
 2431        cx: &mut Context<Self>,
 2432    ) {
 2433        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2434            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2435        }
 2436    }
 2437
 2438    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2439        &self.status_bar
 2440    }
 2441
 2442    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2443        self.sidebar_focus_handle = handle;
 2444    }
 2445
 2446    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2447        StatusBarSettings::get_global(cx).show
 2448    }
 2449
 2450    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2451        self.multi_workspace.as_ref()
 2452    }
 2453
 2454    pub fn set_multi_workspace(
 2455        &mut self,
 2456        multi_workspace: WeakEntity<MultiWorkspace>,
 2457        cx: &mut App,
 2458    ) {
 2459        self.status_bar.update(cx, |status_bar, cx| {
 2460            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2461        });
 2462        self.multi_workspace = Some(multi_workspace);
 2463    }
 2464
 2465    pub fn app_state(&self) -> &Arc<AppState> {
 2466        &self.app_state
 2467    }
 2468
 2469    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2470        self._panels_task = Some(task);
 2471    }
 2472
 2473    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2474        self._panels_task.take()
 2475    }
 2476
 2477    pub fn user_store(&self) -> &Entity<UserStore> {
 2478        &self.app_state.user_store
 2479    }
 2480
 2481    pub fn project(&self) -> &Entity<Project> {
 2482        &self.project
 2483    }
 2484
 2485    pub fn path_style(&self, cx: &App) -> PathStyle {
 2486        self.project.read(cx).path_style(cx)
 2487    }
 2488
 2489    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2490        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2491
 2492        for pane_handle in &self.panes {
 2493            let pane = pane_handle.read(cx);
 2494
 2495            for entry in pane.activation_history() {
 2496                history.insert(
 2497                    entry.entity_id,
 2498                    history
 2499                        .get(&entry.entity_id)
 2500                        .cloned()
 2501                        .unwrap_or(0)
 2502                        .max(entry.timestamp),
 2503                );
 2504            }
 2505        }
 2506
 2507        history
 2508    }
 2509
 2510    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2511        let mut recent_item: Option<Entity<T>> = None;
 2512        let mut recent_timestamp = 0;
 2513        for pane_handle in &self.panes {
 2514            let pane = pane_handle.read(cx);
 2515            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2516                pane.items().map(|item| (item.item_id(), item)).collect();
 2517            for entry in pane.activation_history() {
 2518                if entry.timestamp > recent_timestamp
 2519                    && let Some(&item) = item_map.get(&entry.entity_id)
 2520                    && let Some(typed_item) = item.act_as::<T>(cx)
 2521                {
 2522                    recent_timestamp = entry.timestamp;
 2523                    recent_item = Some(typed_item);
 2524                }
 2525            }
 2526        }
 2527        recent_item
 2528    }
 2529
 2530    pub fn recent_navigation_history_iter(
 2531        &self,
 2532        cx: &App,
 2533    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2534        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2535        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2536
 2537        for pane in &self.panes {
 2538            let pane = pane.read(cx);
 2539
 2540            pane.nav_history()
 2541                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2542                    if let Some(fs_path) = &fs_path {
 2543                        abs_paths_opened
 2544                            .entry(fs_path.clone())
 2545                            .or_default()
 2546                            .insert(project_path.clone());
 2547                    }
 2548                    let timestamp = entry.timestamp;
 2549                    match history.entry(project_path) {
 2550                        hash_map::Entry::Occupied(mut entry) => {
 2551                            let (_, old_timestamp) = entry.get();
 2552                            if &timestamp > old_timestamp {
 2553                                entry.insert((fs_path, timestamp));
 2554                            }
 2555                        }
 2556                        hash_map::Entry::Vacant(entry) => {
 2557                            entry.insert((fs_path, timestamp));
 2558                        }
 2559                    }
 2560                });
 2561
 2562            if let Some(item) = pane.active_item()
 2563                && let Some(project_path) = item.project_path(cx)
 2564            {
 2565                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2566
 2567                if let Some(fs_path) = &fs_path {
 2568                    abs_paths_opened
 2569                        .entry(fs_path.clone())
 2570                        .or_default()
 2571                        .insert(project_path.clone());
 2572                }
 2573
 2574                history.insert(project_path, (fs_path, std::usize::MAX));
 2575            }
 2576        }
 2577
 2578        history
 2579            .into_iter()
 2580            .sorted_by_key(|(_, (_, order))| *order)
 2581            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2582            .rev()
 2583            .filter(move |(history_path, abs_path)| {
 2584                let latest_project_path_opened = abs_path
 2585                    .as_ref()
 2586                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2587                    .and_then(|project_paths| {
 2588                        project_paths
 2589                            .iter()
 2590                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2591                    });
 2592
 2593                latest_project_path_opened.is_none_or(|path| path == history_path)
 2594            })
 2595    }
 2596
 2597    pub fn recent_navigation_history(
 2598        &self,
 2599        limit: Option<usize>,
 2600        cx: &App,
 2601    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2602        self.recent_navigation_history_iter(cx)
 2603            .take(limit.unwrap_or(usize::MAX))
 2604            .collect()
 2605    }
 2606
 2607    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2608        for pane in &self.panes {
 2609            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2610        }
 2611    }
 2612
 2613    fn navigate_history(
 2614        &mut self,
 2615        pane: WeakEntity<Pane>,
 2616        mode: NavigationMode,
 2617        window: &mut Window,
 2618        cx: &mut Context<Workspace>,
 2619    ) -> Task<Result<()>> {
 2620        self.navigate_history_impl(
 2621            pane,
 2622            mode,
 2623            window,
 2624            &mut |history, cx| history.pop(mode, cx),
 2625            cx,
 2626        )
 2627    }
 2628
 2629    fn navigate_tag_history(
 2630        &mut self,
 2631        pane: WeakEntity<Pane>,
 2632        mode: TagNavigationMode,
 2633        window: &mut Window,
 2634        cx: &mut Context<Workspace>,
 2635    ) -> Task<Result<()>> {
 2636        self.navigate_history_impl(
 2637            pane,
 2638            NavigationMode::Normal,
 2639            window,
 2640            &mut |history, _cx| history.pop_tag(mode),
 2641            cx,
 2642        )
 2643    }
 2644
 2645    fn navigate_history_impl(
 2646        &mut self,
 2647        pane: WeakEntity<Pane>,
 2648        mode: NavigationMode,
 2649        window: &mut Window,
 2650        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2651        cx: &mut Context<Workspace>,
 2652    ) -> Task<Result<()>> {
 2653        let to_load = if let Some(pane) = pane.upgrade() {
 2654            pane.update(cx, |pane, cx| {
 2655                window.focus(&pane.focus_handle(cx), cx);
 2656                loop {
 2657                    // Retrieve the weak item handle from the history.
 2658                    let entry = cb(pane.nav_history_mut(), cx)?;
 2659
 2660                    // If the item is still present in this pane, then activate it.
 2661                    if let Some(index) = entry
 2662                        .item
 2663                        .upgrade()
 2664                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2665                    {
 2666                        let prev_active_item_index = pane.active_item_index();
 2667                        pane.nav_history_mut().set_mode(mode);
 2668                        pane.activate_item(index, true, true, window, cx);
 2669                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2670
 2671                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2672                        if let Some(data) = entry.data {
 2673                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2674                        }
 2675
 2676                        if navigated {
 2677                            break None;
 2678                        }
 2679                    } else {
 2680                        // If the item is no longer present in this pane, then retrieve its
 2681                        // path info in order to reopen it.
 2682                        break pane
 2683                            .nav_history()
 2684                            .path_for_item(entry.item.id())
 2685                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2686                    }
 2687                }
 2688            })
 2689        } else {
 2690            None
 2691        };
 2692
 2693        if let Some((project_path, abs_path, entry)) = to_load {
 2694            // If the item was no longer present, then load it again from its previous path, first try the local path
 2695            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2696
 2697            cx.spawn_in(window, async move  |workspace, cx| {
 2698                let open_by_project_path = open_by_project_path.await;
 2699                let mut navigated = false;
 2700                match open_by_project_path
 2701                    .with_context(|| format!("Navigating to {project_path:?}"))
 2702                {
 2703                    Ok((project_entry_id, build_item)) => {
 2704                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2705                            pane.nav_history_mut().set_mode(mode);
 2706                            pane.active_item().map(|p| p.item_id())
 2707                        })?;
 2708
 2709                        pane.update_in(cx, |pane, window, cx| {
 2710                            let item = pane.open_item(
 2711                                project_entry_id,
 2712                                project_path,
 2713                                true,
 2714                                entry.is_preview,
 2715                                true,
 2716                                None,
 2717                                window, cx,
 2718                                build_item,
 2719                            );
 2720                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2721                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2722                            if let Some(data) = entry.data {
 2723                                navigated |= item.navigate(data, window, cx);
 2724                            }
 2725                        })?;
 2726                    }
 2727                    Err(open_by_project_path_e) => {
 2728                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2729                        // and its worktree is now dropped
 2730                        if let Some(abs_path) = abs_path {
 2731                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2732                                pane.nav_history_mut().set_mode(mode);
 2733                                pane.active_item().map(|p| p.item_id())
 2734                            })?;
 2735                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2736                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2737                            })?;
 2738                            match open_by_abs_path
 2739                                .await
 2740                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2741                            {
 2742                                Ok(item) => {
 2743                                    pane.update_in(cx, |pane, window, cx| {
 2744                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2745                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2746                                        if let Some(data) = entry.data {
 2747                                            navigated |= item.navigate(data, window, cx);
 2748                                        }
 2749                                    })?;
 2750                                }
 2751                                Err(open_by_abs_path_e) => {
 2752                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2753                                }
 2754                            }
 2755                        }
 2756                    }
 2757                }
 2758
 2759                if !navigated {
 2760                    workspace
 2761                        .update_in(cx, |workspace, window, cx| {
 2762                            Self::navigate_history(workspace, pane, mode, window, cx)
 2763                        })?
 2764                        .await?;
 2765                }
 2766
 2767                Ok(())
 2768            })
 2769        } else {
 2770            Task::ready(Ok(()))
 2771        }
 2772    }
 2773
 2774    pub fn go_back(
 2775        &mut self,
 2776        pane: WeakEntity<Pane>,
 2777        window: &mut Window,
 2778        cx: &mut Context<Workspace>,
 2779    ) -> Task<Result<()>> {
 2780        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2781    }
 2782
 2783    pub fn go_forward(
 2784        &mut self,
 2785        pane: WeakEntity<Pane>,
 2786        window: &mut Window,
 2787        cx: &mut Context<Workspace>,
 2788    ) -> Task<Result<()>> {
 2789        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2790    }
 2791
 2792    pub fn reopen_closed_item(
 2793        &mut self,
 2794        window: &mut Window,
 2795        cx: &mut Context<Workspace>,
 2796    ) -> Task<Result<()>> {
 2797        self.navigate_history(
 2798            self.active_pane().downgrade(),
 2799            NavigationMode::ReopeningClosedItem,
 2800            window,
 2801            cx,
 2802        )
 2803    }
 2804
 2805    pub fn client(&self) -> &Arc<Client> {
 2806        &self.app_state.client
 2807    }
 2808
 2809    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2810        self.titlebar_item = Some(item);
 2811        cx.notify();
 2812    }
 2813
 2814    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2815        self.on_prompt_for_new_path = Some(prompt)
 2816    }
 2817
 2818    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2819        self.on_prompt_for_open_path = Some(prompt)
 2820    }
 2821
 2822    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2823        self.terminal_provider = Some(Box::new(provider));
 2824    }
 2825
 2826    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2827        self.debugger_provider = Some(Arc::new(provider));
 2828    }
 2829
 2830    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2831        self.open_in_dev_container = value;
 2832    }
 2833
 2834    pub fn open_in_dev_container(&self) -> bool {
 2835        self.open_in_dev_container
 2836    }
 2837
 2838    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2839        self._dev_container_task = Some(task);
 2840    }
 2841
 2842    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2843        self.debugger_provider.clone()
 2844    }
 2845
 2846    pub fn prompt_for_open_path(
 2847        &mut self,
 2848        path_prompt_options: PathPromptOptions,
 2849        lister: DirectoryLister,
 2850        window: &mut Window,
 2851        cx: &mut Context<Self>,
 2852    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2853        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2854            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2855            let rx = prompt(self, lister, window, cx);
 2856            self.on_prompt_for_open_path = Some(prompt);
 2857            rx
 2858        } else {
 2859            let (tx, rx) = oneshot::channel();
 2860            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2861
 2862            cx.spawn_in(window, async move |workspace, cx| {
 2863                let Ok(result) = abs_path.await else {
 2864                    return Ok(());
 2865                };
 2866
 2867                match result {
 2868                    Ok(result) => {
 2869                        tx.send(result).ok();
 2870                    }
 2871                    Err(err) => {
 2872                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2873                            workspace.show_portal_error(err.to_string(), cx);
 2874                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2875                            let rx = prompt(workspace, lister, window, cx);
 2876                            workspace.on_prompt_for_open_path = Some(prompt);
 2877                            rx
 2878                        })?;
 2879                        if let Ok(path) = rx.await {
 2880                            tx.send(path).ok();
 2881                        }
 2882                    }
 2883                };
 2884                anyhow::Ok(())
 2885            })
 2886            .detach();
 2887
 2888            rx
 2889        }
 2890    }
 2891
 2892    pub fn prompt_for_new_path(
 2893        &mut self,
 2894        lister: DirectoryLister,
 2895        suggested_name: Option<String>,
 2896        window: &mut Window,
 2897        cx: &mut Context<Self>,
 2898    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2899        if self.project.read(cx).is_via_collab()
 2900            || self.project.read(cx).is_via_remote_server()
 2901            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2902        {
 2903            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2904            let rx = prompt(self, lister, suggested_name, window, cx);
 2905            self.on_prompt_for_new_path = Some(prompt);
 2906            return rx;
 2907        }
 2908
 2909        let (tx, rx) = oneshot::channel();
 2910        cx.spawn_in(window, async move |workspace, cx| {
 2911            let abs_path = workspace.update(cx, |workspace, cx| {
 2912                let relative_to = workspace
 2913                    .most_recent_active_path(cx)
 2914                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2915                    .or_else(|| {
 2916                        let project = workspace.project.read(cx);
 2917                        project.visible_worktrees(cx).find_map(|worktree| {
 2918                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2919                        })
 2920                    })
 2921                    .or_else(std::env::home_dir)
 2922                    .unwrap_or_else(|| PathBuf::from(""));
 2923                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2924            })?;
 2925            let abs_path = match abs_path.await? {
 2926                Ok(path) => path,
 2927                Err(err) => {
 2928                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2929                        workspace.show_portal_error(err.to_string(), cx);
 2930
 2931                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2932                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2933                        workspace.on_prompt_for_new_path = Some(prompt);
 2934                        rx
 2935                    })?;
 2936                    if let Ok(path) = rx.await {
 2937                        tx.send(path).ok();
 2938                    }
 2939                    return anyhow::Ok(());
 2940                }
 2941            };
 2942
 2943            tx.send(abs_path.map(|path| vec![path])).ok();
 2944            anyhow::Ok(())
 2945        })
 2946        .detach();
 2947
 2948        rx
 2949    }
 2950
 2951    pub fn titlebar_item(&self) -> Option<AnyView> {
 2952        self.titlebar_item.clone()
 2953    }
 2954
 2955    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2956    /// When set, git-related operations should use this worktree instead of deriving
 2957    /// the active worktree from the focused file.
 2958    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2959        self.active_worktree_override
 2960    }
 2961
 2962    pub fn set_active_worktree_override(
 2963        &mut self,
 2964        worktree_id: Option<WorktreeId>,
 2965        cx: &mut Context<Self>,
 2966    ) {
 2967        self.active_worktree_override = worktree_id;
 2968        cx.notify();
 2969    }
 2970
 2971    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2972        self.active_worktree_override = None;
 2973        cx.notify();
 2974    }
 2975
 2976    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2977    ///
 2978    /// If the given workspace has a local project, then it will be passed
 2979    /// to the callback. Otherwise, a new empty window will be created.
 2980    pub fn with_local_workspace<T, F>(
 2981        &mut self,
 2982        window: &mut Window,
 2983        cx: &mut Context<Self>,
 2984        callback: F,
 2985    ) -> Task<Result<T>>
 2986    where
 2987        T: 'static,
 2988        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2989    {
 2990        if self.project.read(cx).is_local() {
 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    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3017    ///
 3018    /// If the given workspace has a local project, then it will be passed
 3019    /// to the callback. Otherwise, a new empty window will be created.
 3020    pub fn with_local_or_wsl_workspace<T, F>(
 3021        &mut self,
 3022        window: &mut Window,
 3023        cx: &mut Context<Self>,
 3024        callback: F,
 3025    ) -> Task<Result<T>>
 3026    where
 3027        T: 'static,
 3028        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3029    {
 3030        let project = self.project.read(cx);
 3031        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3032            Task::ready(Ok(callback(self, window, cx)))
 3033        } else {
 3034            let env = self.project.read(cx).cli_environment(cx);
 3035            let task = Self::new_local(
 3036                Vec::new(),
 3037                self.app_state.clone(),
 3038                None,
 3039                env,
 3040                None,
 3041                OpenMode::Activate,
 3042                cx,
 3043            );
 3044            cx.spawn_in(window, async move |_vh, cx| {
 3045                let OpenResult {
 3046                    window: multi_workspace_window,
 3047                    ..
 3048                } = task.await?;
 3049                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3050                    let workspace = multi_workspace.workspace().clone();
 3051                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3052                })
 3053            })
 3054        }
 3055    }
 3056
 3057    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3058        self.project.read(cx).worktrees(cx)
 3059    }
 3060
 3061    pub fn visible_worktrees<'a>(
 3062        &self,
 3063        cx: &'a App,
 3064    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3065        self.project.read(cx).visible_worktrees(cx)
 3066    }
 3067
 3068    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3069        let futures = self
 3070            .worktrees(cx)
 3071            .filter_map(|worktree| worktree.read(cx).as_local())
 3072            .map(|worktree| worktree.scan_complete())
 3073            .collect::<Vec<_>>();
 3074        async move {
 3075            for future in futures {
 3076                future.await;
 3077            }
 3078        }
 3079    }
 3080
 3081    pub fn close_global(cx: &mut App) {
 3082        cx.defer(|cx| {
 3083            cx.windows().iter().find(|window| {
 3084                window
 3085                    .update(cx, |_, window, _| {
 3086                        if window.is_window_active() {
 3087                            //This can only get called when the window's project connection has been lost
 3088                            //so we don't need to prompt the user for anything and instead just close the window
 3089                            window.remove_window();
 3090                            true
 3091                        } else {
 3092                            false
 3093                        }
 3094                    })
 3095                    .unwrap_or(false)
 3096            });
 3097        });
 3098    }
 3099
 3100    pub fn move_focused_panel_to_next_position(
 3101        &mut self,
 3102        _: &MoveFocusedPanelToNextPosition,
 3103        window: &mut Window,
 3104        cx: &mut Context<Self>,
 3105    ) {
 3106        let docks = self.all_docks();
 3107        let active_dock = docks
 3108            .into_iter()
 3109            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3110
 3111        if let Some(dock) = active_dock {
 3112            dock.update(cx, |dock, cx| {
 3113                let active_panel = dock
 3114                    .active_panel()
 3115                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3116
 3117                if let Some(panel) = active_panel {
 3118                    panel.move_to_next_position(window, cx);
 3119                }
 3120            })
 3121        }
 3122    }
 3123
 3124    pub fn prepare_to_close(
 3125        &mut self,
 3126        close_intent: CloseIntent,
 3127        window: &mut Window,
 3128        cx: &mut Context<Self>,
 3129    ) -> Task<Result<bool>> {
 3130        let active_call = self.active_global_call();
 3131
 3132        cx.spawn_in(window, async move |this, cx| {
 3133            this.update(cx, |this, _| {
 3134                if close_intent == CloseIntent::CloseWindow {
 3135                    this.removing = true;
 3136                }
 3137            })?;
 3138
 3139            let workspace_count = cx.update(|_window, cx| {
 3140                cx.windows()
 3141                    .iter()
 3142                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3143                    .count()
 3144            })?;
 3145
 3146            #[cfg(target_os = "macos")]
 3147            let save_last_workspace = false;
 3148
 3149            // On Linux and Windows, closing the last window should restore the last workspace.
 3150            #[cfg(not(target_os = "macos"))]
 3151            let save_last_workspace = {
 3152                let remaining_workspaces = cx.update(|_window, cx| {
 3153                    cx.windows()
 3154                        .iter()
 3155                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3156                        .filter_map(|multi_workspace| {
 3157                            multi_workspace
 3158                                .update(cx, |multi_workspace, _, cx| {
 3159                                    multi_workspace.workspace().read(cx).removing
 3160                                })
 3161                                .ok()
 3162                        })
 3163                        .filter(|removing| !removing)
 3164                        .count()
 3165                })?;
 3166
 3167                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3168            };
 3169
 3170            if let Some(active_call) = active_call
 3171                && workspace_count == 1
 3172                && cx
 3173                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3174                    .unwrap_or(false)
 3175            {
 3176                if close_intent == CloseIntent::CloseWindow {
 3177                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3178                    let answer = cx.update(|window, cx| {
 3179                        window.prompt(
 3180                            PromptLevel::Warning,
 3181                            "Do you want to leave the current call?",
 3182                            None,
 3183                            &["Close window and hang up", "Cancel"],
 3184                            cx,
 3185                        )
 3186                    })?;
 3187
 3188                    if answer.await.log_err() == Some(1) {
 3189                        return anyhow::Ok(false);
 3190                    } else {
 3191                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3192                            task.await.log_err();
 3193                        }
 3194                    }
 3195                }
 3196                if close_intent == CloseIntent::ReplaceWindow {
 3197                    _ = cx.update(|_window, cx| {
 3198                        let multi_workspace = cx
 3199                            .windows()
 3200                            .iter()
 3201                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3202                            .next()
 3203                            .unwrap();
 3204                        let project = multi_workspace
 3205                            .read(cx)?
 3206                            .workspace()
 3207                            .read(cx)
 3208                            .project
 3209                            .clone();
 3210                        if project.read(cx).is_shared() {
 3211                            active_call.0.unshare_project(project, cx)?;
 3212                        }
 3213                        Ok::<_, anyhow::Error>(())
 3214                    });
 3215                }
 3216            }
 3217
 3218            let save_result = this
 3219                .update_in(cx, |this, window, cx| {
 3220                    this.save_all_internal(SaveIntent::Close, window, cx)
 3221                })?
 3222                .await;
 3223
 3224            // If we're not quitting, but closing, we remove the workspace from
 3225            // the current session.
 3226            if close_intent != CloseIntent::Quit
 3227                && !save_last_workspace
 3228                && save_result.as_ref().is_ok_and(|&res| res)
 3229            {
 3230                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3231                    .await;
 3232            }
 3233
 3234            save_result
 3235        })
 3236    }
 3237
 3238    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3239        self.save_all_internal(
 3240            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3241            window,
 3242            cx,
 3243        )
 3244        .detach_and_log_err(cx);
 3245    }
 3246
 3247    fn send_keystrokes(
 3248        &mut self,
 3249        action: &SendKeystrokes,
 3250        window: &mut Window,
 3251        cx: &mut Context<Self>,
 3252    ) {
 3253        let keystrokes: Vec<Keystroke> = action
 3254            .0
 3255            .split(' ')
 3256            .flat_map(|k| Keystroke::parse(k).log_err())
 3257            .map(|k| {
 3258                cx.keyboard_mapper()
 3259                    .map_key_equivalent(k, false)
 3260                    .inner()
 3261                    .clone()
 3262            })
 3263            .collect();
 3264        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3265    }
 3266
 3267    pub fn send_keystrokes_impl(
 3268        &mut self,
 3269        keystrokes: Vec<Keystroke>,
 3270        window: &mut Window,
 3271        cx: &mut Context<Self>,
 3272    ) -> Shared<Task<()>> {
 3273        let mut state = self.dispatching_keystrokes.borrow_mut();
 3274        if !state.dispatched.insert(keystrokes.clone()) {
 3275            cx.propagate();
 3276            return state.task.clone().unwrap();
 3277        }
 3278
 3279        state.queue.extend(keystrokes);
 3280
 3281        let keystrokes = self.dispatching_keystrokes.clone();
 3282        if state.task.is_none() {
 3283            state.task = Some(
 3284                window
 3285                    .spawn(cx, async move |cx| {
 3286                        // limit to 100 keystrokes to avoid infinite recursion.
 3287                        for _ in 0..100 {
 3288                            let keystroke = {
 3289                                let mut state = keystrokes.borrow_mut();
 3290                                let Some(keystroke) = state.queue.pop_front() else {
 3291                                    state.dispatched.clear();
 3292                                    state.task.take();
 3293                                    return;
 3294                                };
 3295                                keystroke
 3296                            };
 3297                            cx.update(|window, cx| {
 3298                                let focused = window.focused(cx);
 3299                                window.dispatch_keystroke(keystroke.clone(), cx);
 3300                                if window.focused(cx) != focused {
 3301                                    // dispatch_keystroke may cause the focus to change.
 3302                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3303                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3304                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3305                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3306                                    // )
 3307                                    window.draw(cx).clear();
 3308                                }
 3309                            })
 3310                            .ok();
 3311
 3312                            // Yield between synthetic keystrokes so deferred focus and
 3313                            // other effects can settle before dispatching the next key.
 3314                            yield_now().await;
 3315                        }
 3316
 3317                        *keystrokes.borrow_mut() = Default::default();
 3318                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3319                    })
 3320                    .shared(),
 3321            );
 3322        }
 3323        state.task.clone().unwrap()
 3324    }
 3325
 3326    fn save_all_internal(
 3327        &mut self,
 3328        mut save_intent: SaveIntent,
 3329        window: &mut Window,
 3330        cx: &mut Context<Self>,
 3331    ) -> Task<Result<bool>> {
 3332        if self.project.read(cx).is_disconnected(cx) {
 3333            return Task::ready(Ok(true));
 3334        }
 3335        let dirty_items = self
 3336            .panes
 3337            .iter()
 3338            .flat_map(|pane| {
 3339                pane.read(cx).items().filter_map(|item| {
 3340                    if item.is_dirty(cx) {
 3341                        item.tab_content_text(0, cx);
 3342                        Some((pane.downgrade(), item.boxed_clone()))
 3343                    } else {
 3344                        None
 3345                    }
 3346                })
 3347            })
 3348            .collect::<Vec<_>>();
 3349
 3350        let project = self.project.clone();
 3351        cx.spawn_in(window, async move |workspace, cx| {
 3352            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3353                let (serialize_tasks, remaining_dirty_items) =
 3354                    workspace.update_in(cx, |workspace, window, cx| {
 3355                        let mut remaining_dirty_items = Vec::new();
 3356                        let mut serialize_tasks = Vec::new();
 3357                        for (pane, item) in dirty_items {
 3358                            if let Some(task) = item
 3359                                .to_serializable_item_handle(cx)
 3360                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3361                            {
 3362                                serialize_tasks.push(task);
 3363                            } else {
 3364                                remaining_dirty_items.push((pane, item));
 3365                            }
 3366                        }
 3367                        (serialize_tasks, remaining_dirty_items)
 3368                    })?;
 3369
 3370                futures::future::try_join_all(serialize_tasks).await?;
 3371
 3372                if !remaining_dirty_items.is_empty() {
 3373                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3374                }
 3375
 3376                if remaining_dirty_items.len() > 1 {
 3377                    let answer = workspace.update_in(cx, |_, window, cx| {
 3378                        let detail = Pane::file_names_for_prompt(
 3379                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3380                            cx,
 3381                        );
 3382                        window.prompt(
 3383                            PromptLevel::Warning,
 3384                            "Do you want to save all changes in the following files?",
 3385                            Some(&detail),
 3386                            &["Save all", "Discard all", "Cancel"],
 3387                            cx,
 3388                        )
 3389                    })?;
 3390                    match answer.await.log_err() {
 3391                        Some(0) => save_intent = SaveIntent::SaveAll,
 3392                        Some(1) => save_intent = SaveIntent::Skip,
 3393                        Some(2) => return Ok(false),
 3394                        _ => {}
 3395                    }
 3396                }
 3397
 3398                remaining_dirty_items
 3399            } else {
 3400                dirty_items
 3401            };
 3402
 3403            for (pane, item) in dirty_items {
 3404                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3405                    (
 3406                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3407                        item.project_entry_ids(cx),
 3408                    )
 3409                })?;
 3410                if (singleton || !project_entry_ids.is_empty())
 3411                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3412                {
 3413                    return Ok(false);
 3414                }
 3415            }
 3416            Ok(true)
 3417        })
 3418    }
 3419
 3420    pub fn open_workspace_for_paths(
 3421        &mut self,
 3422        // replace_current_window: bool,
 3423        mut open_mode: OpenMode,
 3424        paths: Vec<PathBuf>,
 3425        window: &mut Window,
 3426        cx: &mut Context<Self>,
 3427    ) -> Task<Result<Entity<Workspace>>> {
 3428        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3429        let is_remote = self.project.read(cx).is_via_collab();
 3430        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3431        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3432
 3433        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3434        if workspace_is_empty {
 3435            open_mode = OpenMode::Activate;
 3436        }
 3437
 3438        let app_state = self.app_state.clone();
 3439
 3440        cx.spawn(async move |_, cx| {
 3441            let OpenResult { workspace, .. } = cx
 3442                .update(|cx| {
 3443                    open_paths(
 3444                        &paths,
 3445                        app_state,
 3446                        OpenOptions {
 3447                            requesting_window,
 3448                            open_mode,
 3449                            ..Default::default()
 3450                        },
 3451                        cx,
 3452                    )
 3453                })
 3454                .await?;
 3455            Ok(workspace)
 3456        })
 3457    }
 3458
 3459    #[allow(clippy::type_complexity)]
 3460    pub fn open_paths(
 3461        &mut self,
 3462        mut abs_paths: Vec<PathBuf>,
 3463        options: OpenOptions,
 3464        pane: Option<WeakEntity<Pane>>,
 3465        window: &mut Window,
 3466        cx: &mut Context<Self>,
 3467    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3468        let fs = self.app_state.fs.clone();
 3469
 3470        let caller_ordered_abs_paths = abs_paths.clone();
 3471
 3472        // Sort the paths to ensure we add worktrees for parents before their children.
 3473        abs_paths.sort_unstable();
 3474        cx.spawn_in(window, async move |this, cx| {
 3475            let mut tasks = Vec::with_capacity(abs_paths.len());
 3476
 3477            for abs_path in &abs_paths {
 3478                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3479                    OpenVisible::All => Some(true),
 3480                    OpenVisible::None => Some(false),
 3481                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3482                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3483                        Some(None) => Some(true),
 3484                        None => None,
 3485                    },
 3486                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3487                        Some(Some(metadata)) => Some(metadata.is_dir),
 3488                        Some(None) => Some(false),
 3489                        None => None,
 3490                    },
 3491                };
 3492                let project_path = match visible {
 3493                    Some(visible) => match this
 3494                        .update(cx, |this, cx| {
 3495                            Workspace::project_path_for_path(
 3496                                this.project.clone(),
 3497                                abs_path,
 3498                                visible,
 3499                                cx,
 3500                            )
 3501                        })
 3502                        .log_err()
 3503                    {
 3504                        Some(project_path) => project_path.await.log_err(),
 3505                        None => None,
 3506                    },
 3507                    None => None,
 3508                };
 3509
 3510                let this = this.clone();
 3511                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3512                let fs = fs.clone();
 3513                let pane = pane.clone();
 3514                let task = cx.spawn(async move |cx| {
 3515                    let (_worktree, project_path) = project_path?;
 3516                    if fs.is_dir(&abs_path).await {
 3517                        // Opening a directory should not race to update the active entry.
 3518                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3519                        None
 3520                    } else {
 3521                        Some(
 3522                            this.update_in(cx, |this, window, cx| {
 3523                                this.open_path(
 3524                                    project_path,
 3525                                    pane,
 3526                                    options.focus.unwrap_or(true),
 3527                                    window,
 3528                                    cx,
 3529                                )
 3530                            })
 3531                            .ok()?
 3532                            .await,
 3533                        )
 3534                    }
 3535                });
 3536                tasks.push(task);
 3537            }
 3538
 3539            let results = futures::future::join_all(tasks).await;
 3540
 3541            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3542            let mut winner: Option<(PathBuf, bool)> = None;
 3543            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3544                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3545                    if !metadata.is_dir {
 3546                        winner = Some((abs_path, false));
 3547                        break;
 3548                    }
 3549                    if winner.is_none() {
 3550                        winner = Some((abs_path, true));
 3551                    }
 3552                } else if winner.is_none() {
 3553                    winner = Some((abs_path, false));
 3554                }
 3555            }
 3556
 3557            // Compute the winner entry id on the foreground thread and emit once, after all
 3558            // paths finish opening. This avoids races between concurrently-opening paths
 3559            // (directories in particular) and makes the resulting project panel selection
 3560            // deterministic.
 3561            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3562                'emit_winner: {
 3563                    let winner_abs_path: Arc<Path> =
 3564                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3565
 3566                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3567                        OpenVisible::All => true,
 3568                        OpenVisible::None => false,
 3569                        OpenVisible::OnlyFiles => !winner_is_dir,
 3570                        OpenVisible::OnlyDirectories => winner_is_dir,
 3571                    };
 3572
 3573                    let Some(worktree_task) = this
 3574                        .update(cx, |workspace, cx| {
 3575                            workspace.project.update(cx, |project, cx| {
 3576                                project.find_or_create_worktree(
 3577                                    winner_abs_path.as_ref(),
 3578                                    visible,
 3579                                    cx,
 3580                                )
 3581                            })
 3582                        })
 3583                        .ok()
 3584                    else {
 3585                        break 'emit_winner;
 3586                    };
 3587
 3588                    let Ok((worktree, _)) = worktree_task.await else {
 3589                        break 'emit_winner;
 3590                    };
 3591
 3592                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3593                        let worktree = worktree.read(cx);
 3594                        let worktree_abs_path = worktree.abs_path();
 3595                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3596                            worktree.root_entry()
 3597                        } else {
 3598                            winner_abs_path
 3599                                .strip_prefix(worktree_abs_path.as_ref())
 3600                                .ok()
 3601                                .and_then(|relative_path| {
 3602                                    let relative_path =
 3603                                        RelPath::new(relative_path, PathStyle::local())
 3604                                            .log_err()?;
 3605                                    worktree.entry_for_path(&relative_path)
 3606                                })
 3607                        }?;
 3608                        Some(entry.id)
 3609                    }) else {
 3610                        break 'emit_winner;
 3611                    };
 3612
 3613                    this.update(cx, |workspace, cx| {
 3614                        workspace.project.update(cx, |_, cx| {
 3615                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3616                        });
 3617                    })
 3618                    .ok();
 3619                }
 3620            }
 3621
 3622            results
 3623        })
 3624    }
 3625
 3626    pub fn open_resolved_path(
 3627        &mut self,
 3628        path: ResolvedPath,
 3629        window: &mut Window,
 3630        cx: &mut Context<Self>,
 3631    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3632        match path {
 3633            ResolvedPath::ProjectPath { project_path, .. } => {
 3634                self.open_path(project_path, None, true, window, cx)
 3635            }
 3636            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3637                PathBuf::from(path),
 3638                OpenOptions {
 3639                    visible: Some(OpenVisible::None),
 3640                    ..Default::default()
 3641                },
 3642                window,
 3643                cx,
 3644            ),
 3645        }
 3646    }
 3647
 3648    pub fn absolute_path_of_worktree(
 3649        &self,
 3650        worktree_id: WorktreeId,
 3651        cx: &mut Context<Self>,
 3652    ) -> Option<PathBuf> {
 3653        self.project
 3654            .read(cx)
 3655            .worktree_for_id(worktree_id, cx)
 3656            // TODO: use `abs_path` or `root_dir`
 3657            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3658    }
 3659
 3660    pub fn add_folder_to_project(
 3661        &mut self,
 3662        _: &AddFolderToProject,
 3663        window: &mut Window,
 3664        cx: &mut Context<Self>,
 3665    ) {
 3666        let project = self.project.read(cx);
 3667        if project.is_via_collab() {
 3668            self.show_error(
 3669                &anyhow!("You cannot add folders to someone else's project"),
 3670                cx,
 3671            );
 3672            return;
 3673        }
 3674        let paths = self.prompt_for_open_path(
 3675            PathPromptOptions {
 3676                files: false,
 3677                directories: true,
 3678                multiple: true,
 3679                prompt: None,
 3680            },
 3681            DirectoryLister::Project(self.project.clone()),
 3682            window,
 3683            cx,
 3684        );
 3685        cx.spawn_in(window, async move |this, cx| {
 3686            if let Some(paths) = paths.await.log_err().flatten() {
 3687                let results = this
 3688                    .update_in(cx, |this, window, cx| {
 3689                        this.open_paths(
 3690                            paths,
 3691                            OpenOptions {
 3692                                visible: Some(OpenVisible::All),
 3693                                ..Default::default()
 3694                            },
 3695                            None,
 3696                            window,
 3697                            cx,
 3698                        )
 3699                    })?
 3700                    .await;
 3701                for result in results.into_iter().flatten() {
 3702                    result.log_err();
 3703                }
 3704            }
 3705            anyhow::Ok(())
 3706        })
 3707        .detach_and_log_err(cx);
 3708    }
 3709
 3710    pub fn project_path_for_path(
 3711        project: Entity<Project>,
 3712        abs_path: &Path,
 3713        visible: bool,
 3714        cx: &mut App,
 3715    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3716        let entry = project.update(cx, |project, cx| {
 3717            project.find_or_create_worktree(abs_path, visible, cx)
 3718        });
 3719        cx.spawn(async move |cx| {
 3720            let (worktree, path) = entry.await?;
 3721            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3722            Ok((worktree, ProjectPath { worktree_id, path }))
 3723        })
 3724    }
 3725
 3726    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3727        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3728    }
 3729
 3730    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3731        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3732    }
 3733
 3734    pub fn items_of_type<'a, T: Item>(
 3735        &'a self,
 3736        cx: &'a App,
 3737    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3738        self.panes
 3739            .iter()
 3740            .flat_map(|pane| pane.read(cx).items_of_type())
 3741    }
 3742
 3743    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3744        self.active_pane().read(cx).active_item()
 3745    }
 3746
 3747    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3748        let item = self.active_item(cx)?;
 3749        item.to_any_view().downcast::<I>().ok()
 3750    }
 3751
 3752    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3753        self.active_item(cx).and_then(|item| item.project_path(cx))
 3754    }
 3755
 3756    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3757        self.recent_navigation_history_iter(cx)
 3758            .filter_map(|(path, abs_path)| {
 3759                let worktree = self
 3760                    .project
 3761                    .read(cx)
 3762                    .worktree_for_id(path.worktree_id, cx)?;
 3763                if worktree.read(cx).is_visible() {
 3764                    abs_path
 3765                } else {
 3766                    None
 3767                }
 3768            })
 3769            .next()
 3770    }
 3771
 3772    pub fn save_active_item(
 3773        &mut self,
 3774        save_intent: SaveIntent,
 3775        window: &mut Window,
 3776        cx: &mut App,
 3777    ) -> Task<Result<()>> {
 3778        let project = self.project.clone();
 3779        let pane = self.active_pane();
 3780        let item = pane.read(cx).active_item();
 3781        let pane = pane.downgrade();
 3782
 3783        window.spawn(cx, async move |cx| {
 3784            if let Some(item) = item {
 3785                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3786                    .await
 3787                    .map(|_| ())
 3788            } else {
 3789                Ok(())
 3790            }
 3791        })
 3792    }
 3793
 3794    pub fn close_inactive_items_and_panes(
 3795        &mut self,
 3796        action: &CloseInactiveTabsAndPanes,
 3797        window: &mut Window,
 3798        cx: &mut Context<Self>,
 3799    ) {
 3800        if let Some(task) = self.close_all_internal(
 3801            true,
 3802            action.save_intent.unwrap_or(SaveIntent::Close),
 3803            window,
 3804            cx,
 3805        ) {
 3806            task.detach_and_log_err(cx)
 3807        }
 3808    }
 3809
 3810    pub fn close_all_items_and_panes(
 3811        &mut self,
 3812        action: &CloseAllItemsAndPanes,
 3813        window: &mut Window,
 3814        cx: &mut Context<Self>,
 3815    ) {
 3816        if let Some(task) = self.close_all_internal(
 3817            false,
 3818            action.save_intent.unwrap_or(SaveIntent::Close),
 3819            window,
 3820            cx,
 3821        ) {
 3822            task.detach_and_log_err(cx)
 3823        }
 3824    }
 3825
 3826    /// Closes the active item across all panes.
 3827    pub fn close_item_in_all_panes(
 3828        &mut self,
 3829        action: &CloseItemInAllPanes,
 3830        window: &mut Window,
 3831        cx: &mut Context<Self>,
 3832    ) {
 3833        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3834            return;
 3835        };
 3836
 3837        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3838        let close_pinned = action.close_pinned;
 3839
 3840        if let Some(project_path) = active_item.project_path(cx) {
 3841            self.close_items_with_project_path(
 3842                &project_path,
 3843                save_intent,
 3844                close_pinned,
 3845                window,
 3846                cx,
 3847            );
 3848        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3849            let item_id = active_item.item_id();
 3850            self.active_pane().update(cx, |pane, cx| {
 3851                pane.close_item_by_id(item_id, save_intent, window, cx)
 3852                    .detach_and_log_err(cx);
 3853            });
 3854        }
 3855    }
 3856
 3857    /// Closes all items with the given project path across all panes.
 3858    pub fn close_items_with_project_path(
 3859        &mut self,
 3860        project_path: &ProjectPath,
 3861        save_intent: SaveIntent,
 3862        close_pinned: bool,
 3863        window: &mut Window,
 3864        cx: &mut Context<Self>,
 3865    ) {
 3866        let panes = self.panes().to_vec();
 3867        for pane in panes {
 3868            pane.update(cx, |pane, cx| {
 3869                pane.close_items_for_project_path(
 3870                    project_path,
 3871                    save_intent,
 3872                    close_pinned,
 3873                    window,
 3874                    cx,
 3875                )
 3876                .detach_and_log_err(cx);
 3877            });
 3878        }
 3879    }
 3880
 3881    fn close_all_internal(
 3882        &mut self,
 3883        retain_active_pane: bool,
 3884        save_intent: SaveIntent,
 3885        window: &mut Window,
 3886        cx: &mut Context<Self>,
 3887    ) -> Option<Task<Result<()>>> {
 3888        let current_pane = self.active_pane();
 3889
 3890        let mut tasks = Vec::new();
 3891
 3892        if retain_active_pane {
 3893            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3894                pane.close_other_items(
 3895                    &CloseOtherItems {
 3896                        save_intent: None,
 3897                        close_pinned: false,
 3898                    },
 3899                    None,
 3900                    window,
 3901                    cx,
 3902                )
 3903            });
 3904
 3905            tasks.push(current_pane_close);
 3906        }
 3907
 3908        for pane in self.panes() {
 3909            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3910                continue;
 3911            }
 3912
 3913            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3914                pane.close_all_items(
 3915                    &CloseAllItems {
 3916                        save_intent: Some(save_intent),
 3917                        close_pinned: false,
 3918                    },
 3919                    window,
 3920                    cx,
 3921                )
 3922            });
 3923
 3924            tasks.push(close_pane_items)
 3925        }
 3926
 3927        if tasks.is_empty() {
 3928            None
 3929        } else {
 3930            Some(cx.spawn_in(window, async move |_, _| {
 3931                for task in tasks {
 3932                    task.await?
 3933                }
 3934                Ok(())
 3935            }))
 3936        }
 3937    }
 3938
 3939    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3940        self.dock_at_position(position).read(cx).is_open()
 3941    }
 3942
 3943    pub fn toggle_dock(
 3944        &mut self,
 3945        dock_side: DockPosition,
 3946        window: &mut Window,
 3947        cx: &mut Context<Self>,
 3948    ) {
 3949        let mut focus_center = false;
 3950        let mut reveal_dock = false;
 3951
 3952        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3953        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3954
 3955        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3956            telemetry::event!(
 3957                "Panel Button Clicked",
 3958                name = panel.persistent_name(),
 3959                toggle_state = !was_visible
 3960            );
 3961        }
 3962        if was_visible {
 3963            self.save_open_dock_positions(cx);
 3964        }
 3965
 3966        let dock = self.dock_at_position(dock_side);
 3967        dock.update(cx, |dock, cx| {
 3968            dock.set_open(!was_visible, window, cx);
 3969
 3970            if dock.active_panel().is_none() {
 3971                let Some(panel_ix) = dock
 3972                    .first_enabled_panel_idx(cx)
 3973                    .log_with_level(log::Level::Info)
 3974                else {
 3975                    return;
 3976                };
 3977                dock.activate_panel(panel_ix, window, cx);
 3978            }
 3979
 3980            if let Some(active_panel) = dock.active_panel() {
 3981                if was_visible {
 3982                    if active_panel
 3983                        .panel_focus_handle(cx)
 3984                        .contains_focused(window, cx)
 3985                    {
 3986                        focus_center = true;
 3987                    }
 3988                } else {
 3989                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3990                    window.focus(focus_handle, cx);
 3991                    reveal_dock = true;
 3992                }
 3993            }
 3994        });
 3995
 3996        if reveal_dock {
 3997            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3998        }
 3999
 4000        if focus_center {
 4001            self.active_pane
 4002                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4003        }
 4004
 4005        cx.notify();
 4006        self.serialize_workspace(window, cx);
 4007    }
 4008
 4009    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 4010        self.all_docks().into_iter().find(|&dock| {
 4011            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4012        })
 4013    }
 4014
 4015    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4016        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4017            self.save_open_dock_positions(cx);
 4018            dock.update(cx, |dock, cx| {
 4019                dock.set_open(false, window, cx);
 4020            });
 4021            return true;
 4022        }
 4023        false
 4024    }
 4025
 4026    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4027        self.save_open_dock_positions(cx);
 4028        for dock in self.all_docks() {
 4029            dock.update(cx, |dock, cx| {
 4030                dock.set_open(false, window, cx);
 4031            });
 4032        }
 4033
 4034        cx.focus_self(window);
 4035        cx.notify();
 4036        self.serialize_workspace(window, cx);
 4037    }
 4038
 4039    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4040        self.all_docks()
 4041            .into_iter()
 4042            .filter_map(|dock| {
 4043                let dock_ref = dock.read(cx);
 4044                if dock_ref.is_open() {
 4045                    Some(dock_ref.position())
 4046                } else {
 4047                    None
 4048                }
 4049            })
 4050            .collect()
 4051    }
 4052
 4053    /// Saves the positions of currently open docks.
 4054    ///
 4055    /// Updates `last_open_dock_positions` with positions of all currently open
 4056    /// docks, to later be restored by the 'Toggle All Docks' action.
 4057    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4058        let open_dock_positions = self.get_open_dock_positions(cx);
 4059        if !open_dock_positions.is_empty() {
 4060            self.last_open_dock_positions = open_dock_positions;
 4061        }
 4062    }
 4063
 4064    /// Toggles all docks between open and closed states.
 4065    ///
 4066    /// If any docks are open, closes all and remembers their positions. If all
 4067    /// docks are closed, restores the last remembered dock configuration.
 4068    fn toggle_all_docks(
 4069        &mut self,
 4070        _: &ToggleAllDocks,
 4071        window: &mut Window,
 4072        cx: &mut Context<Self>,
 4073    ) {
 4074        let open_dock_positions = self.get_open_dock_positions(cx);
 4075
 4076        if !open_dock_positions.is_empty() {
 4077            self.close_all_docks(window, cx);
 4078        } else if !self.last_open_dock_positions.is_empty() {
 4079            self.restore_last_open_docks(window, cx);
 4080        }
 4081    }
 4082
 4083    /// Reopens docks from the most recently remembered configuration.
 4084    ///
 4085    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4086    /// and clears the stored positions.
 4087    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4088        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4089
 4090        for position in positions_to_open {
 4091            let dock = self.dock_at_position(position);
 4092            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4093        }
 4094
 4095        cx.focus_self(window);
 4096        cx.notify();
 4097        self.serialize_workspace(window, cx);
 4098    }
 4099
 4100    /// Transfer focus to the panel of the given type.
 4101    pub fn focus_panel<T: Panel>(
 4102        &mut self,
 4103        window: &mut Window,
 4104        cx: &mut Context<Self>,
 4105    ) -> Option<Entity<T>> {
 4106        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4107        panel.to_any().downcast().ok()
 4108    }
 4109
 4110    /// Focus the panel of the given type if it isn't already focused. If it is
 4111    /// already focused, then transfer focus back to the workspace center.
 4112    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4113    /// panel when transferring focus back to the center.
 4114    pub fn toggle_panel_focus<T: Panel>(
 4115        &mut self,
 4116        window: &mut Window,
 4117        cx: &mut Context<Self>,
 4118    ) -> bool {
 4119        let mut did_focus_panel = false;
 4120        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4121            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4122            did_focus_panel
 4123        });
 4124
 4125        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4126            self.close_panel::<T>(window, cx);
 4127        }
 4128
 4129        telemetry::event!(
 4130            "Panel Button Clicked",
 4131            name = T::persistent_name(),
 4132            toggle_state = did_focus_panel
 4133        );
 4134
 4135        did_focus_panel
 4136    }
 4137
 4138    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4139        if let Some(item) = self.active_item(cx) {
 4140            item.item_focus_handle(cx).focus(window, cx);
 4141        } else {
 4142            log::error!("Could not find a focus target when switching focus to the center panes",);
 4143        }
 4144    }
 4145
 4146    pub fn activate_panel_for_proto_id(
 4147        &mut self,
 4148        panel_id: PanelId,
 4149        window: &mut Window,
 4150        cx: &mut Context<Self>,
 4151    ) -> Option<Arc<dyn PanelHandle>> {
 4152        let mut panel = None;
 4153        for dock in self.all_docks() {
 4154            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4155                panel = dock.update(cx, |dock, cx| {
 4156                    dock.activate_panel(panel_index, window, cx);
 4157                    dock.set_open(true, window, cx);
 4158                    dock.active_panel().cloned()
 4159                });
 4160                break;
 4161            }
 4162        }
 4163
 4164        if panel.is_some() {
 4165            cx.notify();
 4166            self.serialize_workspace(window, cx);
 4167        }
 4168
 4169        panel
 4170    }
 4171
 4172    /// Focus or unfocus the given panel type, depending on the given callback.
 4173    fn focus_or_unfocus_panel<T: Panel>(
 4174        &mut self,
 4175        window: &mut Window,
 4176        cx: &mut Context<Self>,
 4177        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4178    ) -> Option<Arc<dyn PanelHandle>> {
 4179        let mut result_panel = None;
 4180        let mut serialize = false;
 4181        for dock in self.all_docks() {
 4182            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4183                let mut focus_center = false;
 4184                let panel = dock.update(cx, |dock, cx| {
 4185                    dock.activate_panel(panel_index, window, cx);
 4186
 4187                    let panel = dock.active_panel().cloned();
 4188                    if let Some(panel) = panel.as_ref() {
 4189                        if should_focus(&**panel, window, cx) {
 4190                            dock.set_open(true, window, cx);
 4191                            panel.panel_focus_handle(cx).focus(window, cx);
 4192                        } else {
 4193                            focus_center = true;
 4194                        }
 4195                    }
 4196                    panel
 4197                });
 4198
 4199                if focus_center {
 4200                    self.active_pane
 4201                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4202                }
 4203
 4204                result_panel = panel;
 4205                serialize = true;
 4206                break;
 4207            }
 4208        }
 4209
 4210        if serialize {
 4211            self.serialize_workspace(window, cx);
 4212        }
 4213
 4214        cx.notify();
 4215        result_panel
 4216    }
 4217
 4218    /// Open the panel of the given type
 4219    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4220        for dock in self.all_docks() {
 4221            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4222                dock.update(cx, |dock, cx| {
 4223                    dock.activate_panel(panel_index, window, cx);
 4224                    dock.set_open(true, window, cx);
 4225                });
 4226            }
 4227        }
 4228    }
 4229
 4230    /// Open the panel of the given type, dismissing any zoomed items that
 4231    /// would obscure it (e.g. a zoomed terminal).
 4232    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4233        let dock_position = self.all_docks().iter().find_map(|dock| {
 4234            let dock = dock.read(cx);
 4235            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4236        });
 4237        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4238        self.open_panel::<T>(window, cx);
 4239    }
 4240
 4241    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4242        for dock in self.all_docks().iter() {
 4243            dock.update(cx, |dock, cx| {
 4244                if dock.panel::<T>().is_some() {
 4245                    dock.set_open(false, window, cx)
 4246                }
 4247            })
 4248        }
 4249    }
 4250
 4251    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4252        self.all_docks()
 4253            .iter()
 4254            .find_map(|dock| dock.read(cx).panel::<T>())
 4255    }
 4256
 4257    fn dismiss_zoomed_items_to_reveal(
 4258        &mut self,
 4259        dock_to_reveal: Option<DockPosition>,
 4260        window: &mut Window,
 4261        cx: &mut Context<Self>,
 4262    ) {
 4263        // If a center pane is zoomed, unzoom it.
 4264        for pane in &self.panes {
 4265            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4266                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4267            }
 4268        }
 4269
 4270        // If another dock is zoomed, hide it.
 4271        let mut focus_center = false;
 4272        for dock in self.all_docks() {
 4273            dock.update(cx, |dock, cx| {
 4274                if Some(dock.position()) != dock_to_reveal
 4275                    && let Some(panel) = dock.active_panel()
 4276                    && panel.is_zoomed(window, cx)
 4277                {
 4278                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4279                    dock.set_open(false, window, cx);
 4280                }
 4281            });
 4282        }
 4283
 4284        if focus_center {
 4285            self.active_pane
 4286                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4287        }
 4288
 4289        if self.zoomed_position != dock_to_reveal {
 4290            self.zoomed = None;
 4291            self.zoomed_position = None;
 4292            cx.emit(Event::ZoomChanged);
 4293        }
 4294
 4295        cx.notify();
 4296    }
 4297
 4298    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4299        let pane = cx.new(|cx| {
 4300            let mut pane = Pane::new(
 4301                self.weak_handle(),
 4302                self.project.clone(),
 4303                self.pane_history_timestamp.clone(),
 4304                None,
 4305                NewFile.boxed_clone(),
 4306                true,
 4307                window,
 4308                cx,
 4309            );
 4310            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4311            pane
 4312        });
 4313        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4314            .detach();
 4315        self.panes.push(pane.clone());
 4316
 4317        window.focus(&pane.focus_handle(cx), cx);
 4318
 4319        cx.emit(Event::PaneAdded(pane.clone()));
 4320        pane
 4321    }
 4322
 4323    pub fn add_item_to_center(
 4324        &mut self,
 4325        item: Box<dyn ItemHandle>,
 4326        window: &mut Window,
 4327        cx: &mut Context<Self>,
 4328    ) -> bool {
 4329        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4330            if let Some(center_pane) = center_pane.upgrade() {
 4331                center_pane.update(cx, |pane, cx| {
 4332                    pane.add_item(item, true, true, None, window, cx)
 4333                });
 4334                true
 4335            } else {
 4336                false
 4337            }
 4338        } else {
 4339            false
 4340        }
 4341    }
 4342
 4343    pub fn add_item_to_active_pane(
 4344        &mut self,
 4345        item: Box<dyn ItemHandle>,
 4346        destination_index: Option<usize>,
 4347        focus_item: bool,
 4348        window: &mut Window,
 4349        cx: &mut App,
 4350    ) {
 4351        self.add_item(
 4352            self.active_pane.clone(),
 4353            item,
 4354            destination_index,
 4355            false,
 4356            focus_item,
 4357            window,
 4358            cx,
 4359        )
 4360    }
 4361
 4362    pub fn add_item(
 4363        &mut self,
 4364        pane: Entity<Pane>,
 4365        item: Box<dyn ItemHandle>,
 4366        destination_index: Option<usize>,
 4367        activate_pane: bool,
 4368        focus_item: bool,
 4369        window: &mut Window,
 4370        cx: &mut App,
 4371    ) {
 4372        pane.update(cx, |pane, cx| {
 4373            pane.add_item(
 4374                item,
 4375                activate_pane,
 4376                focus_item,
 4377                destination_index,
 4378                window,
 4379                cx,
 4380            )
 4381        });
 4382    }
 4383
 4384    pub fn split_item(
 4385        &mut self,
 4386        split_direction: SplitDirection,
 4387        item: Box<dyn ItemHandle>,
 4388        window: &mut Window,
 4389        cx: &mut Context<Self>,
 4390    ) {
 4391        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4392        self.add_item(new_pane, item, None, true, true, window, cx);
 4393    }
 4394
 4395    pub fn open_abs_path(
 4396        &mut self,
 4397        abs_path: PathBuf,
 4398        options: OpenOptions,
 4399        window: &mut Window,
 4400        cx: &mut Context<Self>,
 4401    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4402        cx.spawn_in(window, async move |workspace, cx| {
 4403            let open_paths_task_result = workspace
 4404                .update_in(cx, |workspace, window, cx| {
 4405                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4406                })
 4407                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4408                .await;
 4409            anyhow::ensure!(
 4410                open_paths_task_result.len() == 1,
 4411                "open abs path {abs_path:?} task returned incorrect number of results"
 4412            );
 4413            match open_paths_task_result
 4414                .into_iter()
 4415                .next()
 4416                .expect("ensured single task result")
 4417            {
 4418                Some(open_result) => {
 4419                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4420                }
 4421                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4422            }
 4423        })
 4424    }
 4425
 4426    pub fn split_abs_path(
 4427        &mut self,
 4428        abs_path: PathBuf,
 4429        visible: bool,
 4430        window: &mut Window,
 4431        cx: &mut Context<Self>,
 4432    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4433        let project_path_task =
 4434            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4435        cx.spawn_in(window, async move |this, cx| {
 4436            let (_, path) = project_path_task.await?;
 4437            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4438                .await
 4439        })
 4440    }
 4441
 4442    pub fn open_path(
 4443        &mut self,
 4444        path: impl Into<ProjectPath>,
 4445        pane: Option<WeakEntity<Pane>>,
 4446        focus_item: bool,
 4447        window: &mut Window,
 4448        cx: &mut App,
 4449    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4450        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4451    }
 4452
 4453    pub fn open_path_preview(
 4454        &mut self,
 4455        path: impl Into<ProjectPath>,
 4456        pane: Option<WeakEntity<Pane>>,
 4457        focus_item: bool,
 4458        allow_preview: bool,
 4459        activate: bool,
 4460        window: &mut Window,
 4461        cx: &mut App,
 4462    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4463        let pane = pane.unwrap_or_else(|| {
 4464            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4465                self.panes
 4466                    .first()
 4467                    .expect("There must be an active pane")
 4468                    .downgrade()
 4469            })
 4470        });
 4471
 4472        let project_path = path.into();
 4473        let task = self.load_path(project_path.clone(), window, cx);
 4474        window.spawn(cx, async move |cx| {
 4475            let (project_entry_id, build_item) = task.await?;
 4476
 4477            pane.update_in(cx, |pane, window, cx| {
 4478                pane.open_item(
 4479                    project_entry_id,
 4480                    project_path,
 4481                    focus_item,
 4482                    allow_preview,
 4483                    activate,
 4484                    None,
 4485                    window,
 4486                    cx,
 4487                    build_item,
 4488                )
 4489            })
 4490        })
 4491    }
 4492
 4493    pub fn split_path(
 4494        &mut self,
 4495        path: impl Into<ProjectPath>,
 4496        window: &mut Window,
 4497        cx: &mut Context<Self>,
 4498    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4499        self.split_path_preview(path, false, None, window, cx)
 4500    }
 4501
 4502    pub fn split_path_preview(
 4503        &mut self,
 4504        path: impl Into<ProjectPath>,
 4505        allow_preview: bool,
 4506        split_direction: Option<SplitDirection>,
 4507        window: &mut Window,
 4508        cx: &mut Context<Self>,
 4509    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4510        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4511            self.panes
 4512                .first()
 4513                .expect("There must be an active pane")
 4514                .downgrade()
 4515        });
 4516
 4517        if let Member::Pane(center_pane) = &self.center.root
 4518            && center_pane.read(cx).items_len() == 0
 4519        {
 4520            return self.open_path(path, Some(pane), true, window, cx);
 4521        }
 4522
 4523        let project_path = path.into();
 4524        let task = self.load_path(project_path.clone(), window, cx);
 4525        cx.spawn_in(window, async move |this, cx| {
 4526            let (project_entry_id, build_item) = task.await?;
 4527            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4528                let pane = pane.upgrade()?;
 4529                let new_pane = this.split_pane(
 4530                    pane,
 4531                    split_direction.unwrap_or(SplitDirection::Right),
 4532                    window,
 4533                    cx,
 4534                );
 4535                new_pane.update(cx, |new_pane, cx| {
 4536                    Some(new_pane.open_item(
 4537                        project_entry_id,
 4538                        project_path,
 4539                        true,
 4540                        allow_preview,
 4541                        true,
 4542                        None,
 4543                        window,
 4544                        cx,
 4545                        build_item,
 4546                    ))
 4547                })
 4548            })
 4549            .map(|option| option.context("pane was dropped"))?
 4550        })
 4551    }
 4552
 4553    fn load_path(
 4554        &mut self,
 4555        path: ProjectPath,
 4556        window: &mut Window,
 4557        cx: &mut App,
 4558    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4559        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4560        registry.open_path(self.project(), &path, window, cx)
 4561    }
 4562
 4563    pub fn find_project_item<T>(
 4564        &self,
 4565        pane: &Entity<Pane>,
 4566        project_item: &Entity<T::Item>,
 4567        cx: &App,
 4568    ) -> Option<Entity<T>>
 4569    where
 4570        T: ProjectItem,
 4571    {
 4572        use project::ProjectItem as _;
 4573        let project_item = project_item.read(cx);
 4574        let entry_id = project_item.entry_id(cx);
 4575        let project_path = project_item.project_path(cx);
 4576
 4577        let mut item = None;
 4578        if let Some(entry_id) = entry_id {
 4579            item = pane.read(cx).item_for_entry(entry_id, cx);
 4580        }
 4581        if item.is_none()
 4582            && let Some(project_path) = project_path
 4583        {
 4584            item = pane.read(cx).item_for_path(project_path, cx);
 4585        }
 4586
 4587        item.and_then(|item| item.downcast::<T>())
 4588    }
 4589
 4590    pub fn is_project_item_open<T>(
 4591        &self,
 4592        pane: &Entity<Pane>,
 4593        project_item: &Entity<T::Item>,
 4594        cx: &App,
 4595    ) -> bool
 4596    where
 4597        T: ProjectItem,
 4598    {
 4599        self.find_project_item::<T>(pane, project_item, cx)
 4600            .is_some()
 4601    }
 4602
 4603    pub fn open_project_item<T>(
 4604        &mut self,
 4605        pane: Entity<Pane>,
 4606        project_item: Entity<T::Item>,
 4607        activate_pane: bool,
 4608        focus_item: bool,
 4609        keep_old_preview: bool,
 4610        allow_new_preview: bool,
 4611        window: &mut Window,
 4612        cx: &mut Context<Self>,
 4613    ) -> Entity<T>
 4614    where
 4615        T: ProjectItem,
 4616    {
 4617        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4618
 4619        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4620            if !keep_old_preview
 4621                && let Some(old_id) = old_item_id
 4622                && old_id != item.item_id()
 4623            {
 4624                // switching to a different item, so unpreview old active item
 4625                pane.update(cx, |pane, _| {
 4626                    pane.unpreview_item_if_preview(old_id);
 4627                });
 4628            }
 4629
 4630            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4631            if !allow_new_preview {
 4632                pane.update(cx, |pane, _| {
 4633                    pane.unpreview_item_if_preview(item.item_id());
 4634                });
 4635            }
 4636            return item;
 4637        }
 4638
 4639        let item = pane.update(cx, |pane, cx| {
 4640            cx.new(|cx| {
 4641                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4642            })
 4643        });
 4644        let mut destination_index = None;
 4645        pane.update(cx, |pane, cx| {
 4646            if !keep_old_preview && let Some(old_id) = old_item_id {
 4647                pane.unpreview_item_if_preview(old_id);
 4648            }
 4649            if allow_new_preview {
 4650                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4651            }
 4652        });
 4653
 4654        self.add_item(
 4655            pane,
 4656            Box::new(item.clone()),
 4657            destination_index,
 4658            activate_pane,
 4659            focus_item,
 4660            window,
 4661            cx,
 4662        );
 4663        item
 4664    }
 4665
 4666    pub fn open_shared_screen(
 4667        &mut self,
 4668        peer_id: PeerId,
 4669        window: &mut Window,
 4670        cx: &mut Context<Self>,
 4671    ) {
 4672        if let Some(shared_screen) =
 4673            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4674        {
 4675            self.active_pane.update(cx, |pane, cx| {
 4676                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4677            });
 4678        }
 4679    }
 4680
 4681    pub fn activate_item(
 4682        &mut self,
 4683        item: &dyn ItemHandle,
 4684        activate_pane: bool,
 4685        focus_item: bool,
 4686        window: &mut Window,
 4687        cx: &mut App,
 4688    ) -> bool {
 4689        let result = self.panes.iter().find_map(|pane| {
 4690            pane.read(cx)
 4691                .index_for_item(item)
 4692                .map(|ix| (pane.clone(), ix))
 4693        });
 4694        if let Some((pane, ix)) = result {
 4695            pane.update(cx, |pane, cx| {
 4696                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4697            });
 4698            true
 4699        } else {
 4700            false
 4701        }
 4702    }
 4703
 4704    fn activate_pane_at_index(
 4705        &mut self,
 4706        action: &ActivatePane,
 4707        window: &mut Window,
 4708        cx: &mut Context<Self>,
 4709    ) {
 4710        let panes = self.center.panes();
 4711        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4712            window.focus(&pane.focus_handle(cx), cx);
 4713        } else {
 4714            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4715                .detach();
 4716        }
 4717    }
 4718
 4719    fn move_item_to_pane_at_index(
 4720        &mut self,
 4721        action: &MoveItemToPane,
 4722        window: &mut Window,
 4723        cx: &mut Context<Self>,
 4724    ) {
 4725        let panes = self.center.panes();
 4726        let destination = match panes.get(action.destination) {
 4727            Some(&destination) => destination.clone(),
 4728            None => {
 4729                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4730                    return;
 4731                }
 4732                let direction = SplitDirection::Right;
 4733                let split_off_pane = self
 4734                    .find_pane_in_direction(direction, cx)
 4735                    .unwrap_or_else(|| self.active_pane.clone());
 4736                let new_pane = self.add_pane(window, cx);
 4737                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4738                new_pane
 4739            }
 4740        };
 4741
 4742        if action.clone {
 4743            if self
 4744                .active_pane
 4745                .read(cx)
 4746                .active_item()
 4747                .is_some_and(|item| item.can_split(cx))
 4748            {
 4749                clone_active_item(
 4750                    self.database_id(),
 4751                    &self.active_pane,
 4752                    &destination,
 4753                    action.focus,
 4754                    window,
 4755                    cx,
 4756                );
 4757                return;
 4758            }
 4759        }
 4760        move_active_item(
 4761            &self.active_pane,
 4762            &destination,
 4763            action.focus,
 4764            true,
 4765            window,
 4766            cx,
 4767        )
 4768    }
 4769
 4770    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4771        let panes = self.center.panes();
 4772        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4773            let next_ix = (ix + 1) % panes.len();
 4774            let next_pane = panes[next_ix].clone();
 4775            window.focus(&next_pane.focus_handle(cx), cx);
 4776        }
 4777    }
 4778
 4779    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4780        let panes = self.center.panes();
 4781        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4782            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4783            let prev_pane = panes[prev_ix].clone();
 4784            window.focus(&prev_pane.focus_handle(cx), cx);
 4785        }
 4786    }
 4787
 4788    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4789        let last_pane = self.center.last_pane();
 4790        window.focus(&last_pane.focus_handle(cx), cx);
 4791    }
 4792
 4793    pub fn activate_pane_in_direction(
 4794        &mut self,
 4795        direction: SplitDirection,
 4796        window: &mut Window,
 4797        cx: &mut App,
 4798    ) {
 4799        use ActivateInDirectionTarget as Target;
 4800        enum Origin {
 4801            Sidebar,
 4802            LeftDock,
 4803            RightDock,
 4804            BottomDock,
 4805            Center,
 4806        }
 4807
 4808        let origin: Origin = if self
 4809            .sidebar_focus_handle
 4810            .as_ref()
 4811            .is_some_and(|h| h.contains_focused(window, cx))
 4812        {
 4813            Origin::Sidebar
 4814        } else {
 4815            [
 4816                (&self.left_dock, Origin::LeftDock),
 4817                (&self.right_dock, Origin::RightDock),
 4818                (&self.bottom_dock, Origin::BottomDock),
 4819            ]
 4820            .into_iter()
 4821            .find_map(|(dock, origin)| {
 4822                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4823                    Some(origin)
 4824                } else {
 4825                    None
 4826                }
 4827            })
 4828            .unwrap_or(Origin::Center)
 4829        };
 4830
 4831        let get_last_active_pane = || {
 4832            let pane = self
 4833                .last_active_center_pane
 4834                .clone()
 4835                .unwrap_or_else(|| {
 4836                    self.panes
 4837                        .first()
 4838                        .expect("There must be an active pane")
 4839                        .downgrade()
 4840                })
 4841                .upgrade()?;
 4842            (pane.read(cx).items_len() != 0).then_some(pane)
 4843        };
 4844
 4845        let try_dock =
 4846            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4847
 4848        let sidebar_target = self
 4849            .sidebar_focus_handle
 4850            .as_ref()
 4851            .map(|h| Target::Sidebar(h.clone()));
 4852
 4853        let sidebar_on_right = self
 4854            .multi_workspace
 4855            .as_ref()
 4856            .and_then(|mw| mw.upgrade())
 4857            .map_or(false, |mw| {
 4858                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4859            });
 4860
 4861        let away_from_sidebar = if sidebar_on_right {
 4862            SplitDirection::Left
 4863        } else {
 4864            SplitDirection::Right
 4865        };
 4866
 4867        let (near_dock, far_dock) = if sidebar_on_right {
 4868            (&self.right_dock, &self.left_dock)
 4869        } else {
 4870            (&self.left_dock, &self.right_dock)
 4871        };
 4872
 4873        let target = match (origin, direction) {
 4874            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4875                .or_else(|| get_last_active_pane().map(Target::Pane))
 4876                .or_else(|| try_dock(&self.bottom_dock))
 4877                .or_else(|| try_dock(far_dock)),
 4878
 4879            (Origin::Sidebar, _) => None,
 4880
 4881            // We're in the center, so we first try to go to a different pane,
 4882            // otherwise try to go to a dock.
 4883            (Origin::Center, direction) => {
 4884                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4885                    Some(Target::Pane(pane))
 4886                } else {
 4887                    match direction {
 4888                        SplitDirection::Up => None,
 4889                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4890                        SplitDirection::Left => {
 4891                            let dock_target = try_dock(&self.left_dock);
 4892                            if sidebar_on_right {
 4893                                dock_target
 4894                            } else {
 4895                                dock_target.or(sidebar_target)
 4896                            }
 4897                        }
 4898                        SplitDirection::Right => {
 4899                            let dock_target = try_dock(&self.right_dock);
 4900                            if sidebar_on_right {
 4901                                dock_target.or(sidebar_target)
 4902                            } else {
 4903                                dock_target
 4904                            }
 4905                        }
 4906                    }
 4907                }
 4908            }
 4909
 4910            (Origin::LeftDock, SplitDirection::Right) => {
 4911                if let Some(last_active_pane) = get_last_active_pane() {
 4912                    Some(Target::Pane(last_active_pane))
 4913                } else {
 4914                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4915                }
 4916            }
 4917
 4918            (Origin::LeftDock, SplitDirection::Left) => {
 4919                if sidebar_on_right {
 4920                    None
 4921                } else {
 4922                    sidebar_target
 4923                }
 4924            }
 4925
 4926            (Origin::LeftDock, SplitDirection::Down)
 4927            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4928
 4929            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4930            (Origin::BottomDock, SplitDirection::Left) => {
 4931                let dock_target = try_dock(&self.left_dock);
 4932                if sidebar_on_right {
 4933                    dock_target
 4934                } else {
 4935                    dock_target.or(sidebar_target)
 4936                }
 4937            }
 4938            (Origin::BottomDock, SplitDirection::Right) => {
 4939                let dock_target = try_dock(&self.right_dock);
 4940                if sidebar_on_right {
 4941                    dock_target.or(sidebar_target)
 4942                } else {
 4943                    dock_target
 4944                }
 4945            }
 4946
 4947            (Origin::RightDock, SplitDirection::Left) => {
 4948                if let Some(last_active_pane) = get_last_active_pane() {
 4949                    Some(Target::Pane(last_active_pane))
 4950                } else {
 4951                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4952                }
 4953            }
 4954
 4955            (Origin::RightDock, SplitDirection::Right) => {
 4956                if sidebar_on_right {
 4957                    sidebar_target
 4958                } else {
 4959                    None
 4960                }
 4961            }
 4962
 4963            _ => None,
 4964        };
 4965
 4966        match target {
 4967            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4968                let pane = pane.read(cx);
 4969                if let Some(item) = pane.active_item() {
 4970                    item.item_focus_handle(cx).focus(window, cx);
 4971                } else {
 4972                    log::error!(
 4973                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4974                    );
 4975                }
 4976            }
 4977            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4978                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4979                window.defer(cx, move |window, cx| {
 4980                    let dock = dock.read(cx);
 4981                    if let Some(panel) = dock.active_panel() {
 4982                        panel.panel_focus_handle(cx).focus(window, cx);
 4983                    } else {
 4984                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4985                    }
 4986                })
 4987            }
 4988            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4989                focus_handle.focus(window, cx);
 4990            }
 4991            None => {}
 4992        }
 4993    }
 4994
 4995    pub fn move_item_to_pane_in_direction(
 4996        &mut self,
 4997        action: &MoveItemToPaneInDirection,
 4998        window: &mut Window,
 4999        cx: &mut Context<Self>,
 5000    ) {
 5001        let destination = match self.find_pane_in_direction(action.direction, cx) {
 5002            Some(destination) => destination,
 5003            None => {
 5004                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 5005                    return;
 5006                }
 5007                let new_pane = self.add_pane(window, cx);
 5008                self.center
 5009                    .split(&self.active_pane, &new_pane, action.direction, cx);
 5010                new_pane
 5011            }
 5012        };
 5013
 5014        if action.clone {
 5015            if self
 5016                .active_pane
 5017                .read(cx)
 5018                .active_item()
 5019                .is_some_and(|item| item.can_split(cx))
 5020            {
 5021                clone_active_item(
 5022                    self.database_id(),
 5023                    &self.active_pane,
 5024                    &destination,
 5025                    action.focus,
 5026                    window,
 5027                    cx,
 5028                );
 5029                return;
 5030            }
 5031        }
 5032        move_active_item(
 5033            &self.active_pane,
 5034            &destination,
 5035            action.focus,
 5036            true,
 5037            window,
 5038            cx,
 5039        );
 5040    }
 5041
 5042    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5043        self.center.bounding_box_for_pane(pane)
 5044    }
 5045
 5046    pub fn find_pane_in_direction(
 5047        &mut self,
 5048        direction: SplitDirection,
 5049        cx: &App,
 5050    ) -> Option<Entity<Pane>> {
 5051        self.center
 5052            .find_pane_in_direction(&self.active_pane, direction, cx)
 5053            .cloned()
 5054    }
 5055
 5056    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5057        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5058            self.center.swap(&self.active_pane, &to, cx);
 5059            cx.notify();
 5060        }
 5061    }
 5062
 5063    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5064        if self
 5065            .center
 5066            .move_to_border(&self.active_pane, direction, cx)
 5067            .unwrap()
 5068        {
 5069            cx.notify();
 5070        }
 5071    }
 5072
 5073    pub fn resize_pane(
 5074        &mut self,
 5075        axis: gpui::Axis,
 5076        amount: Pixels,
 5077        window: &mut Window,
 5078        cx: &mut Context<Self>,
 5079    ) {
 5080        let docks = self.all_docks();
 5081        let active_dock = docks
 5082            .into_iter()
 5083            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5084
 5085        if let Some(dock_entity) = active_dock {
 5086            let dock = dock_entity.read(cx);
 5087            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5088                return;
 5089            };
 5090            match dock.position() {
 5091                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5092                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5093                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5094            }
 5095        } else {
 5096            self.center
 5097                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5098        }
 5099        cx.notify();
 5100    }
 5101
 5102    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5103        self.center.reset_pane_sizes(cx);
 5104        cx.notify();
 5105    }
 5106
 5107    fn handle_pane_focused(
 5108        &mut self,
 5109        pane: Entity<Pane>,
 5110        window: &mut Window,
 5111        cx: &mut Context<Self>,
 5112    ) {
 5113        // This is explicitly hoisted out of the following check for pane identity as
 5114        // terminal panel panes are not registered as a center panes.
 5115        self.status_bar.update(cx, |status_bar, cx| {
 5116            status_bar.set_active_pane(&pane, window, cx);
 5117        });
 5118        if self.active_pane != pane {
 5119            self.set_active_pane(&pane, window, cx);
 5120        }
 5121
 5122        if self.last_active_center_pane.is_none() {
 5123            self.last_active_center_pane = Some(pane.downgrade());
 5124        }
 5125
 5126        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5127        // This prevents the dock from closing when focus events fire during window activation.
 5128        // We also preserve any dock whose active panel itself has focus — this covers
 5129        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5130        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5131            let dock_read = dock.read(cx);
 5132            if let Some(panel) = dock_read.active_panel() {
 5133                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5134                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5135                {
 5136                    return Some(dock_read.position());
 5137                }
 5138            }
 5139            None
 5140        });
 5141
 5142        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5143        if pane.read(cx).is_zoomed() {
 5144            self.zoomed = Some(pane.downgrade().into());
 5145        } else {
 5146            self.zoomed = None;
 5147        }
 5148        self.zoomed_position = None;
 5149        cx.emit(Event::ZoomChanged);
 5150        self.update_active_view_for_followers(window, cx);
 5151        pane.update(cx, |pane, _| {
 5152            pane.track_alternate_file_items();
 5153        });
 5154
 5155        cx.notify();
 5156    }
 5157
 5158    fn set_active_pane(
 5159        &mut self,
 5160        pane: &Entity<Pane>,
 5161        window: &mut Window,
 5162        cx: &mut Context<Self>,
 5163    ) {
 5164        self.active_pane = pane.clone();
 5165        self.active_item_path_changed(true, window, cx);
 5166        self.last_active_center_pane = Some(pane.downgrade());
 5167    }
 5168
 5169    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5170        self.update_active_view_for_followers(window, cx);
 5171    }
 5172
 5173    fn handle_pane_event(
 5174        &mut self,
 5175        pane: &Entity<Pane>,
 5176        event: &pane::Event,
 5177        window: &mut Window,
 5178        cx: &mut Context<Self>,
 5179    ) {
 5180        let mut serialize_workspace = true;
 5181        match event {
 5182            pane::Event::AddItem { item } => {
 5183                item.added_to_pane(self, pane.clone(), window, cx);
 5184                cx.emit(Event::ItemAdded {
 5185                    item: item.boxed_clone(),
 5186                });
 5187            }
 5188            pane::Event::Split { direction, mode } => {
 5189                match mode {
 5190                    SplitMode::ClonePane => {
 5191                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5192                            .detach();
 5193                    }
 5194                    SplitMode::EmptyPane => {
 5195                        self.split_pane(pane.clone(), *direction, window, cx);
 5196                    }
 5197                    SplitMode::MovePane => {
 5198                        self.split_and_move(pane.clone(), *direction, window, cx);
 5199                    }
 5200                };
 5201            }
 5202            pane::Event::JoinIntoNext => {
 5203                self.join_pane_into_next(pane.clone(), window, cx);
 5204            }
 5205            pane::Event::JoinAll => {
 5206                self.join_all_panes(window, cx);
 5207            }
 5208            pane::Event::Remove { focus_on_pane } => {
 5209                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5210            }
 5211            pane::Event::ActivateItem {
 5212                local,
 5213                focus_changed,
 5214            } => {
 5215                window.invalidate_character_coordinates();
 5216
 5217                pane.update(cx, |pane, _| {
 5218                    pane.track_alternate_file_items();
 5219                });
 5220                if *local {
 5221                    self.unfollow_in_pane(pane, window, cx);
 5222                }
 5223                serialize_workspace = *focus_changed || pane != self.active_pane();
 5224                if pane == self.active_pane() {
 5225                    self.active_item_path_changed(*focus_changed, window, cx);
 5226                    self.update_active_view_for_followers(window, cx);
 5227                } else if *local {
 5228                    self.set_active_pane(pane, window, cx);
 5229                }
 5230            }
 5231            pane::Event::UserSavedItem { item, save_intent } => {
 5232                cx.emit(Event::UserSavedItem {
 5233                    pane: pane.downgrade(),
 5234                    item: item.boxed_clone(),
 5235                    save_intent: *save_intent,
 5236                });
 5237                serialize_workspace = false;
 5238            }
 5239            pane::Event::ChangeItemTitle => {
 5240                if *pane == self.active_pane {
 5241                    self.active_item_path_changed(false, window, cx);
 5242                }
 5243                serialize_workspace = false;
 5244            }
 5245            pane::Event::RemovedItem { item } => {
 5246                cx.emit(Event::ActiveItemChanged);
 5247                self.update_window_edited(window, cx);
 5248                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5249                    && entry.get().entity_id() == pane.entity_id()
 5250                {
 5251                    entry.remove();
 5252                }
 5253                cx.emit(Event::ItemRemoved {
 5254                    item_id: item.item_id(),
 5255                });
 5256            }
 5257            pane::Event::Focus => {
 5258                window.invalidate_character_coordinates();
 5259                self.handle_pane_focused(pane.clone(), window, cx);
 5260            }
 5261            pane::Event::ZoomIn => {
 5262                if *pane == self.active_pane {
 5263                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5264                    if pane.read(cx).has_focus(window, cx) {
 5265                        self.zoomed = Some(pane.downgrade().into());
 5266                        self.zoomed_position = None;
 5267                        cx.emit(Event::ZoomChanged);
 5268                    }
 5269                    cx.notify();
 5270                }
 5271            }
 5272            pane::Event::ZoomOut => {
 5273                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5274                if self.zoomed_position.is_none() {
 5275                    self.zoomed = None;
 5276                    cx.emit(Event::ZoomChanged);
 5277                }
 5278                cx.notify();
 5279            }
 5280            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5281        }
 5282
 5283        if serialize_workspace {
 5284            self.serialize_workspace(window, cx);
 5285        }
 5286    }
 5287
 5288    pub fn unfollow_in_pane(
 5289        &mut self,
 5290        pane: &Entity<Pane>,
 5291        window: &mut Window,
 5292        cx: &mut Context<Workspace>,
 5293    ) -> Option<CollaboratorId> {
 5294        let leader_id = self.leader_for_pane(pane)?;
 5295        self.unfollow(leader_id, window, cx);
 5296        Some(leader_id)
 5297    }
 5298
 5299    pub fn split_pane(
 5300        &mut self,
 5301        pane_to_split: Entity<Pane>,
 5302        split_direction: SplitDirection,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) -> Entity<Pane> {
 5306        let new_pane = self.add_pane(window, cx);
 5307        self.center
 5308            .split(&pane_to_split, &new_pane, split_direction, cx);
 5309        cx.notify();
 5310        new_pane
 5311    }
 5312
 5313    pub fn split_and_move(
 5314        &mut self,
 5315        pane: Entity<Pane>,
 5316        direction: SplitDirection,
 5317        window: &mut Window,
 5318        cx: &mut Context<Self>,
 5319    ) {
 5320        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5321            return;
 5322        };
 5323        let new_pane = self.add_pane(window, cx);
 5324        new_pane.update(cx, |pane, cx| {
 5325            pane.add_item(item, true, true, None, window, cx)
 5326        });
 5327        self.center.split(&pane, &new_pane, direction, cx);
 5328        cx.notify();
 5329    }
 5330
 5331    pub fn split_and_clone(
 5332        &mut self,
 5333        pane: Entity<Pane>,
 5334        direction: SplitDirection,
 5335        window: &mut Window,
 5336        cx: &mut Context<Self>,
 5337    ) -> Task<Option<Entity<Pane>>> {
 5338        let Some(item) = pane.read(cx).active_item() else {
 5339            return Task::ready(None);
 5340        };
 5341        if !item.can_split(cx) {
 5342            return Task::ready(None);
 5343        }
 5344        let task = item.clone_on_split(self.database_id(), window, cx);
 5345        cx.spawn_in(window, async move |this, cx| {
 5346            if let Some(clone) = task.await {
 5347                this.update_in(cx, |this, window, cx| {
 5348                    let new_pane = this.add_pane(window, cx);
 5349                    let nav_history = pane.read(cx).fork_nav_history();
 5350                    new_pane.update(cx, |pane, cx| {
 5351                        pane.set_nav_history(nav_history, cx);
 5352                        pane.add_item(clone, true, true, None, window, cx)
 5353                    });
 5354                    this.center.split(&pane, &new_pane, direction, cx);
 5355                    cx.notify();
 5356                    new_pane
 5357                })
 5358                .ok()
 5359            } else {
 5360                None
 5361            }
 5362        })
 5363    }
 5364
 5365    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5366        let active_item = self.active_pane.read(cx).active_item();
 5367        for pane in &self.panes {
 5368            join_pane_into_active(&self.active_pane, pane, window, cx);
 5369        }
 5370        if let Some(active_item) = active_item {
 5371            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5372        }
 5373        cx.notify();
 5374    }
 5375
 5376    pub fn join_pane_into_next(
 5377        &mut self,
 5378        pane: Entity<Pane>,
 5379        window: &mut Window,
 5380        cx: &mut Context<Self>,
 5381    ) {
 5382        let next_pane = self
 5383            .find_pane_in_direction(SplitDirection::Right, cx)
 5384            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5385            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5386            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5387        let Some(next_pane) = next_pane else {
 5388            return;
 5389        };
 5390        move_all_items(&pane, &next_pane, window, cx);
 5391        cx.notify();
 5392    }
 5393
 5394    fn remove_pane(
 5395        &mut self,
 5396        pane: Entity<Pane>,
 5397        focus_on: Option<Entity<Pane>>,
 5398        window: &mut Window,
 5399        cx: &mut Context<Self>,
 5400    ) {
 5401        if self.center.remove(&pane, cx).unwrap() {
 5402            self.force_remove_pane(&pane, &focus_on, window, cx);
 5403            self.unfollow_in_pane(&pane, window, cx);
 5404            self.last_leaders_by_pane.remove(&pane.downgrade());
 5405            for removed_item in pane.read(cx).items() {
 5406                self.panes_by_item.remove(&removed_item.item_id());
 5407            }
 5408
 5409            cx.notify();
 5410        } else {
 5411            self.active_item_path_changed(true, window, cx);
 5412        }
 5413        cx.emit(Event::PaneRemoved);
 5414    }
 5415
 5416    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5417        &mut self.panes
 5418    }
 5419
 5420    pub fn panes(&self) -> &[Entity<Pane>] {
 5421        &self.panes
 5422    }
 5423
 5424    pub fn active_pane(&self) -> &Entity<Pane> {
 5425        &self.active_pane
 5426    }
 5427
 5428    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5429        for dock in self.all_docks() {
 5430            if dock.focus_handle(cx).contains_focused(window, cx)
 5431                && let Some(pane) = dock
 5432                    .read(cx)
 5433                    .active_panel()
 5434                    .and_then(|panel| panel.pane(cx))
 5435            {
 5436                return pane;
 5437            }
 5438        }
 5439        self.active_pane().clone()
 5440    }
 5441
 5442    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5443        self.find_pane_in_direction(SplitDirection::Right, cx)
 5444            .unwrap_or_else(|| {
 5445                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5446            })
 5447    }
 5448
 5449    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5450        self.pane_for_item_id(handle.item_id())
 5451    }
 5452
 5453    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5454        let weak_pane = self.panes_by_item.get(&item_id)?;
 5455        weak_pane.upgrade()
 5456    }
 5457
 5458    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5459        self.panes
 5460            .iter()
 5461            .find(|pane| pane.entity_id() == entity_id)
 5462            .cloned()
 5463    }
 5464
 5465    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5466        self.follower_states.retain(|leader_id, state| {
 5467            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5468                for item in state.items_by_leader_view_id.values() {
 5469                    item.view.set_leader_id(None, window, cx);
 5470                }
 5471                false
 5472            } else {
 5473                true
 5474            }
 5475        });
 5476        cx.notify();
 5477    }
 5478
 5479    pub fn start_following(
 5480        &mut self,
 5481        leader_id: impl Into<CollaboratorId>,
 5482        window: &mut Window,
 5483        cx: &mut Context<Self>,
 5484    ) -> Option<Task<Result<()>>> {
 5485        let leader_id = leader_id.into();
 5486        let pane = self.active_pane().clone();
 5487
 5488        self.last_leaders_by_pane
 5489            .insert(pane.downgrade(), leader_id);
 5490        self.unfollow(leader_id, window, cx);
 5491        self.unfollow_in_pane(&pane, window, cx);
 5492        self.follower_states.insert(
 5493            leader_id,
 5494            FollowerState {
 5495                center_pane: pane.clone(),
 5496                dock_pane: None,
 5497                active_view_id: None,
 5498                items_by_leader_view_id: Default::default(),
 5499            },
 5500        );
 5501        cx.notify();
 5502
 5503        match leader_id {
 5504            CollaboratorId::PeerId(leader_peer_id) => {
 5505                let room_id = self.active_call()?.room_id(cx)?;
 5506                let project_id = self.project.read(cx).remote_id();
 5507                let request = self.app_state.client.request(proto::Follow {
 5508                    room_id,
 5509                    project_id,
 5510                    leader_id: Some(leader_peer_id),
 5511                });
 5512
 5513                Some(cx.spawn_in(window, async move |this, cx| {
 5514                    let response = request.await?;
 5515                    this.update(cx, |this, _| {
 5516                        let state = this
 5517                            .follower_states
 5518                            .get_mut(&leader_id)
 5519                            .context("following interrupted")?;
 5520                        state.active_view_id = response
 5521                            .active_view
 5522                            .as_ref()
 5523                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5524                        anyhow::Ok(())
 5525                    })??;
 5526                    if let Some(view) = response.active_view {
 5527                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5528                    }
 5529                    this.update_in(cx, |this, window, cx| {
 5530                        this.leader_updated(leader_id, window, cx)
 5531                    })?;
 5532                    Ok(())
 5533                }))
 5534            }
 5535            CollaboratorId::Agent => {
 5536                self.leader_updated(leader_id, window, cx)?;
 5537                Some(Task::ready(Ok(())))
 5538            }
 5539        }
 5540    }
 5541
 5542    pub fn follow_next_collaborator(
 5543        &mut self,
 5544        _: &FollowNextCollaborator,
 5545        window: &mut Window,
 5546        cx: &mut Context<Self>,
 5547    ) {
 5548        let collaborators = self.project.read(cx).collaborators();
 5549        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5550            let mut collaborators = collaborators.keys().copied();
 5551            for peer_id in collaborators.by_ref() {
 5552                if CollaboratorId::PeerId(peer_id) == leader_id {
 5553                    break;
 5554                }
 5555            }
 5556            collaborators.next().map(CollaboratorId::PeerId)
 5557        } else if let Some(last_leader_id) =
 5558            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5559        {
 5560            match last_leader_id {
 5561                CollaboratorId::PeerId(peer_id) => {
 5562                    if collaborators.contains_key(peer_id) {
 5563                        Some(*last_leader_id)
 5564                    } else {
 5565                        None
 5566                    }
 5567                }
 5568                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5569            }
 5570        } else {
 5571            None
 5572        };
 5573
 5574        let pane = self.active_pane.clone();
 5575        let Some(leader_id) = next_leader_id.or_else(|| {
 5576            Some(CollaboratorId::PeerId(
 5577                collaborators.keys().copied().next()?,
 5578            ))
 5579        }) else {
 5580            return;
 5581        };
 5582        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5583            return;
 5584        }
 5585        if let Some(task) = self.start_following(leader_id, window, cx) {
 5586            task.detach_and_log_err(cx)
 5587        }
 5588    }
 5589
 5590    pub fn follow(
 5591        &mut self,
 5592        leader_id: impl Into<CollaboratorId>,
 5593        window: &mut Window,
 5594        cx: &mut Context<Self>,
 5595    ) {
 5596        let leader_id = leader_id.into();
 5597
 5598        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5599            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5600                return;
 5601            };
 5602            let Some(remote_participant) =
 5603                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5604            else {
 5605                return;
 5606            };
 5607
 5608            let project = self.project.read(cx);
 5609
 5610            let other_project_id = match remote_participant.location {
 5611                ParticipantLocation::External => None,
 5612                ParticipantLocation::UnsharedProject => None,
 5613                ParticipantLocation::SharedProject { project_id } => {
 5614                    if Some(project_id) == project.remote_id() {
 5615                        None
 5616                    } else {
 5617                        Some(project_id)
 5618                    }
 5619                }
 5620            };
 5621
 5622            // if they are active in another project, follow there.
 5623            if let Some(project_id) = other_project_id {
 5624                let app_state = self.app_state.clone();
 5625                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5626                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5627                        Some(format!("{error:#}"))
 5628                    });
 5629            }
 5630        }
 5631
 5632        // if you're already following, find the right pane and focus it.
 5633        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5634            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5635
 5636            return;
 5637        }
 5638
 5639        // Otherwise, follow.
 5640        if let Some(task) = self.start_following(leader_id, window, cx) {
 5641            task.detach_and_log_err(cx)
 5642        }
 5643    }
 5644
 5645    pub fn unfollow(
 5646        &mut self,
 5647        leader_id: impl Into<CollaboratorId>,
 5648        window: &mut Window,
 5649        cx: &mut Context<Self>,
 5650    ) -> Option<()> {
 5651        cx.notify();
 5652
 5653        let leader_id = leader_id.into();
 5654        let state = self.follower_states.remove(&leader_id)?;
 5655        for (_, item) in state.items_by_leader_view_id {
 5656            item.view.set_leader_id(None, window, cx);
 5657        }
 5658
 5659        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5660            let project_id = self.project.read(cx).remote_id();
 5661            let room_id = self.active_call()?.room_id(cx)?;
 5662            self.app_state
 5663                .client
 5664                .send(proto::Unfollow {
 5665                    room_id,
 5666                    project_id,
 5667                    leader_id: Some(leader_peer_id),
 5668                })
 5669                .log_err();
 5670        }
 5671
 5672        Some(())
 5673    }
 5674
 5675    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5676        self.follower_states.contains_key(&id.into())
 5677    }
 5678
 5679    fn active_item_path_changed(
 5680        &mut self,
 5681        focus_changed: bool,
 5682        window: &mut Window,
 5683        cx: &mut Context<Self>,
 5684    ) {
 5685        cx.emit(Event::ActiveItemChanged);
 5686        let active_entry = self.active_project_path(cx);
 5687        self.project.update(cx, |project, cx| {
 5688            project.set_active_path(active_entry.clone(), cx)
 5689        });
 5690
 5691        if focus_changed && let Some(project_path) = &active_entry {
 5692            let git_store_entity = self.project.read(cx).git_store().clone();
 5693            git_store_entity.update(cx, |git_store, cx| {
 5694                git_store.set_active_repo_for_path(project_path, cx);
 5695            });
 5696        }
 5697
 5698        self.update_window_title(window, cx);
 5699    }
 5700
 5701    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5702        let project = self.project().read(cx);
 5703        let mut title = String::new();
 5704
 5705        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5706            let name = {
 5707                let settings_location = SettingsLocation {
 5708                    worktree_id: worktree.read(cx).id(),
 5709                    path: RelPath::empty(),
 5710                };
 5711
 5712                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5713                match &settings.project_name {
 5714                    Some(name) => name.as_str(),
 5715                    None => worktree.read(cx).root_name_str(),
 5716                }
 5717            };
 5718            if i > 0 {
 5719                title.push_str(", ");
 5720            }
 5721            title.push_str(name);
 5722        }
 5723
 5724        if title.is_empty() {
 5725            title = "empty project".to_string();
 5726        }
 5727
 5728        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5729            let filename = path.path.file_name().or_else(|| {
 5730                Some(
 5731                    project
 5732                        .worktree_for_id(path.worktree_id, cx)?
 5733                        .read(cx)
 5734                        .root_name_str(),
 5735                )
 5736            });
 5737
 5738            if let Some(filename) = filename {
 5739                title.push_str("");
 5740                title.push_str(filename.as_ref());
 5741            }
 5742        }
 5743
 5744        if project.is_via_collab() {
 5745            title.push_str("");
 5746        } else if project.is_shared() {
 5747            title.push_str("");
 5748        }
 5749
 5750        if let Some(last_title) = self.last_window_title.as_ref()
 5751            && &title == last_title
 5752        {
 5753            return;
 5754        }
 5755        window.set_window_title(&title);
 5756        SystemWindowTabController::update_tab_title(
 5757            cx,
 5758            window.window_handle().window_id(),
 5759            SharedString::from(&title),
 5760        );
 5761        self.last_window_title = Some(title);
 5762    }
 5763
 5764    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5765        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5766        if is_edited != self.window_edited {
 5767            self.window_edited = is_edited;
 5768            window.set_window_edited(self.window_edited)
 5769        }
 5770    }
 5771
 5772    fn update_item_dirty_state(
 5773        &mut self,
 5774        item: &dyn ItemHandle,
 5775        window: &mut Window,
 5776        cx: &mut App,
 5777    ) {
 5778        let is_dirty = item.is_dirty(cx);
 5779        let item_id = item.item_id();
 5780        let was_dirty = self.dirty_items.contains_key(&item_id);
 5781        if is_dirty == was_dirty {
 5782            return;
 5783        }
 5784        if was_dirty {
 5785            self.dirty_items.remove(&item_id);
 5786            self.update_window_edited(window, cx);
 5787            return;
 5788        }
 5789
 5790        let workspace = self.weak_handle();
 5791        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5792            return;
 5793        };
 5794        let on_release_callback = Box::new(move |cx: &mut App| {
 5795            window_handle
 5796                .update(cx, |_, window, cx| {
 5797                    workspace
 5798                        .update(cx, |workspace, cx| {
 5799                            workspace.dirty_items.remove(&item_id);
 5800                            workspace.update_window_edited(window, cx)
 5801                        })
 5802                        .ok();
 5803                })
 5804                .ok();
 5805        });
 5806
 5807        let s = item.on_release(cx, on_release_callback);
 5808        self.dirty_items.insert(item_id, s);
 5809        self.update_window_edited(window, cx);
 5810    }
 5811
 5812    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5813        if self.notifications.is_empty() {
 5814            None
 5815        } else {
 5816            Some(
 5817                div()
 5818                    .absolute()
 5819                    .right_3()
 5820                    .bottom_3()
 5821                    .w_112()
 5822                    .h_full()
 5823                    .flex()
 5824                    .flex_col()
 5825                    .justify_end()
 5826                    .gap_2()
 5827                    .children(
 5828                        self.notifications
 5829                            .iter()
 5830                            .map(|(_, notification)| notification.clone().into_any()),
 5831                    ),
 5832            )
 5833        }
 5834    }
 5835
 5836    // RPC handlers
 5837
 5838    fn active_view_for_follower(
 5839        &self,
 5840        follower_project_id: Option<u64>,
 5841        window: &mut Window,
 5842        cx: &mut Context<Self>,
 5843    ) -> Option<proto::View> {
 5844        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5845        let item = item?;
 5846        let leader_id = self
 5847            .pane_for(&*item)
 5848            .and_then(|pane| self.leader_for_pane(&pane));
 5849        let leader_peer_id = match leader_id {
 5850            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5851            Some(CollaboratorId::Agent) | None => None,
 5852        };
 5853
 5854        let item_handle = item.to_followable_item_handle(cx)?;
 5855        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5856        let variant = item_handle.to_state_proto(window, cx)?;
 5857
 5858        if item_handle.is_project_item(window, cx)
 5859            && (follower_project_id.is_none()
 5860                || follower_project_id != self.project.read(cx).remote_id())
 5861        {
 5862            return None;
 5863        }
 5864
 5865        Some(proto::View {
 5866            id: id.to_proto(),
 5867            leader_id: leader_peer_id,
 5868            variant: Some(variant),
 5869            panel_id: panel_id.map(|id| id as i32),
 5870        })
 5871    }
 5872
 5873    fn handle_follow(
 5874        &mut self,
 5875        follower_project_id: Option<u64>,
 5876        window: &mut Window,
 5877        cx: &mut Context<Self>,
 5878    ) -> proto::FollowResponse {
 5879        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5880
 5881        cx.notify();
 5882        proto::FollowResponse {
 5883            views: active_view.iter().cloned().collect(),
 5884            active_view,
 5885        }
 5886    }
 5887
 5888    fn handle_update_followers(
 5889        &mut self,
 5890        leader_id: PeerId,
 5891        message: proto::UpdateFollowers,
 5892        _window: &mut Window,
 5893        _cx: &mut Context<Self>,
 5894    ) {
 5895        self.leader_updates_tx
 5896            .unbounded_send((leader_id, message))
 5897            .ok();
 5898    }
 5899
 5900    async fn process_leader_update(
 5901        this: &WeakEntity<Self>,
 5902        leader_id: PeerId,
 5903        update: proto::UpdateFollowers,
 5904        cx: &mut AsyncWindowContext,
 5905    ) -> Result<()> {
 5906        match update.variant.context("invalid update")? {
 5907            proto::update_followers::Variant::CreateView(view) => {
 5908                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5909                let should_add_view = this.update(cx, |this, _| {
 5910                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5911                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5912                    } else {
 5913                        anyhow::Ok(false)
 5914                    }
 5915                })??;
 5916
 5917                if should_add_view {
 5918                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5919                }
 5920            }
 5921            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5922                let should_add_view = this.update(cx, |this, _| {
 5923                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5924                        state.active_view_id = update_active_view
 5925                            .view
 5926                            .as_ref()
 5927                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5928
 5929                        if state.active_view_id.is_some_and(|view_id| {
 5930                            !state.items_by_leader_view_id.contains_key(&view_id)
 5931                        }) {
 5932                            anyhow::Ok(true)
 5933                        } else {
 5934                            anyhow::Ok(false)
 5935                        }
 5936                    } else {
 5937                        anyhow::Ok(false)
 5938                    }
 5939                })??;
 5940
 5941                if should_add_view && let Some(view) = update_active_view.view {
 5942                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5943                }
 5944            }
 5945            proto::update_followers::Variant::UpdateView(update_view) => {
 5946                let variant = update_view.variant.context("missing update view variant")?;
 5947                let id = update_view.id.context("missing update view id")?;
 5948                let mut tasks = Vec::new();
 5949                this.update_in(cx, |this, window, cx| {
 5950                    let project = this.project.clone();
 5951                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5952                        let view_id = ViewId::from_proto(id.clone())?;
 5953                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5954                            tasks.push(item.view.apply_update_proto(
 5955                                &project,
 5956                                variant.clone(),
 5957                                window,
 5958                                cx,
 5959                            ));
 5960                        }
 5961                    }
 5962                    anyhow::Ok(())
 5963                })??;
 5964                try_join_all(tasks).await.log_err();
 5965            }
 5966        }
 5967        this.update_in(cx, |this, window, cx| {
 5968            this.leader_updated(leader_id, window, cx)
 5969        })?;
 5970        Ok(())
 5971    }
 5972
 5973    async fn add_view_from_leader(
 5974        this: WeakEntity<Self>,
 5975        leader_id: PeerId,
 5976        view: &proto::View,
 5977        cx: &mut AsyncWindowContext,
 5978    ) -> Result<()> {
 5979        let this = this.upgrade().context("workspace dropped")?;
 5980
 5981        let Some(id) = view.id.clone() else {
 5982            anyhow::bail!("no id for view");
 5983        };
 5984        let id = ViewId::from_proto(id)?;
 5985        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5986
 5987        let pane = this.update(cx, |this, _cx| {
 5988            let state = this
 5989                .follower_states
 5990                .get(&leader_id.into())
 5991                .context("stopped following")?;
 5992            anyhow::Ok(state.pane().clone())
 5993        })?;
 5994        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5995            let client = this.read(cx).client().clone();
 5996            pane.items().find_map(|item| {
 5997                let item = item.to_followable_item_handle(cx)?;
 5998                if item.remote_id(&client, window, cx) == Some(id) {
 5999                    Some(item)
 6000                } else {
 6001                    None
 6002                }
 6003            })
 6004        })?;
 6005        let item = if let Some(existing_item) = existing_item {
 6006            existing_item
 6007        } else {
 6008            let variant = view.variant.clone();
 6009            anyhow::ensure!(variant.is_some(), "missing view variant");
 6010
 6011            let task = cx.update(|window, cx| {
 6012                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6013            })?;
 6014
 6015            let Some(task) = task else {
 6016                anyhow::bail!(
 6017                    "failed to construct view from leader (maybe from a different version of zed?)"
 6018                );
 6019            };
 6020
 6021            let mut new_item = task.await?;
 6022            pane.update_in(cx, |pane, window, cx| {
 6023                let mut item_to_remove = None;
 6024                for (ix, item) in pane.items().enumerate() {
 6025                    if let Some(item) = item.to_followable_item_handle(cx) {
 6026                        match new_item.dedup(item.as_ref(), window, cx) {
 6027                            Some(item::Dedup::KeepExisting) => {
 6028                                new_item =
 6029                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6030                                break;
 6031                            }
 6032                            Some(item::Dedup::ReplaceExisting) => {
 6033                                item_to_remove = Some((ix, item.item_id()));
 6034                                break;
 6035                            }
 6036                            None => {}
 6037                        }
 6038                    }
 6039                }
 6040
 6041                if let Some((ix, id)) = item_to_remove {
 6042                    pane.remove_item(id, false, false, window, cx);
 6043                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6044                }
 6045            })?;
 6046
 6047            new_item
 6048        };
 6049
 6050        this.update_in(cx, |this, window, cx| {
 6051            let state = this.follower_states.get_mut(&leader_id.into())?;
 6052            item.set_leader_id(Some(leader_id.into()), window, cx);
 6053            state.items_by_leader_view_id.insert(
 6054                id,
 6055                FollowerView {
 6056                    view: item,
 6057                    location: panel_id,
 6058                },
 6059            );
 6060
 6061            Some(())
 6062        })
 6063        .context("no follower state")?;
 6064
 6065        Ok(())
 6066    }
 6067
 6068    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6069        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6070            return;
 6071        };
 6072
 6073        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6074            let buffer_entity_id = agent_location.buffer.entity_id();
 6075            let view_id = ViewId {
 6076                creator: CollaboratorId::Agent,
 6077                id: buffer_entity_id.as_u64(),
 6078            };
 6079            follower_state.active_view_id = Some(view_id);
 6080
 6081            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6082                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6083                hash_map::Entry::Vacant(entry) => {
 6084                    let existing_view =
 6085                        follower_state
 6086                            .center_pane
 6087                            .read(cx)
 6088                            .items()
 6089                            .find_map(|item| {
 6090                                let item = item.to_followable_item_handle(cx)?;
 6091                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6092                                    && item.project_item_model_ids(cx).as_slice()
 6093                                        == [buffer_entity_id]
 6094                                {
 6095                                    Some(item)
 6096                                } else {
 6097                                    None
 6098                                }
 6099                            });
 6100                    let view = existing_view.or_else(|| {
 6101                        agent_location.buffer.upgrade().and_then(|buffer| {
 6102                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6103                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6104                            })?
 6105                            .to_followable_item_handle(cx)
 6106                        })
 6107                    });
 6108
 6109                    view.map(|view| {
 6110                        entry.insert(FollowerView {
 6111                            view,
 6112                            location: None,
 6113                        })
 6114                    })
 6115                }
 6116            };
 6117
 6118            if let Some(item) = item {
 6119                item.view
 6120                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6121                item.view
 6122                    .update_agent_location(agent_location.position, window, cx);
 6123            }
 6124        } else {
 6125            follower_state.active_view_id = None;
 6126        }
 6127
 6128        self.leader_updated(CollaboratorId::Agent, window, cx);
 6129    }
 6130
 6131    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6132        let mut is_project_item = true;
 6133        let mut update = proto::UpdateActiveView::default();
 6134        if window.is_window_active() {
 6135            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6136
 6137            if let Some(item) = active_item
 6138                && item.item_focus_handle(cx).contains_focused(window, cx)
 6139            {
 6140                let leader_id = self
 6141                    .pane_for(&*item)
 6142                    .and_then(|pane| self.leader_for_pane(&pane));
 6143                let leader_peer_id = match leader_id {
 6144                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6145                    Some(CollaboratorId::Agent) | None => None,
 6146                };
 6147
 6148                if let Some(item) = item.to_followable_item_handle(cx) {
 6149                    let id = item
 6150                        .remote_id(&self.app_state.client, window, cx)
 6151                        .map(|id| id.to_proto());
 6152
 6153                    if let Some(id) = id
 6154                        && let Some(variant) = item.to_state_proto(window, cx)
 6155                    {
 6156                        let view = Some(proto::View {
 6157                            id,
 6158                            leader_id: leader_peer_id,
 6159                            variant: Some(variant),
 6160                            panel_id: panel_id.map(|id| id as i32),
 6161                        });
 6162
 6163                        is_project_item = item.is_project_item(window, cx);
 6164                        update = proto::UpdateActiveView { view };
 6165                    };
 6166                }
 6167            }
 6168        }
 6169
 6170        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6171        if active_view_id != self.last_active_view_id.as_ref() {
 6172            self.last_active_view_id = active_view_id.cloned();
 6173            self.update_followers(
 6174                is_project_item,
 6175                proto::update_followers::Variant::UpdateActiveView(update),
 6176                window,
 6177                cx,
 6178            );
 6179        }
 6180    }
 6181
 6182    fn active_item_for_followers(
 6183        &self,
 6184        window: &mut Window,
 6185        cx: &mut App,
 6186    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6187        let mut active_item = None;
 6188        let mut panel_id = None;
 6189        for dock in self.all_docks() {
 6190            if dock.focus_handle(cx).contains_focused(window, cx)
 6191                && let Some(panel) = dock.read(cx).active_panel()
 6192                && let Some(pane) = panel.pane(cx)
 6193                && let Some(item) = pane.read(cx).active_item()
 6194            {
 6195                active_item = Some(item);
 6196                panel_id = panel.remote_id();
 6197                break;
 6198            }
 6199        }
 6200
 6201        if active_item.is_none() {
 6202            active_item = self.active_pane().read(cx).active_item();
 6203        }
 6204        (active_item, panel_id)
 6205    }
 6206
 6207    fn update_followers(
 6208        &self,
 6209        project_only: bool,
 6210        update: proto::update_followers::Variant,
 6211        _: &mut Window,
 6212        cx: &mut App,
 6213    ) -> Option<()> {
 6214        // If this update only applies to for followers in the current project,
 6215        // then skip it unless this project is shared. If it applies to all
 6216        // followers, regardless of project, then set `project_id` to none,
 6217        // indicating that it goes to all followers.
 6218        let project_id = if project_only {
 6219            Some(self.project.read(cx).remote_id()?)
 6220        } else {
 6221            None
 6222        };
 6223        self.app_state().workspace_store.update(cx, |store, cx| {
 6224            store.update_followers(project_id, update, cx)
 6225        })
 6226    }
 6227
 6228    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6229        self.follower_states.iter().find_map(|(leader_id, state)| {
 6230            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6231                Some(*leader_id)
 6232            } else {
 6233                None
 6234            }
 6235        })
 6236    }
 6237
 6238    fn leader_updated(
 6239        &mut self,
 6240        leader_id: impl Into<CollaboratorId>,
 6241        window: &mut Window,
 6242        cx: &mut Context<Self>,
 6243    ) -> Option<Box<dyn ItemHandle>> {
 6244        cx.notify();
 6245
 6246        let leader_id = leader_id.into();
 6247        let (panel_id, item) = match leader_id {
 6248            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6249            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6250        };
 6251
 6252        let state = self.follower_states.get(&leader_id)?;
 6253        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6254        let pane;
 6255        if let Some(panel_id) = panel_id {
 6256            pane = self
 6257                .activate_panel_for_proto_id(panel_id, window, cx)?
 6258                .pane(cx)?;
 6259            let state = self.follower_states.get_mut(&leader_id)?;
 6260            state.dock_pane = Some(pane.clone());
 6261        } else {
 6262            pane = state.center_pane.clone();
 6263            let state = self.follower_states.get_mut(&leader_id)?;
 6264            if let Some(dock_pane) = state.dock_pane.take() {
 6265                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6266            }
 6267        }
 6268
 6269        pane.update(cx, |pane, cx| {
 6270            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6271            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6272                pane.activate_item(index, false, false, window, cx);
 6273            } else {
 6274                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6275            }
 6276
 6277            if focus_active_item {
 6278                pane.focus_active_item(window, cx)
 6279            }
 6280        });
 6281
 6282        Some(item)
 6283    }
 6284
 6285    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6286        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6287        let active_view_id = state.active_view_id?;
 6288        Some(
 6289            state
 6290                .items_by_leader_view_id
 6291                .get(&active_view_id)?
 6292                .view
 6293                .boxed_clone(),
 6294        )
 6295    }
 6296
 6297    fn active_item_for_peer(
 6298        &self,
 6299        peer_id: PeerId,
 6300        window: &mut Window,
 6301        cx: &mut Context<Self>,
 6302    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6303        let call = self.active_call()?;
 6304        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6305        let leader_in_this_app;
 6306        let leader_in_this_project;
 6307        match participant.location {
 6308            ParticipantLocation::SharedProject { project_id } => {
 6309                leader_in_this_app = true;
 6310                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6311            }
 6312            ParticipantLocation::UnsharedProject => {
 6313                leader_in_this_app = true;
 6314                leader_in_this_project = false;
 6315            }
 6316            ParticipantLocation::External => {
 6317                leader_in_this_app = false;
 6318                leader_in_this_project = false;
 6319            }
 6320        };
 6321        let state = self.follower_states.get(&peer_id.into())?;
 6322        let mut item_to_activate = None;
 6323        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6324            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6325                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6326            {
 6327                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6328            }
 6329        } else if let Some(shared_screen) =
 6330            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6331        {
 6332            item_to_activate = Some((None, Box::new(shared_screen)));
 6333        }
 6334        item_to_activate
 6335    }
 6336
 6337    fn shared_screen_for_peer(
 6338        &self,
 6339        peer_id: PeerId,
 6340        pane: &Entity<Pane>,
 6341        window: &mut Window,
 6342        cx: &mut App,
 6343    ) -> Option<Entity<SharedScreen>> {
 6344        self.active_call()?
 6345            .create_shared_screen(peer_id, pane, window, cx)
 6346    }
 6347
 6348    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6349        if window.is_window_active() {
 6350            self.update_active_view_for_followers(window, cx);
 6351
 6352            if let Some(database_id) = self.database_id {
 6353                let db = WorkspaceDb::global(cx);
 6354                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6355                    .detach();
 6356            }
 6357        } else {
 6358            for pane in &self.panes {
 6359                pane.update(cx, |pane, cx| {
 6360                    if let Some(item) = pane.active_item() {
 6361                        item.workspace_deactivated(window, cx);
 6362                    }
 6363                    for item in pane.items() {
 6364                        if matches!(
 6365                            item.workspace_settings(cx).autosave,
 6366                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6367                        ) {
 6368                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6369                                .detach_and_log_err(cx);
 6370                        }
 6371                    }
 6372                });
 6373            }
 6374        }
 6375    }
 6376
 6377    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6378        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6379    }
 6380
 6381    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6382        self.active_call.as_ref().map(|(call, _)| call.clone())
 6383    }
 6384
 6385    fn on_active_call_event(
 6386        &mut self,
 6387        event: &ActiveCallEvent,
 6388        window: &mut Window,
 6389        cx: &mut Context<Self>,
 6390    ) {
 6391        match event {
 6392            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6393            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6394                self.leader_updated(participant_id, window, cx);
 6395            }
 6396        }
 6397    }
 6398
 6399    pub fn database_id(&self) -> Option<WorkspaceId> {
 6400        self.database_id
 6401    }
 6402
 6403    #[cfg(any(test, feature = "test-support"))]
 6404    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6405        self.database_id = Some(id);
 6406    }
 6407
 6408    pub fn session_id(&self) -> Option<String> {
 6409        self.session_id.clone()
 6410    }
 6411
 6412    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6413        let Some(display) = window.display(cx) else {
 6414            return Task::ready(());
 6415        };
 6416        let Ok(display_uuid) = display.uuid() else {
 6417            return Task::ready(());
 6418        };
 6419
 6420        let window_bounds = window.inner_window_bounds();
 6421        let database_id = self.database_id;
 6422        let has_paths = !self.root_paths(cx).is_empty();
 6423        let db = WorkspaceDb::global(cx);
 6424        let kvp = db::kvp::KeyValueStore::global(cx);
 6425
 6426        cx.background_executor().spawn(async move {
 6427            if !has_paths {
 6428                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6429                    .await
 6430                    .log_err();
 6431            }
 6432            if let Some(database_id) = database_id {
 6433                db.set_window_open_status(
 6434                    database_id,
 6435                    SerializedWindowBounds(window_bounds),
 6436                    display_uuid,
 6437                )
 6438                .await
 6439                .log_err();
 6440            } else {
 6441                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6442                    .await
 6443                    .log_err();
 6444            }
 6445        })
 6446    }
 6447
 6448    /// Bypass the 200ms serialization throttle and write workspace state to
 6449    /// the DB immediately. Returns a task the caller can await to ensure the
 6450    /// write completes. Used by the quit handler so the most recent state
 6451    /// isn't lost to a pending throttle timer when the process exits.
 6452    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6453        self._schedule_serialize_workspace.take();
 6454        self._serialize_workspace_task.take();
 6455        self.bounds_save_task_queued.take();
 6456
 6457        let bounds_task = self.save_window_bounds(window, cx);
 6458        let serialize_task = self.serialize_workspace_internal(window, cx);
 6459        cx.spawn(async move |_| {
 6460            bounds_task.await;
 6461            serialize_task.await;
 6462        })
 6463    }
 6464
 6465    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6466        let project = self.project().read(cx);
 6467        project
 6468            .visible_worktrees(cx)
 6469            .map(|worktree| worktree.read(cx).abs_path())
 6470            .collect::<Vec<_>>()
 6471    }
 6472
 6473    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6474        match member {
 6475            Member::Axis(PaneAxis { members, .. }) => {
 6476                for child in members.iter() {
 6477                    self.remove_panes(child.clone(), window, cx)
 6478                }
 6479            }
 6480            Member::Pane(pane) => {
 6481                self.force_remove_pane(&pane, &None, window, cx);
 6482            }
 6483        }
 6484    }
 6485
 6486    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6487        self.session_id.take();
 6488        self.serialize_workspace_internal(window, cx)
 6489    }
 6490
 6491    fn force_remove_pane(
 6492        &mut self,
 6493        pane: &Entity<Pane>,
 6494        focus_on: &Option<Entity<Pane>>,
 6495        window: &mut Window,
 6496        cx: &mut Context<Workspace>,
 6497    ) {
 6498        self.panes.retain(|p| p != pane);
 6499        if let Some(focus_on) = focus_on {
 6500            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6501        } else if self.active_pane() == pane {
 6502            self.panes
 6503                .last()
 6504                .unwrap()
 6505                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6506        }
 6507        if self.last_active_center_pane == Some(pane.downgrade()) {
 6508            self.last_active_center_pane = None;
 6509        }
 6510        cx.notify();
 6511    }
 6512
 6513    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6514        if self._schedule_serialize_workspace.is_none() {
 6515            self._schedule_serialize_workspace =
 6516                Some(cx.spawn_in(window, async move |this, cx| {
 6517                    cx.background_executor()
 6518                        .timer(SERIALIZATION_THROTTLE_TIME)
 6519                        .await;
 6520                    this.update_in(cx, |this, window, cx| {
 6521                        this._serialize_workspace_task =
 6522                            Some(this.serialize_workspace_internal(window, cx));
 6523                        this._schedule_serialize_workspace.take();
 6524                    })
 6525                    .log_err();
 6526                }));
 6527        }
 6528    }
 6529
 6530    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6531        let Some(database_id) = self.database_id() else {
 6532            return Task::ready(());
 6533        };
 6534
 6535        fn serialize_pane_handle(
 6536            pane_handle: &Entity<Pane>,
 6537            window: &mut Window,
 6538            cx: &mut App,
 6539        ) -> SerializedPane {
 6540            let (items, active, pinned_count) = {
 6541                let pane = pane_handle.read(cx);
 6542                let active_item_id = pane.active_item().map(|item| item.item_id());
 6543                (
 6544                    pane.items()
 6545                        .filter_map(|handle| {
 6546                            let handle = handle.to_serializable_item_handle(cx)?;
 6547
 6548                            Some(SerializedItem {
 6549                                kind: Arc::from(handle.serialized_item_kind()),
 6550                                item_id: handle.item_id().as_u64(),
 6551                                active: Some(handle.item_id()) == active_item_id,
 6552                                preview: pane.is_active_preview_item(handle.item_id()),
 6553                            })
 6554                        })
 6555                        .collect::<Vec<_>>(),
 6556                    pane.has_focus(window, cx),
 6557                    pane.pinned_count(),
 6558                )
 6559            };
 6560
 6561            SerializedPane::new(items, active, pinned_count)
 6562        }
 6563
 6564        fn build_serialized_pane_group(
 6565            pane_group: &Member,
 6566            window: &mut Window,
 6567            cx: &mut App,
 6568        ) -> SerializedPaneGroup {
 6569            match pane_group {
 6570                Member::Axis(PaneAxis {
 6571                    axis,
 6572                    members,
 6573                    flexes,
 6574                    bounding_boxes: _,
 6575                }) => SerializedPaneGroup::Group {
 6576                    axis: SerializedAxis(*axis),
 6577                    children: members
 6578                        .iter()
 6579                        .map(|member| build_serialized_pane_group(member, window, cx))
 6580                        .collect::<Vec<_>>(),
 6581                    flexes: Some(flexes.lock().clone()),
 6582                },
 6583                Member::Pane(pane_handle) => {
 6584                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6585                }
 6586            }
 6587        }
 6588
 6589        fn build_serialized_docks(
 6590            this: &Workspace,
 6591            window: &mut Window,
 6592            cx: &mut App,
 6593        ) -> DockStructure {
 6594            this.capture_dock_state(window, cx)
 6595        }
 6596
 6597        match self.workspace_location(cx) {
 6598            WorkspaceLocation::Location(location, paths) => {
 6599                let breakpoints = self.project.update(cx, |project, cx| {
 6600                    project
 6601                        .breakpoint_store()
 6602                        .read(cx)
 6603                        .all_source_breakpoints(cx)
 6604                });
 6605                let user_toolchains = self
 6606                    .project
 6607                    .read(cx)
 6608                    .user_toolchains(cx)
 6609                    .unwrap_or_default();
 6610
 6611                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6612                let docks = build_serialized_docks(self, window, cx);
 6613                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6614
 6615                let serialized_workspace = SerializedWorkspace {
 6616                    id: database_id,
 6617                    location,
 6618                    paths,
 6619                    center_group,
 6620                    window_bounds,
 6621                    display: Default::default(),
 6622                    docks,
 6623                    centered_layout: self.centered_layout,
 6624                    session_id: self.session_id.clone(),
 6625                    breakpoints,
 6626                    window_id: Some(window.window_handle().window_id().as_u64()),
 6627                    user_toolchains,
 6628                };
 6629
 6630                let db = WorkspaceDb::global(cx);
 6631                window.spawn(cx, async move |_| {
 6632                    db.save_workspace(serialized_workspace).await;
 6633                })
 6634            }
 6635            WorkspaceLocation::DetachFromSession => {
 6636                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6637                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6638                // Save dock state for empty local workspaces
 6639                let docks = build_serialized_docks(self, window, cx);
 6640                let db = WorkspaceDb::global(cx);
 6641                let kvp = db::kvp::KeyValueStore::global(cx);
 6642                window.spawn(cx, async move |_| {
 6643                    db.set_window_open_status(
 6644                        database_id,
 6645                        window_bounds,
 6646                        display.unwrap_or_default(),
 6647                    )
 6648                    .await
 6649                    .log_err();
 6650                    db.set_session_id(database_id, None).await.log_err();
 6651                    persistence::write_default_dock_state(&kvp, docks)
 6652                        .await
 6653                        .log_err();
 6654                })
 6655            }
 6656            WorkspaceLocation::None => {
 6657                // Save dock state for empty non-local workspaces
 6658                let docks = build_serialized_docks(self, window, cx);
 6659                let kvp = db::kvp::KeyValueStore::global(cx);
 6660                window.spawn(cx, async move |_| {
 6661                    persistence::write_default_dock_state(&kvp, docks)
 6662                        .await
 6663                        .log_err();
 6664                })
 6665            }
 6666        }
 6667    }
 6668
 6669    fn has_any_items_open(&self, cx: &App) -> bool {
 6670        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6671    }
 6672
 6673    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6674        let paths = PathList::new(&self.root_paths(cx));
 6675        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6676            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6677        } else if self.project.read(cx).is_local() {
 6678            if !paths.is_empty() || self.has_any_items_open(cx) {
 6679                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6680            } else {
 6681                WorkspaceLocation::DetachFromSession
 6682            }
 6683        } else {
 6684            WorkspaceLocation::None
 6685        }
 6686    }
 6687
 6688    fn update_history(&self, cx: &mut App) {
 6689        let Some(id) = self.database_id() else {
 6690            return;
 6691        };
 6692        if !self.project.read(cx).is_local() {
 6693            return;
 6694        }
 6695        if let Some(manager) = HistoryManager::global(cx) {
 6696            let paths = PathList::new(&self.root_paths(cx));
 6697            manager.update(cx, |this, cx| {
 6698                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6699            });
 6700        }
 6701    }
 6702
 6703    async fn serialize_items(
 6704        this: &WeakEntity<Self>,
 6705        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6706        cx: &mut AsyncWindowContext,
 6707    ) -> Result<()> {
 6708        const CHUNK_SIZE: usize = 200;
 6709
 6710        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6711
 6712        while let Some(items_received) = serializable_items.next().await {
 6713            let unique_items =
 6714                items_received
 6715                    .into_iter()
 6716                    .fold(HashMap::default(), |mut acc, item| {
 6717                        acc.entry(item.item_id()).or_insert(item);
 6718                        acc
 6719                    });
 6720
 6721            // We use into_iter() here so that the references to the items are moved into
 6722            // the tasks and not kept alive while we're sleeping.
 6723            for (_, item) in unique_items.into_iter() {
 6724                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6725                    item.serialize(workspace, false, window, cx)
 6726                }) {
 6727                    cx.background_spawn(async move { task.await.log_err() })
 6728                        .detach();
 6729                }
 6730            }
 6731
 6732            cx.background_executor()
 6733                .timer(SERIALIZATION_THROTTLE_TIME)
 6734                .await;
 6735        }
 6736
 6737        Ok(())
 6738    }
 6739
 6740    pub(crate) fn enqueue_item_serialization(
 6741        &mut self,
 6742        item: Box<dyn SerializableItemHandle>,
 6743    ) -> Result<()> {
 6744        self.serializable_items_tx
 6745            .unbounded_send(item)
 6746            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6747    }
 6748
 6749    pub(crate) fn load_workspace(
 6750        serialized_workspace: SerializedWorkspace,
 6751        paths_to_open: Vec<Option<ProjectPath>>,
 6752        window: &mut Window,
 6753        cx: &mut Context<Workspace>,
 6754    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6755        cx.spawn_in(window, async move |workspace, cx| {
 6756            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6757
 6758            let mut center_group = None;
 6759            let mut center_items = None;
 6760
 6761            // Traverse the splits tree and add to things
 6762            if let Some((group, active_pane, items)) = serialized_workspace
 6763                .center_group
 6764                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6765                .await
 6766            {
 6767                center_items = Some(items);
 6768                center_group = Some((group, active_pane))
 6769            }
 6770
 6771            let mut items_by_project_path = HashMap::default();
 6772            let mut item_ids_by_kind = HashMap::default();
 6773            let mut all_deserialized_items = Vec::default();
 6774            cx.update(|_, cx| {
 6775                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6776                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6777                        item_ids_by_kind
 6778                            .entry(serializable_item_handle.serialized_item_kind())
 6779                            .or_insert(Vec::new())
 6780                            .push(item.item_id().as_u64() as ItemId);
 6781                    }
 6782
 6783                    if let Some(project_path) = item.project_path(cx) {
 6784                        items_by_project_path.insert(project_path, item.clone());
 6785                    }
 6786                    all_deserialized_items.push(item);
 6787                }
 6788            })?;
 6789
 6790            let opened_items = paths_to_open
 6791                .into_iter()
 6792                .map(|path_to_open| {
 6793                    path_to_open
 6794                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6795                })
 6796                .collect::<Vec<_>>();
 6797
 6798            // Remove old panes from workspace panes list
 6799            workspace.update_in(cx, |workspace, window, cx| {
 6800                if let Some((center_group, active_pane)) = center_group {
 6801                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6802
 6803                    // Swap workspace center group
 6804                    workspace.center = PaneGroup::with_root(center_group);
 6805                    workspace.center.set_is_center(true);
 6806                    workspace.center.mark_positions(cx);
 6807
 6808                    if let Some(active_pane) = active_pane {
 6809                        workspace.set_active_pane(&active_pane, window, cx);
 6810                        cx.focus_self(window);
 6811                    } else {
 6812                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6813                    }
 6814                }
 6815
 6816                let docks = serialized_workspace.docks;
 6817
 6818                for (dock, serialized_dock) in [
 6819                    (&mut workspace.right_dock, docks.right),
 6820                    (&mut workspace.left_dock, docks.left),
 6821                    (&mut workspace.bottom_dock, docks.bottom),
 6822                ]
 6823                .iter_mut()
 6824                {
 6825                    dock.update(cx, |dock, cx| {
 6826                        dock.serialized_dock = Some(serialized_dock.clone());
 6827                        dock.restore_state(window, cx);
 6828                    });
 6829                }
 6830
 6831                cx.notify();
 6832            })?;
 6833
 6834            let _ = project
 6835                .update(cx, |project, cx| {
 6836                    project
 6837                        .breakpoint_store()
 6838                        .update(cx, |breakpoint_store, cx| {
 6839                            breakpoint_store
 6840                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6841                        })
 6842                })
 6843                .await;
 6844
 6845            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6846            // after loading the items, we might have different items and in order to avoid
 6847            // the database filling up, we delete items that haven't been loaded now.
 6848            //
 6849            // The items that have been loaded, have been saved after they've been added to the workspace.
 6850            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6851                item_ids_by_kind
 6852                    .into_iter()
 6853                    .map(|(item_kind, loaded_items)| {
 6854                        SerializableItemRegistry::cleanup(
 6855                            item_kind,
 6856                            serialized_workspace.id,
 6857                            loaded_items,
 6858                            window,
 6859                            cx,
 6860                        )
 6861                        .log_err()
 6862                    })
 6863                    .collect::<Vec<_>>()
 6864            })?;
 6865
 6866            futures::future::join_all(clean_up_tasks).await;
 6867
 6868            workspace
 6869                .update_in(cx, |workspace, window, cx| {
 6870                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6871                    workspace.serialize_workspace_internal(window, cx).detach();
 6872
 6873                    // Ensure that we mark the window as edited if we did load dirty items
 6874                    workspace.update_window_edited(window, cx);
 6875                })
 6876                .ok();
 6877
 6878            Ok(opened_items)
 6879        })
 6880    }
 6881
 6882    pub fn key_context(&self, cx: &App) -> KeyContext {
 6883        let mut context = KeyContext::new_with_defaults();
 6884        context.add("Workspace");
 6885        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6886        if let Some(status) = self
 6887            .debugger_provider
 6888            .as_ref()
 6889            .and_then(|provider| provider.active_thread_state(cx))
 6890        {
 6891            match status {
 6892                ThreadStatus::Running | ThreadStatus::Stepping => {
 6893                    context.add("debugger_running");
 6894                }
 6895                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6896                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6897            }
 6898        }
 6899
 6900        if self.left_dock.read(cx).is_open() {
 6901            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6902                context.set("left_dock", active_panel.panel_key());
 6903            }
 6904        }
 6905
 6906        if self.right_dock.read(cx).is_open() {
 6907            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6908                context.set("right_dock", active_panel.panel_key());
 6909            }
 6910        }
 6911
 6912        if self.bottom_dock.read(cx).is_open() {
 6913            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6914                context.set("bottom_dock", active_panel.panel_key());
 6915            }
 6916        }
 6917
 6918        context
 6919    }
 6920
 6921    /// Multiworkspace uses this to add workspace action handling to itself
 6922    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6923        self.add_workspace_actions_listeners(div, window, cx)
 6924            .on_action(cx.listener(
 6925                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6926                    for action in &action_sequence.0 {
 6927                        window.dispatch_action(action.boxed_clone(), cx);
 6928                    }
 6929                },
 6930            ))
 6931            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6932            .on_action(cx.listener(Self::close_all_items_and_panes))
 6933            .on_action(cx.listener(Self::close_item_in_all_panes))
 6934            .on_action(cx.listener(Self::save_all))
 6935            .on_action(cx.listener(Self::send_keystrokes))
 6936            .on_action(cx.listener(Self::add_folder_to_project))
 6937            .on_action(cx.listener(Self::follow_next_collaborator))
 6938            .on_action(cx.listener(Self::activate_pane_at_index))
 6939            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6940            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6941            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6942            .on_action(cx.listener(Self::toggle_theme_mode))
 6943            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6944                let pane = workspace.active_pane().clone();
 6945                workspace.unfollow_in_pane(&pane, window, cx);
 6946            }))
 6947            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6948                workspace
 6949                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6950                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6951            }))
 6952            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6953                workspace
 6954                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6955                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6956            }))
 6957            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6958                workspace
 6959                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6960                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6961            }))
 6962            .on_action(
 6963                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6964                    workspace.activate_previous_pane(window, cx)
 6965                }),
 6966            )
 6967            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6968                workspace.activate_next_pane(window, cx)
 6969            }))
 6970            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6971                workspace.activate_last_pane(window, cx)
 6972            }))
 6973            .on_action(
 6974                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6975                    workspace.activate_next_window(cx)
 6976                }),
 6977            )
 6978            .on_action(
 6979                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6980                    workspace.activate_previous_window(cx)
 6981                }),
 6982            )
 6983            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6984                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6985            }))
 6986            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6987                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6988            }))
 6989            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6990                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6991            }))
 6992            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6993                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6994            }))
 6995            .on_action(cx.listener(
 6996                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6997                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6998                },
 6999            ))
 7000            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 7001                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 7002            }))
 7003            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 7004                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 7005            }))
 7006            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 7007                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 7008            }))
 7009            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 7010                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7011            }))
 7012            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7013                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7014                    SplitDirection::Down,
 7015                    SplitDirection::Up,
 7016                    SplitDirection::Right,
 7017                    SplitDirection::Left,
 7018                ];
 7019                for dir in DIRECTION_PRIORITY {
 7020                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7021                        workspace.swap_pane_in_direction(dir, cx);
 7022                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7023                        break;
 7024                    }
 7025                }
 7026            }))
 7027            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7028                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7029            }))
 7030            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7031                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7032            }))
 7033            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7034                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7035            }))
 7036            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7037                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7038            }))
 7039            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7040                this.toggle_dock(DockPosition::Left, window, cx);
 7041            }))
 7042            .on_action(cx.listener(
 7043                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7044                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7045                },
 7046            ))
 7047            .on_action(cx.listener(
 7048                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7049                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7050                },
 7051            ))
 7052            .on_action(cx.listener(
 7053                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7054                    if !workspace.close_active_dock(window, cx) {
 7055                        cx.propagate();
 7056                    }
 7057                },
 7058            ))
 7059            .on_action(
 7060                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7061                    workspace.close_all_docks(window, cx);
 7062                }),
 7063            )
 7064            .on_action(cx.listener(Self::toggle_all_docks))
 7065            .on_action(cx.listener(
 7066                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7067                    workspace.clear_all_notifications(cx);
 7068                },
 7069            ))
 7070            .on_action(cx.listener(
 7071                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7072                    workspace.clear_navigation_history(window, cx);
 7073                },
 7074            ))
 7075            .on_action(cx.listener(
 7076                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7077                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7078                        workspace.suppress_notification(&notification_id, cx);
 7079                    }
 7080                },
 7081            ))
 7082            .on_action(cx.listener(
 7083                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7084                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7085                },
 7086            ))
 7087            .on_action(
 7088                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7089                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7090                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7091                            trusted_worktrees.clear_trusted_paths()
 7092                        });
 7093                        let db = WorkspaceDb::global(cx);
 7094                        cx.spawn(async move |_, cx| {
 7095                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7096                                cx.update(|cx| reload(cx));
 7097                            }
 7098                        })
 7099                        .detach();
 7100                    }
 7101                }),
 7102            )
 7103            .on_action(cx.listener(
 7104                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7105                    workspace.reopen_closed_item(window, cx).detach();
 7106                },
 7107            ))
 7108            .on_action(cx.listener(
 7109                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7110                    for dock in workspace.all_docks() {
 7111                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7112                            let panel = dock.read(cx).active_panel().cloned();
 7113                            if let Some(panel) = panel {
 7114                                dock.update(cx, |dock, cx| {
 7115                                    dock.set_panel_size_state(
 7116                                        panel.as_ref(),
 7117                                        dock::PanelSizeState::default(),
 7118                                        cx,
 7119                                    );
 7120                                });
 7121                            }
 7122                            return;
 7123                        }
 7124                    }
 7125                },
 7126            ))
 7127            .on_action(cx.listener(
 7128                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7129                    for dock in workspace.all_docks() {
 7130                        let panel = dock.read(cx).visible_panel().cloned();
 7131                        if let Some(panel) = panel {
 7132                            dock.update(cx, |dock, cx| {
 7133                                dock.set_panel_size_state(
 7134                                    panel.as_ref(),
 7135                                    dock::PanelSizeState::default(),
 7136                                    cx,
 7137                                );
 7138                            });
 7139                        }
 7140                    }
 7141                },
 7142            ))
 7143            .on_action(cx.listener(
 7144                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7145                    adjust_active_dock_size_by_px(
 7146                        px_with_ui_font_fallback(act.px, cx),
 7147                        workspace,
 7148                        window,
 7149                        cx,
 7150                    );
 7151                },
 7152            ))
 7153            .on_action(cx.listener(
 7154                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7155                    adjust_active_dock_size_by_px(
 7156                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7157                        workspace,
 7158                        window,
 7159                        cx,
 7160                    );
 7161                },
 7162            ))
 7163            .on_action(cx.listener(
 7164                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7165                    adjust_open_docks_size_by_px(
 7166                        px_with_ui_font_fallback(act.px, cx),
 7167                        workspace,
 7168                        window,
 7169                        cx,
 7170                    );
 7171                },
 7172            ))
 7173            .on_action(cx.listener(
 7174                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7175                    adjust_open_docks_size_by_px(
 7176                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7177                        workspace,
 7178                        window,
 7179                        cx,
 7180                    );
 7181                },
 7182            ))
 7183            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7184            .on_action(cx.listener(
 7185                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7186                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7187                        let dock = active_dock.read(cx);
 7188                        if let Some(active_panel) = dock.active_panel() {
 7189                            if active_panel.pane(cx).is_none() {
 7190                                let mut recent_pane: Option<Entity<Pane>> = None;
 7191                                let mut recent_timestamp = 0;
 7192                                for pane_handle in workspace.panes() {
 7193                                    let pane = pane_handle.read(cx);
 7194                                    for entry in pane.activation_history() {
 7195                                        if entry.timestamp > recent_timestamp {
 7196                                            recent_timestamp = entry.timestamp;
 7197                                            recent_pane = Some(pane_handle.clone());
 7198                                        }
 7199                                    }
 7200                                }
 7201
 7202                                if let Some(pane) = recent_pane {
 7203                                    let wrap_around = action.wrap_around;
 7204                                    pane.update(cx, |pane, cx| {
 7205                                        let current_index = pane.active_item_index();
 7206                                        let items_len = pane.items_len();
 7207                                        if items_len > 0 {
 7208                                            let next_index = if current_index + 1 < items_len {
 7209                                                current_index + 1
 7210                                            } else if wrap_around {
 7211                                                0
 7212                                            } else {
 7213                                                return;
 7214                                            };
 7215                                            pane.activate_item(
 7216                                                next_index, false, false, window, cx,
 7217                                            );
 7218                                        }
 7219                                    });
 7220                                    return;
 7221                                }
 7222                            }
 7223                        }
 7224                    }
 7225                    cx.propagate();
 7226                },
 7227            ))
 7228            .on_action(cx.listener(
 7229                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7230                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7231                        let dock = active_dock.read(cx);
 7232                        if let Some(active_panel) = dock.active_panel() {
 7233                            if active_panel.pane(cx).is_none() {
 7234                                let mut recent_pane: Option<Entity<Pane>> = None;
 7235                                let mut recent_timestamp = 0;
 7236                                for pane_handle in workspace.panes() {
 7237                                    let pane = pane_handle.read(cx);
 7238                                    for entry in pane.activation_history() {
 7239                                        if entry.timestamp > recent_timestamp {
 7240                                            recent_timestamp = entry.timestamp;
 7241                                            recent_pane = Some(pane_handle.clone());
 7242                                        }
 7243                                    }
 7244                                }
 7245
 7246                                if let Some(pane) = recent_pane {
 7247                                    let wrap_around = action.wrap_around;
 7248                                    pane.update(cx, |pane, cx| {
 7249                                        let current_index = pane.active_item_index();
 7250                                        let items_len = pane.items_len();
 7251                                        if items_len > 0 {
 7252                                            let prev_index = if current_index > 0 {
 7253                                                current_index - 1
 7254                                            } else if wrap_around {
 7255                                                items_len.saturating_sub(1)
 7256                                            } else {
 7257                                                return;
 7258                                            };
 7259                                            pane.activate_item(
 7260                                                prev_index, false, false, window, cx,
 7261                                            );
 7262                                        }
 7263                                    });
 7264                                    return;
 7265                                }
 7266                            }
 7267                        }
 7268                    }
 7269                    cx.propagate();
 7270                },
 7271            ))
 7272            .on_action(cx.listener(
 7273                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7274                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7275                        let dock = active_dock.read(cx);
 7276                        if let Some(active_panel) = dock.active_panel() {
 7277                            if active_panel.pane(cx).is_none() {
 7278                                let active_pane = workspace.active_pane().clone();
 7279                                active_pane.update(cx, |pane, cx| {
 7280                                    pane.close_active_item(action, window, cx)
 7281                                        .detach_and_log_err(cx);
 7282                                });
 7283                                return;
 7284                            }
 7285                        }
 7286                    }
 7287                    cx.propagate();
 7288                },
 7289            ))
 7290            .on_action(
 7291                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7292                    let pane = workspace.active_pane().clone();
 7293                    if let Some(item) = pane.read(cx).active_item() {
 7294                        item.toggle_read_only(window, cx);
 7295                    }
 7296                }),
 7297            )
 7298            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7299                workspace.focus_center_pane(window, cx);
 7300            }))
 7301            .on_action(cx.listener(Workspace::cancel))
 7302    }
 7303
 7304    #[cfg(any(test, feature = "test-support"))]
 7305    pub fn set_random_database_id(&mut self) {
 7306        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7307    }
 7308
 7309    #[cfg(any(test, feature = "test-support"))]
 7310    pub(crate) fn test_new(
 7311        project: Entity<Project>,
 7312        window: &mut Window,
 7313        cx: &mut Context<Self>,
 7314    ) -> Self {
 7315        use node_runtime::NodeRuntime;
 7316        use session::Session;
 7317
 7318        let client = project.read(cx).client();
 7319        let user_store = project.read(cx).user_store();
 7320        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7321        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7322        window.activate_window();
 7323        let app_state = Arc::new(AppState {
 7324            languages: project.read(cx).languages().clone(),
 7325            workspace_store,
 7326            client,
 7327            user_store,
 7328            fs: project.read(cx).fs().clone(),
 7329            build_window_options: |_, _| Default::default(),
 7330            node_runtime: NodeRuntime::unavailable(),
 7331            session,
 7332        });
 7333        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7334        workspace
 7335            .active_pane
 7336            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7337        workspace
 7338    }
 7339
 7340    pub fn register_action<A: Action>(
 7341        &mut self,
 7342        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7343    ) -> &mut Self {
 7344        let callback = Arc::new(callback);
 7345
 7346        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7347            let callback = callback.clone();
 7348            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7349                (callback)(workspace, event, window, cx)
 7350            }))
 7351        }));
 7352        self
 7353    }
 7354    pub fn register_action_renderer(
 7355        &mut self,
 7356        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7357    ) -> &mut Self {
 7358        self.workspace_actions.push(Box::new(callback));
 7359        self
 7360    }
 7361
 7362    fn add_workspace_actions_listeners(
 7363        &self,
 7364        mut div: Div,
 7365        window: &mut Window,
 7366        cx: &mut Context<Self>,
 7367    ) -> Div {
 7368        for action in self.workspace_actions.iter() {
 7369            div = (action)(div, self, window, cx)
 7370        }
 7371        div
 7372    }
 7373
 7374    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7375        self.modal_layer.read(cx).has_active_modal()
 7376    }
 7377
 7378    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7379        self.modal_layer
 7380            .read(cx)
 7381            .is_active_modal_command_palette(cx)
 7382    }
 7383
 7384    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7385        self.modal_layer.read(cx).active_modal()
 7386    }
 7387
 7388    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7389    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7390    /// If no modal is active, the new modal will be shown.
 7391    ///
 7392    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7393    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7394    /// will not be shown.
 7395    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7396    where
 7397        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7398    {
 7399        self.modal_layer.update(cx, |modal_layer, cx| {
 7400            modal_layer.toggle_modal(window, cx, build)
 7401        })
 7402    }
 7403
 7404    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7405        self.modal_layer
 7406            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7407    }
 7408
 7409    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7410        self.toast_layer
 7411            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7412    }
 7413
 7414    pub fn toggle_centered_layout(
 7415        &mut self,
 7416        _: &ToggleCenteredLayout,
 7417        _: &mut Window,
 7418        cx: &mut Context<Self>,
 7419    ) {
 7420        self.centered_layout = !self.centered_layout;
 7421        if let Some(database_id) = self.database_id() {
 7422            let db = WorkspaceDb::global(cx);
 7423            let centered_layout = self.centered_layout;
 7424            cx.background_spawn(async move {
 7425                db.set_centered_layout(database_id, centered_layout).await
 7426            })
 7427            .detach_and_log_err(cx);
 7428        }
 7429        cx.notify();
 7430    }
 7431
 7432    fn adjust_padding(padding: Option<f32>) -> f32 {
 7433        padding
 7434            .unwrap_or(CenteredPaddingSettings::default().0)
 7435            .clamp(
 7436                CenteredPaddingSettings::MIN_PADDING,
 7437                CenteredPaddingSettings::MAX_PADDING,
 7438            )
 7439    }
 7440
 7441    fn render_dock(
 7442        &self,
 7443        position: DockPosition,
 7444        dock: &Entity<Dock>,
 7445        window: &mut Window,
 7446        cx: &mut App,
 7447    ) -> Option<Div> {
 7448        if self.zoomed_position == Some(position) {
 7449            return None;
 7450        }
 7451
 7452        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7453            let pane = panel.pane(cx)?;
 7454            let follower_states = &self.follower_states;
 7455            leader_border_for_pane(follower_states, &pane, window, cx)
 7456        });
 7457
 7458        let mut container = div()
 7459            .flex()
 7460            .overflow_hidden()
 7461            .flex_none()
 7462            .child(dock.clone())
 7463            .children(leader_border);
 7464
 7465        // Apply sizing only when the dock is open. When closed the dock is still
 7466        // included in the element tree so its focus handle remains mounted — without
 7467        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7468        let dock = dock.read(cx);
 7469        if let Some(panel) = dock.visible_panel() {
 7470            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7471            if position.axis() == Axis::Horizontal {
 7472                let use_flexible = panel.has_flexible_size(window, cx);
 7473                let flex_grow = if use_flexible {
 7474                    size_state
 7475                        .and_then(|state| state.flex)
 7476                        .or_else(|| self.default_dock_flex(position))
 7477                } else {
 7478                    None
 7479                };
 7480                if let Some(grow) = flex_grow {
 7481                    let grow = grow.max(0.001);
 7482                    let style = container.style();
 7483                    style.flex_grow = Some(grow);
 7484                    style.flex_shrink = Some(1.0);
 7485                    style.flex_basis = Some(relative(0.).into());
 7486                } else {
 7487                    let size = size_state
 7488                        .and_then(|state| state.size)
 7489                        .unwrap_or_else(|| panel.default_size(window, cx));
 7490                    container = container.w(size);
 7491                }
 7492            } else {
 7493                let size = size_state
 7494                    .and_then(|state| state.size)
 7495                    .unwrap_or_else(|| panel.default_size(window, cx));
 7496                container = container.h(size);
 7497            }
 7498        }
 7499
 7500        Some(container)
 7501    }
 7502
 7503    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7504        window
 7505            .root::<MultiWorkspace>()
 7506            .flatten()
 7507            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7508    }
 7509
 7510    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7511        self.zoomed.as_ref()
 7512    }
 7513
 7514    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7515        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7516            return;
 7517        };
 7518        let windows = cx.windows();
 7519        let next_window =
 7520            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7521                || {
 7522                    windows
 7523                        .iter()
 7524                        .cycle()
 7525                        .skip_while(|window| window.window_id() != current_window_id)
 7526                        .nth(1)
 7527                },
 7528            );
 7529
 7530        if let Some(window) = next_window {
 7531            window
 7532                .update(cx, |_, window, _| window.activate_window())
 7533                .ok();
 7534        }
 7535    }
 7536
 7537    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7538        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7539            return;
 7540        };
 7541        let windows = cx.windows();
 7542        let prev_window =
 7543            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7544                || {
 7545                    windows
 7546                        .iter()
 7547                        .rev()
 7548                        .cycle()
 7549                        .skip_while(|window| window.window_id() != current_window_id)
 7550                        .nth(1)
 7551                },
 7552            );
 7553
 7554        if let Some(window) = prev_window {
 7555            window
 7556                .update(cx, |_, window, _| window.activate_window())
 7557                .ok();
 7558        }
 7559    }
 7560
 7561    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7562        if cx.stop_active_drag(window) {
 7563        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7564            dismiss_app_notification(&notification_id, cx);
 7565        } else {
 7566            cx.propagate();
 7567        }
 7568    }
 7569
 7570    fn resize_dock(
 7571        &mut self,
 7572        dock_pos: DockPosition,
 7573        new_size: Pixels,
 7574        window: &mut Window,
 7575        cx: &mut Context<Self>,
 7576    ) {
 7577        match dock_pos {
 7578            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7579            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7580            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7581        }
 7582    }
 7583
 7584    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7585        let workspace_width = self.bounds.size.width;
 7586        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7587
 7588        self.right_dock.read_with(cx, |right_dock, cx| {
 7589            let right_dock_size = right_dock
 7590                .stored_active_panel_size(window, cx)
 7591                .unwrap_or(Pixels::ZERO);
 7592            if right_dock_size + size > workspace_width {
 7593                size = workspace_width - right_dock_size
 7594            }
 7595        });
 7596
 7597        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7598        self.left_dock.update(cx, |left_dock, cx| {
 7599            if WorkspaceSettings::get_global(cx)
 7600                .resize_all_panels_in_dock
 7601                .contains(&DockPosition::Left)
 7602            {
 7603                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7604            } else {
 7605                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7606            }
 7607        });
 7608    }
 7609
 7610    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7611        let workspace_width = self.bounds.size.width;
 7612        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7613        self.left_dock.read_with(cx, |left_dock, cx| {
 7614            let left_dock_size = left_dock
 7615                .stored_active_panel_size(window, cx)
 7616                .unwrap_or(Pixels::ZERO);
 7617            if left_dock_size + size > workspace_width {
 7618                size = workspace_width - left_dock_size
 7619            }
 7620        });
 7621        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7622        self.right_dock.update(cx, |right_dock, cx| {
 7623            if WorkspaceSettings::get_global(cx)
 7624                .resize_all_panels_in_dock
 7625                .contains(&DockPosition::Right)
 7626            {
 7627                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7628            } else {
 7629                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7630            }
 7631        });
 7632    }
 7633
 7634    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7635        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7636        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7637            if WorkspaceSettings::get_global(cx)
 7638                .resize_all_panels_in_dock
 7639                .contains(&DockPosition::Bottom)
 7640            {
 7641                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7642            } else {
 7643                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7644            }
 7645        });
 7646    }
 7647
 7648    fn toggle_edit_predictions_all_files(
 7649        &mut self,
 7650        _: &ToggleEditPrediction,
 7651        _window: &mut Window,
 7652        cx: &mut Context<Self>,
 7653    ) {
 7654        let fs = self.project().read(cx).fs().clone();
 7655        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7656        update_settings_file(fs, cx, move |file, _| {
 7657            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7658        });
 7659    }
 7660
 7661    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7662        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7663        let next_mode = match current_mode {
 7664            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7665                theme_settings::ThemeAppearanceMode::Dark
 7666            }
 7667            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7668                theme_settings::ThemeAppearanceMode::Light
 7669            }
 7670            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7671                match cx.theme().appearance() {
 7672                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7673                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7674                }
 7675            }
 7676        };
 7677
 7678        let fs = self.project().read(cx).fs().clone();
 7679        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7680            theme_settings::set_mode(settings, next_mode);
 7681        });
 7682    }
 7683
 7684    pub fn show_worktree_trust_security_modal(
 7685        &mut self,
 7686        toggle: bool,
 7687        window: &mut Window,
 7688        cx: &mut Context<Self>,
 7689    ) {
 7690        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7691            if toggle {
 7692                security_modal.update(cx, |security_modal, cx| {
 7693                    security_modal.dismiss(cx);
 7694                })
 7695            } else {
 7696                security_modal.update(cx, |security_modal, cx| {
 7697                    security_modal.refresh_restricted_paths(cx);
 7698                });
 7699            }
 7700        } else {
 7701            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7702                .map(|trusted_worktrees| {
 7703                    trusted_worktrees
 7704                        .read(cx)
 7705                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7706                })
 7707                .unwrap_or(false);
 7708            if has_restricted_worktrees {
 7709                let project = self.project().read(cx);
 7710                let remote_host = project
 7711                    .remote_connection_options(cx)
 7712                    .map(RemoteHostLocation::from);
 7713                let worktree_store = project.worktree_store().downgrade();
 7714                self.toggle_modal(window, cx, |_, cx| {
 7715                    SecurityModal::new(worktree_store, remote_host, cx)
 7716                });
 7717            }
 7718        }
 7719    }
 7720}
 7721
 7722pub trait AnyActiveCall {
 7723    fn entity(&self) -> AnyEntity;
 7724    fn is_in_room(&self, _: &App) -> bool;
 7725    fn room_id(&self, _: &App) -> Option<u64>;
 7726    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7727    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7728    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7729    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7730    fn is_sharing_project(&self, _: &App) -> bool;
 7731    fn has_remote_participants(&self, _: &App) -> bool;
 7732    fn local_participant_is_guest(&self, _: &App) -> bool;
 7733    fn client(&self, _: &App) -> Arc<Client>;
 7734    fn share_on_join(&self, _: &App) -> bool;
 7735    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7736    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7737    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7738    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7739    fn join_project(
 7740        &self,
 7741        _: u64,
 7742        _: Arc<LanguageRegistry>,
 7743        _: Arc<dyn Fs>,
 7744        _: &mut App,
 7745    ) -> Task<Result<Entity<Project>>>;
 7746    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7747    fn subscribe(
 7748        &self,
 7749        _: &mut Window,
 7750        _: &mut Context<Workspace>,
 7751        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7752    ) -> Subscription;
 7753    fn create_shared_screen(
 7754        &self,
 7755        _: PeerId,
 7756        _: &Entity<Pane>,
 7757        _: &mut Window,
 7758        _: &mut App,
 7759    ) -> Option<Entity<SharedScreen>>;
 7760}
 7761
 7762#[derive(Clone)]
 7763pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7764impl Global for GlobalAnyActiveCall {}
 7765
 7766impl GlobalAnyActiveCall {
 7767    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7768        cx.try_global()
 7769    }
 7770
 7771    pub(crate) fn global(cx: &App) -> &Self {
 7772        cx.global()
 7773    }
 7774}
 7775
 7776/// Workspace-local view of a remote participant's location.
 7777#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7778pub enum ParticipantLocation {
 7779    SharedProject { project_id: u64 },
 7780    UnsharedProject,
 7781    External,
 7782}
 7783
 7784impl ParticipantLocation {
 7785    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7786        match location
 7787            .and_then(|l| l.variant)
 7788            .context("participant location was not provided")?
 7789        {
 7790            proto::participant_location::Variant::SharedProject(project) => {
 7791                Ok(Self::SharedProject {
 7792                    project_id: project.id,
 7793                })
 7794            }
 7795            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7796            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7797        }
 7798    }
 7799}
 7800/// Workspace-local view of a remote collaborator's state.
 7801/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7802#[derive(Clone)]
 7803pub struct RemoteCollaborator {
 7804    pub user: Arc<User>,
 7805    pub peer_id: PeerId,
 7806    pub location: ParticipantLocation,
 7807    pub participant_index: ParticipantIndex,
 7808}
 7809
 7810pub enum ActiveCallEvent {
 7811    ParticipantLocationChanged { participant_id: PeerId },
 7812    RemoteVideoTracksChanged { participant_id: PeerId },
 7813}
 7814
 7815fn leader_border_for_pane(
 7816    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7817    pane: &Entity<Pane>,
 7818    _: &Window,
 7819    cx: &App,
 7820) -> Option<Div> {
 7821    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7822        if state.pane() == pane {
 7823            Some((*leader_id, state))
 7824        } else {
 7825            None
 7826        }
 7827    })?;
 7828
 7829    let mut leader_color = match leader_id {
 7830        CollaboratorId::PeerId(leader_peer_id) => {
 7831            let leader = GlobalAnyActiveCall::try_global(cx)?
 7832                .0
 7833                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7834
 7835            cx.theme()
 7836                .players()
 7837                .color_for_participant(leader.participant_index.0)
 7838                .cursor
 7839        }
 7840        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7841    };
 7842    leader_color.fade_out(0.3);
 7843    Some(
 7844        div()
 7845            .absolute()
 7846            .size_full()
 7847            .left_0()
 7848            .top_0()
 7849            .border_2()
 7850            .border_color(leader_color),
 7851    )
 7852}
 7853
 7854fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7855    ZED_WINDOW_POSITION
 7856        .zip(*ZED_WINDOW_SIZE)
 7857        .map(|(position, size)| Bounds {
 7858            origin: position,
 7859            size,
 7860        })
 7861}
 7862
 7863fn open_items(
 7864    serialized_workspace: Option<SerializedWorkspace>,
 7865    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7866    window: &mut Window,
 7867    cx: &mut Context<Workspace>,
 7868) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7869    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7870        Workspace::load_workspace(
 7871            serialized_workspace,
 7872            project_paths_to_open
 7873                .iter()
 7874                .map(|(_, project_path)| project_path)
 7875                .cloned()
 7876                .collect(),
 7877            window,
 7878            cx,
 7879        )
 7880    });
 7881
 7882    cx.spawn_in(window, async move |workspace, cx| {
 7883        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7884
 7885        if let Some(restored_items) = restored_items {
 7886            let restored_items = restored_items.await?;
 7887
 7888            let restored_project_paths = restored_items
 7889                .iter()
 7890                .filter_map(|item| {
 7891                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7892                        .ok()
 7893                        .flatten()
 7894                })
 7895                .collect::<HashSet<_>>();
 7896
 7897            for restored_item in restored_items {
 7898                opened_items.push(restored_item.map(Ok));
 7899            }
 7900
 7901            project_paths_to_open
 7902                .iter_mut()
 7903                .for_each(|(_, project_path)| {
 7904                    if let Some(project_path_to_open) = project_path
 7905                        && restored_project_paths.contains(project_path_to_open)
 7906                    {
 7907                        *project_path = None;
 7908                    }
 7909                });
 7910        } else {
 7911            for _ in 0..project_paths_to_open.len() {
 7912                opened_items.push(None);
 7913            }
 7914        }
 7915        assert!(opened_items.len() == project_paths_to_open.len());
 7916
 7917        let tasks =
 7918            project_paths_to_open
 7919                .into_iter()
 7920                .enumerate()
 7921                .map(|(ix, (abs_path, project_path))| {
 7922                    let workspace = workspace.clone();
 7923                    cx.spawn(async move |cx| {
 7924                        let file_project_path = project_path?;
 7925                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7926                            workspace.project().update(cx, |project, cx| {
 7927                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7928                            })
 7929                        });
 7930
 7931                        // We only want to open file paths here. If one of the items
 7932                        // here is a directory, it was already opened further above
 7933                        // with a `find_or_create_worktree`.
 7934                        if let Ok(task) = abs_path_task
 7935                            && task.await.is_none_or(|p| p.is_file())
 7936                        {
 7937                            return Some((
 7938                                ix,
 7939                                workspace
 7940                                    .update_in(cx, |workspace, window, cx| {
 7941                                        workspace.open_path(
 7942                                            file_project_path,
 7943                                            None,
 7944                                            true,
 7945                                            window,
 7946                                            cx,
 7947                                        )
 7948                                    })
 7949                                    .log_err()?
 7950                                    .await,
 7951                            ));
 7952                        }
 7953                        None
 7954                    })
 7955                });
 7956
 7957        let tasks = tasks.collect::<Vec<_>>();
 7958
 7959        let tasks = futures::future::join_all(tasks);
 7960        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7961            opened_items[ix] = Some(path_open_result);
 7962        }
 7963
 7964        Ok(opened_items)
 7965    })
 7966}
 7967
 7968#[derive(Clone)]
 7969enum ActivateInDirectionTarget {
 7970    Pane(Entity<Pane>),
 7971    Dock(Entity<Dock>),
 7972    Sidebar(FocusHandle),
 7973}
 7974
 7975fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7976    window
 7977        .update(cx, |multi_workspace, _, cx| {
 7978            let workspace = multi_workspace.workspace().clone();
 7979            workspace.update(cx, |workspace, cx| {
 7980                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7981                    struct DatabaseFailedNotification;
 7982
 7983                    workspace.show_notification(
 7984                        NotificationId::unique::<DatabaseFailedNotification>(),
 7985                        cx,
 7986                        |cx| {
 7987                            cx.new(|cx| {
 7988                                MessageNotification::new("Failed to load the database file.", cx)
 7989                                    .primary_message("File an Issue")
 7990                                    .primary_icon(IconName::Plus)
 7991                                    .primary_on_click(|window, cx| {
 7992                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7993                                    })
 7994                            })
 7995                        },
 7996                    );
 7997                }
 7998            });
 7999        })
 8000        .log_err();
 8001}
 8002
 8003fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 8004    if val == 0 {
 8005        ThemeSettings::get_global(cx).ui_font_size(cx)
 8006    } else {
 8007        px(val as f32)
 8008    }
 8009}
 8010
 8011fn adjust_active_dock_size_by_px(
 8012    px: Pixels,
 8013    workspace: &mut Workspace,
 8014    window: &mut Window,
 8015    cx: &mut Context<Workspace>,
 8016) {
 8017    let Some(active_dock) = workspace
 8018        .all_docks()
 8019        .into_iter()
 8020        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8021    else {
 8022        return;
 8023    };
 8024    let dock = active_dock.read(cx);
 8025    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8026        return;
 8027    };
 8028    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8029}
 8030
 8031fn adjust_open_docks_size_by_px(
 8032    px: Pixels,
 8033    workspace: &mut Workspace,
 8034    window: &mut Window,
 8035    cx: &mut Context<Workspace>,
 8036) {
 8037    let docks = workspace
 8038        .all_docks()
 8039        .into_iter()
 8040        .filter_map(|dock_entity| {
 8041            let dock = dock_entity.read(cx);
 8042            if dock.is_open() {
 8043                let dock_pos = dock.position();
 8044                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8045                Some((dock_pos, panel_size + px))
 8046            } else {
 8047                None
 8048            }
 8049        })
 8050        .collect::<Vec<_>>();
 8051
 8052    for (position, new_size) in docks {
 8053        workspace.resize_dock(position, new_size, window, cx);
 8054    }
 8055}
 8056
 8057impl Focusable for Workspace {
 8058    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8059        self.active_pane.focus_handle(cx)
 8060    }
 8061}
 8062
 8063#[derive(Clone)]
 8064struct DraggedDock(DockPosition);
 8065
 8066impl Render for DraggedDock {
 8067    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8068        gpui::Empty
 8069    }
 8070}
 8071
 8072impl Render for Workspace {
 8073    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8074        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8075        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8076            log::info!("Rendered first frame");
 8077        }
 8078
 8079        let centered_layout = self.centered_layout
 8080            && self.center.panes().len() == 1
 8081            && self.active_item(cx).is_some();
 8082        let render_padding = |size| {
 8083            (size > 0.0).then(|| {
 8084                div()
 8085                    .h_full()
 8086                    .w(relative(size))
 8087                    .bg(cx.theme().colors().editor_background)
 8088                    .border_color(cx.theme().colors().pane_group_border)
 8089            })
 8090        };
 8091        let paddings = if centered_layout {
 8092            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8093            (
 8094                render_padding(Self::adjust_padding(
 8095                    settings.left_padding.map(|padding| padding.0),
 8096                )),
 8097                render_padding(Self::adjust_padding(
 8098                    settings.right_padding.map(|padding| padding.0),
 8099                )),
 8100            )
 8101        } else {
 8102            (None, None)
 8103        };
 8104        let ui_font = theme_settings::setup_ui_font(window, cx);
 8105
 8106        let theme = cx.theme().clone();
 8107        let colors = theme.colors();
 8108        let notification_entities = self
 8109            .notifications
 8110            .iter()
 8111            .map(|(_, notification)| notification.entity_id())
 8112            .collect::<Vec<_>>();
 8113        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8114
 8115        div()
 8116            .relative()
 8117            .size_full()
 8118            .flex()
 8119            .flex_col()
 8120            .font(ui_font)
 8121            .gap_0()
 8122                .justify_start()
 8123                .items_start()
 8124                .text_color(colors.text)
 8125                .overflow_hidden()
 8126                .children(self.titlebar_item.clone())
 8127                .on_modifiers_changed(move |_, _, cx| {
 8128                    for &id in &notification_entities {
 8129                        cx.notify(id);
 8130                    }
 8131                })
 8132                .child(
 8133                    div()
 8134                        .size_full()
 8135                        .relative()
 8136                        .flex_1()
 8137                        .flex()
 8138                        .flex_col()
 8139                        .child(
 8140                            div()
 8141                                .id("workspace")
 8142                                .bg(colors.background)
 8143                                .relative()
 8144                                .flex_1()
 8145                                .w_full()
 8146                                .flex()
 8147                                .flex_col()
 8148                                .overflow_hidden()
 8149                                .border_t_1()
 8150                                .border_b_1()
 8151                                .border_color(colors.border)
 8152                                .child({
 8153                                    let this = cx.entity();
 8154                                    canvas(
 8155                                        move |bounds, window, cx| {
 8156                                            this.update(cx, |this, cx| {
 8157                                                let bounds_changed = this.bounds != bounds;
 8158                                                this.bounds = bounds;
 8159
 8160                                                if bounds_changed {
 8161                                                    this.left_dock.update(cx, |dock, cx| {
 8162                                                        dock.clamp_panel_size(
 8163                                                            bounds.size.width,
 8164                                                            window,
 8165                                                            cx,
 8166                                                        )
 8167                                                    });
 8168
 8169                                                    this.right_dock.update(cx, |dock, cx| {
 8170                                                        dock.clamp_panel_size(
 8171                                                            bounds.size.width,
 8172                                                            window,
 8173                                                            cx,
 8174                                                        )
 8175                                                    });
 8176
 8177                                                    this.bottom_dock.update(cx, |dock, cx| {
 8178                                                        dock.clamp_panel_size(
 8179                                                            bounds.size.height,
 8180                                                            window,
 8181                                                            cx,
 8182                                                        )
 8183                                                    });
 8184                                                }
 8185                                            })
 8186                                        },
 8187                                        |_, _, _, _| {},
 8188                                    )
 8189                                    .absolute()
 8190                                    .size_full()
 8191                                })
 8192                                .when(self.zoomed.is_none(), |this| {
 8193                                    this.on_drag_move(cx.listener(
 8194                                        move |workspace,
 8195                                              e: &DragMoveEvent<DraggedDock>,
 8196                                              window,
 8197                                              cx| {
 8198                                            if workspace.previous_dock_drag_coordinates
 8199                                                != Some(e.event.position)
 8200                                            {
 8201                                                workspace.previous_dock_drag_coordinates =
 8202                                                    Some(e.event.position);
 8203
 8204                                                match e.drag(cx).0 {
 8205                                                    DockPosition::Left => {
 8206                                                        workspace.resize_left_dock(
 8207                                                            e.event.position.x
 8208                                                                - workspace.bounds.left(),
 8209                                                            window,
 8210                                                            cx,
 8211                                                        );
 8212                                                    }
 8213                                                    DockPosition::Right => {
 8214                                                        workspace.resize_right_dock(
 8215                                                            workspace.bounds.right()
 8216                                                                - e.event.position.x,
 8217                                                            window,
 8218                                                            cx,
 8219                                                        );
 8220                                                    }
 8221                                                    DockPosition::Bottom => {
 8222                                                        workspace.resize_bottom_dock(
 8223                                                            workspace.bounds.bottom()
 8224                                                                - e.event.position.y,
 8225                                                            window,
 8226                                                            cx,
 8227                                                        );
 8228                                                    }
 8229                                                };
 8230                                                workspace.serialize_workspace(window, cx);
 8231                                            }
 8232                                        },
 8233                                    ))
 8234
 8235                                })
 8236                                .child({
 8237                                    match bottom_dock_layout {
 8238                                        BottomDockLayout::Full => div()
 8239                                            .flex()
 8240                                            .flex_col()
 8241                                            .h_full()
 8242                                            .child(
 8243                                                div()
 8244                                                    .flex()
 8245                                                    .flex_row()
 8246                                                    .flex_1()
 8247                                                    .overflow_hidden()
 8248                                                    .children(self.render_dock(
 8249                                                        DockPosition::Left,
 8250                                                        &self.left_dock,
 8251                                                        window,
 8252                                                        cx,
 8253                                                    ))
 8254
 8255                                                    .child(
 8256                                                        div()
 8257                                                            .flex()
 8258                                                            .flex_col()
 8259                                                            .flex_1()
 8260                                                            .overflow_hidden()
 8261                                                            .child(
 8262                                                                h_flex()
 8263                                                                    .flex_1()
 8264                                                                    .when_some(
 8265                                                                        paddings.0,
 8266                                                                        |this, p| {
 8267                                                                            this.child(
 8268                                                                                p.border_r_1(),
 8269                                                                            )
 8270                                                                        },
 8271                                                                    )
 8272                                                                    .child(self.center.render(
 8273                                                                        self.zoomed.as_ref(),
 8274                                                                        &PaneRenderContext {
 8275                                                                            follower_states:
 8276                                                                                &self.follower_states,
 8277                                                                            active_call: self.active_call(),
 8278                                                                            active_pane: &self.active_pane,
 8279                                                                            app_state: &self.app_state,
 8280                                                                            project: &self.project,
 8281                                                                            workspace: &self.weak_self,
 8282                                                                        },
 8283                                                                        window,
 8284                                                                        cx,
 8285                                                                    ))
 8286                                                                    .when_some(
 8287                                                                        paddings.1,
 8288                                                                        |this, p| {
 8289                                                                            this.child(
 8290                                                                                p.border_l_1(),
 8291                                                                            )
 8292                                                                        },
 8293                                                                    ),
 8294                                                            ),
 8295                                                    )
 8296
 8297                                                    .children(self.render_dock(
 8298                                                        DockPosition::Right,
 8299                                                        &self.right_dock,
 8300                                                        window,
 8301                                                        cx,
 8302                                                    )),
 8303                                            )
 8304                                            .child(div().w_full().children(self.render_dock(
 8305                                                DockPosition::Bottom,
 8306                                                &self.bottom_dock,
 8307                                                window,
 8308                                                cx
 8309                                            ))),
 8310
 8311                                        BottomDockLayout::LeftAligned => div()
 8312                                            .flex()
 8313                                            .flex_row()
 8314                                            .h_full()
 8315                                            .child(
 8316                                                div()
 8317                                                    .flex()
 8318                                                    .flex_col()
 8319                                                    .flex_1()
 8320                                                    .h_full()
 8321                                                    .child(
 8322                                                        div()
 8323                                                            .flex()
 8324                                                            .flex_row()
 8325                                                            .flex_1()
 8326                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8327
 8328                                                            .child(
 8329                                                                div()
 8330                                                                    .flex()
 8331                                                                    .flex_col()
 8332                                                                    .flex_1()
 8333                                                                    .overflow_hidden()
 8334                                                                    .child(
 8335                                                                        h_flex()
 8336                                                                            .flex_1()
 8337                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8338                                                                            .child(self.center.render(
 8339                                                                                self.zoomed.as_ref(),
 8340                                                                                &PaneRenderContext {
 8341                                                                                    follower_states:
 8342                                                                                        &self.follower_states,
 8343                                                                                    active_call: self.active_call(),
 8344                                                                                    active_pane: &self.active_pane,
 8345                                                                                    app_state: &self.app_state,
 8346                                                                                    project: &self.project,
 8347                                                                                    workspace: &self.weak_self,
 8348                                                                                },
 8349                                                                                window,
 8350                                                                                cx,
 8351                                                                            ))
 8352                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8353                                                                    )
 8354                                                            )
 8355
 8356                                                    )
 8357                                                    .child(
 8358                                                        div()
 8359                                                            .w_full()
 8360                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8361                                                    ),
 8362                                            )
 8363                                            .children(self.render_dock(
 8364                                                DockPosition::Right,
 8365                                                &self.right_dock,
 8366                                                window,
 8367                                                cx,
 8368                                            )),
 8369                                        BottomDockLayout::RightAligned => div()
 8370                                            .flex()
 8371                                            .flex_row()
 8372                                            .h_full()
 8373                                            .children(self.render_dock(
 8374                                                DockPosition::Left,
 8375                                                &self.left_dock,
 8376                                                window,
 8377                                                cx,
 8378                                            ))
 8379
 8380                                            .child(
 8381                                                div()
 8382                                                    .flex()
 8383                                                    .flex_col()
 8384                                                    .flex_1()
 8385                                                    .h_full()
 8386                                                    .child(
 8387                                                        div()
 8388                                                            .flex()
 8389                                                            .flex_row()
 8390                                                            .flex_1()
 8391                                                            .child(
 8392                                                                div()
 8393                                                                    .flex()
 8394                                                                    .flex_col()
 8395                                                                    .flex_1()
 8396                                                                    .overflow_hidden()
 8397                                                                    .child(
 8398                                                                        h_flex()
 8399                                                                            .flex_1()
 8400                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8401                                                                            .child(self.center.render(
 8402                                                                                self.zoomed.as_ref(),
 8403                                                                                &PaneRenderContext {
 8404                                                                                    follower_states:
 8405                                                                                        &self.follower_states,
 8406                                                                                    active_call: self.active_call(),
 8407                                                                                    active_pane: &self.active_pane,
 8408                                                                                    app_state: &self.app_state,
 8409                                                                                    project: &self.project,
 8410                                                                                    workspace: &self.weak_self,
 8411                                                                                },
 8412                                                                                window,
 8413                                                                                cx,
 8414                                                                            ))
 8415                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8416                                                                    )
 8417                                                            )
 8418
 8419                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8420                                                    )
 8421                                                    .child(
 8422                                                        div()
 8423                                                            .w_full()
 8424                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8425                                                    ),
 8426                                            ),
 8427                                        BottomDockLayout::Contained => div()
 8428                                            .flex()
 8429                                            .flex_row()
 8430                                            .h_full()
 8431                                            .children(self.render_dock(
 8432                                                DockPosition::Left,
 8433                                                &self.left_dock,
 8434                                                window,
 8435                                                cx,
 8436                                            ))
 8437
 8438                                            .child(
 8439                                                div()
 8440                                                    .flex()
 8441                                                    .flex_col()
 8442                                                    .flex_1()
 8443                                                    .overflow_hidden()
 8444                                                    .child(
 8445                                                        h_flex()
 8446                                                            .flex_1()
 8447                                                            .when_some(paddings.0, |this, p| {
 8448                                                                this.child(p.border_r_1())
 8449                                                            })
 8450                                                            .child(self.center.render(
 8451                                                                self.zoomed.as_ref(),
 8452                                                                &PaneRenderContext {
 8453                                                                    follower_states:
 8454                                                                        &self.follower_states,
 8455                                                                    active_call: self.active_call(),
 8456                                                                    active_pane: &self.active_pane,
 8457                                                                    app_state: &self.app_state,
 8458                                                                    project: &self.project,
 8459                                                                    workspace: &self.weak_self,
 8460                                                                },
 8461                                                                window,
 8462                                                                cx,
 8463                                                            ))
 8464                                                            .when_some(paddings.1, |this, p| {
 8465                                                                this.child(p.border_l_1())
 8466                                                            }),
 8467                                                    )
 8468                                                    .children(self.render_dock(
 8469                                                        DockPosition::Bottom,
 8470                                                        &self.bottom_dock,
 8471                                                        window,
 8472                                                        cx,
 8473                                                    )),
 8474                                            )
 8475
 8476                                            .children(self.render_dock(
 8477                                                DockPosition::Right,
 8478                                                &self.right_dock,
 8479                                                window,
 8480                                                cx,
 8481                                            )),
 8482                                    }
 8483                                })
 8484                                .children(self.zoomed.as_ref().and_then(|view| {
 8485                                    let zoomed_view = view.upgrade()?;
 8486                                    let div = div()
 8487                                        .occlude()
 8488                                        .absolute()
 8489                                        .overflow_hidden()
 8490                                        .border_color(colors.border)
 8491                                        .bg(colors.background)
 8492                                        .child(zoomed_view)
 8493                                        .inset_0()
 8494                                        .shadow_lg();
 8495
 8496                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8497                                       return Some(div);
 8498                                    }
 8499
 8500                                    Some(match self.zoomed_position {
 8501                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8502                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8503                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8504                                        None => {
 8505                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8506                                        }
 8507                                    })
 8508                                }))
 8509                                .children(self.render_notifications(window, cx)),
 8510                        )
 8511                        .when(self.status_bar_visible(cx), |parent| {
 8512                            parent.child(self.status_bar.clone())
 8513                        })
 8514                        .child(self.toast_layer.clone()),
 8515                )
 8516    }
 8517}
 8518
 8519impl WorkspaceStore {
 8520    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8521        Self {
 8522            workspaces: Default::default(),
 8523            _subscriptions: vec![
 8524                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8525                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8526            ],
 8527            client,
 8528        }
 8529    }
 8530
 8531    pub fn update_followers(
 8532        &self,
 8533        project_id: Option<u64>,
 8534        update: proto::update_followers::Variant,
 8535        cx: &App,
 8536    ) -> Option<()> {
 8537        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8538        let room_id = active_call.0.room_id(cx)?;
 8539        self.client
 8540            .send(proto::UpdateFollowers {
 8541                room_id,
 8542                project_id,
 8543                variant: Some(update),
 8544            })
 8545            .log_err()
 8546    }
 8547
 8548    pub async fn handle_follow(
 8549        this: Entity<Self>,
 8550        envelope: TypedEnvelope<proto::Follow>,
 8551        mut cx: AsyncApp,
 8552    ) -> Result<proto::FollowResponse> {
 8553        this.update(&mut cx, |this, cx| {
 8554            let follower = Follower {
 8555                project_id: envelope.payload.project_id,
 8556                peer_id: envelope.original_sender_id()?,
 8557            };
 8558
 8559            let mut response = proto::FollowResponse::default();
 8560
 8561            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8562                let Some(workspace) = weak_workspace.upgrade() else {
 8563                    return false;
 8564                };
 8565                window_handle
 8566                    .update(cx, |_, window, cx| {
 8567                        workspace.update(cx, |workspace, cx| {
 8568                            let handler_response =
 8569                                workspace.handle_follow(follower.project_id, window, cx);
 8570                            if let Some(active_view) = handler_response.active_view
 8571                                && workspace.project.read(cx).remote_id() == follower.project_id
 8572                            {
 8573                                response.active_view = Some(active_view)
 8574                            }
 8575                        });
 8576                    })
 8577                    .is_ok()
 8578            });
 8579
 8580            Ok(response)
 8581        })
 8582    }
 8583
 8584    async fn handle_update_followers(
 8585        this: Entity<Self>,
 8586        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8587        mut cx: AsyncApp,
 8588    ) -> Result<()> {
 8589        let leader_id = envelope.original_sender_id()?;
 8590        let update = envelope.payload;
 8591
 8592        this.update(&mut cx, |this, cx| {
 8593            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8594                let Some(workspace) = weak_workspace.upgrade() else {
 8595                    return false;
 8596                };
 8597                window_handle
 8598                    .update(cx, |_, window, cx| {
 8599                        workspace.update(cx, |workspace, cx| {
 8600                            let project_id = workspace.project.read(cx).remote_id();
 8601                            if update.project_id != project_id && update.project_id.is_some() {
 8602                                return;
 8603                            }
 8604                            workspace.handle_update_followers(
 8605                                leader_id,
 8606                                update.clone(),
 8607                                window,
 8608                                cx,
 8609                            );
 8610                        });
 8611                    })
 8612                    .is_ok()
 8613            });
 8614            Ok(())
 8615        })
 8616    }
 8617
 8618    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8619        self.workspaces.iter().map(|(_, weak)| weak)
 8620    }
 8621
 8622    pub fn workspaces_with_windows(
 8623        &self,
 8624    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8625        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8626    }
 8627}
 8628
 8629impl ViewId {
 8630    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8631        Ok(Self {
 8632            creator: message
 8633                .creator
 8634                .map(CollaboratorId::PeerId)
 8635                .context("creator is missing")?,
 8636            id: message.id,
 8637        })
 8638    }
 8639
 8640    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8641        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8642            Some(proto::ViewId {
 8643                creator: Some(peer_id),
 8644                id: self.id,
 8645            })
 8646        } else {
 8647            None
 8648        }
 8649    }
 8650}
 8651
 8652impl FollowerState {
 8653    fn pane(&self) -> &Entity<Pane> {
 8654        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8655    }
 8656}
 8657
 8658pub trait WorkspaceHandle {
 8659    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8660}
 8661
 8662impl WorkspaceHandle for Entity<Workspace> {
 8663    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8664        self.read(cx)
 8665            .worktrees(cx)
 8666            .flat_map(|worktree| {
 8667                let worktree_id = worktree.read(cx).id();
 8668                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8669                    worktree_id,
 8670                    path: f.path.clone(),
 8671                })
 8672            })
 8673            .collect::<Vec<_>>()
 8674    }
 8675}
 8676
 8677pub async fn last_opened_workspace_location(
 8678    db: &WorkspaceDb,
 8679    fs: &dyn fs::Fs,
 8680) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8681    db.last_workspace(fs)
 8682        .await
 8683        .log_err()
 8684        .flatten()
 8685        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8686}
 8687
 8688pub async fn last_session_workspace_locations(
 8689    db: &WorkspaceDb,
 8690    last_session_id: &str,
 8691    last_session_window_stack: Option<Vec<WindowId>>,
 8692    fs: &dyn fs::Fs,
 8693) -> Option<Vec<SessionWorkspace>> {
 8694    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8695        .await
 8696        .log_err()
 8697}
 8698
 8699pub async fn restore_multiworkspace(
 8700    multi_workspace: SerializedMultiWorkspace,
 8701    app_state: Arc<AppState>,
 8702    cx: &mut AsyncApp,
 8703) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8704    let SerializedMultiWorkspace {
 8705        active_workspace,
 8706        state,
 8707    } = multi_workspace;
 8708    let MultiWorkspaceState {
 8709        sidebar_open,
 8710        project_group_keys,
 8711        sidebar_state,
 8712        ..
 8713    } = state;
 8714
 8715    let window_handle = if active_workspace.paths.is_empty() {
 8716        cx.update(|cx| {
 8717            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8718        })
 8719        .await?
 8720    } else {
 8721        let OpenResult { window, .. } = cx
 8722            .update(|cx| {
 8723                Workspace::new_local(
 8724                    active_workspace.paths.paths().to_vec(),
 8725                    app_state.clone(),
 8726                    None,
 8727                    None,
 8728                    None,
 8729                    OpenMode::Activate,
 8730                    cx,
 8731                )
 8732            })
 8733            .await?;
 8734        window
 8735    };
 8736
 8737    if !project_group_keys.is_empty() {
 8738        let restored_keys: Vec<ProjectGroupKey> =
 8739            project_group_keys.into_iter().map(Into::into).collect();
 8740        window_handle
 8741            .update(cx, |multi_workspace, _window, _cx| {
 8742                multi_workspace.restore_project_group_keys(restored_keys);
 8743            })
 8744            .ok();
 8745    }
 8746
 8747    if sidebar_open {
 8748        window_handle
 8749            .update(cx, |multi_workspace, _, cx| {
 8750                multi_workspace.open_sidebar(cx);
 8751            })
 8752            .ok();
 8753    }
 8754
 8755    if let Some(sidebar_state) = sidebar_state {
 8756        window_handle
 8757            .update(cx, |multi_workspace, window, cx| {
 8758                if let Some(sidebar) = multi_workspace.sidebar() {
 8759                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8760                }
 8761                multi_workspace.serialize(cx);
 8762            })
 8763            .ok();
 8764    }
 8765
 8766    window_handle
 8767        .update(cx, |_, window, _cx| {
 8768            window.activate_window();
 8769        })
 8770        .ok();
 8771
 8772    Ok(window_handle)
 8773}
 8774
 8775actions!(
 8776    collab,
 8777    [
 8778        /// Opens the channel notes for the current call.
 8779        ///
 8780        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8781        /// channel in the collab panel.
 8782        ///
 8783        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8784        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8785        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8786        OpenChannelNotes,
 8787        /// Mutes your microphone.
 8788        Mute,
 8789        /// Deafens yourself (mute both microphone and speakers).
 8790        Deafen,
 8791        /// Leaves the current call.
 8792        LeaveCall,
 8793        /// Shares the current project with collaborators.
 8794        ShareProject,
 8795        /// Shares your screen with collaborators.
 8796        ScreenShare,
 8797        /// Copies the current room name and session id for debugging purposes.
 8798        CopyRoomId,
 8799    ]
 8800);
 8801
 8802/// Opens the channel notes for a specific channel by its ID.
 8803#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8804#[action(namespace = collab)]
 8805#[serde(deny_unknown_fields)]
 8806pub struct OpenChannelNotesById {
 8807    pub channel_id: u64,
 8808}
 8809
 8810actions!(
 8811    zed,
 8812    [
 8813        /// Opens the Zed log file.
 8814        OpenLog,
 8815        /// Reveals the Zed log file in the system file manager.
 8816        RevealLogInFileManager
 8817    ]
 8818);
 8819
 8820async fn join_channel_internal(
 8821    channel_id: ChannelId,
 8822    app_state: &Arc<AppState>,
 8823    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8824    requesting_workspace: Option<WeakEntity<Workspace>>,
 8825    active_call: &dyn AnyActiveCall,
 8826    cx: &mut AsyncApp,
 8827) -> Result<bool> {
 8828    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8829        if !active_call.is_in_room(cx) {
 8830            return (false, false);
 8831        }
 8832
 8833        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8834        let should_prompt = active_call.is_sharing_project(cx)
 8835            && active_call.has_remote_participants(cx)
 8836            && !already_in_channel;
 8837        (should_prompt, already_in_channel)
 8838    });
 8839
 8840    if already_in_channel {
 8841        let task = cx.update(|cx| {
 8842            if let Some((project, host)) = active_call.most_active_project(cx) {
 8843                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8844            } else {
 8845                None
 8846            }
 8847        });
 8848        if let Some(task) = task {
 8849            task.await?;
 8850        }
 8851        return anyhow::Ok(true);
 8852    }
 8853
 8854    if should_prompt {
 8855        if let Some(multi_workspace) = requesting_window {
 8856            let answer = multi_workspace
 8857                .update(cx, |_, window, cx| {
 8858                    window.prompt(
 8859                        PromptLevel::Warning,
 8860                        "Do you want to switch channels?",
 8861                        Some("Leaving this call will unshare your current project."),
 8862                        &["Yes, Join Channel", "Cancel"],
 8863                        cx,
 8864                    )
 8865                })?
 8866                .await;
 8867
 8868            if answer == Ok(1) {
 8869                return Ok(false);
 8870            }
 8871        } else {
 8872            return Ok(false);
 8873        }
 8874    }
 8875
 8876    let client = cx.update(|cx| active_call.client(cx));
 8877
 8878    let mut client_status = client.status();
 8879
 8880    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8881    'outer: loop {
 8882        let Some(status) = client_status.recv().await else {
 8883            anyhow::bail!("error connecting");
 8884        };
 8885
 8886        match status {
 8887            Status::Connecting
 8888            | Status::Authenticating
 8889            | Status::Authenticated
 8890            | Status::Reconnecting
 8891            | Status::Reauthenticating
 8892            | Status::Reauthenticated => continue,
 8893            Status::Connected { .. } => break 'outer,
 8894            Status::SignedOut | Status::AuthenticationError => {
 8895                return Err(ErrorCode::SignedOut.into());
 8896            }
 8897            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8898            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8899                return Err(ErrorCode::Disconnected.into());
 8900            }
 8901        }
 8902    }
 8903
 8904    let joined = cx
 8905        .update(|cx| active_call.join_channel(channel_id, cx))
 8906        .await?;
 8907
 8908    if !joined {
 8909        return anyhow::Ok(true);
 8910    }
 8911
 8912    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8913
 8914    let task = cx.update(|cx| {
 8915        if let Some((project, host)) = active_call.most_active_project(cx) {
 8916            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8917        }
 8918
 8919        // If you are the first to join a channel, see if you should share your project.
 8920        if !active_call.has_remote_participants(cx)
 8921            && !active_call.local_participant_is_guest(cx)
 8922            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8923        {
 8924            let project = workspace.update(cx, |workspace, cx| {
 8925                let project = workspace.project.read(cx);
 8926
 8927                if !active_call.share_on_join(cx) {
 8928                    return None;
 8929                }
 8930
 8931                if (project.is_local() || project.is_via_remote_server())
 8932                    && project.visible_worktrees(cx).any(|tree| {
 8933                        tree.read(cx)
 8934                            .root_entry()
 8935                            .is_some_and(|entry| entry.is_dir())
 8936                    })
 8937                {
 8938                    Some(workspace.project.clone())
 8939                } else {
 8940                    None
 8941                }
 8942            });
 8943            if let Some(project) = project {
 8944                let share_task = active_call.share_project(project, cx);
 8945                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8946                    share_task.await?;
 8947                    Ok(())
 8948                }));
 8949            }
 8950        }
 8951
 8952        None
 8953    });
 8954    if let Some(task) = task {
 8955        task.await?;
 8956        return anyhow::Ok(true);
 8957    }
 8958    anyhow::Ok(false)
 8959}
 8960
 8961pub fn join_channel(
 8962    channel_id: ChannelId,
 8963    app_state: Arc<AppState>,
 8964    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8965    requesting_workspace: Option<WeakEntity<Workspace>>,
 8966    cx: &mut App,
 8967) -> Task<Result<()>> {
 8968    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8969    cx.spawn(async move |cx| {
 8970        let result = join_channel_internal(
 8971            channel_id,
 8972            &app_state,
 8973            requesting_window,
 8974            requesting_workspace,
 8975            &*active_call.0,
 8976            cx,
 8977        )
 8978        .await;
 8979
 8980        // join channel succeeded, and opened a window
 8981        if matches!(result, Ok(true)) {
 8982            return anyhow::Ok(());
 8983        }
 8984
 8985        // find an existing workspace to focus and show call controls
 8986        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8987        if active_window.is_none() {
 8988            // no open workspaces, make one to show the error in (blergh)
 8989            let OpenResult {
 8990                window: window_handle,
 8991                ..
 8992            } = cx
 8993                .update(|cx| {
 8994                    Workspace::new_local(
 8995                        vec![],
 8996                        app_state.clone(),
 8997                        requesting_window,
 8998                        None,
 8999                        None,
 9000                        OpenMode::Activate,
 9001                        cx,
 9002                    )
 9003                })
 9004                .await?;
 9005
 9006            window_handle
 9007                .update(cx, |_, window, _cx| {
 9008                    window.activate_window();
 9009                })
 9010                .ok();
 9011
 9012            if result.is_ok() {
 9013                cx.update(|cx| {
 9014                    cx.dispatch_action(&OpenChannelNotes);
 9015                });
 9016            }
 9017
 9018            active_window = Some(window_handle);
 9019        }
 9020
 9021        if let Err(err) = result {
 9022            log::error!("failed to join channel: {}", err);
 9023            if let Some(active_window) = active_window {
 9024                active_window
 9025                    .update(cx, |_, window, cx| {
 9026                        let detail: SharedString = match err.error_code() {
 9027                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9028                            ErrorCode::UpgradeRequired => concat!(
 9029                                "Your are running an unsupported version of Zed. ",
 9030                                "Please update to continue."
 9031                            )
 9032                            .into(),
 9033                            ErrorCode::NoSuchChannel => concat!(
 9034                                "No matching channel was found. ",
 9035                                "Please check the link and try again."
 9036                            )
 9037                            .into(),
 9038                            ErrorCode::Forbidden => concat!(
 9039                                "This channel is private, and you do not have access. ",
 9040                                "Please ask someone to add you and try again."
 9041                            )
 9042                            .into(),
 9043                            ErrorCode::Disconnected => {
 9044                                "Please check your internet connection and try again.".into()
 9045                            }
 9046                            _ => format!("{}\n\nPlease try again.", err).into(),
 9047                        };
 9048                        window.prompt(
 9049                            PromptLevel::Critical,
 9050                            "Failed to join channel",
 9051                            Some(&detail),
 9052                            &["Ok"],
 9053                            cx,
 9054                        )
 9055                    })?
 9056                    .await
 9057                    .ok();
 9058            }
 9059        }
 9060
 9061        // return ok, we showed the error to the user.
 9062        anyhow::Ok(())
 9063    })
 9064}
 9065
 9066pub async fn get_any_active_multi_workspace(
 9067    app_state: Arc<AppState>,
 9068    mut cx: AsyncApp,
 9069) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9070    // find an existing workspace to focus and show call controls
 9071    let active_window = activate_any_workspace_window(&mut cx);
 9072    if active_window.is_none() {
 9073        cx.update(|cx| {
 9074            Workspace::new_local(
 9075                vec![],
 9076                app_state.clone(),
 9077                None,
 9078                None,
 9079                None,
 9080                OpenMode::Activate,
 9081                cx,
 9082            )
 9083        })
 9084        .await?;
 9085    }
 9086    activate_any_workspace_window(&mut cx).context("could not open zed")
 9087}
 9088
 9089fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9090    cx.update(|cx| {
 9091        if let Some(workspace_window) = cx
 9092            .active_window()
 9093            .and_then(|window| window.downcast::<MultiWorkspace>())
 9094        {
 9095            return Some(workspace_window);
 9096        }
 9097
 9098        for window in cx.windows() {
 9099            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9100                workspace_window
 9101                    .update(cx, |_, window, _| window.activate_window())
 9102                    .ok();
 9103                return Some(workspace_window);
 9104            }
 9105        }
 9106        None
 9107    })
 9108}
 9109
 9110pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9111    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9112}
 9113
 9114pub fn workspace_windows_for_location(
 9115    serialized_location: &SerializedWorkspaceLocation,
 9116    cx: &App,
 9117) -> Vec<WindowHandle<MultiWorkspace>> {
 9118    cx.windows()
 9119        .into_iter()
 9120        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9121        .filter(|multi_workspace| {
 9122            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9123                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9124                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9125                }
 9126                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9127                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9128                    a.distro_name == b.distro_name
 9129                }
 9130                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9131                    a.container_id == b.container_id
 9132                }
 9133                #[cfg(any(test, feature = "test-support"))]
 9134                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9135                    a.id == b.id
 9136                }
 9137                _ => false,
 9138            };
 9139
 9140            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9141                multi_workspace.workspaces().any(|workspace| {
 9142                    match workspace.read(cx).workspace_location(cx) {
 9143                        WorkspaceLocation::Location(location, _) => {
 9144                            match (&location, serialized_location) {
 9145                                (
 9146                                    SerializedWorkspaceLocation::Local,
 9147                                    SerializedWorkspaceLocation::Local,
 9148                                ) => true,
 9149                                (
 9150                                    SerializedWorkspaceLocation::Remote(a),
 9151                                    SerializedWorkspaceLocation::Remote(b),
 9152                                ) => same_host(a, b),
 9153                                _ => false,
 9154                            }
 9155                        }
 9156                        _ => false,
 9157                    }
 9158                })
 9159            })
 9160        })
 9161        .collect()
 9162}
 9163
 9164pub async fn find_existing_workspace(
 9165    abs_paths: &[PathBuf],
 9166    open_options: &OpenOptions,
 9167    location: &SerializedWorkspaceLocation,
 9168    cx: &mut AsyncApp,
 9169) -> (
 9170    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9171    OpenVisible,
 9172) {
 9173    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9174    let mut open_visible = OpenVisible::All;
 9175    let mut best_match = None;
 9176
 9177    cx.update(|cx| {
 9178        for window in workspace_windows_for_location(location, cx) {
 9179            if let Ok(multi_workspace) = window.read(cx) {
 9180                for workspace in multi_workspace.workspaces() {
 9181                    let project = workspace.read(cx).project.read(cx);
 9182                    let m = project.visibility_for_paths(
 9183                        abs_paths,
 9184                        open_options.open_new_workspace == None,
 9185                        cx,
 9186                    );
 9187                    if m > best_match {
 9188                        existing = Some((window, workspace.clone()));
 9189                        best_match = m;
 9190                    } else if best_match.is_none() && open_options.open_new_workspace == Some(false)
 9191                    {
 9192                        existing = Some((window, workspace.clone()))
 9193                    }
 9194                }
 9195            }
 9196        }
 9197    });
 9198
 9199    // With -n, only reuse a window if the path is genuinely contained
 9200    // within an existing worktree (don't fall back to any arbitrary window).
 9201    if open_options.open_new_workspace == Some(true) && best_match.is_none() {
 9202        existing = None;
 9203    }
 9204
 9205    if open_options.open_new_workspace != Some(true) {
 9206        let all_paths_are_files = existing
 9207            .as_ref()
 9208            .and_then(|(_, target_workspace)| {
 9209                cx.update(|cx| {
 9210                    let workspace = target_workspace.read(cx);
 9211                    let project = workspace.project.read(cx);
 9212                    let path_style = workspace.path_style(cx);
 9213                    Some(!abs_paths.iter().any(|path| {
 9214                        let path = util::paths::SanitizedPath::new(path);
 9215                        project.worktrees(cx).any(|worktree| {
 9216                            let worktree = worktree.read(cx);
 9217                            let abs_path = worktree.abs_path();
 9218                            path_style
 9219                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9220                                .and_then(|rel| worktree.entry_for_path(&rel))
 9221                                .is_some_and(|e| e.is_dir())
 9222                        })
 9223                    }))
 9224                })
 9225            })
 9226            .unwrap_or(false);
 9227
 9228        if open_options.open_new_workspace.is_none()
 9229            && existing.is_some()
 9230            && open_options.wait
 9231            && all_paths_are_files
 9232        {
 9233            cx.update(|cx| {
 9234                let windows = workspace_windows_for_location(location, cx);
 9235                let window = cx
 9236                    .active_window()
 9237                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9238                    .filter(|window| windows.contains(window))
 9239                    .or_else(|| windows.into_iter().next());
 9240                if let Some(window) = window {
 9241                    if let Ok(multi_workspace) = window.read(cx) {
 9242                        let active_workspace = multi_workspace.workspace().clone();
 9243                        existing = Some((window, active_workspace));
 9244                        open_visible = OpenVisible::None;
 9245                    }
 9246                }
 9247            });
 9248        }
 9249    }
 9250    (existing, open_visible)
 9251}
 9252
 9253#[derive(Default, Clone)]
 9254pub struct OpenOptions {
 9255    pub visible: Option<OpenVisible>,
 9256    pub focus: Option<bool>,
 9257    pub open_new_workspace: Option<bool>,
 9258    pub wait: bool,
 9259    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9260    pub open_mode: OpenMode,
 9261    pub env: Option<HashMap<String, String>>,
 9262    pub open_in_dev_container: bool,
 9263}
 9264
 9265/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9266/// or [`Workspace::open_workspace_for_paths`].
 9267pub struct OpenResult {
 9268    pub window: WindowHandle<MultiWorkspace>,
 9269    pub workspace: Entity<Workspace>,
 9270    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9271}
 9272
 9273/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9274pub fn open_workspace_by_id(
 9275    workspace_id: WorkspaceId,
 9276    app_state: Arc<AppState>,
 9277    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9278    cx: &mut App,
 9279) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9280    let project_handle = Project::local(
 9281        app_state.client.clone(),
 9282        app_state.node_runtime.clone(),
 9283        app_state.user_store.clone(),
 9284        app_state.languages.clone(),
 9285        app_state.fs.clone(),
 9286        None,
 9287        project::LocalProjectFlags {
 9288            init_worktree_trust: true,
 9289            ..project::LocalProjectFlags::default()
 9290        },
 9291        cx,
 9292    );
 9293
 9294    let db = WorkspaceDb::global(cx);
 9295    let kvp = db::kvp::KeyValueStore::global(cx);
 9296    cx.spawn(async move |cx| {
 9297        let serialized_workspace = db
 9298            .workspace_for_id(workspace_id)
 9299            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9300
 9301        let centered_layout = serialized_workspace.centered_layout;
 9302
 9303        let (window, workspace) = if let Some(window) = requesting_window {
 9304            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9305                let workspace = cx.new(|cx| {
 9306                    let mut workspace = Workspace::new(
 9307                        Some(workspace_id),
 9308                        project_handle.clone(),
 9309                        app_state.clone(),
 9310                        window,
 9311                        cx,
 9312                    );
 9313                    workspace.centered_layout = centered_layout;
 9314                    workspace
 9315                });
 9316                multi_workspace.add(workspace.clone(), &*window, cx);
 9317                workspace
 9318            })?;
 9319            (window, workspace)
 9320        } else {
 9321            let window_bounds_override = window_bounds_env_override();
 9322
 9323            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9324                (Some(WindowBounds::Windowed(bounds)), None)
 9325            } else if let Some(display) = serialized_workspace.display
 9326                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9327            {
 9328                (Some(bounds.0), Some(display))
 9329            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9330                (Some(bounds), Some(display))
 9331            } else {
 9332                (None, None)
 9333            };
 9334
 9335            let options = cx.update(|cx| {
 9336                let mut options = (app_state.build_window_options)(display, cx);
 9337                options.window_bounds = window_bounds;
 9338                options
 9339            });
 9340
 9341            let window = cx.open_window(options, {
 9342                let app_state = app_state.clone();
 9343                let project_handle = project_handle.clone();
 9344                move |window, cx| {
 9345                    let workspace = cx.new(|cx| {
 9346                        let mut workspace = Workspace::new(
 9347                            Some(workspace_id),
 9348                            project_handle,
 9349                            app_state,
 9350                            window,
 9351                            cx,
 9352                        );
 9353                        workspace.centered_layout = centered_layout;
 9354                        workspace
 9355                    });
 9356                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9357                }
 9358            })?;
 9359
 9360            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9361                multi_workspace.workspace().clone()
 9362            })?;
 9363
 9364            (window, workspace)
 9365        };
 9366
 9367        notify_if_database_failed(window, cx);
 9368
 9369        // Restore items from the serialized workspace
 9370        window
 9371            .update(cx, |_, window, cx| {
 9372                workspace.update(cx, |_workspace, cx| {
 9373                    open_items(Some(serialized_workspace), vec![], window, cx)
 9374                })
 9375            })?
 9376            .await?;
 9377
 9378        window.update(cx, |_, window, cx| {
 9379            workspace.update(cx, |workspace, cx| {
 9380                workspace.serialize_workspace(window, cx);
 9381            });
 9382        })?;
 9383
 9384        Ok(window)
 9385    })
 9386}
 9387
 9388#[allow(clippy::type_complexity)]
 9389pub fn open_paths(
 9390    abs_paths: &[PathBuf],
 9391    app_state: Arc<AppState>,
 9392    mut open_options: OpenOptions,
 9393    cx: &mut App,
 9394) -> Task<anyhow::Result<OpenResult>> {
 9395    let abs_paths = abs_paths.to_vec();
 9396    #[cfg(target_os = "windows")]
 9397    let wsl_path = abs_paths
 9398        .iter()
 9399        .find_map(|p| util::paths::WslPath::from_path(p));
 9400
 9401    cx.spawn(async move |cx| {
 9402        let (mut existing, mut open_visible) = find_existing_workspace(
 9403            &abs_paths,
 9404            &open_options,
 9405            &SerializedWorkspaceLocation::Local,
 9406            cx,
 9407        )
 9408        .await;
 9409
 9410        // Fallback: if no workspace contains the paths and all paths are files,
 9411        // prefer an existing local workspace window (active window first).
 9412        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9413            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9414            let all_metadatas = futures::future::join_all(all_paths)
 9415                .await
 9416                .into_iter()
 9417                .filter_map(|result| result.ok().flatten());
 9418
 9419            if all_metadatas.into_iter().all(|file| !file.is_dir) {
 9420                cx.update(|cx| {
 9421                    let windows = workspace_windows_for_location(
 9422                        &SerializedWorkspaceLocation::Local,
 9423                        cx,
 9424                    );
 9425                    let window = cx
 9426                        .active_window()
 9427                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9428                        .filter(|window| windows.contains(window))
 9429                        .or_else(|| windows.into_iter().next());
 9430                    if let Some(window) = window {
 9431                        if let Ok(multi_workspace) = window.read(cx) {
 9432                            let active_workspace = multi_workspace.workspace().clone();
 9433                            existing = Some((window, active_workspace));
 9434                            open_visible = OpenVisible::None;
 9435                        }
 9436                    }
 9437                });
 9438            }
 9439        }
 9440
 9441        // Fallback for directories: when no flag is specified and no existing
 9442        // workspace matched, add the directory as a new workspace in the
 9443        // active window's MultiWorkspace (instead of opening a new window).
 9444        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9445            let target_window = cx.update(|cx| {
 9446                let windows = workspace_windows_for_location(
 9447                    &SerializedWorkspaceLocation::Local,
 9448                    cx,
 9449                );
 9450                let window = cx
 9451                    .active_window()
 9452                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9453                    .filter(|window| windows.contains(window))
 9454                    .or_else(|| windows.into_iter().next());
 9455                window.filter(|window| {
 9456                    window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
 9457                })
 9458            });
 9459
 9460            if let Some(window) = target_window {
 9461                open_options.requesting_window = Some(window);
 9462                window
 9463                    .update(cx, |multi_workspace, _, cx| {
 9464                        multi_workspace.open_sidebar(cx);
 9465                    })
 9466                    .log_err();
 9467            }
 9468        }
 9469
 9470        let open_in_dev_container = open_options.open_in_dev_container;
 9471
 9472        let result = if let Some((existing, target_workspace)) = existing {
 9473            let open_task = existing
 9474                .update(cx, |multi_workspace, window, cx| {
 9475                    window.activate_window();
 9476                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9477                    target_workspace.update(cx, |workspace, cx| {
 9478                        if open_in_dev_container {
 9479                            workspace.set_open_in_dev_container(true);
 9480                        }
 9481                        workspace.open_paths(
 9482                            abs_paths,
 9483                            OpenOptions {
 9484                                visible: Some(open_visible),
 9485                                ..Default::default()
 9486                            },
 9487                            None,
 9488                            window,
 9489                            cx,
 9490                        )
 9491                    })
 9492                })?
 9493                .await;
 9494
 9495            _ = existing.update(cx, |multi_workspace, _, cx| {
 9496                let workspace = multi_workspace.workspace().clone();
 9497                workspace.update(cx, |workspace, cx| {
 9498                    for item in open_task.iter().flatten() {
 9499                        if let Err(e) = item {
 9500                            workspace.show_error(&e, cx);
 9501                        }
 9502                    }
 9503                });
 9504            });
 9505
 9506            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9507        } else {
 9508            let init = if open_in_dev_container {
 9509                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9510                    workspace.set_open_in_dev_container(true);
 9511                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9512            } else {
 9513                None
 9514            };
 9515            let result = cx
 9516                .update(move |cx| {
 9517                    Workspace::new_local(
 9518                        abs_paths,
 9519                        app_state.clone(),
 9520                        open_options.requesting_window,
 9521                        open_options.env,
 9522                        init,
 9523                        open_options.open_mode,
 9524                        cx,
 9525                    )
 9526                })
 9527                .await;
 9528
 9529            if let Ok(ref result) = result {
 9530                result.window
 9531                    .update(cx, |_, window, _cx| {
 9532                        window.activate_window();
 9533                    })
 9534                    .log_err();
 9535            }
 9536
 9537            result
 9538        };
 9539
 9540        #[cfg(target_os = "windows")]
 9541        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9542            && let Ok(ref result) = result
 9543        {
 9544            result.window
 9545                .update(cx, move |multi_workspace, _window, cx| {
 9546                    struct OpenInWsl;
 9547                    let workspace = multi_workspace.workspace().clone();
 9548                    workspace.update(cx, |workspace, cx| {
 9549                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9550                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9551                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9552                            cx.new(move |cx| {
 9553                                MessageNotification::new(msg, cx)
 9554                                    .primary_message("Open in WSL")
 9555                                    .primary_icon(IconName::FolderOpen)
 9556                                    .primary_on_click(move |window, cx| {
 9557                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9558                                                distro: remote::WslConnectionOptions {
 9559                                                        distro_name: distro.clone(),
 9560                                                    user: None,
 9561                                                },
 9562                                                paths: vec![path.clone().into()],
 9563                                            }), cx)
 9564                                    })
 9565                            })
 9566                        });
 9567                    });
 9568                })
 9569                .unwrap();
 9570        };
 9571        result
 9572    })
 9573}
 9574
 9575pub fn open_new(
 9576    open_options: OpenOptions,
 9577    app_state: Arc<AppState>,
 9578    cx: &mut App,
 9579    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9580) -> Task<anyhow::Result<()>> {
 9581    let addition = open_options.open_mode;
 9582    let task = Workspace::new_local(
 9583        Vec::new(),
 9584        app_state,
 9585        open_options.requesting_window,
 9586        open_options.env,
 9587        Some(Box::new(init)),
 9588        addition,
 9589        cx,
 9590    );
 9591    cx.spawn(async move |cx| {
 9592        let OpenResult { window, .. } = task.await?;
 9593        window
 9594            .update(cx, |_, window, _cx| {
 9595                window.activate_window();
 9596            })
 9597            .ok();
 9598        Ok(())
 9599    })
 9600}
 9601
 9602pub fn create_and_open_local_file(
 9603    path: &'static Path,
 9604    window: &mut Window,
 9605    cx: &mut Context<Workspace>,
 9606    default_content: impl 'static + Send + FnOnce() -> Rope,
 9607) -> Task<Result<Box<dyn ItemHandle>>> {
 9608    cx.spawn_in(window, async move |workspace, cx| {
 9609        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9610        if !fs.is_file(path).await {
 9611            fs.create_file(path, Default::default()).await?;
 9612            fs.save(path, &default_content(), Default::default())
 9613                .await?;
 9614        }
 9615
 9616        workspace
 9617            .update_in(cx, |workspace, window, cx| {
 9618                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9619                    let path = workspace
 9620                        .project
 9621                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9622                    cx.spawn_in(window, async move |workspace, cx| {
 9623                        let path = path.await?;
 9624
 9625                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9626
 9627                        let mut items = workspace
 9628                            .update_in(cx, |workspace, window, cx| {
 9629                                workspace.open_paths(
 9630                                    vec![path.to_path_buf()],
 9631                                    OpenOptions {
 9632                                        visible: Some(OpenVisible::None),
 9633                                        ..Default::default()
 9634                                    },
 9635                                    None,
 9636                                    window,
 9637                                    cx,
 9638                                )
 9639                            })?
 9640                            .await;
 9641                        let item = items.pop().flatten();
 9642                        item.with_context(|| format!("path {path:?} is not a file"))?
 9643                    })
 9644                })
 9645            })?
 9646            .await?
 9647            .await
 9648    })
 9649}
 9650
 9651pub fn open_remote_project_with_new_connection(
 9652    window: WindowHandle<MultiWorkspace>,
 9653    remote_connection: Arc<dyn RemoteConnection>,
 9654    cancel_rx: oneshot::Receiver<()>,
 9655    delegate: Arc<dyn RemoteClientDelegate>,
 9656    app_state: Arc<AppState>,
 9657    paths: Vec<PathBuf>,
 9658    cx: &mut App,
 9659) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9660    cx.spawn(async move |cx| {
 9661        let (workspace_id, serialized_workspace) =
 9662            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9663                .await?;
 9664
 9665        let session = match cx
 9666            .update(|cx| {
 9667                remote::RemoteClient::new(
 9668                    ConnectionIdentifier::Workspace(workspace_id.0),
 9669                    remote_connection,
 9670                    cancel_rx,
 9671                    delegate,
 9672                    cx,
 9673                )
 9674            })
 9675            .await?
 9676        {
 9677            Some(result) => result,
 9678            None => return Ok(Vec::new()),
 9679        };
 9680
 9681        let project = cx.update(|cx| {
 9682            project::Project::remote(
 9683                session,
 9684                app_state.client.clone(),
 9685                app_state.node_runtime.clone(),
 9686                app_state.user_store.clone(),
 9687                app_state.languages.clone(),
 9688                app_state.fs.clone(),
 9689                true,
 9690                cx,
 9691            )
 9692        });
 9693
 9694        open_remote_project_inner(
 9695            project,
 9696            paths,
 9697            workspace_id,
 9698            serialized_workspace,
 9699            app_state,
 9700            window,
 9701            cx,
 9702        )
 9703        .await
 9704    })
 9705}
 9706
 9707pub fn open_remote_project_with_existing_connection(
 9708    connection_options: RemoteConnectionOptions,
 9709    project: Entity<Project>,
 9710    paths: Vec<PathBuf>,
 9711    app_state: Arc<AppState>,
 9712    window: WindowHandle<MultiWorkspace>,
 9713    cx: &mut AsyncApp,
 9714) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9715    cx.spawn(async move |cx| {
 9716        let (workspace_id, serialized_workspace) =
 9717            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9718
 9719        open_remote_project_inner(
 9720            project,
 9721            paths,
 9722            workspace_id,
 9723            serialized_workspace,
 9724            app_state,
 9725            window,
 9726            cx,
 9727        )
 9728        .await
 9729    })
 9730}
 9731
 9732async fn open_remote_project_inner(
 9733    project: Entity<Project>,
 9734    paths: Vec<PathBuf>,
 9735    workspace_id: WorkspaceId,
 9736    serialized_workspace: Option<SerializedWorkspace>,
 9737    app_state: Arc<AppState>,
 9738    window: WindowHandle<MultiWorkspace>,
 9739    cx: &mut AsyncApp,
 9740) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9741    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9742    let toolchains = db.toolchains(workspace_id).await?;
 9743    for (toolchain, worktree_path, path) in toolchains {
 9744        project
 9745            .update(cx, |this, cx| {
 9746                let Some(worktree_id) =
 9747                    this.find_worktree(&worktree_path, cx)
 9748                        .and_then(|(worktree, rel_path)| {
 9749                            if rel_path.is_empty() {
 9750                                Some(worktree.read(cx).id())
 9751                            } else {
 9752                                None
 9753                            }
 9754                        })
 9755                else {
 9756                    return Task::ready(None);
 9757                };
 9758
 9759                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9760            })
 9761            .await;
 9762    }
 9763    let mut project_paths_to_open = vec![];
 9764    let mut project_path_errors = vec![];
 9765
 9766    for path in paths {
 9767        let result = cx
 9768            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9769            .await;
 9770        match result {
 9771            Ok((_, project_path)) => {
 9772                project_paths_to_open.push((path.clone(), Some(project_path)));
 9773            }
 9774            Err(error) => {
 9775                project_path_errors.push(error);
 9776            }
 9777        };
 9778    }
 9779
 9780    if project_paths_to_open.is_empty() {
 9781        return Err(project_path_errors.pop().context("no paths given")?);
 9782    }
 9783
 9784    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9785        telemetry::event!("SSH Project Opened");
 9786
 9787        let new_workspace = cx.new(|cx| {
 9788            let mut workspace =
 9789                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9790            workspace.update_history(cx);
 9791
 9792            if let Some(ref serialized) = serialized_workspace {
 9793                workspace.centered_layout = serialized.centered_layout;
 9794            }
 9795
 9796            workspace
 9797        });
 9798
 9799        multi_workspace.activate(new_workspace.clone(), window, cx);
 9800        new_workspace
 9801    })?;
 9802
 9803    let items = window
 9804        .update(cx, |_, window, cx| {
 9805            window.activate_window();
 9806            workspace.update(cx, |_workspace, cx| {
 9807                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9808            })
 9809        })?
 9810        .await?;
 9811
 9812    workspace.update(cx, |workspace, cx| {
 9813        for error in project_path_errors {
 9814            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9815                if let Some(path) = error.error_tag("path") {
 9816                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9817                }
 9818            } else {
 9819                workspace.show_error(&error, cx)
 9820            }
 9821        }
 9822    });
 9823
 9824    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9825}
 9826
 9827fn deserialize_remote_project(
 9828    connection_options: RemoteConnectionOptions,
 9829    paths: Vec<PathBuf>,
 9830    cx: &AsyncApp,
 9831) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9832    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9833    cx.background_spawn(async move {
 9834        let remote_connection_id = db
 9835            .get_or_create_remote_connection(connection_options)
 9836            .await?;
 9837
 9838        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9839
 9840        let workspace_id = if let Some(workspace_id) =
 9841            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9842        {
 9843            workspace_id
 9844        } else {
 9845            db.next_id().await?
 9846        };
 9847
 9848        Ok((workspace_id, serialized_workspace))
 9849    })
 9850}
 9851
 9852pub fn join_in_room_project(
 9853    project_id: u64,
 9854    follow_user_id: u64,
 9855    app_state: Arc<AppState>,
 9856    cx: &mut App,
 9857) -> Task<Result<()>> {
 9858    let windows = cx.windows();
 9859    cx.spawn(async move |cx| {
 9860        let existing_window_and_workspace: Option<(
 9861            WindowHandle<MultiWorkspace>,
 9862            Entity<Workspace>,
 9863        )> = windows.into_iter().find_map(|window_handle| {
 9864            window_handle
 9865                .downcast::<MultiWorkspace>()
 9866                .and_then(|window_handle| {
 9867                    window_handle
 9868                        .update(cx, |multi_workspace, _window, cx| {
 9869                            for workspace in multi_workspace.workspaces() {
 9870                                if workspace.read(cx).project().read(cx).remote_id()
 9871                                    == Some(project_id)
 9872                                {
 9873                                    return Some((window_handle, workspace.clone()));
 9874                                }
 9875                            }
 9876                            None
 9877                        })
 9878                        .unwrap_or(None)
 9879                })
 9880        });
 9881
 9882        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9883            existing_window_and_workspace
 9884        {
 9885            existing_window
 9886                .update(cx, |multi_workspace, window, cx| {
 9887                    multi_workspace.activate(target_workspace, window, cx);
 9888                })
 9889                .ok();
 9890            existing_window
 9891        } else {
 9892            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9893            let project = cx
 9894                .update(|cx| {
 9895                    active_call.0.join_project(
 9896                        project_id,
 9897                        app_state.languages.clone(),
 9898                        app_state.fs.clone(),
 9899                        cx,
 9900                    )
 9901                })
 9902                .await?;
 9903
 9904            let window_bounds_override = window_bounds_env_override();
 9905            cx.update(|cx| {
 9906                let mut options = (app_state.build_window_options)(None, cx);
 9907                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9908                cx.open_window(options, |window, cx| {
 9909                    let workspace = cx.new(|cx| {
 9910                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9911                    });
 9912                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9913                })
 9914            })?
 9915        };
 9916
 9917        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9918            cx.activate(true);
 9919            window.activate_window();
 9920
 9921            // We set the active workspace above, so this is the correct workspace.
 9922            let workspace = multi_workspace.workspace().clone();
 9923            workspace.update(cx, |workspace, cx| {
 9924                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9925                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9926                    .or_else(|| {
 9927                        // If we couldn't follow the given user, follow the host instead.
 9928                        let collaborator = workspace
 9929                            .project()
 9930                            .read(cx)
 9931                            .collaborators()
 9932                            .values()
 9933                            .find(|collaborator| collaborator.is_host)?;
 9934                        Some(collaborator.peer_id)
 9935                    });
 9936
 9937                if let Some(follow_peer_id) = follow_peer_id {
 9938                    workspace.follow(follow_peer_id, window, cx);
 9939                }
 9940            });
 9941        })?;
 9942
 9943        anyhow::Ok(())
 9944    })
 9945}
 9946
 9947pub fn reload(cx: &mut App) {
 9948    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9949    let mut workspace_windows = cx
 9950        .windows()
 9951        .into_iter()
 9952        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9953        .collect::<Vec<_>>();
 9954
 9955    // If multiple windows have unsaved changes, and need a save prompt,
 9956    // prompt in the active window before switching to a different window.
 9957    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9958
 9959    let mut prompt = None;
 9960    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9961        prompt = window
 9962            .update(cx, |_, window, cx| {
 9963                window.prompt(
 9964                    PromptLevel::Info,
 9965                    "Are you sure you want to restart?",
 9966                    None,
 9967                    &["Restart", "Cancel"],
 9968                    cx,
 9969                )
 9970            })
 9971            .ok();
 9972    }
 9973
 9974    cx.spawn(async move |cx| {
 9975        if let Some(prompt) = prompt {
 9976            let answer = prompt.await?;
 9977            if answer != 0 {
 9978                return anyhow::Ok(());
 9979            }
 9980        }
 9981
 9982        // If the user cancels any save prompt, then keep the app open.
 9983        for window in workspace_windows {
 9984            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9985                let workspace = multi_workspace.workspace().clone();
 9986                workspace.update(cx, |workspace, cx| {
 9987                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9988                })
 9989            }) && !should_close.await?
 9990            {
 9991                return anyhow::Ok(());
 9992            }
 9993        }
 9994        cx.update(|cx| cx.restart());
 9995        anyhow::Ok(())
 9996    })
 9997    .detach_and_log_err(cx);
 9998}
 9999
10000fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10001    let mut parts = value.split(',');
10002    let x: usize = parts.next()?.parse().ok()?;
10003    let y: usize = parts.next()?.parse().ok()?;
10004    Some(point(px(x as f32), px(y as f32)))
10005}
10006
10007fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10008    let mut parts = value.split(',');
10009    let width: usize = parts.next()?.parse().ok()?;
10010    let height: usize = parts.next()?.parse().ok()?;
10011    Some(size(px(width as f32), px(height as f32)))
10012}
10013
10014/// Add client-side decorations (rounded corners, shadows, resize handling) when
10015/// appropriate.
10016///
10017/// The `border_radius_tiling` parameter allows overriding which corners get
10018/// rounded, independently of the actual window tiling state. This is used
10019/// specifically for the workspace switcher sidebar: when the sidebar is open,
10020/// we want square corners on the left (so the sidebar appears flush with the
10021/// window edge) but we still need the shadow padding for proper visual
10022/// appearance. Unlike actual window tiling, this only affects border radius -
10023/// not padding or shadows.
10024pub fn client_side_decorations(
10025    element: impl IntoElement,
10026    window: &mut Window,
10027    cx: &mut App,
10028    border_radius_tiling: Tiling,
10029) -> Stateful<Div> {
10030    const BORDER_SIZE: Pixels = px(1.0);
10031    let decorations = window.window_decorations();
10032    let tiling = match decorations {
10033        Decorations::Server => Tiling::default(),
10034        Decorations::Client { tiling } => tiling,
10035    };
10036
10037    match decorations {
10038        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10039        Decorations::Server => window.set_client_inset(px(0.0)),
10040    }
10041
10042    struct GlobalResizeEdge(ResizeEdge);
10043    impl Global for GlobalResizeEdge {}
10044
10045    div()
10046        .id("window-backdrop")
10047        .bg(transparent_black())
10048        .map(|div| match decorations {
10049            Decorations::Server => div,
10050            Decorations::Client { .. } => div
10051                .when(
10052                    !(tiling.top
10053                        || tiling.right
10054                        || border_radius_tiling.top
10055                        || border_radius_tiling.right),
10056                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10057                )
10058                .when(
10059                    !(tiling.top
10060                        || tiling.left
10061                        || border_radius_tiling.top
10062                        || border_radius_tiling.left),
10063                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10064                )
10065                .when(
10066                    !(tiling.bottom
10067                        || tiling.right
10068                        || border_radius_tiling.bottom
10069                        || border_radius_tiling.right),
10070                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10071                )
10072                .when(
10073                    !(tiling.bottom
10074                        || tiling.left
10075                        || border_radius_tiling.bottom
10076                        || border_radius_tiling.left),
10077                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10078                )
10079                .when(!tiling.top, |div| {
10080                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10081                })
10082                .when(!tiling.bottom, |div| {
10083                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10084                })
10085                .when(!tiling.left, |div| {
10086                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10087                })
10088                .when(!tiling.right, |div| {
10089                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10090                })
10091                .on_mouse_move(move |e, window, cx| {
10092                    let size = window.window_bounds().get_bounds().size;
10093                    let pos = e.position;
10094
10095                    let new_edge =
10096                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10097
10098                    let edge = cx.try_global::<GlobalResizeEdge>();
10099                    if new_edge != edge.map(|edge| edge.0) {
10100                        window
10101                            .window_handle()
10102                            .update(cx, |workspace, _, cx| {
10103                                cx.notify(workspace.entity_id());
10104                            })
10105                            .ok();
10106                    }
10107                })
10108                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10109                    let size = window.window_bounds().get_bounds().size;
10110                    let pos = e.position;
10111
10112                    let edge = match resize_edge(
10113                        pos,
10114                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10115                        size,
10116                        tiling,
10117                    ) {
10118                        Some(value) => value,
10119                        None => return,
10120                    };
10121
10122                    window.start_window_resize(edge);
10123                }),
10124        })
10125        .size_full()
10126        .child(
10127            div()
10128                .cursor(CursorStyle::Arrow)
10129                .map(|div| match decorations {
10130                    Decorations::Server => div,
10131                    Decorations::Client { .. } => div
10132                        .border_color(cx.theme().colors().border)
10133                        .when(
10134                            !(tiling.top
10135                                || tiling.right
10136                                || border_radius_tiling.top
10137                                || border_radius_tiling.right),
10138                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10139                        )
10140                        .when(
10141                            !(tiling.top
10142                                || tiling.left
10143                                || border_radius_tiling.top
10144                                || border_radius_tiling.left),
10145                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10146                        )
10147                        .when(
10148                            !(tiling.bottom
10149                                || tiling.right
10150                                || border_radius_tiling.bottom
10151                                || border_radius_tiling.right),
10152                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10153                        )
10154                        .when(
10155                            !(tiling.bottom
10156                                || tiling.left
10157                                || border_radius_tiling.bottom
10158                                || border_radius_tiling.left),
10159                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10160                        )
10161                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10162                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10163                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10164                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10165                        .when(!tiling.is_tiled(), |div| {
10166                            div.shadow(vec![gpui::BoxShadow {
10167                                color: Hsla {
10168                                    h: 0.,
10169                                    s: 0.,
10170                                    l: 0.,
10171                                    a: 0.4,
10172                                },
10173                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10174                                spread_radius: px(0.),
10175                                offset: point(px(0.0), px(0.0)),
10176                            }])
10177                        }),
10178                })
10179                .on_mouse_move(|_e, _, cx| {
10180                    cx.stop_propagation();
10181                })
10182                .size_full()
10183                .child(element),
10184        )
10185        .map(|div| match decorations {
10186            Decorations::Server => div,
10187            Decorations::Client { tiling, .. } => div.child(
10188                canvas(
10189                    |_bounds, window, _| {
10190                        window.insert_hitbox(
10191                            Bounds::new(
10192                                point(px(0.0), px(0.0)),
10193                                window.window_bounds().get_bounds().size,
10194                            ),
10195                            HitboxBehavior::Normal,
10196                        )
10197                    },
10198                    move |_bounds, hitbox, window, cx| {
10199                        let mouse = window.mouse_position();
10200                        let size = window.window_bounds().get_bounds().size;
10201                        let Some(edge) =
10202                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10203                        else {
10204                            return;
10205                        };
10206                        cx.set_global(GlobalResizeEdge(edge));
10207                        window.set_cursor_style(
10208                            match edge {
10209                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10210                                ResizeEdge::Left | ResizeEdge::Right => {
10211                                    CursorStyle::ResizeLeftRight
10212                                }
10213                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10214                                    CursorStyle::ResizeUpLeftDownRight
10215                                }
10216                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10217                                    CursorStyle::ResizeUpRightDownLeft
10218                                }
10219                            },
10220                            &hitbox,
10221                        );
10222                    },
10223                )
10224                .size_full()
10225                .absolute(),
10226            ),
10227        })
10228}
10229
10230fn resize_edge(
10231    pos: Point<Pixels>,
10232    shadow_size: Pixels,
10233    window_size: Size<Pixels>,
10234    tiling: Tiling,
10235) -> Option<ResizeEdge> {
10236    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10237    if bounds.contains(&pos) {
10238        return None;
10239    }
10240
10241    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10242    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10243    if !tiling.top && top_left_bounds.contains(&pos) {
10244        return Some(ResizeEdge::TopLeft);
10245    }
10246
10247    let top_right_bounds = Bounds::new(
10248        Point::new(window_size.width - corner_size.width, px(0.)),
10249        corner_size,
10250    );
10251    if !tiling.top && top_right_bounds.contains(&pos) {
10252        return Some(ResizeEdge::TopRight);
10253    }
10254
10255    let bottom_left_bounds = Bounds::new(
10256        Point::new(px(0.), window_size.height - corner_size.height),
10257        corner_size,
10258    );
10259    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10260        return Some(ResizeEdge::BottomLeft);
10261    }
10262
10263    let bottom_right_bounds = Bounds::new(
10264        Point::new(
10265            window_size.width - corner_size.width,
10266            window_size.height - corner_size.height,
10267        ),
10268        corner_size,
10269    );
10270    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10271        return Some(ResizeEdge::BottomRight);
10272    }
10273
10274    if !tiling.top && pos.y < shadow_size {
10275        Some(ResizeEdge::Top)
10276    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10277        Some(ResizeEdge::Bottom)
10278    } else if !tiling.left && pos.x < shadow_size {
10279        Some(ResizeEdge::Left)
10280    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10281        Some(ResizeEdge::Right)
10282    } else {
10283        None
10284    }
10285}
10286
10287fn join_pane_into_active(
10288    active_pane: &Entity<Pane>,
10289    pane: &Entity<Pane>,
10290    window: &mut Window,
10291    cx: &mut App,
10292) {
10293    if pane == active_pane {
10294    } else if pane.read(cx).items_len() == 0 {
10295        pane.update(cx, |_, cx| {
10296            cx.emit(pane::Event::Remove {
10297                focus_on_pane: None,
10298            });
10299        })
10300    } else {
10301        move_all_items(pane, active_pane, window, cx);
10302    }
10303}
10304
10305fn move_all_items(
10306    from_pane: &Entity<Pane>,
10307    to_pane: &Entity<Pane>,
10308    window: &mut Window,
10309    cx: &mut App,
10310) {
10311    let destination_is_different = from_pane != to_pane;
10312    let mut moved_items = 0;
10313    for (item_ix, item_handle) in from_pane
10314        .read(cx)
10315        .items()
10316        .enumerate()
10317        .map(|(ix, item)| (ix, item.clone()))
10318        .collect::<Vec<_>>()
10319    {
10320        let ix = item_ix - moved_items;
10321        if destination_is_different {
10322            // Close item from previous pane
10323            from_pane.update(cx, |source, cx| {
10324                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10325            });
10326            moved_items += 1;
10327        }
10328
10329        // This automatically removes duplicate items in the pane
10330        to_pane.update(cx, |destination, cx| {
10331            destination.add_item(item_handle, true, true, None, window, cx);
10332            window.focus(&destination.focus_handle(cx), cx)
10333        });
10334    }
10335}
10336
10337pub fn move_item(
10338    source: &Entity<Pane>,
10339    destination: &Entity<Pane>,
10340    item_id_to_move: EntityId,
10341    destination_index: usize,
10342    activate: bool,
10343    window: &mut Window,
10344    cx: &mut App,
10345) {
10346    let Some((item_ix, item_handle)) = source
10347        .read(cx)
10348        .items()
10349        .enumerate()
10350        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10351        .map(|(ix, item)| (ix, item.clone()))
10352    else {
10353        // Tab was closed during drag
10354        return;
10355    };
10356
10357    if source != destination {
10358        // Close item from previous pane
10359        source.update(cx, |source, cx| {
10360            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10361        });
10362    }
10363
10364    // This automatically removes duplicate items in the pane
10365    destination.update(cx, |destination, cx| {
10366        destination.add_item_inner(
10367            item_handle,
10368            activate,
10369            activate,
10370            activate,
10371            Some(destination_index),
10372            window,
10373            cx,
10374        );
10375        if activate {
10376            window.focus(&destination.focus_handle(cx), cx)
10377        }
10378    });
10379}
10380
10381pub fn move_active_item(
10382    source: &Entity<Pane>,
10383    destination: &Entity<Pane>,
10384    focus_destination: bool,
10385    close_if_empty: bool,
10386    window: &mut Window,
10387    cx: &mut App,
10388) {
10389    if source == destination {
10390        return;
10391    }
10392    let Some(active_item) = source.read(cx).active_item() else {
10393        return;
10394    };
10395    source.update(cx, |source_pane, cx| {
10396        let item_id = active_item.item_id();
10397        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10398        destination.update(cx, |target_pane, cx| {
10399            target_pane.add_item(
10400                active_item,
10401                focus_destination,
10402                focus_destination,
10403                Some(target_pane.items_len()),
10404                window,
10405                cx,
10406            );
10407        });
10408    });
10409}
10410
10411pub fn clone_active_item(
10412    workspace_id: Option<WorkspaceId>,
10413    source: &Entity<Pane>,
10414    destination: &Entity<Pane>,
10415    focus_destination: bool,
10416    window: &mut Window,
10417    cx: &mut App,
10418) {
10419    if source == destination {
10420        return;
10421    }
10422    let Some(active_item) = source.read(cx).active_item() else {
10423        return;
10424    };
10425    if !active_item.can_split(cx) {
10426        return;
10427    }
10428    let destination = destination.downgrade();
10429    let task = active_item.clone_on_split(workspace_id, window, cx);
10430    window
10431        .spawn(cx, async move |cx| {
10432            let Some(clone) = task.await else {
10433                return;
10434            };
10435            destination
10436                .update_in(cx, |target_pane, window, cx| {
10437                    target_pane.add_item(
10438                        clone,
10439                        focus_destination,
10440                        focus_destination,
10441                        Some(target_pane.items_len()),
10442                        window,
10443                        cx,
10444                    );
10445                })
10446                .log_err();
10447        })
10448        .detach();
10449}
10450
10451#[derive(Debug)]
10452pub struct WorkspacePosition {
10453    pub window_bounds: Option<WindowBounds>,
10454    pub display: Option<Uuid>,
10455    pub centered_layout: bool,
10456}
10457
10458pub fn remote_workspace_position_from_db(
10459    connection_options: RemoteConnectionOptions,
10460    paths_to_open: &[PathBuf],
10461    cx: &App,
10462) -> Task<Result<WorkspacePosition>> {
10463    let paths = paths_to_open.to_vec();
10464    let db = WorkspaceDb::global(cx);
10465    let kvp = db::kvp::KeyValueStore::global(cx);
10466
10467    cx.background_spawn(async move {
10468        let remote_connection_id = db
10469            .get_or_create_remote_connection(connection_options)
10470            .await
10471            .context("fetching serialized ssh project")?;
10472        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10473
10474        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10475            (Some(WindowBounds::Windowed(bounds)), None)
10476        } else {
10477            let restorable_bounds = serialized_workspace
10478                .as_ref()
10479                .and_then(|workspace| {
10480                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10481                })
10482                .or_else(|| persistence::read_default_window_bounds(&kvp));
10483
10484            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10485                (Some(serialized_bounds), Some(serialized_display))
10486            } else {
10487                (None, None)
10488            }
10489        };
10490
10491        let centered_layout = serialized_workspace
10492            .as_ref()
10493            .map(|w| w.centered_layout)
10494            .unwrap_or(false);
10495
10496        Ok(WorkspacePosition {
10497            window_bounds,
10498            display,
10499            centered_layout,
10500        })
10501    })
10502}
10503
10504pub fn with_active_or_new_workspace(
10505    cx: &mut App,
10506    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10507) {
10508    match cx
10509        .active_window()
10510        .and_then(|w| w.downcast::<MultiWorkspace>())
10511    {
10512        Some(multi_workspace) => {
10513            cx.defer(move |cx| {
10514                multi_workspace
10515                    .update(cx, |multi_workspace, window, cx| {
10516                        let workspace = multi_workspace.workspace().clone();
10517                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10518                    })
10519                    .log_err();
10520            });
10521        }
10522        None => {
10523            let app_state = AppState::global(cx);
10524            open_new(
10525                OpenOptions::default(),
10526                app_state,
10527                cx,
10528                move |workspace, window, cx| f(workspace, window, cx),
10529            )
10530            .detach_and_log_err(cx);
10531        }
10532    }
10533}
10534
10535/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10536/// key. This migration path only runs once per panel per workspace.
10537fn load_legacy_panel_size(
10538    panel_key: &str,
10539    dock_position: DockPosition,
10540    workspace: &Workspace,
10541    cx: &mut App,
10542) -> Option<Pixels> {
10543    #[derive(Deserialize)]
10544    struct LegacyPanelState {
10545        #[serde(default)]
10546        width: Option<Pixels>,
10547        #[serde(default)]
10548        height: Option<Pixels>,
10549    }
10550
10551    let workspace_id = workspace
10552        .database_id()
10553        .map(|id| i64::from(id).to_string())
10554        .or_else(|| workspace.session_id())?;
10555
10556    let legacy_key = match panel_key {
10557        "ProjectPanel" => {
10558            format!("{}-{:?}", "ProjectPanel", workspace_id)
10559        }
10560        "OutlinePanel" => {
10561            format!("{}-{:?}", "OutlinePanel", workspace_id)
10562        }
10563        "GitPanel" => {
10564            format!("{}-{:?}", "GitPanel", workspace_id)
10565        }
10566        "TerminalPanel" => {
10567            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10568        }
10569        _ => return None,
10570    };
10571
10572    let kvp = db::kvp::KeyValueStore::global(cx);
10573    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10574    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10575    let size = match dock_position {
10576        DockPosition::Bottom => state.height,
10577        DockPosition::Left | DockPosition::Right => state.width,
10578    }?;
10579
10580    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10581        .detach_and_log_err(cx);
10582
10583    Some(size)
10584}
10585
10586#[cfg(test)]
10587mod tests {
10588    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10589
10590    use super::*;
10591    use crate::{
10592        dock::{PanelEvent, test::TestPanel},
10593        item::{
10594            ItemBufferKind, ItemEvent,
10595            test::{TestItem, TestProjectItem},
10596        },
10597    };
10598    use fs::FakeFs;
10599    use gpui::{
10600        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10601        UpdateGlobal, VisualTestContext, px,
10602    };
10603    use project::{Project, ProjectEntryId};
10604    use serde_json::json;
10605    use settings::SettingsStore;
10606    use util::path;
10607    use util::rel_path::rel_path;
10608
10609    #[gpui::test]
10610    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10611        init_test(cx);
10612
10613        let fs = FakeFs::new(cx.executor());
10614        let project = Project::test(fs, [], cx).await;
10615        let (workspace, cx) =
10616            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10617
10618        // Adding an item with no ambiguity renders the tab without detail.
10619        let item1 = cx.new(|cx| {
10620            let mut item = TestItem::new(cx);
10621            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10622            item
10623        });
10624        workspace.update_in(cx, |workspace, window, cx| {
10625            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10626        });
10627        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10628
10629        // Adding an item that creates ambiguity increases the level of detail on
10630        // both tabs.
10631        let item2 = cx.new_window_entity(|_window, cx| {
10632            let mut item = TestItem::new(cx);
10633            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10634            item
10635        });
10636        workspace.update_in(cx, |workspace, window, cx| {
10637            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10638        });
10639        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10640        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10641
10642        // Adding an item that creates ambiguity increases the level of detail only
10643        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10644        // we stop at the highest detail available.
10645        let item3 = cx.new(|cx| {
10646            let mut item = TestItem::new(cx);
10647            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10648            item
10649        });
10650        workspace.update_in(cx, |workspace, window, cx| {
10651            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10652        });
10653        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10654        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10655        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10656    }
10657
10658    #[gpui::test]
10659    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10660        init_test(cx);
10661
10662        let fs = FakeFs::new(cx.executor());
10663        fs.insert_tree(
10664            "/root1",
10665            json!({
10666                "one.txt": "",
10667                "two.txt": "",
10668            }),
10669        )
10670        .await;
10671        fs.insert_tree(
10672            "/root2",
10673            json!({
10674                "three.txt": "",
10675            }),
10676        )
10677        .await;
10678
10679        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10680        let (workspace, cx) =
10681            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10682        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10683        let worktree_id = project.update(cx, |project, cx| {
10684            project.worktrees(cx).next().unwrap().read(cx).id()
10685        });
10686
10687        let item1 = cx.new(|cx| {
10688            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10689        });
10690        let item2 = cx.new(|cx| {
10691            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10692        });
10693
10694        // Add an item to an empty pane
10695        workspace.update_in(cx, |workspace, window, cx| {
10696            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10697        });
10698        project.update(cx, |project, cx| {
10699            assert_eq!(
10700                project.active_entry(),
10701                project
10702                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10703                    .map(|e| e.id)
10704            );
10705        });
10706        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10707
10708        // Add a second item to a non-empty pane
10709        workspace.update_in(cx, |workspace, window, cx| {
10710            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10711        });
10712        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10713        project.update(cx, |project, cx| {
10714            assert_eq!(
10715                project.active_entry(),
10716                project
10717                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10718                    .map(|e| e.id)
10719            );
10720        });
10721
10722        // Close the active item
10723        pane.update_in(cx, |pane, window, cx| {
10724            pane.close_active_item(&Default::default(), window, cx)
10725        })
10726        .await
10727        .unwrap();
10728        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10729        project.update(cx, |project, cx| {
10730            assert_eq!(
10731                project.active_entry(),
10732                project
10733                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10734                    .map(|e| e.id)
10735            );
10736        });
10737
10738        // Add a project folder
10739        project
10740            .update(cx, |project, cx| {
10741                project.find_or_create_worktree("root2", true, cx)
10742            })
10743            .await
10744            .unwrap();
10745        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10746
10747        // Remove a project folder
10748        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10749        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10750    }
10751
10752    #[gpui::test]
10753    async fn test_close_window(cx: &mut TestAppContext) {
10754        init_test(cx);
10755
10756        let fs = FakeFs::new(cx.executor());
10757        fs.insert_tree("/root", json!({ "one": "" })).await;
10758
10759        let project = Project::test(fs, ["root".as_ref()], cx).await;
10760        let (workspace, cx) =
10761            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10762
10763        // When there are no dirty items, there's nothing to do.
10764        let item1 = cx.new(TestItem::new);
10765        workspace.update_in(cx, |w, window, cx| {
10766            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10767        });
10768        let task = workspace.update_in(cx, |w, window, cx| {
10769            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10770        });
10771        assert!(task.await.unwrap());
10772
10773        // When there are dirty untitled items, prompt to save each one. If the user
10774        // cancels any prompt, then abort.
10775        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10776        let item3 = cx.new(|cx| {
10777            TestItem::new(cx)
10778                .with_dirty(true)
10779                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10780        });
10781        workspace.update_in(cx, |w, window, cx| {
10782            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10783            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10784        });
10785        let task = workspace.update_in(cx, |w, window, cx| {
10786            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10787        });
10788        cx.executor().run_until_parked();
10789        cx.simulate_prompt_answer("Cancel"); // cancel save all
10790        cx.executor().run_until_parked();
10791        assert!(!cx.has_pending_prompt());
10792        assert!(!task.await.unwrap());
10793    }
10794
10795    #[gpui::test]
10796    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10797        init_test(cx);
10798
10799        let fs = FakeFs::new(cx.executor());
10800        fs.insert_tree("/root", json!({ "one": "" })).await;
10801
10802        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10803        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10804        let multi_workspace_handle =
10805            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10806        cx.run_until_parked();
10807
10808        multi_workspace_handle
10809            .update(cx, |mw, _window, cx| {
10810                mw.open_sidebar(cx);
10811            })
10812            .unwrap();
10813
10814        let workspace_a = multi_workspace_handle
10815            .read_with(cx, |mw, _| mw.workspace().clone())
10816            .unwrap();
10817
10818        let workspace_b = multi_workspace_handle
10819            .update(cx, |mw, window, cx| {
10820                mw.test_add_workspace(project_b, window, cx)
10821            })
10822            .unwrap();
10823
10824        // Activate workspace A
10825        multi_workspace_handle
10826            .update(cx, |mw, window, cx| {
10827                let workspace = mw.workspaces().next().unwrap().clone();
10828                mw.activate(workspace, window, cx);
10829            })
10830            .unwrap();
10831
10832        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10833
10834        // Workspace A has a clean item
10835        let item_a = cx.new(TestItem::new);
10836        workspace_a.update_in(cx, |w, window, cx| {
10837            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10838        });
10839
10840        // Workspace B has a dirty item
10841        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10842        workspace_b.update_in(cx, |w, window, cx| {
10843            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10844        });
10845
10846        // Verify workspace A is active
10847        multi_workspace_handle
10848            .read_with(cx, |mw, _| {
10849                assert_eq!(mw.workspace(), &workspace_a);
10850            })
10851            .unwrap();
10852
10853        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10854        multi_workspace_handle
10855            .update(cx, |mw, window, cx| {
10856                mw.close_window(&CloseWindow, window, cx);
10857            })
10858            .unwrap();
10859        cx.run_until_parked();
10860
10861        // Workspace B should now be active since it has dirty items that need attention
10862        multi_workspace_handle
10863            .read_with(cx, |mw, _| {
10864                assert_eq!(
10865                    mw.workspace(),
10866                    &workspace_b,
10867                    "workspace B should be activated when it prompts"
10868                );
10869            })
10870            .unwrap();
10871
10872        // User cancels the save prompt from workspace B
10873        cx.simulate_prompt_answer("Cancel");
10874        cx.run_until_parked();
10875
10876        // Window should still exist because workspace B's close was cancelled
10877        assert!(
10878            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10879            "window should still exist after cancelling one workspace's close"
10880        );
10881    }
10882
10883    #[gpui::test]
10884    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10885        init_test(cx);
10886
10887        // Register TestItem as a serializable item
10888        cx.update(|cx| {
10889            register_serializable_item::<TestItem>(cx);
10890        });
10891
10892        let fs = FakeFs::new(cx.executor());
10893        fs.insert_tree("/root", json!({ "one": "" })).await;
10894
10895        let project = Project::test(fs, ["root".as_ref()], cx).await;
10896        let (workspace, cx) =
10897            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10898
10899        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10900        let item1 = cx.new(|cx| {
10901            TestItem::new(cx)
10902                .with_dirty(true)
10903                .with_serialize(|| Some(Task::ready(Ok(()))))
10904        });
10905        let item2 = cx.new(|cx| {
10906            TestItem::new(cx)
10907                .with_dirty(true)
10908                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10909                .with_serialize(|| Some(Task::ready(Ok(()))))
10910        });
10911        workspace.update_in(cx, |w, window, cx| {
10912            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10913            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10914        });
10915        let task = workspace.update_in(cx, |w, window, cx| {
10916            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10917        });
10918        assert!(task.await.unwrap());
10919    }
10920
10921    #[gpui::test]
10922    async fn test_close_pane_items(cx: &mut TestAppContext) {
10923        init_test(cx);
10924
10925        let fs = FakeFs::new(cx.executor());
10926
10927        let project = Project::test(fs, None, cx).await;
10928        let (workspace, cx) =
10929            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10930
10931        let item1 = cx.new(|cx| {
10932            TestItem::new(cx)
10933                .with_dirty(true)
10934                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10935        });
10936        let item2 = cx.new(|cx| {
10937            TestItem::new(cx)
10938                .with_dirty(true)
10939                .with_conflict(true)
10940                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10941        });
10942        let item3 = cx.new(|cx| {
10943            TestItem::new(cx)
10944                .with_dirty(true)
10945                .with_conflict(true)
10946                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10947        });
10948        let item4 = cx.new(|cx| {
10949            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10950                let project_item = TestProjectItem::new_untitled(cx);
10951                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10952                project_item
10953            }])
10954        });
10955        let pane = workspace.update_in(cx, |workspace, window, cx| {
10956            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10957            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10958            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10959            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10960            workspace.active_pane().clone()
10961        });
10962
10963        let close_items = pane.update_in(cx, |pane, window, cx| {
10964            pane.activate_item(1, true, true, window, cx);
10965            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10966            let item1_id = item1.item_id();
10967            let item3_id = item3.item_id();
10968            let item4_id = item4.item_id();
10969            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10970                [item1_id, item3_id, item4_id].contains(&id)
10971            })
10972        });
10973        cx.executor().run_until_parked();
10974
10975        assert!(cx.has_pending_prompt());
10976        cx.simulate_prompt_answer("Save all");
10977
10978        cx.executor().run_until_parked();
10979
10980        // Item 1 is saved. There's a prompt to save item 3.
10981        pane.update(cx, |pane, cx| {
10982            assert_eq!(item1.read(cx).save_count, 1);
10983            assert_eq!(item1.read(cx).save_as_count, 0);
10984            assert_eq!(item1.read(cx).reload_count, 0);
10985            assert_eq!(pane.items_len(), 3);
10986            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10987        });
10988        assert!(cx.has_pending_prompt());
10989
10990        // Cancel saving item 3.
10991        cx.simulate_prompt_answer("Discard");
10992        cx.executor().run_until_parked();
10993
10994        // Item 3 is reloaded. There's a prompt to save item 4.
10995        pane.update(cx, |pane, cx| {
10996            assert_eq!(item3.read(cx).save_count, 0);
10997            assert_eq!(item3.read(cx).save_as_count, 0);
10998            assert_eq!(item3.read(cx).reload_count, 1);
10999            assert_eq!(pane.items_len(), 2);
11000            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11001        });
11002
11003        // There's a prompt for a path for item 4.
11004        cx.simulate_new_path_selection(|_| Some(Default::default()));
11005        close_items.await.unwrap();
11006
11007        // The requested items are closed.
11008        pane.update(cx, |pane, cx| {
11009            assert_eq!(item4.read(cx).save_count, 0);
11010            assert_eq!(item4.read(cx).save_as_count, 1);
11011            assert_eq!(item4.read(cx).reload_count, 0);
11012            assert_eq!(pane.items_len(), 1);
11013            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11014        });
11015    }
11016
11017    #[gpui::test]
11018    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11019        init_test(cx);
11020
11021        let fs = FakeFs::new(cx.executor());
11022        let project = Project::test(fs, [], cx).await;
11023        let (workspace, cx) =
11024            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11025
11026        // Create several workspace items with single project entries, and two
11027        // workspace items with multiple project entries.
11028        let single_entry_items = (0..=4)
11029            .map(|project_entry_id| {
11030                cx.new(|cx| {
11031                    TestItem::new(cx)
11032                        .with_dirty(true)
11033                        .with_project_items(&[dirty_project_item(
11034                            project_entry_id,
11035                            &format!("{project_entry_id}.txt"),
11036                            cx,
11037                        )])
11038                })
11039            })
11040            .collect::<Vec<_>>();
11041        let item_2_3 = cx.new(|cx| {
11042            TestItem::new(cx)
11043                .with_dirty(true)
11044                .with_buffer_kind(ItemBufferKind::Multibuffer)
11045                .with_project_items(&[
11046                    single_entry_items[2].read(cx).project_items[0].clone(),
11047                    single_entry_items[3].read(cx).project_items[0].clone(),
11048                ])
11049        });
11050        let item_3_4 = cx.new(|cx| {
11051            TestItem::new(cx)
11052                .with_dirty(true)
11053                .with_buffer_kind(ItemBufferKind::Multibuffer)
11054                .with_project_items(&[
11055                    single_entry_items[3].read(cx).project_items[0].clone(),
11056                    single_entry_items[4].read(cx).project_items[0].clone(),
11057                ])
11058        });
11059
11060        // Create two panes that contain the following project entries:
11061        //   left pane:
11062        //     multi-entry items:   (2, 3)
11063        //     single-entry items:  0, 2, 3, 4
11064        //   right pane:
11065        //     single-entry items:  4, 1
11066        //     multi-entry items:   (3, 4)
11067        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11068            let left_pane = workspace.active_pane().clone();
11069            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11070            workspace.add_item_to_active_pane(
11071                single_entry_items[0].boxed_clone(),
11072                None,
11073                true,
11074                window,
11075                cx,
11076            );
11077            workspace.add_item_to_active_pane(
11078                single_entry_items[2].boxed_clone(),
11079                None,
11080                true,
11081                window,
11082                cx,
11083            );
11084            workspace.add_item_to_active_pane(
11085                single_entry_items[3].boxed_clone(),
11086                None,
11087                true,
11088                window,
11089                cx,
11090            );
11091            workspace.add_item_to_active_pane(
11092                single_entry_items[4].boxed_clone(),
11093                None,
11094                true,
11095                window,
11096                cx,
11097            );
11098
11099            let right_pane =
11100                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11101
11102            let boxed_clone = single_entry_items[1].boxed_clone();
11103            let right_pane = window.spawn(cx, async move |cx| {
11104                right_pane.await.inspect(|right_pane| {
11105                    right_pane
11106                        .update_in(cx, |pane, window, cx| {
11107                            pane.add_item(boxed_clone, true, true, None, window, cx);
11108                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11109                        })
11110                        .unwrap();
11111                })
11112            });
11113
11114            (left_pane, right_pane)
11115        });
11116        let right_pane = right_pane.await.unwrap();
11117        cx.focus(&right_pane);
11118
11119        let close = right_pane.update_in(cx, |pane, window, cx| {
11120            pane.close_all_items(&CloseAllItems::default(), window, cx)
11121                .unwrap()
11122        });
11123        cx.executor().run_until_parked();
11124
11125        let msg = cx.pending_prompt().unwrap().0;
11126        assert!(msg.contains("1.txt"));
11127        assert!(!msg.contains("2.txt"));
11128        assert!(!msg.contains("3.txt"));
11129        assert!(!msg.contains("4.txt"));
11130
11131        // With best-effort close, cancelling item 1 keeps it open but items 4
11132        // and (3,4) still close since their entries exist in left pane.
11133        cx.simulate_prompt_answer("Cancel");
11134        close.await;
11135
11136        right_pane.read_with(cx, |pane, _| {
11137            assert_eq!(pane.items_len(), 1);
11138        });
11139
11140        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11141        left_pane
11142            .update_in(cx, |left_pane, window, cx| {
11143                left_pane.close_item_by_id(
11144                    single_entry_items[3].entity_id(),
11145                    SaveIntent::Skip,
11146                    window,
11147                    cx,
11148                )
11149            })
11150            .await
11151            .unwrap();
11152
11153        let close = left_pane.update_in(cx, |pane, window, cx| {
11154            pane.close_all_items(&CloseAllItems::default(), window, cx)
11155                .unwrap()
11156        });
11157        cx.executor().run_until_parked();
11158
11159        let details = cx.pending_prompt().unwrap().1;
11160        assert!(details.contains("0.txt"));
11161        assert!(details.contains("3.txt"));
11162        assert!(details.contains("4.txt"));
11163        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11164        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11165        // assert!(!details.contains("2.txt"));
11166
11167        cx.simulate_prompt_answer("Save all");
11168        cx.executor().run_until_parked();
11169        close.await;
11170
11171        left_pane.read_with(cx, |pane, _| {
11172            assert_eq!(pane.items_len(), 0);
11173        });
11174    }
11175
11176    #[gpui::test]
11177    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11178        init_test(cx);
11179
11180        let fs = FakeFs::new(cx.executor());
11181        let project = Project::test(fs, [], cx).await;
11182        let (workspace, cx) =
11183            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11184        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11185
11186        let item = cx.new(|cx| {
11187            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11188        });
11189        let item_id = item.entity_id();
11190        workspace.update_in(cx, |workspace, window, cx| {
11191            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11192        });
11193
11194        // Autosave on window change.
11195        item.update(cx, |item, cx| {
11196            SettingsStore::update_global(cx, |settings, cx| {
11197                settings.update_user_settings(cx, |settings| {
11198                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11199                })
11200            });
11201            item.is_dirty = true;
11202        });
11203
11204        // Deactivating the window saves the file.
11205        cx.deactivate_window();
11206        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11207
11208        // Re-activating the window doesn't save the file.
11209        cx.update(|window, _| window.activate_window());
11210        cx.executor().run_until_parked();
11211        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11212
11213        // Autosave on focus change.
11214        item.update_in(cx, |item, window, cx| {
11215            cx.focus_self(window);
11216            SettingsStore::update_global(cx, |settings, cx| {
11217                settings.update_user_settings(cx, |settings| {
11218                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11219                })
11220            });
11221            item.is_dirty = true;
11222        });
11223        // Blurring the item saves the file.
11224        item.update_in(cx, |_, window, _| window.blur());
11225        cx.executor().run_until_parked();
11226        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11227
11228        // Deactivating the window still saves the file.
11229        item.update_in(cx, |item, window, cx| {
11230            cx.focus_self(window);
11231            item.is_dirty = true;
11232        });
11233        cx.deactivate_window();
11234        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11235
11236        // Autosave after delay.
11237        item.update(cx, |item, cx| {
11238            SettingsStore::update_global(cx, |settings, cx| {
11239                settings.update_user_settings(cx, |settings| {
11240                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11241                        milliseconds: 500.into(),
11242                    });
11243                })
11244            });
11245            item.is_dirty = true;
11246            cx.emit(ItemEvent::Edit);
11247        });
11248
11249        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11250        cx.executor().advance_clock(Duration::from_millis(250));
11251        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11252
11253        // After delay expires, the file is saved.
11254        cx.executor().advance_clock(Duration::from_millis(250));
11255        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11256
11257        // Autosave after delay, should save earlier than delay if tab is closed
11258        item.update(cx, |item, cx| {
11259            item.is_dirty = true;
11260            cx.emit(ItemEvent::Edit);
11261        });
11262        cx.executor().advance_clock(Duration::from_millis(250));
11263        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11264
11265        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11266        pane.update_in(cx, |pane, window, cx| {
11267            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11268        })
11269        .await
11270        .unwrap();
11271        assert!(!cx.has_pending_prompt());
11272        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11273
11274        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11275        workspace.update_in(cx, |workspace, window, cx| {
11276            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11277        });
11278        item.update_in(cx, |item, _window, cx| {
11279            item.is_dirty = true;
11280            for project_item in &mut item.project_items {
11281                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11282            }
11283        });
11284        cx.run_until_parked();
11285        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11286
11287        // Autosave on focus change, ensuring closing the tab counts as such.
11288        item.update(cx, |item, cx| {
11289            SettingsStore::update_global(cx, |settings, cx| {
11290                settings.update_user_settings(cx, |settings| {
11291                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11292                })
11293            });
11294            item.is_dirty = true;
11295            for project_item in &mut item.project_items {
11296                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11297            }
11298        });
11299
11300        pane.update_in(cx, |pane, window, cx| {
11301            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11302        })
11303        .await
11304        .unwrap();
11305        assert!(!cx.has_pending_prompt());
11306        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11307
11308        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11309        workspace.update_in(cx, |workspace, window, cx| {
11310            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11311        });
11312        item.update_in(cx, |item, window, cx| {
11313            item.project_items[0].update(cx, |item, _| {
11314                item.entry_id = None;
11315            });
11316            item.is_dirty = true;
11317            window.blur();
11318        });
11319        cx.run_until_parked();
11320        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11321
11322        // Ensure autosave is prevented for deleted files also when closing the buffer.
11323        let _close_items = pane.update_in(cx, |pane, window, cx| {
11324            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11325        });
11326        cx.run_until_parked();
11327        assert!(cx.has_pending_prompt());
11328        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11329    }
11330
11331    #[gpui::test]
11332    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11333        init_test(cx);
11334
11335        let fs = FakeFs::new(cx.executor());
11336        let project = Project::test(fs, [], cx).await;
11337        let (workspace, cx) =
11338            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11339
11340        // Create a multibuffer-like item with two child focus handles,
11341        // simulating individual buffer editors within a multibuffer.
11342        let item = cx.new(|cx| {
11343            TestItem::new(cx)
11344                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11345                .with_child_focus_handles(2, cx)
11346        });
11347        workspace.update_in(cx, |workspace, window, cx| {
11348            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11349        });
11350
11351        // Set autosave to OnFocusChange and focus the first child handle,
11352        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11353        item.update_in(cx, |item, window, cx| {
11354            SettingsStore::update_global(cx, |settings, cx| {
11355                settings.update_user_settings(cx, |settings| {
11356                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11357                })
11358            });
11359            item.is_dirty = true;
11360            window.focus(&item.child_focus_handles[0], cx);
11361        });
11362        cx.executor().run_until_parked();
11363        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11364
11365        // Moving focus from one child to another within the same item should
11366        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11367        item.update_in(cx, |item, window, cx| {
11368            window.focus(&item.child_focus_handles[1], cx);
11369        });
11370        cx.executor().run_until_parked();
11371        item.read_with(cx, |item, _| {
11372            assert_eq!(
11373                item.save_count, 0,
11374                "Switching focus between children within the same item should not autosave"
11375            );
11376        });
11377
11378        // Blurring the item saves the file. This is the core regression scenario:
11379        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11380        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11381        // the leaf is always a child focus handle, so `on_blur` never detected
11382        // focus leaving the item.
11383        item.update_in(cx, |_, window, _| window.blur());
11384        cx.executor().run_until_parked();
11385        item.read_with(cx, |item, _| {
11386            assert_eq!(
11387                item.save_count, 1,
11388                "Blurring should trigger autosave when focus was on a child of the item"
11389            );
11390        });
11391
11392        // Deactivating the window should also trigger autosave when a child of
11393        // the multibuffer item currently owns focus.
11394        item.update_in(cx, |item, window, cx| {
11395            item.is_dirty = true;
11396            window.focus(&item.child_focus_handles[0], cx);
11397        });
11398        cx.executor().run_until_parked();
11399        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11400
11401        cx.deactivate_window();
11402        item.read_with(cx, |item, _| {
11403            assert_eq!(
11404                item.save_count, 2,
11405                "Deactivating window should trigger autosave when focus was on a child"
11406            );
11407        });
11408    }
11409
11410    #[gpui::test]
11411    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11412        init_test(cx);
11413
11414        let fs = FakeFs::new(cx.executor());
11415
11416        let project = Project::test(fs, [], cx).await;
11417        let (workspace, cx) =
11418            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11419
11420        let item = cx.new(|cx| {
11421            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11422        });
11423        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11424        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11425        let toolbar_notify_count = Rc::new(RefCell::new(0));
11426
11427        workspace.update_in(cx, |workspace, window, cx| {
11428            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11429            let toolbar_notification_count = toolbar_notify_count.clone();
11430            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11431                *toolbar_notification_count.borrow_mut() += 1
11432            })
11433            .detach();
11434        });
11435
11436        pane.read_with(cx, |pane, _| {
11437            assert!(!pane.can_navigate_backward());
11438            assert!(!pane.can_navigate_forward());
11439        });
11440
11441        item.update_in(cx, |item, _, cx| {
11442            item.set_state("one".to_string(), cx);
11443        });
11444
11445        // Toolbar must be notified to re-render the navigation buttons
11446        assert_eq!(*toolbar_notify_count.borrow(), 1);
11447
11448        pane.read_with(cx, |pane, _| {
11449            assert!(pane.can_navigate_backward());
11450            assert!(!pane.can_navigate_forward());
11451        });
11452
11453        workspace
11454            .update_in(cx, |workspace, window, cx| {
11455                workspace.go_back(pane.downgrade(), window, cx)
11456            })
11457            .await
11458            .unwrap();
11459
11460        assert_eq!(*toolbar_notify_count.borrow(), 2);
11461        pane.read_with(cx, |pane, _| {
11462            assert!(!pane.can_navigate_backward());
11463            assert!(pane.can_navigate_forward());
11464        });
11465    }
11466
11467    /// Tests that the navigation history deduplicates entries for the same item.
11468    ///
11469    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11470    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11471    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11472    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11473    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11474    ///
11475    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11476    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11477    #[gpui::test]
11478    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11479        init_test(cx);
11480
11481        let fs = FakeFs::new(cx.executor());
11482        let project = Project::test(fs, [], cx).await;
11483        let (workspace, cx) =
11484            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11485
11486        let item_a = cx.new(|cx| {
11487            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11488        });
11489        let item_b = cx.new(|cx| {
11490            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11491        });
11492        let item_c = cx.new(|cx| {
11493            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11494        });
11495
11496        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11497
11498        workspace.update_in(cx, |workspace, window, cx| {
11499            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11500            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11501            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11502        });
11503
11504        workspace.update_in(cx, |workspace, window, cx| {
11505            workspace.activate_item(&item_a, false, false, window, cx);
11506        });
11507        cx.run_until_parked();
11508
11509        workspace.update_in(cx, |workspace, window, cx| {
11510            workspace.activate_item(&item_b, false, false, window, cx);
11511        });
11512        cx.run_until_parked();
11513
11514        workspace.update_in(cx, |workspace, window, cx| {
11515            workspace.activate_item(&item_a, false, false, window, cx);
11516        });
11517        cx.run_until_parked();
11518
11519        workspace.update_in(cx, |workspace, window, cx| {
11520            workspace.activate_item(&item_b, false, false, window, cx);
11521        });
11522        cx.run_until_parked();
11523
11524        workspace.update_in(cx, |workspace, window, cx| {
11525            workspace.activate_item(&item_a, false, false, window, cx);
11526        });
11527        cx.run_until_parked();
11528
11529        workspace.update_in(cx, |workspace, window, cx| {
11530            workspace.activate_item(&item_b, false, false, window, cx);
11531        });
11532        cx.run_until_parked();
11533
11534        workspace.update_in(cx, |workspace, window, cx| {
11535            workspace.activate_item(&item_c, false, false, window, cx);
11536        });
11537        cx.run_until_parked();
11538
11539        let backward_count = pane.read_with(cx, |pane, cx| {
11540            let mut count = 0;
11541            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11542                count += 1;
11543            });
11544            count
11545        });
11546        assert!(
11547            backward_count <= 4,
11548            "Should have at most 4 entries, got {}",
11549            backward_count
11550        );
11551
11552        workspace
11553            .update_in(cx, |workspace, window, cx| {
11554                workspace.go_back(pane.downgrade(), window, cx)
11555            })
11556            .await
11557            .unwrap();
11558
11559        let active_item = workspace.read_with(cx, |workspace, cx| {
11560            workspace.active_item(cx).unwrap().item_id()
11561        });
11562        assert_eq!(
11563            active_item,
11564            item_b.entity_id(),
11565            "After first go_back, should be at item B"
11566        );
11567
11568        workspace
11569            .update_in(cx, |workspace, window, cx| {
11570                workspace.go_back(pane.downgrade(), window, cx)
11571            })
11572            .await
11573            .unwrap();
11574
11575        let active_item = workspace.read_with(cx, |workspace, cx| {
11576            workspace.active_item(cx).unwrap().item_id()
11577        });
11578        assert_eq!(
11579            active_item,
11580            item_a.entity_id(),
11581            "After second go_back, should be at item A"
11582        );
11583
11584        pane.read_with(cx, |pane, _| {
11585            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11586        });
11587    }
11588
11589    #[gpui::test]
11590    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11591        init_test(cx);
11592        let fs = FakeFs::new(cx.executor());
11593        let project = Project::test(fs, [], cx).await;
11594        let (multi_workspace, cx) =
11595            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11596        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11597
11598        workspace.update_in(cx, |workspace, window, cx| {
11599            let first_item = cx.new(|cx| {
11600                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11601            });
11602            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11603            workspace.split_pane(
11604                workspace.active_pane().clone(),
11605                SplitDirection::Right,
11606                window,
11607                cx,
11608            );
11609            workspace.split_pane(
11610                workspace.active_pane().clone(),
11611                SplitDirection::Right,
11612                window,
11613                cx,
11614            );
11615        });
11616
11617        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11618            let panes = workspace.center.panes();
11619            assert!(panes.len() >= 2);
11620            (
11621                panes.first().expect("at least one pane").entity_id(),
11622                panes.last().expect("at least one pane").entity_id(),
11623            )
11624        });
11625
11626        workspace.update_in(cx, |workspace, window, cx| {
11627            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11628        });
11629        workspace.update(cx, |workspace, _| {
11630            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11631            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11632        });
11633
11634        cx.dispatch_action(ActivateLastPane);
11635
11636        workspace.update(cx, |workspace, _| {
11637            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11638        });
11639    }
11640
11641    #[gpui::test]
11642    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11643        init_test(cx);
11644        let fs = FakeFs::new(cx.executor());
11645
11646        let project = Project::test(fs, [], cx).await;
11647        let (workspace, cx) =
11648            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11649
11650        let panel = workspace.update_in(cx, |workspace, window, cx| {
11651            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11652            workspace.add_panel(panel.clone(), window, cx);
11653
11654            workspace
11655                .right_dock()
11656                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11657
11658            panel
11659        });
11660
11661        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11662        pane.update_in(cx, |pane, window, cx| {
11663            let item = cx.new(TestItem::new);
11664            pane.add_item(Box::new(item), true, true, None, window, cx);
11665        });
11666
11667        // Transfer focus from center to panel
11668        workspace.update_in(cx, |workspace, window, cx| {
11669            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11670        });
11671
11672        workspace.update_in(cx, |workspace, window, cx| {
11673            assert!(workspace.right_dock().read(cx).is_open());
11674            assert!(!panel.is_zoomed(window, cx));
11675            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11676        });
11677
11678        // Transfer focus from panel to center
11679        workspace.update_in(cx, |workspace, window, cx| {
11680            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11681        });
11682
11683        workspace.update_in(cx, |workspace, window, cx| {
11684            assert!(workspace.right_dock().read(cx).is_open());
11685            assert!(!panel.is_zoomed(window, cx));
11686            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11687            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11688        });
11689
11690        // Close the dock
11691        workspace.update_in(cx, |workspace, window, cx| {
11692            workspace.toggle_dock(DockPosition::Right, window, cx);
11693        });
11694
11695        workspace.update_in(cx, |workspace, window, cx| {
11696            assert!(!workspace.right_dock().read(cx).is_open());
11697            assert!(!panel.is_zoomed(window, cx));
11698            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11699            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11700        });
11701
11702        // Open the dock
11703        workspace.update_in(cx, |workspace, window, cx| {
11704            workspace.toggle_dock(DockPosition::Right, window, cx);
11705        });
11706
11707        workspace.update_in(cx, |workspace, window, cx| {
11708            assert!(workspace.right_dock().read(cx).is_open());
11709            assert!(!panel.is_zoomed(window, cx));
11710            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11711        });
11712
11713        // Focus and zoom panel
11714        panel.update_in(cx, |panel, window, cx| {
11715            cx.focus_self(window);
11716            panel.set_zoomed(true, window, cx)
11717        });
11718
11719        workspace.update_in(cx, |workspace, window, cx| {
11720            assert!(workspace.right_dock().read(cx).is_open());
11721            assert!(panel.is_zoomed(window, cx));
11722            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11723        });
11724
11725        // Transfer focus to the center closes the dock
11726        workspace.update_in(cx, |workspace, window, cx| {
11727            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11728        });
11729
11730        workspace.update_in(cx, |workspace, window, cx| {
11731            assert!(!workspace.right_dock().read(cx).is_open());
11732            assert!(panel.is_zoomed(window, cx));
11733            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11734        });
11735
11736        // Transferring focus back to the panel keeps it zoomed
11737        workspace.update_in(cx, |workspace, window, cx| {
11738            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11739        });
11740
11741        workspace.update_in(cx, |workspace, window, cx| {
11742            assert!(workspace.right_dock().read(cx).is_open());
11743            assert!(panel.is_zoomed(window, cx));
11744            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11745        });
11746
11747        // Close the dock while it is zoomed
11748        workspace.update_in(cx, |workspace, window, cx| {
11749            workspace.toggle_dock(DockPosition::Right, window, cx)
11750        });
11751
11752        workspace.update_in(cx, |workspace, window, cx| {
11753            assert!(!workspace.right_dock().read(cx).is_open());
11754            assert!(panel.is_zoomed(window, cx));
11755            assert!(workspace.zoomed.is_none());
11756            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11757        });
11758
11759        // Opening the dock, when it's zoomed, retains focus
11760        workspace.update_in(cx, |workspace, window, cx| {
11761            workspace.toggle_dock(DockPosition::Right, window, cx)
11762        });
11763
11764        workspace.update_in(cx, |workspace, window, cx| {
11765            assert!(workspace.right_dock().read(cx).is_open());
11766            assert!(panel.is_zoomed(window, cx));
11767            assert!(workspace.zoomed.is_some());
11768            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11769        });
11770
11771        // Unzoom and close the panel, zoom the active pane.
11772        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11773        workspace.update_in(cx, |workspace, window, cx| {
11774            workspace.toggle_dock(DockPosition::Right, window, cx)
11775        });
11776        pane.update_in(cx, |pane, window, cx| {
11777            pane.toggle_zoom(&Default::default(), window, cx)
11778        });
11779
11780        // Opening a dock unzooms the pane.
11781        workspace.update_in(cx, |workspace, window, cx| {
11782            workspace.toggle_dock(DockPosition::Right, window, cx)
11783        });
11784        workspace.update_in(cx, |workspace, window, cx| {
11785            let pane = pane.read(cx);
11786            assert!(!pane.is_zoomed());
11787            assert!(!pane.focus_handle(cx).is_focused(window));
11788            assert!(workspace.right_dock().read(cx).is_open());
11789            assert!(workspace.zoomed.is_none());
11790        });
11791    }
11792
11793    #[gpui::test]
11794    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11795        init_test(cx);
11796        let fs = FakeFs::new(cx.executor());
11797
11798        let project = Project::test(fs, [], cx).await;
11799        let (workspace, cx) =
11800            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11801
11802        let panel = workspace.update_in(cx, |workspace, window, cx| {
11803            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11804            workspace.add_panel(panel.clone(), window, cx);
11805            panel
11806        });
11807
11808        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11809        pane.update_in(cx, |pane, window, cx| {
11810            let item = cx.new(TestItem::new);
11811            pane.add_item(Box::new(item), true, true, None, window, cx);
11812        });
11813
11814        // Enable close_panel_on_toggle
11815        cx.update_global(|store: &mut SettingsStore, cx| {
11816            store.update_user_settings(cx, |settings| {
11817                settings.workspace.close_panel_on_toggle = Some(true);
11818            });
11819        });
11820
11821        // Panel starts closed. Toggling should open and focus it.
11822        workspace.update_in(cx, |workspace, window, cx| {
11823            assert!(!workspace.right_dock().read(cx).is_open());
11824            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11825        });
11826
11827        workspace.update_in(cx, |workspace, window, cx| {
11828            assert!(
11829                workspace.right_dock().read(cx).is_open(),
11830                "Dock should be open after toggling from center"
11831            );
11832            assert!(
11833                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11834                "Panel should be focused after toggling from center"
11835            );
11836        });
11837
11838        // Panel is open and focused. Toggling should close the panel and
11839        // return focus to the center.
11840        workspace.update_in(cx, |workspace, window, cx| {
11841            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11842        });
11843
11844        workspace.update_in(cx, |workspace, window, cx| {
11845            assert!(
11846                !workspace.right_dock().read(cx).is_open(),
11847                "Dock should be closed after toggling from focused panel"
11848            );
11849            assert!(
11850                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11851                "Panel should not be focused after toggling from focused panel"
11852            );
11853        });
11854
11855        // Open the dock and focus something else so the panel is open but not
11856        // focused. Toggling should focus the panel (not close it).
11857        workspace.update_in(cx, |workspace, window, cx| {
11858            workspace
11859                .right_dock()
11860                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11861            window.focus(&pane.read(cx).focus_handle(cx), cx);
11862        });
11863
11864        workspace.update_in(cx, |workspace, window, cx| {
11865            assert!(workspace.right_dock().read(cx).is_open());
11866            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11867            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11868        });
11869
11870        workspace.update_in(cx, |workspace, window, cx| {
11871            assert!(
11872                workspace.right_dock().read(cx).is_open(),
11873                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11874            );
11875            assert!(
11876                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11877                "Panel should be focused after toggling an open-but-unfocused panel"
11878            );
11879        });
11880
11881        // Now disable the setting and verify the original behavior: toggling
11882        // from a focused panel moves focus to center but leaves the dock open.
11883        cx.update_global(|store: &mut SettingsStore, cx| {
11884            store.update_user_settings(cx, |settings| {
11885                settings.workspace.close_panel_on_toggle = Some(false);
11886            });
11887        });
11888
11889        workspace.update_in(cx, |workspace, window, cx| {
11890            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11891        });
11892
11893        workspace.update_in(cx, |workspace, window, cx| {
11894            assert!(
11895                workspace.right_dock().read(cx).is_open(),
11896                "Dock should remain open when setting is disabled"
11897            );
11898            assert!(
11899                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11900                "Panel should not be focused after toggling with setting disabled"
11901            );
11902        });
11903    }
11904
11905    #[gpui::test]
11906    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11907        init_test(cx);
11908        let fs = FakeFs::new(cx.executor());
11909
11910        let project = Project::test(fs, [], cx).await;
11911        let (workspace, cx) =
11912            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11913
11914        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11915            workspace.active_pane().clone()
11916        });
11917
11918        // Add an item to the pane so it can be zoomed
11919        workspace.update_in(cx, |workspace, window, cx| {
11920            let item = cx.new(TestItem::new);
11921            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11922        });
11923
11924        // Initially not zoomed
11925        workspace.update_in(cx, |workspace, _window, cx| {
11926            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11927            assert!(
11928                workspace.zoomed.is_none(),
11929                "Workspace should track no zoomed pane"
11930            );
11931            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11932        });
11933
11934        // Zoom In
11935        pane.update_in(cx, |pane, window, cx| {
11936            pane.zoom_in(&crate::ZoomIn, window, cx);
11937        });
11938
11939        workspace.update_in(cx, |workspace, window, cx| {
11940            assert!(
11941                pane.read(cx).is_zoomed(),
11942                "Pane should be zoomed after ZoomIn"
11943            );
11944            assert!(
11945                workspace.zoomed.is_some(),
11946                "Workspace should track the zoomed pane"
11947            );
11948            assert!(
11949                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11950                "ZoomIn should focus the pane"
11951            );
11952        });
11953
11954        // Zoom In again is a no-op
11955        pane.update_in(cx, |pane, window, cx| {
11956            pane.zoom_in(&crate::ZoomIn, window, cx);
11957        });
11958
11959        workspace.update_in(cx, |workspace, window, cx| {
11960            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11961            assert!(
11962                workspace.zoomed.is_some(),
11963                "Workspace still tracks zoomed pane"
11964            );
11965            assert!(
11966                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11967                "Pane remains focused after repeated ZoomIn"
11968            );
11969        });
11970
11971        // Zoom Out
11972        pane.update_in(cx, |pane, window, cx| {
11973            pane.zoom_out(&crate::ZoomOut, window, cx);
11974        });
11975
11976        workspace.update_in(cx, |workspace, _window, cx| {
11977            assert!(
11978                !pane.read(cx).is_zoomed(),
11979                "Pane should unzoom after ZoomOut"
11980            );
11981            assert!(
11982                workspace.zoomed.is_none(),
11983                "Workspace clears zoom tracking after ZoomOut"
11984            );
11985        });
11986
11987        // Zoom Out again is a no-op
11988        pane.update_in(cx, |pane, window, cx| {
11989            pane.zoom_out(&crate::ZoomOut, window, cx);
11990        });
11991
11992        workspace.update_in(cx, |workspace, _window, cx| {
11993            assert!(
11994                !pane.read(cx).is_zoomed(),
11995                "Second ZoomOut keeps pane unzoomed"
11996            );
11997            assert!(
11998                workspace.zoomed.is_none(),
11999                "Workspace remains without zoomed pane"
12000            );
12001        });
12002    }
12003
12004    #[gpui::test]
12005    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12006        init_test(cx);
12007        let fs = FakeFs::new(cx.executor());
12008
12009        let project = Project::test(fs, [], cx).await;
12010        let (workspace, cx) =
12011            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12012        workspace.update_in(cx, |workspace, window, cx| {
12013            // Open two docks
12014            let left_dock = workspace.dock_at_position(DockPosition::Left);
12015            let right_dock = workspace.dock_at_position(DockPosition::Right);
12016
12017            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12018            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12019
12020            assert!(left_dock.read(cx).is_open());
12021            assert!(right_dock.read(cx).is_open());
12022        });
12023
12024        workspace.update_in(cx, |workspace, window, cx| {
12025            // Toggle all docks - should close both
12026            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12027
12028            let left_dock = workspace.dock_at_position(DockPosition::Left);
12029            let right_dock = workspace.dock_at_position(DockPosition::Right);
12030            assert!(!left_dock.read(cx).is_open());
12031            assert!(!right_dock.read(cx).is_open());
12032        });
12033
12034        workspace.update_in(cx, |workspace, window, cx| {
12035            // Toggle again - should reopen both
12036            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12037
12038            let left_dock = workspace.dock_at_position(DockPosition::Left);
12039            let right_dock = workspace.dock_at_position(DockPosition::Right);
12040            assert!(left_dock.read(cx).is_open());
12041            assert!(right_dock.read(cx).is_open());
12042        });
12043    }
12044
12045    #[gpui::test]
12046    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12047        init_test(cx);
12048        let fs = FakeFs::new(cx.executor());
12049
12050        let project = Project::test(fs, [], cx).await;
12051        let (workspace, cx) =
12052            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12053        workspace.update_in(cx, |workspace, window, cx| {
12054            // Open two docks
12055            let left_dock = workspace.dock_at_position(DockPosition::Left);
12056            let right_dock = workspace.dock_at_position(DockPosition::Right);
12057
12058            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12059            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12060
12061            assert!(left_dock.read(cx).is_open());
12062            assert!(right_dock.read(cx).is_open());
12063        });
12064
12065        workspace.update_in(cx, |workspace, window, cx| {
12066            // Close them manually
12067            workspace.toggle_dock(DockPosition::Left, window, cx);
12068            workspace.toggle_dock(DockPosition::Right, window, cx);
12069
12070            let left_dock = workspace.dock_at_position(DockPosition::Left);
12071            let right_dock = workspace.dock_at_position(DockPosition::Right);
12072            assert!(!left_dock.read(cx).is_open());
12073            assert!(!right_dock.read(cx).is_open());
12074        });
12075
12076        workspace.update_in(cx, |workspace, window, cx| {
12077            // Toggle all docks - only last closed (right dock) should reopen
12078            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12079
12080            let left_dock = workspace.dock_at_position(DockPosition::Left);
12081            let right_dock = workspace.dock_at_position(DockPosition::Right);
12082            assert!(!left_dock.read(cx).is_open());
12083            assert!(right_dock.read(cx).is_open());
12084        });
12085    }
12086
12087    #[gpui::test]
12088    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12089        init_test(cx);
12090        let fs = FakeFs::new(cx.executor());
12091        let project = Project::test(fs, [], cx).await;
12092        let (multi_workspace, cx) =
12093            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12094        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12095
12096        // Open two docks (left and right) with one panel each
12097        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12098            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12099            workspace.add_panel(left_panel.clone(), window, cx);
12100
12101            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12102            workspace.add_panel(right_panel.clone(), window, cx);
12103
12104            workspace.toggle_dock(DockPosition::Left, window, cx);
12105            workspace.toggle_dock(DockPosition::Right, window, cx);
12106
12107            // Verify initial state
12108            assert!(
12109                workspace.left_dock().read(cx).is_open(),
12110                "Left dock should be open"
12111            );
12112            assert_eq!(
12113                workspace
12114                    .left_dock()
12115                    .read(cx)
12116                    .visible_panel()
12117                    .unwrap()
12118                    .panel_id(),
12119                left_panel.panel_id(),
12120                "Left panel should be visible in left dock"
12121            );
12122            assert!(
12123                workspace.right_dock().read(cx).is_open(),
12124                "Right dock should be open"
12125            );
12126            assert_eq!(
12127                workspace
12128                    .right_dock()
12129                    .read(cx)
12130                    .visible_panel()
12131                    .unwrap()
12132                    .panel_id(),
12133                right_panel.panel_id(),
12134                "Right panel should be visible in right dock"
12135            );
12136            assert!(
12137                !workspace.bottom_dock().read(cx).is_open(),
12138                "Bottom dock should be closed"
12139            );
12140
12141            (left_panel, right_panel)
12142        });
12143
12144        // Focus the left panel and move it to the next position (bottom dock)
12145        workspace.update_in(cx, |workspace, window, cx| {
12146            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12147            assert!(
12148                left_panel.read(cx).focus_handle(cx).is_focused(window),
12149                "Left panel should be focused"
12150            );
12151        });
12152
12153        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12154
12155        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12156        workspace.update(cx, |workspace, cx| {
12157            assert!(
12158                !workspace.left_dock().read(cx).is_open(),
12159                "Left dock should be closed"
12160            );
12161            assert!(
12162                workspace.bottom_dock().read(cx).is_open(),
12163                "Bottom dock should now be open"
12164            );
12165            assert_eq!(
12166                left_panel.read(cx).position,
12167                DockPosition::Bottom,
12168                "Left panel should now be in the bottom dock"
12169            );
12170            assert_eq!(
12171                workspace
12172                    .bottom_dock()
12173                    .read(cx)
12174                    .visible_panel()
12175                    .unwrap()
12176                    .panel_id(),
12177                left_panel.panel_id(),
12178                "Left panel should be the visible panel in the bottom dock"
12179            );
12180        });
12181
12182        // Toggle all docks off
12183        workspace.update_in(cx, |workspace, window, cx| {
12184            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12185            assert!(
12186                !workspace.left_dock().read(cx).is_open(),
12187                "Left dock should be closed"
12188            );
12189            assert!(
12190                !workspace.right_dock().read(cx).is_open(),
12191                "Right dock should be closed"
12192            );
12193            assert!(
12194                !workspace.bottom_dock().read(cx).is_open(),
12195                "Bottom dock should be closed"
12196            );
12197        });
12198
12199        // Toggle all docks back on and verify positions are restored
12200        workspace.update_in(cx, |workspace, window, cx| {
12201            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12202            assert!(
12203                !workspace.left_dock().read(cx).is_open(),
12204                "Left dock should remain closed"
12205            );
12206            assert!(
12207                workspace.right_dock().read(cx).is_open(),
12208                "Right dock should remain open"
12209            );
12210            assert!(
12211                workspace.bottom_dock().read(cx).is_open(),
12212                "Bottom dock should remain open"
12213            );
12214            assert_eq!(
12215                left_panel.read(cx).position,
12216                DockPosition::Bottom,
12217                "Left panel should remain in the bottom dock"
12218            );
12219            assert_eq!(
12220                right_panel.read(cx).position,
12221                DockPosition::Right,
12222                "Right panel should remain in the right dock"
12223            );
12224            assert_eq!(
12225                workspace
12226                    .bottom_dock()
12227                    .read(cx)
12228                    .visible_panel()
12229                    .unwrap()
12230                    .panel_id(),
12231                left_panel.panel_id(),
12232                "Left panel should be the visible panel in the right dock"
12233            );
12234        });
12235    }
12236
12237    #[gpui::test]
12238    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12239        init_test(cx);
12240
12241        let fs = FakeFs::new(cx.executor());
12242
12243        let project = Project::test(fs, None, cx).await;
12244        let (workspace, cx) =
12245            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12246
12247        // Let's arrange the panes like this:
12248        //
12249        // +-----------------------+
12250        // |         top           |
12251        // +------+--------+-------+
12252        // | left | center | right |
12253        // +------+--------+-------+
12254        // |        bottom         |
12255        // +-----------------------+
12256
12257        let top_item = cx.new(|cx| {
12258            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12259        });
12260        let bottom_item = cx.new(|cx| {
12261            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12262        });
12263        let left_item = cx.new(|cx| {
12264            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12265        });
12266        let right_item = cx.new(|cx| {
12267            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12268        });
12269        let center_item = cx.new(|cx| {
12270            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12271        });
12272
12273        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12274            let top_pane_id = workspace.active_pane().entity_id();
12275            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12276            workspace.split_pane(
12277                workspace.active_pane().clone(),
12278                SplitDirection::Down,
12279                window,
12280                cx,
12281            );
12282            top_pane_id
12283        });
12284        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12285            let bottom_pane_id = workspace.active_pane().entity_id();
12286            workspace.add_item_to_active_pane(
12287                Box::new(bottom_item.clone()),
12288                None,
12289                false,
12290                window,
12291                cx,
12292            );
12293            workspace.split_pane(
12294                workspace.active_pane().clone(),
12295                SplitDirection::Up,
12296                window,
12297                cx,
12298            );
12299            bottom_pane_id
12300        });
12301        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12302            let left_pane_id = workspace.active_pane().entity_id();
12303            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12304            workspace.split_pane(
12305                workspace.active_pane().clone(),
12306                SplitDirection::Right,
12307                window,
12308                cx,
12309            );
12310            left_pane_id
12311        });
12312        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12313            let right_pane_id = workspace.active_pane().entity_id();
12314            workspace.add_item_to_active_pane(
12315                Box::new(right_item.clone()),
12316                None,
12317                false,
12318                window,
12319                cx,
12320            );
12321            workspace.split_pane(
12322                workspace.active_pane().clone(),
12323                SplitDirection::Left,
12324                window,
12325                cx,
12326            );
12327            right_pane_id
12328        });
12329        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12330            let center_pane_id = workspace.active_pane().entity_id();
12331            workspace.add_item_to_active_pane(
12332                Box::new(center_item.clone()),
12333                None,
12334                false,
12335                window,
12336                cx,
12337            );
12338            center_pane_id
12339        });
12340        cx.executor().run_until_parked();
12341
12342        workspace.update_in(cx, |workspace, window, cx| {
12343            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12344
12345            // Join into next from center pane into right
12346            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12347        });
12348
12349        workspace.update_in(cx, |workspace, window, cx| {
12350            let active_pane = workspace.active_pane();
12351            assert_eq!(right_pane_id, active_pane.entity_id());
12352            assert_eq!(2, active_pane.read(cx).items_len());
12353            let item_ids_in_pane =
12354                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12355            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12356            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12357
12358            // Join into next from right pane into bottom
12359            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12360        });
12361
12362        workspace.update_in(cx, |workspace, window, cx| {
12363            let active_pane = workspace.active_pane();
12364            assert_eq!(bottom_pane_id, active_pane.entity_id());
12365            assert_eq!(3, active_pane.read(cx).items_len());
12366            let item_ids_in_pane =
12367                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12368            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12369            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12370            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12371
12372            // Join into next from bottom pane into left
12373            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12374        });
12375
12376        workspace.update_in(cx, |workspace, window, cx| {
12377            let active_pane = workspace.active_pane();
12378            assert_eq!(left_pane_id, active_pane.entity_id());
12379            assert_eq!(4, active_pane.read(cx).items_len());
12380            let item_ids_in_pane =
12381                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12382            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12383            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12384            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12385            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12386
12387            // Join into next from left pane into top
12388            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12389        });
12390
12391        workspace.update_in(cx, |workspace, window, cx| {
12392            let active_pane = workspace.active_pane();
12393            assert_eq!(top_pane_id, active_pane.entity_id());
12394            assert_eq!(5, active_pane.read(cx).items_len());
12395            let item_ids_in_pane =
12396                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12397            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12398            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12399            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12400            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12401            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12402
12403            // Single pane left: no-op
12404            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12405        });
12406
12407        workspace.update(cx, |workspace, _cx| {
12408            let active_pane = workspace.active_pane();
12409            assert_eq!(top_pane_id, active_pane.entity_id());
12410        });
12411    }
12412
12413    fn add_an_item_to_active_pane(
12414        cx: &mut VisualTestContext,
12415        workspace: &Entity<Workspace>,
12416        item_id: u64,
12417    ) -> Entity<TestItem> {
12418        let item = cx.new(|cx| {
12419            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12420                item_id,
12421                "item{item_id}.txt",
12422                cx,
12423            )])
12424        });
12425        workspace.update_in(cx, |workspace, window, cx| {
12426            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12427        });
12428        item
12429    }
12430
12431    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12432        workspace.update_in(cx, |workspace, window, cx| {
12433            workspace.split_pane(
12434                workspace.active_pane().clone(),
12435                SplitDirection::Right,
12436                window,
12437                cx,
12438            )
12439        })
12440    }
12441
12442    #[gpui::test]
12443    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12444        init_test(cx);
12445        let fs = FakeFs::new(cx.executor());
12446        let project = Project::test(fs, None, cx).await;
12447        let (workspace, cx) =
12448            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12449
12450        add_an_item_to_active_pane(cx, &workspace, 1);
12451        split_pane(cx, &workspace);
12452        add_an_item_to_active_pane(cx, &workspace, 2);
12453        split_pane(cx, &workspace); // empty pane
12454        split_pane(cx, &workspace);
12455        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12456
12457        cx.executor().run_until_parked();
12458
12459        workspace.update(cx, |workspace, cx| {
12460            let num_panes = workspace.panes().len();
12461            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12462            let active_item = workspace
12463                .active_pane()
12464                .read(cx)
12465                .active_item()
12466                .expect("item is in focus");
12467
12468            assert_eq!(num_panes, 4);
12469            assert_eq!(num_items_in_current_pane, 1);
12470            assert_eq!(active_item.item_id(), last_item.item_id());
12471        });
12472
12473        workspace.update_in(cx, |workspace, window, cx| {
12474            workspace.join_all_panes(window, cx);
12475        });
12476
12477        workspace.update(cx, |workspace, cx| {
12478            let num_panes = workspace.panes().len();
12479            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12480            let active_item = workspace
12481                .active_pane()
12482                .read(cx)
12483                .active_item()
12484                .expect("item is in focus");
12485
12486            assert_eq!(num_panes, 1);
12487            assert_eq!(num_items_in_current_pane, 3);
12488            assert_eq!(active_item.item_id(), last_item.item_id());
12489        });
12490    }
12491
12492    #[gpui::test]
12493    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12494        init_test(cx);
12495        let fs = FakeFs::new(cx.executor());
12496
12497        let project = Project::test(fs, [], cx).await;
12498        let (multi_workspace, cx) =
12499            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12500        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12501
12502        workspace.update(cx, |workspace, _cx| {
12503            workspace.bounds.size.width = px(800.);
12504        });
12505
12506        workspace.update_in(cx, |workspace, window, cx| {
12507            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12508            workspace.add_panel(panel, window, cx);
12509            workspace.toggle_dock(DockPosition::Right, window, cx);
12510        });
12511
12512        let (panel, resized_width, ratio_basis_width) =
12513            workspace.update_in(cx, |workspace, window, cx| {
12514                let item = cx.new(|cx| {
12515                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12516                });
12517                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12518
12519                let dock = workspace.right_dock().read(cx);
12520                let workspace_width = workspace.bounds.size.width;
12521                let initial_width = workspace
12522                    .dock_size(&dock, window, cx)
12523                    .expect("flexible dock should have an initial width");
12524
12525                assert_eq!(initial_width, workspace_width / 2.);
12526
12527                workspace.resize_right_dock(px(300.), window, cx);
12528
12529                let dock = workspace.right_dock().read(cx);
12530                let resized_width = workspace
12531                    .dock_size(&dock, window, cx)
12532                    .expect("flexible dock should keep its resized width");
12533
12534                assert_eq!(resized_width, px(300.));
12535
12536                let panel = workspace
12537                    .right_dock()
12538                    .read(cx)
12539                    .visible_panel()
12540                    .expect("flexible dock should have a visible panel")
12541                    .panel_id();
12542
12543                (panel, resized_width, workspace_width)
12544            });
12545
12546        workspace.update_in(cx, |workspace, window, cx| {
12547            workspace.toggle_dock(DockPosition::Right, window, cx);
12548            workspace.toggle_dock(DockPosition::Right, window, cx);
12549
12550            let dock = workspace.right_dock().read(cx);
12551            let reopened_width = workspace
12552                .dock_size(&dock, window, cx)
12553                .expect("flexible dock should restore when reopened");
12554
12555            assert_eq!(reopened_width, resized_width);
12556
12557            let right_dock = workspace.right_dock().read(cx);
12558            let flexible_panel = right_dock
12559                .visible_panel()
12560                .expect("flexible dock should still have a visible panel");
12561            assert_eq!(flexible_panel.panel_id(), panel);
12562            assert_eq!(
12563                right_dock
12564                    .stored_panel_size_state(flexible_panel.as_ref())
12565                    .and_then(|size_state| size_state.flex),
12566                Some(
12567                    resized_width.to_f64() as f32
12568                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12569                )
12570            );
12571        });
12572
12573        workspace.update_in(cx, |workspace, window, cx| {
12574            workspace.split_pane(
12575                workspace.active_pane().clone(),
12576                SplitDirection::Right,
12577                window,
12578                cx,
12579            );
12580
12581            let dock = workspace.right_dock().read(cx);
12582            let split_width = workspace
12583                .dock_size(&dock, window, cx)
12584                .expect("flexible dock should keep its user-resized proportion");
12585
12586            assert_eq!(split_width, px(300.));
12587
12588            workspace.bounds.size.width = px(1600.);
12589
12590            let dock = workspace.right_dock().read(cx);
12591            let resized_window_width = workspace
12592                .dock_size(&dock, window, cx)
12593                .expect("flexible dock should preserve proportional size on window resize");
12594
12595            assert_eq!(
12596                resized_window_width,
12597                workspace.bounds.size.width
12598                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12599            );
12600        });
12601    }
12602
12603    #[gpui::test]
12604    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12605        init_test(cx);
12606        let fs = FakeFs::new(cx.executor());
12607
12608        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12609        {
12610            let project = Project::test(fs.clone(), [], cx).await;
12611            let (multi_workspace, cx) =
12612                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12613            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12614
12615            workspace.update(cx, |workspace, _cx| {
12616                workspace.set_random_database_id();
12617                workspace.bounds.size.width = px(800.);
12618            });
12619
12620            let panel = workspace.update_in(cx, |workspace, window, cx| {
12621                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12622                workspace.add_panel(panel.clone(), window, cx);
12623                workspace.toggle_dock(DockPosition::Left, window, cx);
12624                panel
12625            });
12626
12627            workspace.update_in(cx, |workspace, window, cx| {
12628                workspace.resize_left_dock(px(350.), window, cx);
12629            });
12630
12631            cx.run_until_parked();
12632
12633            let persisted = workspace.read_with(cx, |workspace, cx| {
12634                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12635            });
12636            assert_eq!(
12637                persisted.and_then(|s| s.size),
12638                Some(px(350.)),
12639                "fixed-width panel size should be persisted to KVP"
12640            );
12641
12642            // Remove the panel and re-add a fresh instance with the same key.
12643            // The new instance should have its size state restored from KVP.
12644            workspace.update_in(cx, |workspace, window, cx| {
12645                workspace.remove_panel(&panel, window, cx);
12646            });
12647
12648            workspace.update_in(cx, |workspace, window, cx| {
12649                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12650                workspace.add_panel(new_panel, window, cx);
12651
12652                let left_dock = workspace.left_dock().read(cx);
12653                let size_state = left_dock
12654                    .panel::<TestPanel>()
12655                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12656                assert_eq!(
12657                    size_state.and_then(|s| s.size),
12658                    Some(px(350.)),
12659                    "re-added fixed-width panel should restore persisted size from KVP"
12660                );
12661            });
12662        }
12663
12664        // Flexible panel: both pixel size and ratio are persisted and restored.
12665        {
12666            let project = Project::test(fs.clone(), [], cx).await;
12667            let (multi_workspace, cx) =
12668                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12669            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12670
12671            workspace.update(cx, |workspace, _cx| {
12672                workspace.set_random_database_id();
12673                workspace.bounds.size.width = px(800.);
12674            });
12675
12676            let panel = workspace.update_in(cx, |workspace, window, cx| {
12677                let item = cx.new(|cx| {
12678                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12679                });
12680                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12681
12682                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12683                workspace.add_panel(panel.clone(), window, cx);
12684                workspace.toggle_dock(DockPosition::Right, window, cx);
12685                panel
12686            });
12687
12688            workspace.update_in(cx, |workspace, window, cx| {
12689                workspace.resize_right_dock(px(300.), window, cx);
12690            });
12691
12692            cx.run_until_parked();
12693
12694            let persisted = workspace
12695                .read_with(cx, |workspace, cx| {
12696                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12697                })
12698                .expect("flexible panel state should be persisted to KVP");
12699            assert_eq!(
12700                persisted.size, None,
12701                "flexible panel should not persist a redundant pixel size"
12702            );
12703            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12704
12705            // Remove the panel and re-add: both size and ratio should be restored.
12706            workspace.update_in(cx, |workspace, window, cx| {
12707                workspace.remove_panel(&panel, window, cx);
12708            });
12709
12710            workspace.update_in(cx, |workspace, window, cx| {
12711                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12712                workspace.add_panel(new_panel, window, cx);
12713
12714                let right_dock = workspace.right_dock().read(cx);
12715                let size_state = right_dock
12716                    .panel::<TestPanel>()
12717                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12718                    .expect("re-added flexible panel should have restored size state from KVP");
12719                assert_eq!(
12720                    size_state.size, None,
12721                    "re-added flexible panel should not have a persisted pixel size"
12722                );
12723                assert_eq!(
12724                    size_state.flex,
12725                    Some(original_ratio),
12726                    "re-added flexible panel should restore persisted flex"
12727                );
12728            });
12729        }
12730    }
12731
12732    #[gpui::test]
12733    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12734        init_test(cx);
12735        let fs = FakeFs::new(cx.executor());
12736
12737        let project = Project::test(fs, [], cx).await;
12738        let (multi_workspace, cx) =
12739            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12740        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12741
12742        workspace.update(cx, |workspace, _cx| {
12743            workspace.bounds.size.width = px(900.);
12744        });
12745
12746        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12747        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12748        // and the center pane each take half the workspace width.
12749        workspace.update_in(cx, |workspace, window, cx| {
12750            let item = cx.new(|cx| {
12751                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12752            });
12753            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12754
12755            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12756            workspace.add_panel(panel, window, cx);
12757            workspace.toggle_dock(DockPosition::Left, window, cx);
12758
12759            let left_dock = workspace.left_dock().read(cx);
12760            let left_width = workspace
12761                .dock_size(&left_dock, window, cx)
12762                .expect("left dock should have an active panel");
12763
12764            assert_eq!(
12765                left_width,
12766                workspace.bounds.size.width / 2.,
12767                "flexible left panel should split evenly with the center pane"
12768            );
12769        });
12770
12771        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12772        // change horizontal width fractions, so the flexible panel stays at the same
12773        // width as each half of the split.
12774        workspace.update_in(cx, |workspace, window, cx| {
12775            workspace.split_pane(
12776                workspace.active_pane().clone(),
12777                SplitDirection::Down,
12778                window,
12779                cx,
12780            );
12781
12782            let left_dock = workspace.left_dock().read(cx);
12783            let left_width = workspace
12784                .dock_size(&left_dock, window, cx)
12785                .expect("left dock should still have an active panel after vertical split");
12786
12787            assert_eq!(
12788                left_width,
12789                workspace.bounds.size.width / 2.,
12790                "flexible left panel width should match each vertically-split pane"
12791            );
12792        });
12793
12794        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12795        // size reduces the available width, so the flexible left panel and the center
12796        // panes all shrink proportionally to accommodate it.
12797        workspace.update_in(cx, |workspace, window, cx| {
12798            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12799            workspace.add_panel(panel, window, cx);
12800            workspace.toggle_dock(DockPosition::Right, window, cx);
12801
12802            let right_dock = workspace.right_dock().read(cx);
12803            let right_width = workspace
12804                .dock_size(&right_dock, window, cx)
12805                .expect("right dock should have an active panel");
12806
12807            let left_dock = workspace.left_dock().read(cx);
12808            let left_width = workspace
12809                .dock_size(&left_dock, window, cx)
12810                .expect("left dock should still have an active panel");
12811
12812            let available_width = workspace.bounds.size.width - right_width;
12813            assert_eq!(
12814                left_width,
12815                available_width / 2.,
12816                "flexible left panel should shrink proportionally as the right dock takes space"
12817            );
12818        });
12819
12820        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12821        // flex sizing and the workspace width is divided among left-flex, center
12822        // (implicit flex 1.0), and right-flex.
12823        workspace.update_in(cx, |workspace, window, cx| {
12824            let right_dock = workspace.right_dock().clone();
12825            let right_panel = right_dock
12826                .read(cx)
12827                .visible_panel()
12828                .expect("right dock should have a visible panel")
12829                .clone();
12830            workspace.toggle_dock_panel_flexible_size(
12831                &right_dock,
12832                right_panel.as_ref(),
12833                window,
12834                cx,
12835            );
12836
12837            let right_dock = right_dock.read(cx);
12838            let right_panel = right_dock
12839                .visible_panel()
12840                .expect("right dock should still have a visible panel");
12841            assert!(
12842                right_panel.has_flexible_size(window, cx),
12843                "right panel should now be flexible"
12844            );
12845
12846            let right_size_state = right_dock
12847                .stored_panel_size_state(right_panel.as_ref())
12848                .expect("right panel should have a stored size state after toggling");
12849            let right_flex = right_size_state
12850                .flex
12851                .expect("right panel should have a flex value after toggling");
12852
12853            let left_dock = workspace.left_dock().read(cx);
12854            let left_width = workspace
12855                .dock_size(&left_dock, window, cx)
12856                .expect("left dock should still have an active panel");
12857            let right_width = workspace
12858                .dock_size(&right_dock, window, cx)
12859                .expect("right dock should still have an active panel");
12860
12861            let left_flex = workspace
12862                .default_dock_flex(DockPosition::Left)
12863                .expect("left dock should have a default flex");
12864
12865            let total_flex = left_flex + 1.0 + right_flex;
12866            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12867            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12868            assert_eq!(
12869                left_width, expected_left,
12870                "flexible left panel should share workspace width via flex ratios"
12871            );
12872            assert_eq!(
12873                right_width, expected_right,
12874                "flexible right panel should share workspace width via flex ratios"
12875            );
12876        });
12877    }
12878
12879    struct TestModal(FocusHandle);
12880
12881    impl TestModal {
12882        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12883            Self(cx.focus_handle())
12884        }
12885    }
12886
12887    impl EventEmitter<DismissEvent> for TestModal {}
12888
12889    impl Focusable for TestModal {
12890        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12891            self.0.clone()
12892        }
12893    }
12894
12895    impl ModalView for TestModal {}
12896
12897    impl Render for TestModal {
12898        fn render(
12899            &mut self,
12900            _window: &mut Window,
12901            _cx: &mut Context<TestModal>,
12902        ) -> impl IntoElement {
12903            div().track_focus(&self.0)
12904        }
12905    }
12906
12907    #[gpui::test]
12908    async fn test_panels(cx: &mut gpui::TestAppContext) {
12909        init_test(cx);
12910        let fs = FakeFs::new(cx.executor());
12911
12912        let project = Project::test(fs, [], cx).await;
12913        let (multi_workspace, cx) =
12914            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12915        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12916
12917        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12918            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12919            workspace.add_panel(panel_1.clone(), window, cx);
12920            workspace.toggle_dock(DockPosition::Left, window, cx);
12921            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12922            workspace.add_panel(panel_2.clone(), window, cx);
12923            workspace.toggle_dock(DockPosition::Right, window, cx);
12924
12925            let left_dock = workspace.left_dock();
12926            assert_eq!(
12927                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12928                panel_1.panel_id()
12929            );
12930            assert_eq!(
12931                workspace.dock_size(&left_dock.read(cx), window, cx),
12932                Some(px(300.))
12933            );
12934
12935            workspace.resize_left_dock(px(1337.), window, cx);
12936            assert_eq!(
12937                workspace
12938                    .right_dock()
12939                    .read(cx)
12940                    .visible_panel()
12941                    .unwrap()
12942                    .panel_id(),
12943                panel_2.panel_id(),
12944            );
12945
12946            (panel_1, panel_2)
12947        });
12948
12949        // Move panel_1 to the right
12950        panel_1.update_in(cx, |panel_1, window, cx| {
12951            panel_1.set_position(DockPosition::Right, window, cx)
12952        });
12953
12954        workspace.update_in(cx, |workspace, window, cx| {
12955            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12956            // Since it was the only panel on the left, the left dock should now be closed.
12957            assert!(!workspace.left_dock().read(cx).is_open());
12958            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12959            let right_dock = workspace.right_dock();
12960            assert_eq!(
12961                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12962                panel_1.panel_id()
12963            );
12964            assert_eq!(
12965                right_dock
12966                    .read(cx)
12967                    .active_panel_size()
12968                    .unwrap()
12969                    .size
12970                    .unwrap(),
12971                px(1337.)
12972            );
12973
12974            // Now we move panel_2 to the left
12975            panel_2.set_position(DockPosition::Left, window, cx);
12976        });
12977
12978        workspace.update(cx, |workspace, cx| {
12979            // Since panel_2 was not visible on the right, we don't open the left dock.
12980            assert!(!workspace.left_dock().read(cx).is_open());
12981            // And the right dock is unaffected in its displaying of panel_1
12982            assert!(workspace.right_dock().read(cx).is_open());
12983            assert_eq!(
12984                workspace
12985                    .right_dock()
12986                    .read(cx)
12987                    .visible_panel()
12988                    .unwrap()
12989                    .panel_id(),
12990                panel_1.panel_id(),
12991            );
12992        });
12993
12994        // Move panel_1 back to the left
12995        panel_1.update_in(cx, |panel_1, window, cx| {
12996            panel_1.set_position(DockPosition::Left, window, cx)
12997        });
12998
12999        workspace.update_in(cx, |workspace, window, cx| {
13000            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13001            let left_dock = workspace.left_dock();
13002            assert!(left_dock.read(cx).is_open());
13003            assert_eq!(
13004                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13005                panel_1.panel_id()
13006            );
13007            assert_eq!(
13008                workspace.dock_size(&left_dock.read(cx), window, cx),
13009                Some(px(1337.))
13010            );
13011            // And the right dock should be closed as it no longer has any panels.
13012            assert!(!workspace.right_dock().read(cx).is_open());
13013
13014            // Now we move panel_1 to the bottom
13015            panel_1.set_position(DockPosition::Bottom, window, cx);
13016        });
13017
13018        workspace.update_in(cx, |workspace, window, cx| {
13019            // Since panel_1 was visible on the left, we close the left dock.
13020            assert!(!workspace.left_dock().read(cx).is_open());
13021            // The bottom dock is sized based on the panel's default size,
13022            // since the panel orientation changed from vertical to horizontal.
13023            let bottom_dock = workspace.bottom_dock();
13024            assert_eq!(
13025                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13026                Some(px(300.))
13027            );
13028            // Close bottom dock and move panel_1 back to the left.
13029            bottom_dock.update(cx, |bottom_dock, cx| {
13030                bottom_dock.set_open(false, window, cx)
13031            });
13032            panel_1.set_position(DockPosition::Left, window, cx);
13033        });
13034
13035        // Emit activated event on panel 1
13036        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13037
13038        // Now the left dock is open and panel_1 is active and focused.
13039        workspace.update_in(cx, |workspace, window, cx| {
13040            let left_dock = workspace.left_dock();
13041            assert!(left_dock.read(cx).is_open());
13042            assert_eq!(
13043                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13044                panel_1.panel_id(),
13045            );
13046            assert!(panel_1.focus_handle(cx).is_focused(window));
13047        });
13048
13049        // Emit closed event on panel 2, which is not active
13050        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13051
13052        // Wo don't close the left dock, because panel_2 wasn't the active panel
13053        workspace.update(cx, |workspace, cx| {
13054            let left_dock = workspace.left_dock();
13055            assert!(left_dock.read(cx).is_open());
13056            assert_eq!(
13057                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13058                panel_1.panel_id(),
13059            );
13060        });
13061
13062        // Emitting a ZoomIn event shows the panel as zoomed.
13063        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13064        workspace.read_with(cx, |workspace, _| {
13065            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13066            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13067        });
13068
13069        // Move panel to another dock while it is zoomed
13070        panel_1.update_in(cx, |panel, window, cx| {
13071            panel.set_position(DockPosition::Right, window, cx)
13072        });
13073        workspace.read_with(cx, |workspace, _| {
13074            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13075
13076            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13077        });
13078
13079        // This is a helper for getting a:
13080        // - valid focus on an element,
13081        // - that isn't a part of the panes and panels system of the Workspace,
13082        // - and doesn't trigger the 'on_focus_lost' API.
13083        let focus_other_view = {
13084            let workspace = workspace.clone();
13085            move |cx: &mut VisualTestContext| {
13086                workspace.update_in(cx, |workspace, window, cx| {
13087                    if workspace.active_modal::<TestModal>(cx).is_some() {
13088                        workspace.toggle_modal(window, cx, TestModal::new);
13089                        workspace.toggle_modal(window, cx, TestModal::new);
13090                    } else {
13091                        workspace.toggle_modal(window, cx, TestModal::new);
13092                    }
13093                })
13094            }
13095        };
13096
13097        // If focus is transferred to another view that's not a panel or another pane, we still show
13098        // the panel as zoomed.
13099        focus_other_view(cx);
13100        workspace.read_with(cx, |workspace, _| {
13101            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13102            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13103        });
13104
13105        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13106        workspace.update_in(cx, |_workspace, window, cx| {
13107            cx.focus_self(window);
13108        });
13109        workspace.read_with(cx, |workspace, _| {
13110            assert_eq!(workspace.zoomed, None);
13111            assert_eq!(workspace.zoomed_position, None);
13112        });
13113
13114        // If focus is transferred again to another view that's not a panel or a pane, we won't
13115        // show the panel as zoomed because it wasn't zoomed before.
13116        focus_other_view(cx);
13117        workspace.read_with(cx, |workspace, _| {
13118            assert_eq!(workspace.zoomed, None);
13119            assert_eq!(workspace.zoomed_position, None);
13120        });
13121
13122        // When the panel is activated, it is zoomed again.
13123        cx.dispatch_action(ToggleRightDock);
13124        workspace.read_with(cx, |workspace, _| {
13125            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13126            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13127        });
13128
13129        // Emitting a ZoomOut event unzooms the panel.
13130        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13131        workspace.read_with(cx, |workspace, _| {
13132            assert_eq!(workspace.zoomed, None);
13133            assert_eq!(workspace.zoomed_position, None);
13134        });
13135
13136        // Emit closed event on panel 1, which is active
13137        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13138
13139        // Now the left dock is closed, because panel_1 was the active panel
13140        workspace.update(cx, |workspace, cx| {
13141            let right_dock = workspace.right_dock();
13142            assert!(!right_dock.read(cx).is_open());
13143        });
13144    }
13145
13146    #[gpui::test]
13147    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13148        init_test(cx);
13149
13150        let fs = FakeFs::new(cx.background_executor.clone());
13151        let project = Project::test(fs, [], cx).await;
13152        let (workspace, cx) =
13153            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13154        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13155
13156        let dirty_regular_buffer = cx.new(|cx| {
13157            TestItem::new(cx)
13158                .with_dirty(true)
13159                .with_label("1.txt")
13160                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13161        });
13162        let dirty_regular_buffer_2 = cx.new(|cx| {
13163            TestItem::new(cx)
13164                .with_dirty(true)
13165                .with_label("2.txt")
13166                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13167        });
13168        let dirty_multi_buffer_with_both = cx.new(|cx| {
13169            TestItem::new(cx)
13170                .with_dirty(true)
13171                .with_buffer_kind(ItemBufferKind::Multibuffer)
13172                .with_label("Fake Project Search")
13173                .with_project_items(&[
13174                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13175                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13176                ])
13177        });
13178        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13179        workspace.update_in(cx, |workspace, window, cx| {
13180            workspace.add_item(
13181                pane.clone(),
13182                Box::new(dirty_regular_buffer.clone()),
13183                None,
13184                false,
13185                false,
13186                window,
13187                cx,
13188            );
13189            workspace.add_item(
13190                pane.clone(),
13191                Box::new(dirty_regular_buffer_2.clone()),
13192                None,
13193                false,
13194                false,
13195                window,
13196                cx,
13197            );
13198            workspace.add_item(
13199                pane.clone(),
13200                Box::new(dirty_multi_buffer_with_both.clone()),
13201                None,
13202                false,
13203                false,
13204                window,
13205                cx,
13206            );
13207        });
13208
13209        pane.update_in(cx, |pane, window, cx| {
13210            pane.activate_item(2, true, true, window, cx);
13211            assert_eq!(
13212                pane.active_item().unwrap().item_id(),
13213                multi_buffer_with_both_files_id,
13214                "Should select the multi buffer in the pane"
13215            );
13216        });
13217        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13218            pane.close_other_items(
13219                &CloseOtherItems {
13220                    save_intent: Some(SaveIntent::Save),
13221                    close_pinned: true,
13222                },
13223                None,
13224                window,
13225                cx,
13226            )
13227        });
13228        cx.background_executor.run_until_parked();
13229        assert!(!cx.has_pending_prompt());
13230        close_all_but_multi_buffer_task
13231            .await
13232            .expect("Closing all buffers but the multi buffer failed");
13233        pane.update(cx, |pane, cx| {
13234            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13235            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13236            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13237            assert_eq!(pane.items_len(), 1);
13238            assert_eq!(
13239                pane.active_item().unwrap().item_id(),
13240                multi_buffer_with_both_files_id,
13241                "Should have only the multi buffer left in the pane"
13242            );
13243            assert!(
13244                dirty_multi_buffer_with_both.read(cx).is_dirty,
13245                "The multi buffer containing the unsaved buffer should still be dirty"
13246            );
13247        });
13248
13249        dirty_regular_buffer.update(cx, |buffer, cx| {
13250            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13251        });
13252
13253        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13254            pane.close_active_item(
13255                &CloseActiveItem {
13256                    save_intent: Some(SaveIntent::Close),
13257                    close_pinned: false,
13258                },
13259                window,
13260                cx,
13261            )
13262        });
13263        cx.background_executor.run_until_parked();
13264        assert!(
13265            cx.has_pending_prompt(),
13266            "Dirty multi buffer should prompt a save dialog"
13267        );
13268        cx.simulate_prompt_answer("Save");
13269        cx.background_executor.run_until_parked();
13270        close_multi_buffer_task
13271            .await
13272            .expect("Closing the multi buffer failed");
13273        pane.update(cx, |pane, cx| {
13274            assert_eq!(
13275                dirty_multi_buffer_with_both.read(cx).save_count,
13276                1,
13277                "Multi buffer item should get be saved"
13278            );
13279            // Test impl does not save inner items, so we do not assert them
13280            assert_eq!(
13281                pane.items_len(),
13282                0,
13283                "No more items should be left in the pane"
13284            );
13285            assert!(pane.active_item().is_none());
13286        });
13287    }
13288
13289    #[gpui::test]
13290    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13291        cx: &mut TestAppContext,
13292    ) {
13293        init_test(cx);
13294
13295        let fs = FakeFs::new(cx.background_executor.clone());
13296        let project = Project::test(fs, [], cx).await;
13297        let (workspace, cx) =
13298            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13299        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13300
13301        let dirty_regular_buffer = cx.new(|cx| {
13302            TestItem::new(cx)
13303                .with_dirty(true)
13304                .with_label("1.txt")
13305                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13306        });
13307        let dirty_regular_buffer_2 = cx.new(|cx| {
13308            TestItem::new(cx)
13309                .with_dirty(true)
13310                .with_label("2.txt")
13311                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13312        });
13313        let clear_regular_buffer = cx.new(|cx| {
13314            TestItem::new(cx)
13315                .with_label("3.txt")
13316                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13317        });
13318
13319        let dirty_multi_buffer_with_both = cx.new(|cx| {
13320            TestItem::new(cx)
13321                .with_dirty(true)
13322                .with_buffer_kind(ItemBufferKind::Multibuffer)
13323                .with_label("Fake Project Search")
13324                .with_project_items(&[
13325                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13326                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13327                    clear_regular_buffer.read(cx).project_items[0].clone(),
13328                ])
13329        });
13330        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13331        workspace.update_in(cx, |workspace, window, cx| {
13332            workspace.add_item(
13333                pane.clone(),
13334                Box::new(dirty_regular_buffer.clone()),
13335                None,
13336                false,
13337                false,
13338                window,
13339                cx,
13340            );
13341            workspace.add_item(
13342                pane.clone(),
13343                Box::new(dirty_multi_buffer_with_both.clone()),
13344                None,
13345                false,
13346                false,
13347                window,
13348                cx,
13349            );
13350        });
13351
13352        pane.update_in(cx, |pane, window, cx| {
13353            pane.activate_item(1, true, true, window, cx);
13354            assert_eq!(
13355                pane.active_item().unwrap().item_id(),
13356                multi_buffer_with_both_files_id,
13357                "Should select the multi buffer in the pane"
13358            );
13359        });
13360        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13361            pane.close_active_item(
13362                &CloseActiveItem {
13363                    save_intent: None,
13364                    close_pinned: false,
13365                },
13366                window,
13367                cx,
13368            )
13369        });
13370        cx.background_executor.run_until_parked();
13371        assert!(
13372            cx.has_pending_prompt(),
13373            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13374        );
13375    }
13376
13377    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13378    /// closed when they are deleted from disk.
13379    #[gpui::test]
13380    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13381        init_test(cx);
13382
13383        // Enable the close_on_disk_deletion setting
13384        cx.update_global(|store: &mut SettingsStore, cx| {
13385            store.update_user_settings(cx, |settings| {
13386                settings.workspace.close_on_file_delete = Some(true);
13387            });
13388        });
13389
13390        let fs = FakeFs::new(cx.background_executor.clone());
13391        let project = Project::test(fs, [], cx).await;
13392        let (workspace, cx) =
13393            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13394        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13395
13396        // Create a test item that simulates a file
13397        let item = cx.new(|cx| {
13398            TestItem::new(cx)
13399                .with_label("test.txt")
13400                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13401        });
13402
13403        // Add item to workspace
13404        workspace.update_in(cx, |workspace, window, cx| {
13405            workspace.add_item(
13406                pane.clone(),
13407                Box::new(item.clone()),
13408                None,
13409                false,
13410                false,
13411                window,
13412                cx,
13413            );
13414        });
13415
13416        // Verify the item is in the pane
13417        pane.read_with(cx, |pane, _| {
13418            assert_eq!(pane.items().count(), 1);
13419        });
13420
13421        // Simulate file deletion by setting the item's deleted state
13422        item.update(cx, |item, _| {
13423            item.set_has_deleted_file(true);
13424        });
13425
13426        // Emit UpdateTab event to trigger the close behavior
13427        cx.run_until_parked();
13428        item.update(cx, |_, cx| {
13429            cx.emit(ItemEvent::UpdateTab);
13430        });
13431
13432        // Allow the close operation to complete
13433        cx.run_until_parked();
13434
13435        // Verify the item was automatically closed
13436        pane.read_with(cx, |pane, _| {
13437            assert_eq!(
13438                pane.items().count(),
13439                0,
13440                "Item should be automatically closed when file is deleted"
13441            );
13442        });
13443    }
13444
13445    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13446    /// open with a strikethrough when they are deleted from disk.
13447    #[gpui::test]
13448    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13449        init_test(cx);
13450
13451        // Ensure close_on_disk_deletion is disabled (default)
13452        cx.update_global(|store: &mut SettingsStore, cx| {
13453            store.update_user_settings(cx, |settings| {
13454                settings.workspace.close_on_file_delete = Some(false);
13455            });
13456        });
13457
13458        let fs = FakeFs::new(cx.background_executor.clone());
13459        let project = Project::test(fs, [], cx).await;
13460        let (workspace, cx) =
13461            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13462        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13463
13464        // Create a test item that simulates a file
13465        let item = cx.new(|cx| {
13466            TestItem::new(cx)
13467                .with_label("test.txt")
13468                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13469        });
13470
13471        // Add item to workspace
13472        workspace.update_in(cx, |workspace, window, cx| {
13473            workspace.add_item(
13474                pane.clone(),
13475                Box::new(item.clone()),
13476                None,
13477                false,
13478                false,
13479                window,
13480                cx,
13481            );
13482        });
13483
13484        // Verify the item is in the pane
13485        pane.read_with(cx, |pane, _| {
13486            assert_eq!(pane.items().count(), 1);
13487        });
13488
13489        // Simulate file deletion
13490        item.update(cx, |item, _| {
13491            item.set_has_deleted_file(true);
13492        });
13493
13494        // Emit UpdateTab event
13495        cx.run_until_parked();
13496        item.update(cx, |_, cx| {
13497            cx.emit(ItemEvent::UpdateTab);
13498        });
13499
13500        // Allow any potential close operation to complete
13501        cx.run_until_parked();
13502
13503        // Verify the item remains open (with strikethrough)
13504        pane.read_with(cx, |pane, _| {
13505            assert_eq!(
13506                pane.items().count(),
13507                1,
13508                "Item should remain open when close_on_disk_deletion is disabled"
13509            );
13510        });
13511
13512        // Verify the item shows as deleted
13513        item.read_with(cx, |item, _| {
13514            assert!(
13515                item.has_deleted_file,
13516                "Item should be marked as having deleted file"
13517            );
13518        });
13519    }
13520
13521    /// Tests that dirty files are not automatically closed when deleted from disk,
13522    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13523    /// unsaved changes without being prompted.
13524    #[gpui::test]
13525    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13526        init_test(cx);
13527
13528        // Enable the close_on_file_delete setting
13529        cx.update_global(|store: &mut SettingsStore, cx| {
13530            store.update_user_settings(cx, |settings| {
13531                settings.workspace.close_on_file_delete = Some(true);
13532            });
13533        });
13534
13535        let fs = FakeFs::new(cx.background_executor.clone());
13536        let project = Project::test(fs, [], cx).await;
13537        let (workspace, cx) =
13538            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13539        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13540
13541        // Create a dirty test item
13542        let item = cx.new(|cx| {
13543            TestItem::new(cx)
13544                .with_dirty(true)
13545                .with_label("test.txt")
13546                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13547        });
13548
13549        // Add item to workspace
13550        workspace.update_in(cx, |workspace, window, cx| {
13551            workspace.add_item(
13552                pane.clone(),
13553                Box::new(item.clone()),
13554                None,
13555                false,
13556                false,
13557                window,
13558                cx,
13559            );
13560        });
13561
13562        // Simulate file deletion
13563        item.update(cx, |item, _| {
13564            item.set_has_deleted_file(true);
13565        });
13566
13567        // Emit UpdateTab event to trigger the close behavior
13568        cx.run_until_parked();
13569        item.update(cx, |_, cx| {
13570            cx.emit(ItemEvent::UpdateTab);
13571        });
13572
13573        // Allow any potential close operation to complete
13574        cx.run_until_parked();
13575
13576        // Verify the item remains open (dirty files are not auto-closed)
13577        pane.read_with(cx, |pane, _| {
13578            assert_eq!(
13579                pane.items().count(),
13580                1,
13581                "Dirty items should not be automatically closed even when file is deleted"
13582            );
13583        });
13584
13585        // Verify the item is marked as deleted and still dirty
13586        item.read_with(cx, |item, _| {
13587            assert!(
13588                item.has_deleted_file,
13589                "Item should be marked as having deleted file"
13590            );
13591            assert!(item.is_dirty, "Item should still be dirty");
13592        });
13593    }
13594
13595    /// Tests that navigation history is cleaned up when files are auto-closed
13596    /// due to deletion from disk.
13597    #[gpui::test]
13598    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13599        init_test(cx);
13600
13601        // Enable the close_on_file_delete setting
13602        cx.update_global(|store: &mut SettingsStore, cx| {
13603            store.update_user_settings(cx, |settings| {
13604                settings.workspace.close_on_file_delete = Some(true);
13605            });
13606        });
13607
13608        let fs = FakeFs::new(cx.background_executor.clone());
13609        let project = Project::test(fs, [], cx).await;
13610        let (workspace, cx) =
13611            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13612        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13613
13614        // Create test items
13615        let item1 = cx.new(|cx| {
13616            TestItem::new(cx)
13617                .with_label("test1.txt")
13618                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13619        });
13620        let item1_id = item1.item_id();
13621
13622        let item2 = cx.new(|cx| {
13623            TestItem::new(cx)
13624                .with_label("test2.txt")
13625                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13626        });
13627
13628        // Add items to workspace
13629        workspace.update_in(cx, |workspace, window, cx| {
13630            workspace.add_item(
13631                pane.clone(),
13632                Box::new(item1.clone()),
13633                None,
13634                false,
13635                false,
13636                window,
13637                cx,
13638            );
13639            workspace.add_item(
13640                pane.clone(),
13641                Box::new(item2.clone()),
13642                None,
13643                false,
13644                false,
13645                window,
13646                cx,
13647            );
13648        });
13649
13650        // Activate item1 to ensure it gets navigation entries
13651        pane.update_in(cx, |pane, window, cx| {
13652            pane.activate_item(0, true, true, window, cx);
13653        });
13654
13655        // Switch to item2 and back to create navigation history
13656        pane.update_in(cx, |pane, window, cx| {
13657            pane.activate_item(1, true, true, window, cx);
13658        });
13659        cx.run_until_parked();
13660
13661        pane.update_in(cx, |pane, window, cx| {
13662            pane.activate_item(0, true, true, window, cx);
13663        });
13664        cx.run_until_parked();
13665
13666        // Simulate file deletion for item1
13667        item1.update(cx, |item, _| {
13668            item.set_has_deleted_file(true);
13669        });
13670
13671        // Emit UpdateTab event to trigger the close behavior
13672        item1.update(cx, |_, cx| {
13673            cx.emit(ItemEvent::UpdateTab);
13674        });
13675        cx.run_until_parked();
13676
13677        // Verify item1 was closed
13678        pane.read_with(cx, |pane, _| {
13679            assert_eq!(
13680                pane.items().count(),
13681                1,
13682                "Should have 1 item remaining after auto-close"
13683            );
13684        });
13685
13686        // Check navigation history after close
13687        let has_item = pane.read_with(cx, |pane, cx| {
13688            let mut has_item = false;
13689            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13690                if entry.item.id() == item1_id {
13691                    has_item = true;
13692                }
13693            });
13694            has_item
13695        });
13696
13697        assert!(
13698            !has_item,
13699            "Navigation history should not contain closed item entries"
13700        );
13701    }
13702
13703    #[gpui::test]
13704    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13705        cx: &mut TestAppContext,
13706    ) {
13707        init_test(cx);
13708
13709        let fs = FakeFs::new(cx.background_executor.clone());
13710        let project = Project::test(fs, [], cx).await;
13711        let (workspace, cx) =
13712            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13713        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13714
13715        let dirty_regular_buffer = cx.new(|cx| {
13716            TestItem::new(cx)
13717                .with_dirty(true)
13718                .with_label("1.txt")
13719                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13720        });
13721        let dirty_regular_buffer_2 = cx.new(|cx| {
13722            TestItem::new(cx)
13723                .with_dirty(true)
13724                .with_label("2.txt")
13725                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13726        });
13727        let clear_regular_buffer = cx.new(|cx| {
13728            TestItem::new(cx)
13729                .with_label("3.txt")
13730                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13731        });
13732
13733        let dirty_multi_buffer = cx.new(|cx| {
13734            TestItem::new(cx)
13735                .with_dirty(true)
13736                .with_buffer_kind(ItemBufferKind::Multibuffer)
13737                .with_label("Fake Project Search")
13738                .with_project_items(&[
13739                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13740                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13741                    clear_regular_buffer.read(cx).project_items[0].clone(),
13742                ])
13743        });
13744        workspace.update_in(cx, |workspace, window, cx| {
13745            workspace.add_item(
13746                pane.clone(),
13747                Box::new(dirty_regular_buffer.clone()),
13748                None,
13749                false,
13750                false,
13751                window,
13752                cx,
13753            );
13754            workspace.add_item(
13755                pane.clone(),
13756                Box::new(dirty_regular_buffer_2.clone()),
13757                None,
13758                false,
13759                false,
13760                window,
13761                cx,
13762            );
13763            workspace.add_item(
13764                pane.clone(),
13765                Box::new(dirty_multi_buffer.clone()),
13766                None,
13767                false,
13768                false,
13769                window,
13770                cx,
13771            );
13772        });
13773
13774        pane.update_in(cx, |pane, window, cx| {
13775            pane.activate_item(2, true, true, window, cx);
13776            assert_eq!(
13777                pane.active_item().unwrap().item_id(),
13778                dirty_multi_buffer.item_id(),
13779                "Should select the multi buffer in the pane"
13780            );
13781        });
13782        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13783            pane.close_active_item(
13784                &CloseActiveItem {
13785                    save_intent: None,
13786                    close_pinned: false,
13787                },
13788                window,
13789                cx,
13790            )
13791        });
13792        cx.background_executor.run_until_parked();
13793        assert!(
13794            !cx.has_pending_prompt(),
13795            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13796        );
13797        close_multi_buffer_task
13798            .await
13799            .expect("Closing multi buffer failed");
13800        pane.update(cx, |pane, cx| {
13801            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13802            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13803            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13804            assert_eq!(
13805                pane.items()
13806                    .map(|item| item.item_id())
13807                    .sorted()
13808                    .collect::<Vec<_>>(),
13809                vec![
13810                    dirty_regular_buffer.item_id(),
13811                    dirty_regular_buffer_2.item_id(),
13812                ],
13813                "Should have no multi buffer left in the pane"
13814            );
13815            assert!(dirty_regular_buffer.read(cx).is_dirty);
13816            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13817        });
13818    }
13819
13820    #[gpui::test]
13821    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13822        init_test(cx);
13823        let fs = FakeFs::new(cx.executor());
13824        let project = Project::test(fs, [], cx).await;
13825        let (multi_workspace, cx) =
13826            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13827        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13828
13829        // Add a new panel to the right dock, opening the dock and setting the
13830        // focus to the new panel.
13831        let panel = workspace.update_in(cx, |workspace, window, cx| {
13832            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13833            workspace.add_panel(panel.clone(), window, cx);
13834
13835            workspace
13836                .right_dock()
13837                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13838
13839            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13840
13841            panel
13842        });
13843
13844        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13845        // panel to the next valid position which, in this case, is the left
13846        // dock.
13847        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13848        workspace.update(cx, |workspace, cx| {
13849            assert!(workspace.left_dock().read(cx).is_open());
13850            assert_eq!(panel.read(cx).position, DockPosition::Left);
13851        });
13852
13853        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13854        // panel to the next valid position which, in this case, is the bottom
13855        // dock.
13856        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13857        workspace.update(cx, |workspace, cx| {
13858            assert!(workspace.bottom_dock().read(cx).is_open());
13859            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13860        });
13861
13862        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13863        // around moving the panel to its initial position, the right dock.
13864        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13865        workspace.update(cx, |workspace, cx| {
13866            assert!(workspace.right_dock().read(cx).is_open());
13867            assert_eq!(panel.read(cx).position, DockPosition::Right);
13868        });
13869
13870        // Remove focus from the panel, ensuring that, if the panel is not
13871        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13872        // the panel's position, so the panel is still in the right dock.
13873        workspace.update_in(cx, |workspace, window, cx| {
13874            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13875        });
13876
13877        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13878        workspace.update(cx, |workspace, cx| {
13879            assert!(workspace.right_dock().read(cx).is_open());
13880            assert_eq!(panel.read(cx).position, DockPosition::Right);
13881        });
13882    }
13883
13884    #[gpui::test]
13885    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13886        init_test(cx);
13887
13888        let fs = FakeFs::new(cx.executor());
13889        let project = Project::test(fs, [], cx).await;
13890        let (workspace, cx) =
13891            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13892
13893        let item_1 = cx.new(|cx| {
13894            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13895        });
13896        workspace.update_in(cx, |workspace, window, cx| {
13897            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13898            workspace.move_item_to_pane_in_direction(
13899                &MoveItemToPaneInDirection {
13900                    direction: SplitDirection::Right,
13901                    focus: true,
13902                    clone: false,
13903                },
13904                window,
13905                cx,
13906            );
13907            workspace.move_item_to_pane_at_index(
13908                &MoveItemToPane {
13909                    destination: 3,
13910                    focus: true,
13911                    clone: false,
13912                },
13913                window,
13914                cx,
13915            );
13916
13917            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13918            assert_eq!(
13919                pane_items_paths(&workspace.active_pane, cx),
13920                vec!["first.txt".to_string()],
13921                "Single item was not moved anywhere"
13922            );
13923        });
13924
13925        let item_2 = cx.new(|cx| {
13926            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13927        });
13928        workspace.update_in(cx, |workspace, window, cx| {
13929            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13930            assert_eq!(
13931                pane_items_paths(&workspace.panes[0], cx),
13932                vec!["first.txt".to_string(), "second.txt".to_string()],
13933            );
13934            workspace.move_item_to_pane_in_direction(
13935                &MoveItemToPaneInDirection {
13936                    direction: SplitDirection::Right,
13937                    focus: true,
13938                    clone: false,
13939                },
13940                window,
13941                cx,
13942            );
13943
13944            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13945            assert_eq!(
13946                pane_items_paths(&workspace.panes[0], cx),
13947                vec!["first.txt".to_string()],
13948                "After moving, one item should be left in the original pane"
13949            );
13950            assert_eq!(
13951                pane_items_paths(&workspace.panes[1], cx),
13952                vec!["second.txt".to_string()],
13953                "New item should have been moved to the new pane"
13954            );
13955        });
13956
13957        let item_3 = cx.new(|cx| {
13958            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13959        });
13960        workspace.update_in(cx, |workspace, window, cx| {
13961            let original_pane = workspace.panes[0].clone();
13962            workspace.set_active_pane(&original_pane, window, cx);
13963            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13964            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13965            assert_eq!(
13966                pane_items_paths(&workspace.active_pane, cx),
13967                vec!["first.txt".to_string(), "third.txt".to_string()],
13968                "New pane should be ready to move one item out"
13969            );
13970
13971            workspace.move_item_to_pane_at_index(
13972                &MoveItemToPane {
13973                    destination: 3,
13974                    focus: true,
13975                    clone: false,
13976                },
13977                window,
13978                cx,
13979            );
13980            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13981            assert_eq!(
13982                pane_items_paths(&workspace.active_pane, cx),
13983                vec!["first.txt".to_string()],
13984                "After moving, one item should be left in the original pane"
13985            );
13986            assert_eq!(
13987                pane_items_paths(&workspace.panes[1], cx),
13988                vec!["second.txt".to_string()],
13989                "Previously created pane should be unchanged"
13990            );
13991            assert_eq!(
13992                pane_items_paths(&workspace.panes[2], cx),
13993                vec!["third.txt".to_string()],
13994                "New item should have been moved to the new pane"
13995            );
13996        });
13997    }
13998
13999    #[gpui::test]
14000    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14001        init_test(cx);
14002
14003        let fs = FakeFs::new(cx.executor());
14004        let project = Project::test(fs, [], cx).await;
14005        let (workspace, cx) =
14006            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14007
14008        let item_1 = cx.new(|cx| {
14009            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14010        });
14011        workspace.update_in(cx, |workspace, window, cx| {
14012            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14013            workspace.move_item_to_pane_in_direction(
14014                &MoveItemToPaneInDirection {
14015                    direction: SplitDirection::Right,
14016                    focus: true,
14017                    clone: true,
14018                },
14019                window,
14020                cx,
14021            );
14022        });
14023        cx.run_until_parked();
14024        workspace.update_in(cx, |workspace, window, cx| {
14025            workspace.move_item_to_pane_at_index(
14026                &MoveItemToPane {
14027                    destination: 3,
14028                    focus: true,
14029                    clone: true,
14030                },
14031                window,
14032                cx,
14033            );
14034        });
14035        cx.run_until_parked();
14036
14037        workspace.update(cx, |workspace, cx| {
14038            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14039            for pane in workspace.panes() {
14040                assert_eq!(
14041                    pane_items_paths(pane, cx),
14042                    vec!["first.txt".to_string()],
14043                    "Single item exists in all panes"
14044                );
14045            }
14046        });
14047
14048        // verify that the active pane has been updated after waiting for the
14049        // pane focus event to fire and resolve
14050        workspace.read_with(cx, |workspace, _app| {
14051            assert_eq!(
14052                workspace.active_pane(),
14053                &workspace.panes[2],
14054                "The third pane should be the active one: {:?}",
14055                workspace.panes
14056            );
14057        })
14058    }
14059
14060    #[gpui::test]
14061    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14062        init_test(cx);
14063
14064        let fs = FakeFs::new(cx.executor());
14065        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14066
14067        let project = Project::test(fs, ["root".as_ref()], cx).await;
14068        let (workspace, cx) =
14069            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14070
14071        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14072        // Add item to pane A with project path
14073        let item_a = cx.new(|cx| {
14074            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14075        });
14076        workspace.update_in(cx, |workspace, window, cx| {
14077            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14078        });
14079
14080        // Split to create pane B
14081        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14082            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14083        });
14084
14085        // Add item with SAME project path to pane B, and pin it
14086        let item_b = cx.new(|cx| {
14087            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14088        });
14089        pane_b.update_in(cx, |pane, window, cx| {
14090            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14091            pane.set_pinned_count(1);
14092        });
14093
14094        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14095        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14096
14097        // close_pinned: false should only close the unpinned copy
14098        workspace.update_in(cx, |workspace, window, cx| {
14099            workspace.close_item_in_all_panes(
14100                &CloseItemInAllPanes {
14101                    save_intent: Some(SaveIntent::Close),
14102                    close_pinned: false,
14103                },
14104                window,
14105                cx,
14106            )
14107        });
14108        cx.executor().run_until_parked();
14109
14110        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14111        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14112        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14113        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14114
14115        // Split again, seeing as closing the previous item also closed its
14116        // pane, so only pane remains, which does not allow us to properly test
14117        // that both items close when `close_pinned: true`.
14118        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14119            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14120        });
14121
14122        // Add an item with the same project path to pane C so that
14123        // close_item_in_all_panes can determine what to close across all panes
14124        // (it reads the active item from the active pane, and split_pane
14125        // creates an empty pane).
14126        let item_c = cx.new(|cx| {
14127            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14128        });
14129        pane_c.update_in(cx, |pane, window, cx| {
14130            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14131        });
14132
14133        // close_pinned: true should close the pinned copy too
14134        workspace.update_in(cx, |workspace, window, cx| {
14135            let panes_count = workspace.panes().len();
14136            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14137
14138            workspace.close_item_in_all_panes(
14139                &CloseItemInAllPanes {
14140                    save_intent: Some(SaveIntent::Close),
14141                    close_pinned: true,
14142                },
14143                window,
14144                cx,
14145            )
14146        });
14147        cx.executor().run_until_parked();
14148
14149        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14150        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14151        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14152        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14153    }
14154
14155    mod register_project_item_tests {
14156
14157        use super::*;
14158
14159        // View
14160        struct TestPngItemView {
14161            focus_handle: FocusHandle,
14162        }
14163        // Model
14164        struct TestPngItem {}
14165
14166        impl project::ProjectItem for TestPngItem {
14167            fn try_open(
14168                _project: &Entity<Project>,
14169                path: &ProjectPath,
14170                cx: &mut App,
14171            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14172                if path.path.extension().unwrap() == "png" {
14173                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14174                } else {
14175                    None
14176                }
14177            }
14178
14179            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14180                None
14181            }
14182
14183            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14184                None
14185            }
14186
14187            fn is_dirty(&self) -> bool {
14188                false
14189            }
14190        }
14191
14192        impl Item for TestPngItemView {
14193            type Event = ();
14194            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14195                "".into()
14196            }
14197        }
14198        impl EventEmitter<()> for TestPngItemView {}
14199        impl Focusable for TestPngItemView {
14200            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14201                self.focus_handle.clone()
14202            }
14203        }
14204
14205        impl Render for TestPngItemView {
14206            fn render(
14207                &mut self,
14208                _window: &mut Window,
14209                _cx: &mut Context<Self>,
14210            ) -> impl IntoElement {
14211                Empty
14212            }
14213        }
14214
14215        impl ProjectItem for TestPngItemView {
14216            type Item = TestPngItem;
14217
14218            fn for_project_item(
14219                _project: Entity<Project>,
14220                _pane: Option<&Pane>,
14221                _item: Entity<Self::Item>,
14222                _: &mut Window,
14223                cx: &mut Context<Self>,
14224            ) -> Self
14225            where
14226                Self: Sized,
14227            {
14228                Self {
14229                    focus_handle: cx.focus_handle(),
14230                }
14231            }
14232        }
14233
14234        // View
14235        struct TestIpynbItemView {
14236            focus_handle: FocusHandle,
14237        }
14238        // Model
14239        struct TestIpynbItem {}
14240
14241        impl project::ProjectItem for TestIpynbItem {
14242            fn try_open(
14243                _project: &Entity<Project>,
14244                path: &ProjectPath,
14245                cx: &mut App,
14246            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14247                if path.path.extension().unwrap() == "ipynb" {
14248                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14249                } else {
14250                    None
14251                }
14252            }
14253
14254            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14255                None
14256            }
14257
14258            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14259                None
14260            }
14261
14262            fn is_dirty(&self) -> bool {
14263                false
14264            }
14265        }
14266
14267        impl Item for TestIpynbItemView {
14268            type Event = ();
14269            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14270                "".into()
14271            }
14272        }
14273        impl EventEmitter<()> for TestIpynbItemView {}
14274        impl Focusable for TestIpynbItemView {
14275            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14276                self.focus_handle.clone()
14277            }
14278        }
14279
14280        impl Render for TestIpynbItemView {
14281            fn render(
14282                &mut self,
14283                _window: &mut Window,
14284                _cx: &mut Context<Self>,
14285            ) -> impl IntoElement {
14286                Empty
14287            }
14288        }
14289
14290        impl ProjectItem for TestIpynbItemView {
14291            type Item = TestIpynbItem;
14292
14293            fn for_project_item(
14294                _project: Entity<Project>,
14295                _pane: Option<&Pane>,
14296                _item: Entity<Self::Item>,
14297                _: &mut Window,
14298                cx: &mut Context<Self>,
14299            ) -> Self
14300            where
14301                Self: Sized,
14302            {
14303                Self {
14304                    focus_handle: cx.focus_handle(),
14305                }
14306            }
14307        }
14308
14309        struct TestAlternatePngItemView {
14310            focus_handle: FocusHandle,
14311        }
14312
14313        impl Item for TestAlternatePngItemView {
14314            type Event = ();
14315            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14316                "".into()
14317            }
14318        }
14319
14320        impl EventEmitter<()> for TestAlternatePngItemView {}
14321        impl Focusable for TestAlternatePngItemView {
14322            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14323                self.focus_handle.clone()
14324            }
14325        }
14326
14327        impl Render for TestAlternatePngItemView {
14328            fn render(
14329                &mut self,
14330                _window: &mut Window,
14331                _cx: &mut Context<Self>,
14332            ) -> impl IntoElement {
14333                Empty
14334            }
14335        }
14336
14337        impl ProjectItem for TestAlternatePngItemView {
14338            type Item = TestPngItem;
14339
14340            fn for_project_item(
14341                _project: Entity<Project>,
14342                _pane: Option<&Pane>,
14343                _item: Entity<Self::Item>,
14344                _: &mut Window,
14345                cx: &mut Context<Self>,
14346            ) -> Self
14347            where
14348                Self: Sized,
14349            {
14350                Self {
14351                    focus_handle: cx.focus_handle(),
14352                }
14353            }
14354        }
14355
14356        #[gpui::test]
14357        async fn test_register_project_item(cx: &mut TestAppContext) {
14358            init_test(cx);
14359
14360            cx.update(|cx| {
14361                register_project_item::<TestPngItemView>(cx);
14362                register_project_item::<TestIpynbItemView>(cx);
14363            });
14364
14365            let fs = FakeFs::new(cx.executor());
14366            fs.insert_tree(
14367                "/root1",
14368                json!({
14369                    "one.png": "BINARYDATAHERE",
14370                    "two.ipynb": "{ totally a notebook }",
14371                    "three.txt": "editing text, sure why not?"
14372                }),
14373            )
14374            .await;
14375
14376            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14377            let (workspace, cx) =
14378                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14379
14380            let worktree_id = project.update(cx, |project, cx| {
14381                project.worktrees(cx).next().unwrap().read(cx).id()
14382            });
14383
14384            let handle = workspace
14385                .update_in(cx, |workspace, window, cx| {
14386                    let project_path = (worktree_id, rel_path("one.png"));
14387                    workspace.open_path(project_path, None, true, window, cx)
14388                })
14389                .await
14390                .unwrap();
14391
14392            // Now we can check if the handle we got back errored or not
14393            assert_eq!(
14394                handle.to_any_view().entity_type(),
14395                TypeId::of::<TestPngItemView>()
14396            );
14397
14398            let handle = workspace
14399                .update_in(cx, |workspace, window, cx| {
14400                    let project_path = (worktree_id, rel_path("two.ipynb"));
14401                    workspace.open_path(project_path, None, true, window, cx)
14402                })
14403                .await
14404                .unwrap();
14405
14406            assert_eq!(
14407                handle.to_any_view().entity_type(),
14408                TypeId::of::<TestIpynbItemView>()
14409            );
14410
14411            let handle = workspace
14412                .update_in(cx, |workspace, window, cx| {
14413                    let project_path = (worktree_id, rel_path("three.txt"));
14414                    workspace.open_path(project_path, None, true, window, cx)
14415                })
14416                .await;
14417            assert!(handle.is_err());
14418        }
14419
14420        #[gpui::test]
14421        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14422            init_test(cx);
14423
14424            cx.update(|cx| {
14425                register_project_item::<TestPngItemView>(cx);
14426                register_project_item::<TestAlternatePngItemView>(cx);
14427            });
14428
14429            let fs = FakeFs::new(cx.executor());
14430            fs.insert_tree(
14431                "/root1",
14432                json!({
14433                    "one.png": "BINARYDATAHERE",
14434                    "two.ipynb": "{ totally a notebook }",
14435                    "three.txt": "editing text, sure why not?"
14436                }),
14437            )
14438            .await;
14439            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14440            let (workspace, cx) =
14441                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14442            let worktree_id = project.update(cx, |project, cx| {
14443                project.worktrees(cx).next().unwrap().read(cx).id()
14444            });
14445
14446            let handle = workspace
14447                .update_in(cx, |workspace, window, cx| {
14448                    let project_path = (worktree_id, rel_path("one.png"));
14449                    workspace.open_path(project_path, None, true, window, cx)
14450                })
14451                .await
14452                .unwrap();
14453
14454            // This _must_ be the second item registered
14455            assert_eq!(
14456                handle.to_any_view().entity_type(),
14457                TypeId::of::<TestAlternatePngItemView>()
14458            );
14459
14460            let handle = workspace
14461                .update_in(cx, |workspace, window, cx| {
14462                    let project_path = (worktree_id, rel_path("three.txt"));
14463                    workspace.open_path(project_path, None, true, window, cx)
14464                })
14465                .await;
14466            assert!(handle.is_err());
14467        }
14468    }
14469
14470    #[gpui::test]
14471    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14472        init_test(cx);
14473
14474        let fs = FakeFs::new(cx.executor());
14475        let project = Project::test(fs, [], cx).await;
14476        let (workspace, _cx) =
14477            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14478
14479        // Test with status bar shown (default)
14480        workspace.read_with(cx, |workspace, cx| {
14481            let visible = workspace.status_bar_visible(cx);
14482            assert!(visible, "Status bar should be visible by default");
14483        });
14484
14485        // Test with status bar hidden
14486        cx.update_global(|store: &mut SettingsStore, cx| {
14487            store.update_user_settings(cx, |settings| {
14488                settings.status_bar.get_or_insert_default().show = Some(false);
14489            });
14490        });
14491
14492        workspace.read_with(cx, |workspace, cx| {
14493            let visible = workspace.status_bar_visible(cx);
14494            assert!(!visible, "Status bar should be hidden when show is false");
14495        });
14496
14497        // Test with status bar shown explicitly
14498        cx.update_global(|store: &mut SettingsStore, cx| {
14499            store.update_user_settings(cx, |settings| {
14500                settings.status_bar.get_or_insert_default().show = Some(true);
14501            });
14502        });
14503
14504        workspace.read_with(cx, |workspace, cx| {
14505            let visible = workspace.status_bar_visible(cx);
14506            assert!(visible, "Status bar should be visible when show is true");
14507        });
14508    }
14509
14510    #[gpui::test]
14511    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14512        init_test(cx);
14513
14514        let fs = FakeFs::new(cx.executor());
14515        let project = Project::test(fs, [], cx).await;
14516        let (multi_workspace, cx) =
14517            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14518        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14519        let panel = workspace.update_in(cx, |workspace, window, cx| {
14520            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14521            workspace.add_panel(panel.clone(), window, cx);
14522
14523            workspace
14524                .right_dock()
14525                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14526
14527            panel
14528        });
14529
14530        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14531        let item_a = cx.new(TestItem::new);
14532        let item_b = cx.new(TestItem::new);
14533        let item_a_id = item_a.entity_id();
14534        let item_b_id = item_b.entity_id();
14535
14536        pane.update_in(cx, |pane, window, cx| {
14537            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14538            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14539        });
14540
14541        pane.read_with(cx, |pane, _| {
14542            assert_eq!(pane.items_len(), 2);
14543            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14544        });
14545
14546        workspace.update_in(cx, |workspace, window, cx| {
14547            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14548        });
14549
14550        workspace.update_in(cx, |_, window, cx| {
14551            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14552        });
14553
14554        // Assert that the `pane::CloseActiveItem` action is handled at the
14555        // workspace level when one of the dock panels is focused and, in that
14556        // case, the center pane's active item is closed but the focus is not
14557        // moved.
14558        cx.dispatch_action(pane::CloseActiveItem::default());
14559        cx.run_until_parked();
14560
14561        pane.read_with(cx, |pane, _| {
14562            assert_eq!(pane.items_len(), 1);
14563            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14564        });
14565
14566        workspace.update_in(cx, |workspace, window, cx| {
14567            assert!(workspace.right_dock().read(cx).is_open());
14568            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14569        });
14570    }
14571
14572    #[gpui::test]
14573    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14574        init_test(cx);
14575        let fs = FakeFs::new(cx.executor());
14576
14577        let project_a = Project::test(fs.clone(), [], cx).await;
14578        let project_b = Project::test(fs, [], cx).await;
14579
14580        let multi_workspace_handle =
14581            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14582        cx.run_until_parked();
14583
14584        multi_workspace_handle
14585            .update(cx, |mw, _window, cx| {
14586                mw.open_sidebar(cx);
14587            })
14588            .unwrap();
14589
14590        let workspace_a = multi_workspace_handle
14591            .read_with(cx, |mw, _| mw.workspace().clone())
14592            .unwrap();
14593
14594        let _workspace_b = multi_workspace_handle
14595            .update(cx, |mw, window, cx| {
14596                mw.test_add_workspace(project_b, window, cx)
14597            })
14598            .unwrap();
14599
14600        // Switch to workspace A
14601        multi_workspace_handle
14602            .update(cx, |mw, window, cx| {
14603                let workspace = mw.workspaces().next().unwrap().clone();
14604                mw.activate(workspace, window, cx);
14605            })
14606            .unwrap();
14607
14608        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14609
14610        // Add a panel to workspace A's right dock and open the dock
14611        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14612            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14613            workspace.add_panel(panel.clone(), window, cx);
14614            workspace
14615                .right_dock()
14616                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14617            panel
14618        });
14619
14620        // Focus the panel through the workspace (matching existing test pattern)
14621        workspace_a.update_in(cx, |workspace, window, cx| {
14622            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14623        });
14624
14625        // Zoom the panel
14626        panel.update_in(cx, |panel, window, cx| {
14627            panel.set_zoomed(true, window, cx);
14628        });
14629
14630        // Verify the panel is zoomed and the dock is open
14631        workspace_a.update_in(cx, |workspace, window, cx| {
14632            assert!(
14633                workspace.right_dock().read(cx).is_open(),
14634                "dock should be open before switch"
14635            );
14636            assert!(
14637                panel.is_zoomed(window, cx),
14638                "panel should be zoomed before switch"
14639            );
14640            assert!(
14641                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14642                "panel should be focused before switch"
14643            );
14644        });
14645
14646        // Switch to workspace B
14647        multi_workspace_handle
14648            .update(cx, |mw, window, cx| {
14649                let workspace = mw.workspaces().nth(1).unwrap().clone();
14650                mw.activate(workspace, window, cx);
14651            })
14652            .unwrap();
14653        cx.run_until_parked();
14654
14655        // Switch back to workspace A
14656        multi_workspace_handle
14657            .update(cx, |mw, window, cx| {
14658                let workspace = mw.workspaces().next().unwrap().clone();
14659                mw.activate(workspace, window, cx);
14660            })
14661            .unwrap();
14662        cx.run_until_parked();
14663
14664        // Verify the panel is still zoomed and the dock is still open
14665        workspace_a.update_in(cx, |workspace, window, cx| {
14666            assert!(
14667                workspace.right_dock().read(cx).is_open(),
14668                "dock should still be open after switching back"
14669            );
14670            assert!(
14671                panel.is_zoomed(window, cx),
14672                "panel should still be zoomed after switching back"
14673            );
14674        });
14675    }
14676
14677    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14678        pane.read(cx)
14679            .items()
14680            .flat_map(|item| {
14681                item.project_paths(cx)
14682                    .into_iter()
14683                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14684            })
14685            .collect()
14686    }
14687
14688    pub fn init_test(cx: &mut TestAppContext) {
14689        cx.update(|cx| {
14690            let settings_store = SettingsStore::test(cx);
14691            cx.set_global(settings_store);
14692            cx.set_global(db::AppDatabase::test_new());
14693            theme_settings::init(theme::LoadThemes::JustBase, cx);
14694        });
14695    }
14696
14697    #[gpui::test]
14698    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14699        use settings::{ThemeName, ThemeSelection};
14700        use theme::SystemAppearance;
14701        use zed_actions::theme::ToggleMode;
14702
14703        init_test(cx);
14704
14705        let fs = FakeFs::new(cx.executor());
14706        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14707
14708        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14709            .await;
14710
14711        // Build a test project and workspace view so the test can invoke
14712        // the workspace action handler the same way the UI would.
14713        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14714        let (workspace, cx) =
14715            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14716
14717        // Seed the settings file with a plain static light theme so the
14718        // first toggle always starts from a known persisted state.
14719        workspace.update_in(cx, |_workspace, _window, cx| {
14720            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14721            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14722                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14723            });
14724        });
14725        cx.executor().advance_clock(Duration::from_millis(200));
14726        cx.run_until_parked();
14727
14728        // Confirm the initial persisted settings contain the static theme
14729        // we just wrote before any toggling happens.
14730        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14731        assert!(settings_text.contains(r#""theme": "One Light""#));
14732
14733        // Toggle once. This should migrate the persisted theme settings
14734        // into light/dark slots and enable system mode.
14735        workspace.update_in(cx, |workspace, window, cx| {
14736            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14737        });
14738        cx.executor().advance_clock(Duration::from_millis(200));
14739        cx.run_until_parked();
14740
14741        // 1. Static -> Dynamic
14742        // this assertion checks theme changed from static to dynamic.
14743        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14744        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14745        assert_eq!(
14746            parsed["theme"],
14747            serde_json::json!({
14748                "mode": "system",
14749                "light": "One Light",
14750                "dark": "One Dark"
14751            })
14752        );
14753
14754        // 2. Toggle again, suppose it will change the mode to light
14755        workspace.update_in(cx, |workspace, window, cx| {
14756            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14757        });
14758        cx.executor().advance_clock(Duration::from_millis(200));
14759        cx.run_until_parked();
14760
14761        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14762        assert!(settings_text.contains(r#""mode": "light""#));
14763    }
14764
14765    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14766        let item = TestProjectItem::new(id, path, cx);
14767        item.update(cx, |item, _| {
14768            item.is_dirty = true;
14769        });
14770        item
14771    }
14772
14773    #[gpui::test]
14774    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14775        cx: &mut gpui::TestAppContext,
14776    ) {
14777        init_test(cx);
14778        let fs = FakeFs::new(cx.executor());
14779
14780        let project = Project::test(fs, [], cx).await;
14781        let (workspace, cx) =
14782            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14783
14784        let panel = workspace.update_in(cx, |workspace, window, cx| {
14785            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14786            workspace.add_panel(panel.clone(), window, cx);
14787            workspace
14788                .right_dock()
14789                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14790            panel
14791        });
14792
14793        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14794        pane.update_in(cx, |pane, window, cx| {
14795            let item = cx.new(TestItem::new);
14796            pane.add_item(Box::new(item), true, true, None, window, cx);
14797        });
14798
14799        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14800        // mirrors the real-world flow and avoids side effects from directly
14801        // focusing the panel while the center pane is active.
14802        workspace.update_in(cx, |workspace, window, cx| {
14803            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14804        });
14805
14806        panel.update_in(cx, |panel, window, cx| {
14807            panel.set_zoomed(true, window, cx);
14808        });
14809
14810        workspace.update_in(cx, |workspace, window, cx| {
14811            assert!(workspace.right_dock().read(cx).is_open());
14812            assert!(panel.is_zoomed(window, cx));
14813            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14814        });
14815
14816        // Simulate a spurious pane::Event::Focus on the center pane while the
14817        // panel still has focus. This mirrors what happens during macOS window
14818        // activation: the center pane fires a focus event even though actual
14819        // focus remains on the dock panel.
14820        pane.update_in(cx, |_, _, cx| {
14821            cx.emit(pane::Event::Focus);
14822        });
14823
14824        // The dock must remain open because the panel had focus at the time the
14825        // event was processed. Before the fix, dock_to_preserve was None for
14826        // panels that don't implement pane(), causing the dock to close.
14827        workspace.update_in(cx, |workspace, window, cx| {
14828            assert!(
14829                workspace.right_dock().read(cx).is_open(),
14830                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14831            );
14832            assert!(panel.is_zoomed(window, cx));
14833        });
14834    }
14835
14836    #[gpui::test]
14837    async fn test_panels_stay_open_after_position_change_and_settings_update(
14838        cx: &mut gpui::TestAppContext,
14839    ) {
14840        init_test(cx);
14841        let fs = FakeFs::new(cx.executor());
14842        let project = Project::test(fs, [], cx).await;
14843        let (workspace, cx) =
14844            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14845
14846        // Add two panels to the left dock and open it.
14847        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14848            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14849            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14850            workspace.add_panel(panel_a.clone(), window, cx);
14851            workspace.add_panel(panel_b.clone(), window, cx);
14852            workspace.left_dock().update(cx, |dock, cx| {
14853                dock.set_open(true, window, cx);
14854                dock.activate_panel(0, window, cx);
14855            });
14856            (panel_a, panel_b)
14857        });
14858
14859        workspace.update_in(cx, |workspace, _, cx| {
14860            assert!(workspace.left_dock().read(cx).is_open());
14861        });
14862
14863        // Simulate a feature flag changing default dock positions: both panels
14864        // move from Left to Right.
14865        workspace.update_in(cx, |_workspace, _window, cx| {
14866            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14867            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14868            cx.update_global::<SettingsStore, _>(|_, _| {});
14869        });
14870
14871        // Both panels should now be in the right dock.
14872        workspace.update_in(cx, |workspace, _, cx| {
14873            let right_dock = workspace.right_dock().read(cx);
14874            assert_eq!(right_dock.panels_len(), 2);
14875        });
14876
14877        // Open the right dock and activate panel_b (simulating the user
14878        // opening the panel after it moved).
14879        workspace.update_in(cx, |workspace, window, cx| {
14880            workspace.right_dock().update(cx, |dock, cx| {
14881                dock.set_open(true, window, cx);
14882                dock.activate_panel(1, window, cx);
14883            });
14884        });
14885
14886        // Now trigger another SettingsStore change
14887        workspace.update_in(cx, |_workspace, _window, cx| {
14888            cx.update_global::<SettingsStore, _>(|_, _| {});
14889        });
14890
14891        workspace.update_in(cx, |workspace, _, cx| {
14892            assert!(
14893                workspace.right_dock().read(cx).is_open(),
14894                "Right dock should still be open after a settings change"
14895            );
14896            assert_eq!(
14897                workspace.right_dock().read(cx).panels_len(),
14898                2,
14899                "Both panels should still be in the right dock"
14900            );
14901        });
14902    }
14903}