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;
   22mod status_bar;
   23pub mod tasks;
   24mod theme_preview;
   25mod toast_layer;
   26mod toolbar;
   27pub mod welcome;
   28mod workspace_settings;
   29
   30pub use crate::notifications::NotificationFrame;
   31pub use dock::Panel;
   32pub use multi_workspace::{
   33    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   34    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, ProjectGroup, ProjectGroupKey, Sidebar,
   35    SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
   36    sidebar_side_context_menu,
   37};
   38pub use path_list::{PathList, SerializedPathList};
   39pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   40
   41use anyhow::{Context as _, Result, anyhow};
   42use client::{
   43    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   44    proto::{self, ErrorCode, PanelId, PeerId},
   45};
   46use collections::{HashMap, HashSet, hash_map};
   47use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   48use fs::Fs;
   49use futures::{
   50    Future, FutureExt, StreamExt,
   51    channel::{
   52        mpsc::{self, UnboundedReceiver, UnboundedSender},
   53        oneshot,
   54    },
   55    future::{Shared, try_join_all},
   56};
   57use gpui::{
   58    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   59    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   60    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   61    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   62    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   63    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   64};
   65pub use history_manager::*;
   66pub use item::{
   67    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   68    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   69};
   70use itertools::Itertools;
   71use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   72pub use modal_layer::*;
   73use node_runtime::NodeRuntime;
   74use notifications::{
   75    DetachAndPromptErr, Notifications, dismiss_app_notification,
   76    simple_message_notification::MessageNotification,
   77};
   78pub use pane::*;
   79pub use pane_group::{
   80    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   81    SplitDirection,
   82};
   83use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   84pub use persistence::{
   85    WorkspaceDb, delete_unloaded_items,
   86    model::{
   87        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   88        SessionWorkspace,
   89    },
   90    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   91};
   92use postage::stream::Stream;
   93use project::{
   94    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   95    WorktreeSettings,
   96    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   97    project_settings::ProjectSettings,
   98    toolchain_store::ToolchainStoreEvent,
   99    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  100};
  101use remote::{
  102    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  103    remote_client::ConnectionIdentifier,
  104};
  105use schemars::JsonSchema;
  106use serde::Deserialize;
  107use session::AppSession;
  108use settings::{
  109    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  110};
  111
  112use sqlez::{
  113    bindable::{Bind, Column, StaticColumnCount},
  114    statement::Statement,
  115};
  116use status_bar::StatusBar;
  117pub use status_bar::StatusItemView;
  118use std::{
  119    any::TypeId,
  120    borrow::Cow,
  121    cell::RefCell,
  122    cmp,
  123    collections::VecDeque,
  124    env,
  125    hash::Hash,
  126    path::{Path, PathBuf},
  127    process::ExitStatus,
  128    rc::Rc,
  129    sync::{
  130        Arc, LazyLock,
  131        atomic::{AtomicBool, AtomicUsize},
  132    },
  133    time::Duration,
  134};
  135use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  136use theme::{ActiveTheme, SystemAppearance};
  137use theme_settings::ThemeSettings;
  138pub use toolbar::{
  139    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  140};
  141pub use ui;
  142use ui::{Window, prelude::*};
  143use util::{
  144    ResultExt, TryFutureExt,
  145    paths::{PathStyle, SanitizedPath},
  146    rel_path::RelPath,
  147    serde::default_true,
  148};
  149use uuid::Uuid;
  150pub use workspace_settings::{
  151    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  152    WorkspaceSettings,
  153};
  154use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  155
  156use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  157use crate::{
  158    persistence::{
  159        SerializedAxis,
  160        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  161    },
  162    security_modal::SecurityModal,
  163};
  164
  165pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  166
  167static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  168    env::var("ZED_WINDOW_SIZE")
  169        .ok()
  170        .as_deref()
  171        .and_then(parse_pixel_size_env_var)
  172});
  173
  174static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  175    env::var("ZED_WINDOW_POSITION")
  176        .ok()
  177        .as_deref()
  178        .and_then(parse_pixel_position_env_var)
  179});
  180
  181pub trait TerminalProvider {
  182    fn spawn(
  183        &self,
  184        task: SpawnInTerminal,
  185        window: &mut Window,
  186        cx: &mut App,
  187    ) -> Task<Option<Result<ExitStatus>>>;
  188}
  189
  190pub trait DebuggerProvider {
  191    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  192    fn start_session(
  193        &self,
  194        definition: DebugScenario,
  195        task_context: SharedTaskContext,
  196        active_buffer: Option<Entity<Buffer>>,
  197        worktree_id: Option<WorktreeId>,
  198        window: &mut Window,
  199        cx: &mut App,
  200    );
  201
  202    fn spawn_task_or_modal(
  203        &self,
  204        workspace: &mut Workspace,
  205        action: &Spawn,
  206        window: &mut Window,
  207        cx: &mut Context<Workspace>,
  208    );
  209
  210    fn task_scheduled(&self, cx: &mut App);
  211    fn debug_scenario_scheduled(&self, cx: &mut App);
  212    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  213
  214    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  215}
  216
  217/// Opens a file or directory.
  218#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  219#[action(namespace = workspace)]
  220pub struct Open {
  221    /// When true, opens in a new window. When false, adds to the current
  222    /// window as a new workspace (multi-workspace).
  223    #[serde(default = "Open::default_create_new_window")]
  224    pub create_new_window: bool,
  225}
  226
  227impl Open {
  228    pub const DEFAULT: Self = Self {
  229        create_new_window: true,
  230    };
  231
  232    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  233    /// the serde default and `Open::DEFAULT` stay in sync.
  234    fn default_create_new_window() -> bool {
  235        Self::DEFAULT.create_new_window
  236    }
  237}
  238
  239impl Default for Open {
  240    fn default() -> Self {
  241        Self::DEFAULT
  242    }
  243}
  244
  245actions!(
  246    workspace,
  247    [
  248        /// Activates the next pane in the workspace.
  249        ActivateNextPane,
  250        /// Activates the previous pane in the workspace.
  251        ActivatePreviousPane,
  252        /// Activates the last pane in the workspace.
  253        ActivateLastPane,
  254        /// Switches to the next window.
  255        ActivateNextWindow,
  256        /// Switches to the previous window.
  257        ActivatePreviousWindow,
  258        /// Adds a folder to the current project.
  259        AddFolderToProject,
  260        /// Clears all notifications.
  261        ClearAllNotifications,
  262        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  263        ClearNavigationHistory,
  264        /// Closes the active dock.
  265        CloseActiveDock,
  266        /// Closes all docks.
  267        CloseAllDocks,
  268        /// Toggles all docks.
  269        ToggleAllDocks,
  270        /// Closes the current window.
  271        CloseWindow,
  272        /// Closes the current project.
  273        CloseProject,
  274        /// Opens the feedback dialog.
  275        Feedback,
  276        /// Follows the next collaborator in the session.
  277        FollowNextCollaborator,
  278        /// Moves the focused panel to the next position.
  279        MoveFocusedPanelToNextPosition,
  280        /// Creates a new file.
  281        NewFile,
  282        /// Creates a new file in a vertical split.
  283        NewFileSplitVertical,
  284        /// Creates a new file in a horizontal split.
  285        NewFileSplitHorizontal,
  286        /// Opens a new search.
  287        NewSearch,
  288        /// Opens a new window.
  289        NewWindow,
  290        /// Opens multiple files.
  291        OpenFiles,
  292        /// Opens the current location in terminal.
  293        OpenInTerminal,
  294        /// Opens the component preview.
  295        OpenComponentPreview,
  296        /// Reloads the active item.
  297        ReloadActiveItem,
  298        /// Resets the active dock to its default size.
  299        ResetActiveDockSize,
  300        /// Resets all open docks to their default sizes.
  301        ResetOpenDocksSize,
  302        /// Reloads the application
  303        Reload,
  304        /// Saves the current file with a new name.
  305        SaveAs,
  306        /// Saves without formatting.
  307        SaveWithoutFormat,
  308        /// Shuts down all debug adapters.
  309        ShutdownDebugAdapters,
  310        /// Suppresses the current notification.
  311        SuppressNotification,
  312        /// Toggles the bottom dock.
  313        ToggleBottomDock,
  314        /// Toggles centered layout mode.
  315        ToggleCenteredLayout,
  316        /// Toggles edit prediction feature globally for all files.
  317        ToggleEditPrediction,
  318        /// Toggles the left dock.
  319        ToggleLeftDock,
  320        /// Toggles the right dock.
  321        ToggleRightDock,
  322        /// Toggles zoom on the active pane.
  323        ToggleZoom,
  324        /// Toggles read-only mode for the active item (if supported by that item).
  325        ToggleReadOnlyFile,
  326        /// Zooms in on the active pane.
  327        ZoomIn,
  328        /// Zooms out of the active pane.
  329        ZoomOut,
  330        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  331        /// If the modal is shown already, closes it without trusting any worktree.
  332        ToggleWorktreeSecurity,
  333        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  334        /// Requires restart to take effect on already opened projects.
  335        ClearTrustedWorktrees,
  336        /// Stops following a collaborator.
  337        Unfollow,
  338        /// Restores the banner.
  339        RestoreBanner,
  340        /// Toggles expansion of the selected item.
  341        ToggleExpandItem,
  342    ]
  343);
  344
  345/// Activates a specific pane by its index.
  346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348pub struct ActivatePane(pub usize);
  349
  350/// Moves an item to a specific pane by index.
  351#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  352#[action(namespace = workspace)]
  353#[serde(deny_unknown_fields)]
  354pub struct MoveItemToPane {
  355    #[serde(default = "default_1")]
  356    pub destination: usize,
  357    #[serde(default = "default_true")]
  358    pub focus: bool,
  359    #[serde(default)]
  360    pub clone: bool,
  361}
  362
  363fn default_1() -> usize {
  364    1
  365}
  366
  367/// Moves an item to a pane in the specified direction.
  368#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  369#[action(namespace = workspace)]
  370#[serde(deny_unknown_fields)]
  371pub struct MoveItemToPaneInDirection {
  372    #[serde(default = "default_right")]
  373    pub direction: SplitDirection,
  374    #[serde(default = "default_true")]
  375    pub focus: bool,
  376    #[serde(default)]
  377    pub clone: bool,
  378}
  379
  380/// Creates a new file in a split of the desired direction.
  381#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  382#[action(namespace = workspace)]
  383#[serde(deny_unknown_fields)]
  384pub struct NewFileSplit(pub SplitDirection);
  385
  386fn default_right() -> SplitDirection {
  387    SplitDirection::Right
  388}
  389
  390/// Saves all open files in the workspace.
  391#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  392#[action(namespace = workspace)]
  393#[serde(deny_unknown_fields)]
  394pub struct SaveAll {
  395    #[serde(default)]
  396    pub save_intent: Option<SaveIntent>,
  397}
  398
  399/// Saves the current file with the specified options.
  400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  401#[action(namespace = workspace)]
  402#[serde(deny_unknown_fields)]
  403pub struct Save {
  404    #[serde(default)]
  405    pub save_intent: Option<SaveIntent>,
  406}
  407
  408/// Moves Focus to the central panes in the workspace.
  409#[derive(Clone, Debug, PartialEq, Eq, Action)]
  410#[action(namespace = workspace)]
  411pub struct FocusCenterPane;
  412
  413///  Closes all items and panes in the workspace.
  414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  415#[action(namespace = workspace)]
  416#[serde(deny_unknown_fields)]
  417pub struct CloseAllItemsAndPanes {
  418    #[serde(default)]
  419    pub save_intent: Option<SaveIntent>,
  420}
  421
  422/// Closes all inactive tabs and panes in the workspace.
  423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  424#[action(namespace = workspace)]
  425#[serde(deny_unknown_fields)]
  426pub struct CloseInactiveTabsAndPanes {
  427    #[serde(default)]
  428    pub save_intent: Option<SaveIntent>,
  429}
  430
  431/// Closes the active item across all panes.
  432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  433#[action(namespace = workspace)]
  434#[serde(deny_unknown_fields)]
  435pub struct CloseItemInAllPanes {
  436    #[serde(default)]
  437    pub save_intent: Option<SaveIntent>,
  438    #[serde(default)]
  439    pub close_pinned: bool,
  440}
  441
  442/// Sends a sequence of keystrokes to the active element.
  443#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  444#[action(namespace = workspace)]
  445pub struct SendKeystrokes(pub String);
  446
  447actions!(
  448    project_symbols,
  449    [
  450        /// Toggles the project symbols search.
  451        #[action(name = "Toggle")]
  452        ToggleProjectSymbols
  453    ]
  454);
  455
  456/// Toggles the file finder interface.
  457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  458#[action(namespace = file_finder, name = "Toggle")]
  459#[serde(deny_unknown_fields)]
  460pub struct ToggleFileFinder {
  461    #[serde(default)]
  462    pub separate_history: bool,
  463}
  464
  465/// Opens a new terminal in the center.
  466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  467#[action(namespace = workspace)]
  468#[serde(deny_unknown_fields)]
  469pub struct NewCenterTerminal {
  470    /// If true, creates a local terminal even in remote projects.
  471    #[serde(default)]
  472    pub local: bool,
  473}
  474
  475/// Opens a new terminal.
  476#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  477#[action(namespace = workspace)]
  478#[serde(deny_unknown_fields)]
  479pub struct NewTerminal {
  480    /// If true, creates a local terminal even in remote projects.
  481    #[serde(default)]
  482    pub local: bool,
  483}
  484
  485/// Increases size of a currently focused dock by a given amount of pixels.
  486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  487#[action(namespace = workspace)]
  488#[serde(deny_unknown_fields)]
  489pub struct IncreaseActiveDockSize {
  490    /// For 0px parameter, uses UI font size value.
  491    #[serde(default)]
  492    pub px: u32,
  493}
  494
  495/// Decreases size of a currently focused dock by a given amount of pixels.
  496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  497#[action(namespace = workspace)]
  498#[serde(deny_unknown_fields)]
  499pub struct DecreaseActiveDockSize {
  500    /// For 0px parameter, uses UI font size value.
  501    #[serde(default)]
  502    pub px: u32,
  503}
  504
  505/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  507#[action(namespace = workspace)]
  508#[serde(deny_unknown_fields)]
  509pub struct IncreaseOpenDocksSize {
  510    /// For 0px parameter, uses UI font size value.
  511    #[serde(default)]
  512    pub px: u32,
  513}
  514
  515/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  516#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  517#[action(namespace = workspace)]
  518#[serde(deny_unknown_fields)]
  519pub struct DecreaseOpenDocksSize {
  520    /// For 0px parameter, uses UI font size value.
  521    #[serde(default)]
  522    pub px: u32,
  523}
  524
  525actions!(
  526    workspace,
  527    [
  528        /// Activates the pane to the left.
  529        ActivatePaneLeft,
  530        /// Activates the pane to the right.
  531        ActivatePaneRight,
  532        /// Activates the pane above.
  533        ActivatePaneUp,
  534        /// Activates the pane below.
  535        ActivatePaneDown,
  536        /// Swaps the current pane with the one to the left.
  537        SwapPaneLeft,
  538        /// Swaps the current pane with the one to the right.
  539        SwapPaneRight,
  540        /// Swaps the current pane with the one above.
  541        SwapPaneUp,
  542        /// Swaps the current pane with the one below.
  543        SwapPaneDown,
  544        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  545        SwapPaneAdjacent,
  546        /// Move the current pane to be at the far left.
  547        MovePaneLeft,
  548        /// Move the current pane to be at the far right.
  549        MovePaneRight,
  550        /// Move the current pane to be at the very top.
  551        MovePaneUp,
  552        /// Move the current pane to be at the very bottom.
  553        MovePaneDown,
  554    ]
  555);
  556
  557#[derive(PartialEq, Eq, Debug)]
  558pub enum CloseIntent {
  559    /// Quit the program entirely.
  560    Quit,
  561    /// Close a window.
  562    CloseWindow,
  563    /// Replace the workspace in an existing window.
  564    ReplaceWindow,
  565}
  566
  567#[derive(Clone)]
  568pub struct Toast {
  569    id: NotificationId,
  570    msg: Cow<'static, str>,
  571    autohide: bool,
  572    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  573}
  574
  575impl Toast {
  576    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  577        Toast {
  578            id,
  579            msg: msg.into(),
  580            on_click: None,
  581            autohide: false,
  582        }
  583    }
  584
  585    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  586    where
  587        M: Into<Cow<'static, str>>,
  588        F: Fn(&mut Window, &mut App) + 'static,
  589    {
  590        self.on_click = Some((message.into(), Arc::new(on_click)));
  591        self
  592    }
  593
  594    pub fn autohide(mut self) -> Self {
  595        self.autohide = true;
  596        self
  597    }
  598}
  599
  600impl PartialEq for Toast {
  601    fn eq(&self, other: &Self) -> bool {
  602        self.id == other.id
  603            && self.msg == other.msg
  604            && self.on_click.is_some() == other.on_click.is_some()
  605    }
  606}
  607
  608/// Opens a new terminal with the specified working directory.
  609#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  610#[action(namespace = workspace)]
  611#[serde(deny_unknown_fields)]
  612pub struct OpenTerminal {
  613    pub working_directory: PathBuf,
  614    /// If true, creates a local terminal even in remote projects.
  615    #[serde(default)]
  616    pub local: bool,
  617}
  618
  619#[derive(
  620    Clone,
  621    Copy,
  622    Debug,
  623    Default,
  624    Hash,
  625    PartialEq,
  626    Eq,
  627    PartialOrd,
  628    Ord,
  629    serde::Serialize,
  630    serde::Deserialize,
  631)]
  632pub struct WorkspaceId(i64);
  633
  634impl WorkspaceId {
  635    pub fn from_i64(value: i64) -> Self {
  636        Self(value)
  637    }
  638}
  639
  640impl StaticColumnCount for WorkspaceId {}
  641impl Bind for WorkspaceId {
  642    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  643        self.0.bind(statement, start_index)
  644    }
  645}
  646impl Column for WorkspaceId {
  647    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  648        i64::column(statement, start_index)
  649            .map(|(i, next_index)| (Self(i), next_index))
  650            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  651    }
  652}
  653impl From<WorkspaceId> for i64 {
  654    fn from(val: WorkspaceId) -> Self {
  655        val.0
  656    }
  657}
  658
  659fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  660    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  661        workspace_window
  662            .update(cx, |multi_workspace, window, cx| {
  663                let workspace = multi_workspace.workspace().clone();
  664                workspace.update(cx, |workspace, cx| {
  665                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  666                });
  667            })
  668            .ok();
  669    } else {
  670        let task = Workspace::new_local(
  671            Vec::new(),
  672            app_state.clone(),
  673            None,
  674            None,
  675            None,
  676            OpenMode::Replace,
  677            cx,
  678        );
  679        cx.spawn(async move |cx| {
  680            let OpenResult { window, .. } = task.await?;
  681            window.update(cx, |multi_workspace, window, cx| {
  682                window.activate_window();
  683                let workspace = multi_workspace.workspace().clone();
  684                workspace.update(cx, |workspace, cx| {
  685                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  686                });
  687            })?;
  688            anyhow::Ok(())
  689        })
  690        .detach_and_log_err(cx);
  691    }
  692}
  693
  694pub fn prompt_for_open_path_and_open(
  695    workspace: &mut Workspace,
  696    app_state: Arc<AppState>,
  697    options: PathPromptOptions,
  698    create_new_window: bool,
  699    window: &mut Window,
  700    cx: &mut Context<Workspace>,
  701) {
  702    let paths = workspace.prompt_for_open_path(
  703        options,
  704        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  705        window,
  706        cx,
  707    );
  708    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  709    cx.spawn_in(window, async move |this, cx| {
  710        let Some(paths) = paths.await.log_err().flatten() else {
  711            return;
  712        };
  713        if !create_new_window {
  714            if let Some(handle) = multi_workspace_handle {
  715                if let Some(task) = handle
  716                    .update(cx, |multi_workspace, window, cx| {
  717                        multi_workspace.open_project(paths, OpenMode::Replace, window, cx)
  718                    })
  719                    .log_err()
  720                {
  721                    task.await.log_err();
  722                }
  723                return;
  724            }
  725        }
  726        if let Some(task) = this
  727            .update_in(cx, |this, window, cx| {
  728                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  729            })
  730            .log_err()
  731        {
  732            task.await.log_err();
  733        }
  734    })
  735    .detach();
  736}
  737
  738pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  739    component::init();
  740    theme_preview::init(cx);
  741    toast_layer::init(cx);
  742    history_manager::init(app_state.fs.clone(), cx);
  743
  744    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  745        .on_action(|_: &Reload, cx| reload(cx))
  746        .on_action(|_: &Open, cx: &mut App| {
  747            let app_state = AppState::global(cx);
  748            prompt_and_open_paths(
  749                app_state,
  750                PathPromptOptions {
  751                    files: true,
  752                    directories: true,
  753                    multiple: true,
  754                    prompt: None,
  755                },
  756                cx,
  757            );
  758        })
  759        .on_action(|_: &OpenFiles, cx: &mut App| {
  760            let directories = cx.can_select_mixed_files_and_dirs();
  761            let app_state = AppState::global(cx);
  762            prompt_and_open_paths(
  763                app_state,
  764                PathPromptOptions {
  765                    files: true,
  766                    directories,
  767                    multiple: true,
  768                    prompt: None,
  769                },
  770                cx,
  771            );
  772        });
  773}
  774
  775type BuildProjectItemFn =
  776    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  777
  778type BuildProjectItemForPathFn =
  779    fn(
  780        &Entity<Project>,
  781        &ProjectPath,
  782        &mut Window,
  783        &mut App,
  784    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  785
  786#[derive(Clone, Default)]
  787struct ProjectItemRegistry {
  788    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  789    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  790}
  791
  792impl ProjectItemRegistry {
  793    fn register<T: ProjectItem>(&mut self) {
  794        self.build_project_item_fns_by_type.insert(
  795            TypeId::of::<T::Item>(),
  796            |item, project, pane, window, cx| {
  797                let item = item.downcast().unwrap();
  798                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  799                    as Box<dyn ItemHandle>
  800            },
  801        );
  802        self.build_project_item_for_path_fns
  803            .push(|project, project_path, window, cx| {
  804                let project_path = project_path.clone();
  805                let is_file = project
  806                    .read(cx)
  807                    .entry_for_path(&project_path, cx)
  808                    .is_some_and(|entry| entry.is_file());
  809                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  810                let is_local = project.read(cx).is_local();
  811                let project_item =
  812                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  813                let project = project.clone();
  814                Some(window.spawn(cx, async move |cx| {
  815                    match project_item.await.with_context(|| {
  816                        format!(
  817                            "opening project path {:?}",
  818                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  819                        )
  820                    }) {
  821                        Ok(project_item) => {
  822                            let project_item = project_item;
  823                            let project_entry_id: Option<ProjectEntryId> =
  824                                project_item.read_with(cx, project::ProjectItem::entry_id);
  825                            let build_workspace_item = Box::new(
  826                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  827                                    Box::new(cx.new(|cx| {
  828                                        T::for_project_item(
  829                                            project,
  830                                            Some(pane),
  831                                            project_item,
  832                                            window,
  833                                            cx,
  834                                        )
  835                                    })) as Box<dyn ItemHandle>
  836                                },
  837                            ) as Box<_>;
  838                            Ok((project_entry_id, build_workspace_item))
  839                        }
  840                        Err(e) => {
  841                            log::warn!("Failed to open a project item: {e:#}");
  842                            if e.error_code() == ErrorCode::Internal {
  843                                if let Some(abs_path) =
  844                                    entry_abs_path.as_deref().filter(|_| is_file)
  845                                {
  846                                    if let Some(broken_project_item_view) =
  847                                        cx.update(|window, cx| {
  848                                            T::for_broken_project_item(
  849                                                abs_path, is_local, &e, window, cx,
  850                                            )
  851                                        })?
  852                                    {
  853                                        let build_workspace_item = Box::new(
  854                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  855                                                cx.new(|_| broken_project_item_view).boxed_clone()
  856                                            },
  857                                        )
  858                                        as Box<_>;
  859                                        return Ok((None, build_workspace_item));
  860                                    }
  861                                }
  862                            }
  863                            Err(e)
  864                        }
  865                    }
  866                }))
  867            });
  868    }
  869
  870    fn open_path(
  871        &self,
  872        project: &Entity<Project>,
  873        path: &ProjectPath,
  874        window: &mut Window,
  875        cx: &mut App,
  876    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  877        let Some(open_project_item) = self
  878            .build_project_item_for_path_fns
  879            .iter()
  880            .rev()
  881            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  882        else {
  883            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  884        };
  885        open_project_item
  886    }
  887
  888    fn build_item<T: project::ProjectItem>(
  889        &self,
  890        item: Entity<T>,
  891        project: Entity<Project>,
  892        pane: Option<&Pane>,
  893        window: &mut Window,
  894        cx: &mut App,
  895    ) -> Option<Box<dyn ItemHandle>> {
  896        let build = self
  897            .build_project_item_fns_by_type
  898            .get(&TypeId::of::<T>())?;
  899        Some(build(item.into_any(), project, pane, window, cx))
  900    }
  901}
  902
  903type WorkspaceItemBuilder =
  904    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  905
  906impl Global for ProjectItemRegistry {}
  907
  908/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  909/// items will get a chance to open the file, starting from the project item that
  910/// was added last.
  911pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  912    cx.default_global::<ProjectItemRegistry>().register::<I>();
  913}
  914
  915#[derive(Default)]
  916pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  917
  918struct FollowableViewDescriptor {
  919    from_state_proto: fn(
  920        Entity<Workspace>,
  921        ViewId,
  922        &mut Option<proto::view::Variant>,
  923        &mut Window,
  924        &mut App,
  925    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  926    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  927}
  928
  929impl Global for FollowableViewRegistry {}
  930
  931impl FollowableViewRegistry {
  932    pub fn register<I: FollowableItem>(cx: &mut App) {
  933        cx.default_global::<Self>().0.insert(
  934            TypeId::of::<I>(),
  935            FollowableViewDescriptor {
  936                from_state_proto: |workspace, id, state, window, cx| {
  937                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  938                        cx.foreground_executor()
  939                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  940                    })
  941                },
  942                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  943            },
  944        );
  945    }
  946
  947    pub fn from_state_proto(
  948        workspace: Entity<Workspace>,
  949        view_id: ViewId,
  950        mut state: Option<proto::view::Variant>,
  951        window: &mut Window,
  952        cx: &mut App,
  953    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  954        cx.update_default_global(|this: &mut Self, cx| {
  955            this.0.values().find_map(|descriptor| {
  956                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  957            })
  958        })
  959    }
  960
  961    pub fn to_followable_view(
  962        view: impl Into<AnyView>,
  963        cx: &App,
  964    ) -> Option<Box<dyn FollowableItemHandle>> {
  965        let this = cx.try_global::<Self>()?;
  966        let view = view.into();
  967        let descriptor = this.0.get(&view.entity_type())?;
  968        Some((descriptor.to_followable_view)(&view))
  969    }
  970}
  971
  972#[derive(Copy, Clone)]
  973struct SerializableItemDescriptor {
  974    deserialize: fn(
  975        Entity<Project>,
  976        WeakEntity<Workspace>,
  977        WorkspaceId,
  978        ItemId,
  979        &mut Window,
  980        &mut Context<Pane>,
  981    ) -> Task<Result<Box<dyn ItemHandle>>>,
  982    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  983    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  984}
  985
  986#[derive(Default)]
  987struct SerializableItemRegistry {
  988    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  989    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  990}
  991
  992impl Global for SerializableItemRegistry {}
  993
  994impl SerializableItemRegistry {
  995    fn deserialize(
  996        item_kind: &str,
  997        project: Entity<Project>,
  998        workspace: WeakEntity<Workspace>,
  999        workspace_id: WorkspaceId,
 1000        item_item: ItemId,
 1001        window: &mut Window,
 1002        cx: &mut Context<Pane>,
 1003    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1004        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1005            return Task::ready(Err(anyhow!(
 1006                "cannot deserialize {}, descriptor not found",
 1007                item_kind
 1008            )));
 1009        };
 1010
 1011        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1012    }
 1013
 1014    fn cleanup(
 1015        item_kind: &str,
 1016        workspace_id: WorkspaceId,
 1017        loaded_items: Vec<ItemId>,
 1018        window: &mut Window,
 1019        cx: &mut App,
 1020    ) -> Task<Result<()>> {
 1021        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1022            return Task::ready(Err(anyhow!(
 1023                "cannot cleanup {}, descriptor not found",
 1024                item_kind
 1025            )));
 1026        };
 1027
 1028        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1029    }
 1030
 1031    fn view_to_serializable_item_handle(
 1032        view: AnyView,
 1033        cx: &App,
 1034    ) -> Option<Box<dyn SerializableItemHandle>> {
 1035        let this = cx.try_global::<Self>()?;
 1036        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1037        Some((descriptor.view_to_serializable_item)(view))
 1038    }
 1039
 1040    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1041        let this = cx.try_global::<Self>()?;
 1042        this.descriptors_by_kind.get(item_kind).copied()
 1043    }
 1044}
 1045
 1046pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1047    let serialized_item_kind = I::serialized_item_kind();
 1048
 1049    let registry = cx.default_global::<SerializableItemRegistry>();
 1050    let descriptor = SerializableItemDescriptor {
 1051        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1052            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1053            cx.foreground_executor()
 1054                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1055        },
 1056        cleanup: |workspace_id, loaded_items, window, cx| {
 1057            I::cleanup(workspace_id, loaded_items, window, cx)
 1058        },
 1059        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1060    };
 1061    registry
 1062        .descriptors_by_kind
 1063        .insert(Arc::from(serialized_item_kind), descriptor);
 1064    registry
 1065        .descriptors_by_type
 1066        .insert(TypeId::of::<I>(), descriptor);
 1067}
 1068
 1069pub struct AppState {
 1070    pub languages: Arc<LanguageRegistry>,
 1071    pub client: Arc<Client>,
 1072    pub user_store: Entity<UserStore>,
 1073    pub workspace_store: Entity<WorkspaceStore>,
 1074    pub fs: Arc<dyn fs::Fs>,
 1075    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1076    pub node_runtime: NodeRuntime,
 1077    pub session: Entity<AppSession>,
 1078}
 1079
 1080struct GlobalAppState(Arc<AppState>);
 1081
 1082impl Global for GlobalAppState {}
 1083
 1084pub struct WorkspaceStore {
 1085    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1086    client: Arc<Client>,
 1087    _subscriptions: Vec<client::Subscription>,
 1088}
 1089
 1090#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1091pub enum CollaboratorId {
 1092    PeerId(PeerId),
 1093    Agent,
 1094}
 1095
 1096impl From<PeerId> for CollaboratorId {
 1097    fn from(peer_id: PeerId) -> Self {
 1098        CollaboratorId::PeerId(peer_id)
 1099    }
 1100}
 1101
 1102impl From<&PeerId> for CollaboratorId {
 1103    fn from(peer_id: &PeerId) -> Self {
 1104        CollaboratorId::PeerId(*peer_id)
 1105    }
 1106}
 1107
 1108#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1109struct Follower {
 1110    project_id: Option<u64>,
 1111    peer_id: PeerId,
 1112}
 1113
 1114impl AppState {
 1115    #[track_caller]
 1116    pub fn global(cx: &App) -> Arc<Self> {
 1117        cx.global::<GlobalAppState>().0.clone()
 1118    }
 1119    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1120        cx.try_global::<GlobalAppState>()
 1121            .map(|state| state.0.clone())
 1122    }
 1123    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1124        cx.set_global(GlobalAppState(state));
 1125    }
 1126
 1127    #[cfg(any(test, feature = "test-support"))]
 1128    pub fn test(cx: &mut App) -> Arc<Self> {
 1129        use fs::Fs;
 1130        use node_runtime::NodeRuntime;
 1131        use session::Session;
 1132        use settings::SettingsStore;
 1133
 1134        if !cx.has_global::<SettingsStore>() {
 1135            let settings_store = SettingsStore::test(cx);
 1136            cx.set_global(settings_store);
 1137        }
 1138
 1139        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1140        <dyn Fs>::set_global(fs.clone(), cx);
 1141        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1142        let clock = Arc::new(clock::FakeSystemClock::new());
 1143        let http_client = http_client::FakeHttpClient::with_404_response();
 1144        let client = Client::new(clock, http_client, cx);
 1145        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1146        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1147        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1148
 1149        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1150        client::init(&client, cx);
 1151
 1152        Arc::new(Self {
 1153            client,
 1154            fs,
 1155            languages,
 1156            user_store,
 1157            workspace_store,
 1158            node_runtime: NodeRuntime::unavailable(),
 1159            build_window_options: |_, _| Default::default(),
 1160            session,
 1161        })
 1162    }
 1163}
 1164
 1165struct DelayedDebouncedEditAction {
 1166    task: Option<Task<()>>,
 1167    cancel_channel: Option<oneshot::Sender<()>>,
 1168}
 1169
 1170impl DelayedDebouncedEditAction {
 1171    fn new() -> DelayedDebouncedEditAction {
 1172        DelayedDebouncedEditAction {
 1173            task: None,
 1174            cancel_channel: None,
 1175        }
 1176    }
 1177
 1178    fn fire_new<F>(
 1179        &mut self,
 1180        delay: Duration,
 1181        window: &mut Window,
 1182        cx: &mut Context<Workspace>,
 1183        func: F,
 1184    ) where
 1185        F: 'static
 1186            + Send
 1187            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1188    {
 1189        if let Some(channel) = self.cancel_channel.take() {
 1190            _ = channel.send(());
 1191        }
 1192
 1193        let (sender, mut receiver) = oneshot::channel::<()>();
 1194        self.cancel_channel = Some(sender);
 1195
 1196        let previous_task = self.task.take();
 1197        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1198            let mut timer = cx.background_executor().timer(delay).fuse();
 1199            if let Some(previous_task) = previous_task {
 1200                previous_task.await;
 1201            }
 1202
 1203            futures::select_biased! {
 1204                _ = receiver => return,
 1205                    _ = timer => {}
 1206            }
 1207
 1208            if let Some(result) = workspace
 1209                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1210                .log_err()
 1211            {
 1212                result.await.log_err();
 1213            }
 1214        }));
 1215    }
 1216}
 1217
 1218pub enum Event {
 1219    PaneAdded(Entity<Pane>),
 1220    PaneRemoved,
 1221    ItemAdded {
 1222        item: Box<dyn ItemHandle>,
 1223    },
 1224    ActiveItemChanged,
 1225    ItemRemoved {
 1226        item_id: EntityId,
 1227    },
 1228    UserSavedItem {
 1229        pane: WeakEntity<Pane>,
 1230        item: Box<dyn WeakItemHandle>,
 1231        save_intent: SaveIntent,
 1232    },
 1233    ContactRequestedJoin(u64),
 1234    WorkspaceCreated(WeakEntity<Workspace>),
 1235    OpenBundledFile {
 1236        text: Cow<'static, str>,
 1237        title: &'static str,
 1238        language: &'static str,
 1239    },
 1240    ZoomChanged,
 1241    ModalOpened,
 1242    Activate,
 1243    PanelAdded(AnyView),
 1244}
 1245
 1246#[derive(Debug, Clone)]
 1247pub enum OpenVisible {
 1248    All,
 1249    None,
 1250    OnlyFiles,
 1251    OnlyDirectories,
 1252}
 1253
 1254enum WorkspaceLocation {
 1255    // Valid local paths or SSH project to serialize
 1256    Location(SerializedWorkspaceLocation, PathList),
 1257    // No valid location found hence clear session id
 1258    DetachFromSession,
 1259    // No valid location found to serialize
 1260    None,
 1261}
 1262
 1263type PromptForNewPath = Box<
 1264    dyn Fn(
 1265        &mut Workspace,
 1266        DirectoryLister,
 1267        Option<String>,
 1268        &mut Window,
 1269        &mut Context<Workspace>,
 1270    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1271>;
 1272
 1273type PromptForOpenPath = Box<
 1274    dyn Fn(
 1275        &mut Workspace,
 1276        DirectoryLister,
 1277        &mut Window,
 1278        &mut Context<Workspace>,
 1279    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1280>;
 1281
 1282#[derive(Default)]
 1283struct DispatchingKeystrokes {
 1284    dispatched: HashSet<Vec<Keystroke>>,
 1285    queue: VecDeque<Keystroke>,
 1286    task: Option<Shared<Task<()>>>,
 1287}
 1288
 1289/// Collects everything project-related for a certain window opened.
 1290/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1291///
 1292/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1293/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1294/// that can be used to register a global action to be triggered from any place in the window.
 1295pub struct Workspace {
 1296    weak_self: WeakEntity<Self>,
 1297    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1298    zoomed: Option<AnyWeakView>,
 1299    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1300    zoomed_position: Option<DockPosition>,
 1301    center: PaneGroup,
 1302    left_dock: Entity<Dock>,
 1303    bottom_dock: Entity<Dock>,
 1304    right_dock: Entity<Dock>,
 1305    panes: Vec<Entity<Pane>>,
 1306    active_worktree_override: Option<WorktreeId>,
 1307    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1308    active_pane: Entity<Pane>,
 1309    last_active_center_pane: Option<WeakEntity<Pane>>,
 1310    last_active_view_id: Option<proto::ViewId>,
 1311    status_bar: Entity<StatusBar>,
 1312    pub(crate) modal_layer: Entity<ModalLayer>,
 1313    toast_layer: Entity<ToastLayer>,
 1314    titlebar_item: Option<AnyView>,
 1315    notifications: Notifications,
 1316    suppressed_notifications: HashSet<NotificationId>,
 1317    project: Entity<Project>,
 1318    follower_states: HashMap<CollaboratorId, FollowerState>,
 1319    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1320    window_edited: bool,
 1321    last_window_title: Option<String>,
 1322    dirty_items: HashMap<EntityId, Subscription>,
 1323    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1324    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1325    database_id: Option<WorkspaceId>,
 1326    app_state: Arc<AppState>,
 1327    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1328    _subscriptions: Vec<Subscription>,
 1329    _apply_leader_updates: Task<Result<()>>,
 1330    _observe_current_user: Task<Result<()>>,
 1331    _schedule_serialize_workspace: Option<Task<()>>,
 1332    _serialize_workspace_task: Option<Task<()>>,
 1333    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1334    pane_history_timestamp: Arc<AtomicUsize>,
 1335    bounds: Bounds<Pixels>,
 1336    pub centered_layout: bool,
 1337    bounds_save_task_queued: Option<Task<()>>,
 1338    on_prompt_for_new_path: Option<PromptForNewPath>,
 1339    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1340    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1341    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1342    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1343    _items_serializer: Task<Result<()>>,
 1344    session_id: Option<String>,
 1345    scheduled_tasks: Vec<Task<()>>,
 1346    last_open_dock_positions: Vec<DockPosition>,
 1347    removing: bool,
 1348    open_in_dev_container: bool,
 1349    _dev_container_task: Option<Task<Result<()>>>,
 1350    _panels_task: Option<Task<Result<()>>>,
 1351    sidebar_focus_handle: Option<FocusHandle>,
 1352    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1353}
 1354
 1355impl EventEmitter<Event> for Workspace {}
 1356
 1357#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1358pub struct ViewId {
 1359    pub creator: CollaboratorId,
 1360    pub id: u64,
 1361}
 1362
 1363pub struct FollowerState {
 1364    center_pane: Entity<Pane>,
 1365    dock_pane: Option<Entity<Pane>>,
 1366    active_view_id: Option<ViewId>,
 1367    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1368}
 1369
 1370struct FollowerView {
 1371    view: Box<dyn FollowableItemHandle>,
 1372    location: Option<proto::PanelId>,
 1373}
 1374
 1375#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1376pub enum OpenMode {
 1377    /// Open the workspace in a new window.
 1378    NewWindow,
 1379    /// Add to the window's multi workspace without activating it (used during deserialization).
 1380    Add,
 1381    /// Add to the window's multi workspace and activate it.
 1382    #[default]
 1383    Activate,
 1384    /// Replace the currently active workspace, and any of it's linked workspaces
 1385    Replace,
 1386}
 1387
 1388impl Workspace {
 1389    pub fn new(
 1390        workspace_id: Option<WorkspaceId>,
 1391        project: Entity<Project>,
 1392        app_state: Arc<AppState>,
 1393        window: &mut Window,
 1394        cx: &mut Context<Self>,
 1395    ) -> Self {
 1396        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1397            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1398                if let TrustedWorktreesEvent::Trusted(..) = e {
 1399                    // Do not persist auto trusted worktrees
 1400                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1401                        worktrees_store.update(cx, |worktrees_store, cx| {
 1402                            worktrees_store.schedule_serialization(
 1403                                cx,
 1404                                |new_trusted_worktrees, cx| {
 1405                                    let timeout =
 1406                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1407                                    let db = WorkspaceDb::global(cx);
 1408                                    cx.background_spawn(async move {
 1409                                        timeout.await;
 1410                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1411                                            .await
 1412                                            .log_err();
 1413                                    })
 1414                                },
 1415                            )
 1416                        });
 1417                    }
 1418                }
 1419            })
 1420            .detach();
 1421
 1422            cx.observe_global::<SettingsStore>(|_, cx| {
 1423                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1424                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1425                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1426                            trusted_worktrees.auto_trust_all(cx);
 1427                        })
 1428                    }
 1429                }
 1430            })
 1431            .detach();
 1432        }
 1433
 1434        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1435            match event {
 1436                project::Event::RemoteIdChanged(_) => {
 1437                    this.update_window_title(window, cx);
 1438                }
 1439
 1440                project::Event::CollaboratorLeft(peer_id) => {
 1441                    this.collaborator_left(*peer_id, window, cx);
 1442                }
 1443
 1444                &project::Event::WorktreeRemoved(_) => {
 1445                    this.update_window_title(window, cx);
 1446                    this.serialize_workspace(window, cx);
 1447                    this.update_history(cx);
 1448                }
 1449
 1450                &project::Event::WorktreeAdded(id) => {
 1451                    this.update_window_title(window, cx);
 1452                    if this
 1453                        .project()
 1454                        .read(cx)
 1455                        .worktree_for_id(id, cx)
 1456                        .is_some_and(|wt| wt.read(cx).is_visible())
 1457                    {
 1458                        this.serialize_workspace(window, cx);
 1459                        this.update_history(cx);
 1460                    }
 1461                }
 1462                project::Event::WorktreeUpdatedEntries(..) => {
 1463                    this.update_window_title(window, cx);
 1464                    this.serialize_workspace(window, cx);
 1465                }
 1466
 1467                project::Event::DisconnectedFromHost => {
 1468                    this.update_window_edited(window, cx);
 1469                    let leaders_to_unfollow =
 1470                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1471                    for leader_id in leaders_to_unfollow {
 1472                        this.unfollow(leader_id, window, cx);
 1473                    }
 1474                }
 1475
 1476                project::Event::DisconnectedFromRemote {
 1477                    server_not_running: _,
 1478                } => {
 1479                    this.update_window_edited(window, cx);
 1480                }
 1481
 1482                project::Event::Closed => {
 1483                    window.remove_window();
 1484                }
 1485
 1486                project::Event::DeletedEntry(_, entry_id) => {
 1487                    for pane in this.panes.iter() {
 1488                        pane.update(cx, |pane, cx| {
 1489                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1490                        });
 1491                    }
 1492                }
 1493
 1494                project::Event::Toast {
 1495                    notification_id,
 1496                    message,
 1497                    link,
 1498                } => this.show_notification(
 1499                    NotificationId::named(notification_id.clone()),
 1500                    cx,
 1501                    |cx| {
 1502                        let mut notification = MessageNotification::new(message.clone(), cx);
 1503                        if let Some(link) = link {
 1504                            notification = notification
 1505                                .more_info_message(link.label)
 1506                                .more_info_url(link.url);
 1507                        }
 1508
 1509                        cx.new(|_| notification)
 1510                    },
 1511                ),
 1512
 1513                project::Event::HideToast { notification_id } => {
 1514                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1515                }
 1516
 1517                project::Event::LanguageServerPrompt(request) => {
 1518                    struct LanguageServerPrompt;
 1519
 1520                    this.show_notification(
 1521                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1522                        cx,
 1523                        |cx| {
 1524                            cx.new(|cx| {
 1525                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1526                            })
 1527                        },
 1528                    );
 1529                }
 1530
 1531                project::Event::AgentLocationChanged => {
 1532                    this.handle_agent_location_changed(window, cx)
 1533                }
 1534
 1535                _ => {}
 1536            }
 1537            cx.notify()
 1538        })
 1539        .detach();
 1540
 1541        cx.subscribe_in(
 1542            &project.read(cx).breakpoint_store(),
 1543            window,
 1544            |workspace, _, event, window, cx| match event {
 1545                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1546                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1547                    workspace.serialize_workspace(window, cx);
 1548                }
 1549                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1550            },
 1551        )
 1552        .detach();
 1553        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1554            cx.subscribe_in(
 1555                &toolchain_store,
 1556                window,
 1557                |workspace, _, event, window, cx| match event {
 1558                    ToolchainStoreEvent::CustomToolchainsModified => {
 1559                        workspace.serialize_workspace(window, cx);
 1560                    }
 1561                    _ => {}
 1562                },
 1563            )
 1564            .detach();
 1565        }
 1566
 1567        cx.on_focus_lost(window, |this, window, cx| {
 1568            let focus_handle = this.focus_handle(cx);
 1569            window.focus(&focus_handle, cx);
 1570        })
 1571        .detach();
 1572
 1573        let weak_handle = cx.entity().downgrade();
 1574        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1575
 1576        let center_pane = cx.new(|cx| {
 1577            let mut center_pane = Pane::new(
 1578                weak_handle.clone(),
 1579                project.clone(),
 1580                pane_history_timestamp.clone(),
 1581                None,
 1582                NewFile.boxed_clone(),
 1583                true,
 1584                window,
 1585                cx,
 1586            );
 1587            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1588            center_pane.set_should_display_welcome_page(true);
 1589            center_pane
 1590        });
 1591        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1592            .detach();
 1593
 1594        window.focus(&center_pane.focus_handle(cx), cx);
 1595
 1596        cx.emit(Event::PaneAdded(center_pane.clone()));
 1597
 1598        let any_window_handle = window.window_handle();
 1599        app_state.workspace_store.update(cx, |store, _| {
 1600            store
 1601                .workspaces
 1602                .insert((any_window_handle, weak_handle.clone()));
 1603        });
 1604
 1605        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1606        let mut connection_status = app_state.client.status();
 1607        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1608            current_user.next().await;
 1609            connection_status.next().await;
 1610            let mut stream =
 1611                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1612
 1613            while stream.recv().await.is_some() {
 1614                this.update(cx, |_, cx| cx.notify())?;
 1615            }
 1616            anyhow::Ok(())
 1617        });
 1618
 1619        // All leader updates are enqueued and then processed in a single task, so
 1620        // that each asynchronous operation can be run in order.
 1621        let (leader_updates_tx, mut leader_updates_rx) =
 1622            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1623        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1624            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1625                Self::process_leader_update(&this, leader_id, update, cx)
 1626                    .await
 1627                    .log_err();
 1628            }
 1629
 1630            Ok(())
 1631        });
 1632
 1633        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1634        let modal_layer = cx.new(|_| ModalLayer::new());
 1635        let toast_layer = cx.new(|_| ToastLayer::new());
 1636        cx.subscribe(
 1637            &modal_layer,
 1638            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1639                cx.emit(Event::ModalOpened);
 1640            },
 1641        )
 1642        .detach();
 1643
 1644        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1645        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1646        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1647        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1648        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1649        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1650        let multi_workspace = window
 1651            .root::<MultiWorkspace>()
 1652            .flatten()
 1653            .map(|mw| mw.downgrade());
 1654        let status_bar = cx.new(|cx| {
 1655            let mut status_bar =
 1656                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1657            status_bar.add_left_item(left_dock_buttons, window, cx);
 1658            status_bar.add_right_item(right_dock_buttons, window, cx);
 1659            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1660            status_bar
 1661        });
 1662
 1663        let session_id = app_state.session.read(cx).id().to_owned();
 1664
 1665        let mut active_call = None;
 1666        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1667            let subscriptions =
 1668                vec![
 1669                    call.0
 1670                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1671                ];
 1672            active_call = Some((call, subscriptions));
 1673        }
 1674
 1675        let (serializable_items_tx, serializable_items_rx) =
 1676            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1677        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1678            Self::serialize_items(&this, serializable_items_rx, cx).await
 1679        });
 1680
 1681        let subscriptions = vec![
 1682            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1683            cx.observe_window_bounds(window, move |this, window, cx| {
 1684                if this.bounds_save_task_queued.is_some() {
 1685                    return;
 1686                }
 1687                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1688                    cx.background_executor()
 1689                        .timer(Duration::from_millis(100))
 1690                        .await;
 1691                    this.update_in(cx, |this, window, cx| {
 1692                        this.save_window_bounds(window, cx).detach();
 1693                        this.bounds_save_task_queued.take();
 1694                    })
 1695                    .ok();
 1696                }));
 1697                cx.notify();
 1698            }),
 1699            cx.observe_window_appearance(window, |_, window, cx| {
 1700                let window_appearance = window.appearance();
 1701
 1702                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1703
 1704                theme_settings::reload_theme(cx);
 1705                theme_settings::reload_icon_theme(cx);
 1706            }),
 1707            cx.on_release({
 1708                let weak_handle = weak_handle.clone();
 1709                move |this, cx| {
 1710                    this.app_state.workspace_store.update(cx, move |store, _| {
 1711                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1712                    })
 1713                }
 1714            }),
 1715        ];
 1716
 1717        cx.defer_in(window, move |this, window, cx| {
 1718            this.update_window_title(window, cx);
 1719            this.show_initial_notifications(cx);
 1720        });
 1721
 1722        let mut center = PaneGroup::new(center_pane.clone());
 1723        center.set_is_center(true);
 1724        center.mark_positions(cx);
 1725
 1726        Workspace {
 1727            weak_self: weak_handle.clone(),
 1728            zoomed: None,
 1729            zoomed_position: None,
 1730            previous_dock_drag_coordinates: None,
 1731            center,
 1732            panes: vec![center_pane.clone()],
 1733            panes_by_item: Default::default(),
 1734            active_pane: center_pane.clone(),
 1735            last_active_center_pane: Some(center_pane.downgrade()),
 1736            last_active_view_id: None,
 1737            status_bar,
 1738            modal_layer,
 1739            toast_layer,
 1740            titlebar_item: None,
 1741            active_worktree_override: None,
 1742            notifications: Notifications::default(),
 1743            suppressed_notifications: HashSet::default(),
 1744            left_dock,
 1745            bottom_dock,
 1746            right_dock,
 1747            _panels_task: None,
 1748            project: project.clone(),
 1749            follower_states: Default::default(),
 1750            last_leaders_by_pane: Default::default(),
 1751            dispatching_keystrokes: Default::default(),
 1752            window_edited: false,
 1753            last_window_title: None,
 1754            dirty_items: Default::default(),
 1755            active_call,
 1756            database_id: workspace_id,
 1757            app_state,
 1758            _observe_current_user,
 1759            _apply_leader_updates,
 1760            _schedule_serialize_workspace: None,
 1761            _serialize_workspace_task: None,
 1762            _schedule_serialize_ssh_paths: None,
 1763            leader_updates_tx,
 1764            _subscriptions: subscriptions,
 1765            pane_history_timestamp,
 1766            workspace_actions: Default::default(),
 1767            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1768            bounds: Default::default(),
 1769            centered_layout: false,
 1770            bounds_save_task_queued: None,
 1771            on_prompt_for_new_path: None,
 1772            on_prompt_for_open_path: None,
 1773            terminal_provider: None,
 1774            debugger_provider: None,
 1775            serializable_items_tx,
 1776            _items_serializer,
 1777            session_id: Some(session_id),
 1778
 1779            scheduled_tasks: Vec::new(),
 1780            last_open_dock_positions: Vec::new(),
 1781            removing: false,
 1782            sidebar_focus_handle: None,
 1783            multi_workspace,
 1784            open_in_dev_container: false,
 1785            _dev_container_task: None,
 1786        }
 1787    }
 1788
 1789    pub fn new_local(
 1790        abs_paths: Vec<PathBuf>,
 1791        app_state: Arc<AppState>,
 1792        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1793        env: Option<HashMap<String, String>>,
 1794        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1795        open_mode: OpenMode,
 1796        cx: &mut App,
 1797    ) -> Task<anyhow::Result<OpenResult>> {
 1798        let project_handle = Project::local(
 1799            app_state.client.clone(),
 1800            app_state.node_runtime.clone(),
 1801            app_state.user_store.clone(),
 1802            app_state.languages.clone(),
 1803            app_state.fs.clone(),
 1804            env,
 1805            Default::default(),
 1806            cx,
 1807        );
 1808
 1809        let db = WorkspaceDb::global(cx);
 1810        let kvp = db::kvp::KeyValueStore::global(cx);
 1811        cx.spawn(async move |cx| {
 1812            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1813            for path in abs_paths.into_iter() {
 1814                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1815                    paths_to_open.push(canonical)
 1816                } else {
 1817                    paths_to_open.push(path)
 1818                }
 1819            }
 1820
 1821            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1822
 1823            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1824                paths_to_open = paths.ordered_paths().cloned().collect();
 1825                if !paths.is_lexicographically_ordered() {
 1826                    project_handle.update(cx, |project, cx| {
 1827                        project.set_worktrees_reordered(true, cx);
 1828                    });
 1829                }
 1830            }
 1831
 1832            // Get project paths for all of the abs_paths
 1833            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1834                Vec::with_capacity(paths_to_open.len());
 1835
 1836            for path in paths_to_open.into_iter() {
 1837                if let Some((_, project_entry)) = cx
 1838                    .update(|cx| {
 1839                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1840                    })
 1841                    .await
 1842                    .log_err()
 1843                {
 1844                    project_paths.push((path, Some(project_entry)));
 1845                } else {
 1846                    project_paths.push((path, None));
 1847                }
 1848            }
 1849
 1850            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1851                serialized_workspace.id
 1852            } else {
 1853                db.next_id().await.unwrap_or_else(|_| Default::default())
 1854            };
 1855
 1856            let toolchains = db.toolchains(workspace_id).await?;
 1857
 1858            for (toolchain, worktree_path, path) in toolchains {
 1859                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1860                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1861                    this.find_worktree(&worktree_path, cx)
 1862                        .and_then(|(worktree, rel_path)| {
 1863                            if rel_path.is_empty() {
 1864                                Some(worktree.read(cx).id())
 1865                            } else {
 1866                                None
 1867                            }
 1868                        })
 1869                }) else {
 1870                    // We did not find a worktree with a given path, but that's whatever.
 1871                    continue;
 1872                };
 1873                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1874                    continue;
 1875                }
 1876
 1877                project_handle
 1878                    .update(cx, |this, cx| {
 1879                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1880                    })
 1881                    .await;
 1882            }
 1883            if let Some(workspace) = serialized_workspace.as_ref() {
 1884                project_handle.update(cx, |this, cx| {
 1885                    for (scope, toolchains) in &workspace.user_toolchains {
 1886                        for toolchain in toolchains {
 1887                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1888                        }
 1889                    }
 1890                });
 1891            }
 1892
 1893            let window_to_replace = match open_mode {
 1894                OpenMode::NewWindow => None,
 1895                _ => requesting_window,
 1896            };
 1897
 1898            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1899                if let Some(window) = window_to_replace {
 1900                    let centered_layout = serialized_workspace
 1901                        .as_ref()
 1902                        .map(|w| w.centered_layout)
 1903                        .unwrap_or(false);
 1904
 1905                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1906                        let workspace = cx.new(|cx| {
 1907                            let mut workspace = Workspace::new(
 1908                                Some(workspace_id),
 1909                                project_handle.clone(),
 1910                                app_state.clone(),
 1911                                window,
 1912                                cx,
 1913                            );
 1914
 1915                            workspace.centered_layout = centered_layout;
 1916
 1917                            // Call init callback to add items before window renders
 1918                            if let Some(init) = init {
 1919                                init(&mut workspace, window, cx);
 1920                            }
 1921
 1922                            workspace
 1923                        });
 1924                        match open_mode {
 1925                            OpenMode::Replace => {
 1926                                multi_workspace.replace(workspace.clone(), window, cx);
 1927                            }
 1928                            OpenMode::Activate => {
 1929                                multi_workspace.activate(workspace.clone(), window, cx);
 1930                            }
 1931                            OpenMode::Add => {
 1932                                multi_workspace.add(workspace.clone(), &*window, cx);
 1933                            }
 1934                            OpenMode::NewWindow => {
 1935                                unreachable!()
 1936                            }
 1937                        }
 1938                        workspace
 1939                    })?;
 1940                    (window, workspace)
 1941                } else {
 1942                    let window_bounds_override = window_bounds_env_override();
 1943
 1944                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1945                        (Some(WindowBounds::Windowed(bounds)), None)
 1946                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1947                        && let Some(display) = workspace.display
 1948                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1949                    {
 1950                        // Reopening an existing workspace - restore its saved bounds
 1951                        (Some(bounds.0), Some(display))
 1952                    } else if let Some((display, bounds)) =
 1953                        persistence::read_default_window_bounds(&kvp)
 1954                    {
 1955                        // New or empty workspace - use the last known window bounds
 1956                        (Some(bounds), Some(display))
 1957                    } else {
 1958                        // New window - let GPUI's default_bounds() handle cascading
 1959                        (None, None)
 1960                    };
 1961
 1962                    // Use the serialized workspace to construct the new window
 1963                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1964                    options.window_bounds = window_bounds;
 1965                    let centered_layout = serialized_workspace
 1966                        .as_ref()
 1967                        .map(|w| w.centered_layout)
 1968                        .unwrap_or(false);
 1969                    let window = cx.open_window(options, {
 1970                        let app_state = app_state.clone();
 1971                        let project_handle = project_handle.clone();
 1972                        move |window, cx| {
 1973                            let workspace = cx.new(|cx| {
 1974                                let mut workspace = Workspace::new(
 1975                                    Some(workspace_id),
 1976                                    project_handle,
 1977                                    app_state,
 1978                                    window,
 1979                                    cx,
 1980                                );
 1981                                workspace.centered_layout = centered_layout;
 1982
 1983                                // Call init callback to add items before window renders
 1984                                if let Some(init) = init {
 1985                                    init(&mut workspace, window, cx);
 1986                                }
 1987
 1988                                workspace
 1989                            });
 1990                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1991                        }
 1992                    })?;
 1993                    let workspace =
 1994                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1995                            multi_workspace.workspace().clone()
 1996                        })?;
 1997                    (window, workspace)
 1998                };
 1999
 2000            notify_if_database_failed(window, cx);
 2001            // Check if this is an empty workspace (no paths to open)
 2002            // An empty workspace is one where project_paths is empty
 2003            let is_empty_workspace = project_paths.is_empty();
 2004            // Check if serialized workspace has paths before it's moved
 2005            let serialized_workspace_has_paths = serialized_workspace
 2006                .as_ref()
 2007                .map(|ws| !ws.paths.is_empty())
 2008                .unwrap_or(false);
 2009
 2010            let opened_items = window
 2011                .update(cx, |_, window, cx| {
 2012                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2013                        open_items(serialized_workspace, project_paths, window, cx)
 2014                    })
 2015                })?
 2016                .await
 2017                .unwrap_or_default();
 2018
 2019            // Restore default dock state for empty workspaces
 2020            // Only restore if:
 2021            // 1. This is an empty workspace (no paths), AND
 2022            // 2. The serialized workspace either doesn't exist or has no paths
 2023            if is_empty_workspace && !serialized_workspace_has_paths {
 2024                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2025                    window
 2026                        .update(cx, |_, window, cx| {
 2027                            workspace.update(cx, |workspace, cx| {
 2028                                for (dock, serialized_dock) in [
 2029                                    (&workspace.right_dock, &default_docks.right),
 2030                                    (&workspace.left_dock, &default_docks.left),
 2031                                    (&workspace.bottom_dock, &default_docks.bottom),
 2032                                ] {
 2033                                    dock.update(cx, |dock, cx| {
 2034                                        dock.serialized_dock = Some(serialized_dock.clone());
 2035                                        dock.restore_state(window, cx);
 2036                                    });
 2037                                }
 2038                                cx.notify();
 2039                            });
 2040                        })
 2041                        .log_err();
 2042                }
 2043            }
 2044
 2045            window
 2046                .update(cx, |_, _window, cx| {
 2047                    workspace.update(cx, |this: &mut Workspace, cx| {
 2048                        this.update_history(cx);
 2049                    });
 2050                })
 2051                .log_err();
 2052            Ok(OpenResult {
 2053                window,
 2054                workspace,
 2055                opened_items,
 2056            })
 2057        })
 2058    }
 2059
 2060    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2061        self.weak_self.clone()
 2062    }
 2063
 2064    pub fn left_dock(&self) -> &Entity<Dock> {
 2065        &self.left_dock
 2066    }
 2067
 2068    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2069        &self.bottom_dock
 2070    }
 2071
 2072    pub fn set_bottom_dock_layout(
 2073        &mut self,
 2074        layout: BottomDockLayout,
 2075        window: &mut Window,
 2076        cx: &mut Context<Self>,
 2077    ) {
 2078        let fs = self.project().read(cx).fs();
 2079        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2080            content.workspace.bottom_dock_layout = Some(layout);
 2081        });
 2082
 2083        cx.notify();
 2084        self.serialize_workspace(window, cx);
 2085    }
 2086
 2087    pub fn right_dock(&self) -> &Entity<Dock> {
 2088        &self.right_dock
 2089    }
 2090
 2091    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2092        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2093    }
 2094
 2095    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2096        let left_dock = self.left_dock.read(cx);
 2097        let left_visible = left_dock.is_open();
 2098        let left_active_panel = left_dock
 2099            .active_panel()
 2100            .map(|panel| panel.persistent_name().to_string());
 2101        // `zoomed_position` is kept in sync with individual panel zoom state
 2102        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2103        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2104
 2105        let right_dock = self.right_dock.read(cx);
 2106        let right_visible = right_dock.is_open();
 2107        let right_active_panel = right_dock
 2108            .active_panel()
 2109            .map(|panel| panel.persistent_name().to_string());
 2110        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2111
 2112        let bottom_dock = self.bottom_dock.read(cx);
 2113        let bottom_visible = bottom_dock.is_open();
 2114        let bottom_active_panel = bottom_dock
 2115            .active_panel()
 2116            .map(|panel| panel.persistent_name().to_string());
 2117        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2118
 2119        DockStructure {
 2120            left: DockData {
 2121                visible: left_visible,
 2122                active_panel: left_active_panel,
 2123                zoom: left_dock_zoom,
 2124            },
 2125            right: DockData {
 2126                visible: right_visible,
 2127                active_panel: right_active_panel,
 2128                zoom: right_dock_zoom,
 2129            },
 2130            bottom: DockData {
 2131                visible: bottom_visible,
 2132                active_panel: bottom_active_panel,
 2133                zoom: bottom_dock_zoom,
 2134            },
 2135        }
 2136    }
 2137
 2138    pub fn set_dock_structure(
 2139        &self,
 2140        docks: DockStructure,
 2141        window: &mut Window,
 2142        cx: &mut Context<Self>,
 2143    ) {
 2144        for (dock, data) in [
 2145            (&self.left_dock, docks.left),
 2146            (&self.bottom_dock, docks.bottom),
 2147            (&self.right_dock, docks.right),
 2148        ] {
 2149            dock.update(cx, |dock, cx| {
 2150                dock.serialized_dock = Some(data);
 2151                dock.restore_state(window, cx);
 2152            });
 2153        }
 2154    }
 2155
 2156    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2157        self.items(cx)
 2158            .filter_map(|item| {
 2159                let project_path = item.project_path(cx)?;
 2160                self.project.read(cx).absolute_path(&project_path, cx)
 2161            })
 2162            .collect()
 2163    }
 2164
 2165    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2166        match position {
 2167            DockPosition::Left => &self.left_dock,
 2168            DockPosition::Bottom => &self.bottom_dock,
 2169            DockPosition::Right => &self.right_dock,
 2170        }
 2171    }
 2172
 2173    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2174        self.all_docks().into_iter().find_map(|dock| {
 2175            let dock = dock.read(cx);
 2176            dock.has_agent_panel(cx).then_some(dock.position())
 2177        })
 2178    }
 2179
 2180    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2181        self.all_docks().into_iter().find_map(|dock| {
 2182            let dock = dock.read(cx);
 2183            let panel = dock.panel::<T>()?;
 2184            dock.stored_panel_size_state(&panel)
 2185        })
 2186    }
 2187
 2188    pub fn persisted_panel_size_state(
 2189        &self,
 2190        panel_key: &'static str,
 2191        cx: &App,
 2192    ) -> Option<dock::PanelSizeState> {
 2193        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2194    }
 2195
 2196    pub fn persist_panel_size_state(
 2197        &self,
 2198        panel_key: &str,
 2199        size_state: dock::PanelSizeState,
 2200        cx: &mut App,
 2201    ) {
 2202        let Some(workspace_id) = self
 2203            .database_id()
 2204            .map(|id| i64::from(id).to_string())
 2205            .or(self.session_id())
 2206        else {
 2207            return;
 2208        };
 2209
 2210        let kvp = db::kvp::KeyValueStore::global(cx);
 2211        let panel_key = panel_key.to_string();
 2212        cx.background_spawn(async move {
 2213            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2214            scope
 2215                .write(
 2216                    format!("{workspace_id}:{panel_key}"),
 2217                    serde_json::to_string(&size_state)?,
 2218                )
 2219                .await
 2220        })
 2221        .detach_and_log_err(cx);
 2222    }
 2223
 2224    pub fn set_panel_size_state<T: Panel>(
 2225        &mut self,
 2226        size_state: dock::PanelSizeState,
 2227        window: &mut Window,
 2228        cx: &mut Context<Self>,
 2229    ) -> bool {
 2230        let Some(panel) = self.panel::<T>(cx) else {
 2231            return false;
 2232        };
 2233
 2234        let dock = self.dock_at_position(panel.position(window, cx));
 2235        let did_set = dock.update(cx, |dock, cx| {
 2236            dock.set_panel_size_state(&panel, size_state, cx)
 2237        });
 2238
 2239        if did_set {
 2240            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2241        }
 2242
 2243        did_set
 2244    }
 2245
 2246    pub fn toggle_dock_panel_flexible_size(
 2247        &self,
 2248        dock: &Entity<Dock>,
 2249        panel: &dyn PanelHandle,
 2250        window: &mut Window,
 2251        cx: &mut App,
 2252    ) {
 2253        let position = dock.read(cx).position();
 2254        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2255        let current_flex =
 2256            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2257        dock.update(cx, |dock, cx| {
 2258            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2259        });
 2260    }
 2261
 2262    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2263        let panel = dock.active_panel()?;
 2264        let size_state = dock
 2265            .stored_panel_size_state(panel.as_ref())
 2266            .unwrap_or_default();
 2267        let position = dock.position();
 2268
 2269        let use_flex = panel.has_flexible_size(window, cx);
 2270
 2271        if position.axis() == Axis::Horizontal
 2272            && use_flex
 2273            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2274        {
 2275            let workspace_width = self.bounds.size.width;
 2276            if workspace_width <= Pixels::ZERO {
 2277                return None;
 2278            }
 2279            let flex = flex.max(0.001);
 2280            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2281            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2282                // Both docks are flex items sharing the full workspace width.
 2283                let total_flex = flex + 1.0 + opposite_flex;
 2284                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2285            } else {
 2286                // Opposite dock is fixed-width; flex items share (W - fixed).
 2287                let opposite_fixed = opposite
 2288                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2289                    .unwrap_or_default();
 2290                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2291                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2292            }
 2293        }
 2294
 2295        Some(
 2296            size_state
 2297                .size
 2298                .unwrap_or_else(|| panel.default_size(window, cx)),
 2299        )
 2300    }
 2301
 2302    pub fn dock_flex_for_size(
 2303        &self,
 2304        position: DockPosition,
 2305        size: Pixels,
 2306        window: &Window,
 2307        cx: &App,
 2308    ) -> Option<f32> {
 2309        if position.axis() != Axis::Horizontal {
 2310            return None;
 2311        }
 2312
 2313        let workspace_width = self.bounds.size.width;
 2314        if workspace_width <= Pixels::ZERO {
 2315            return None;
 2316        }
 2317
 2318        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2319        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2320            let size = size.clamp(px(0.), workspace_width - px(1.));
 2321            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2322        } else {
 2323            let opposite_width = opposite
 2324                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2325                .unwrap_or_default();
 2326            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2327            let remaining = (available - size).max(px(1.));
 2328            Some((size / remaining).max(0.0))
 2329        }
 2330    }
 2331
 2332    fn opposite_dock_panel_and_size_state(
 2333        &self,
 2334        position: DockPosition,
 2335        window: &Window,
 2336        cx: &App,
 2337    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2338        let opposite_position = match position {
 2339            DockPosition::Left => DockPosition::Right,
 2340            DockPosition::Right => DockPosition::Left,
 2341            DockPosition::Bottom => return None,
 2342        };
 2343
 2344        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2345        let panel = opposite_dock.visible_panel()?;
 2346        let mut size_state = opposite_dock
 2347            .stored_panel_size_state(panel.as_ref())
 2348            .unwrap_or_default();
 2349        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2350            size_state.flex = self.default_dock_flex(opposite_position);
 2351        }
 2352        Some((panel.clone(), size_state))
 2353    }
 2354
 2355    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2356        if position.axis() != Axis::Horizontal {
 2357            return None;
 2358        }
 2359
 2360        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2361        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2362    }
 2363
 2364    pub fn is_edited(&self) -> bool {
 2365        self.window_edited
 2366    }
 2367
 2368    pub fn add_panel<T: Panel>(
 2369        &mut self,
 2370        panel: Entity<T>,
 2371        window: &mut Window,
 2372        cx: &mut Context<Self>,
 2373    ) {
 2374        let focus_handle = panel.panel_focus_handle(cx);
 2375        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2376            .detach();
 2377
 2378        let dock_position = panel.position(window, cx);
 2379        let dock = self.dock_at_position(dock_position);
 2380        let any_panel = panel.to_any();
 2381        let persisted_size_state =
 2382            self.persisted_panel_size_state(T::panel_key(), cx)
 2383                .or_else(|| {
 2384                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2385                        let state = dock::PanelSizeState {
 2386                            size: Some(size),
 2387                            flex: None,
 2388                        };
 2389                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2390                        state
 2391                    })
 2392                });
 2393
 2394        dock.update(cx, |dock, cx| {
 2395            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2396            if let Some(size_state) = persisted_size_state {
 2397                dock.set_panel_size_state(&panel, size_state, cx);
 2398            }
 2399            index
 2400        });
 2401
 2402        cx.emit(Event::PanelAdded(any_panel));
 2403    }
 2404
 2405    pub fn remove_panel<T: Panel>(
 2406        &mut self,
 2407        panel: &Entity<T>,
 2408        window: &mut Window,
 2409        cx: &mut Context<Self>,
 2410    ) {
 2411        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2412            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2413        }
 2414    }
 2415
 2416    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2417        &self.status_bar
 2418    }
 2419
 2420    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2421        self.sidebar_focus_handle = handle;
 2422    }
 2423
 2424    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2425        StatusBarSettings::get_global(cx).show
 2426    }
 2427
 2428    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2429        self.multi_workspace.as_ref()
 2430    }
 2431
 2432    pub fn set_multi_workspace(
 2433        &mut self,
 2434        multi_workspace: WeakEntity<MultiWorkspace>,
 2435        cx: &mut App,
 2436    ) {
 2437        self.status_bar.update(cx, |status_bar, cx| {
 2438            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2439        });
 2440        self.multi_workspace = Some(multi_workspace);
 2441    }
 2442
 2443    pub fn app_state(&self) -> &Arc<AppState> {
 2444        &self.app_state
 2445    }
 2446
 2447    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2448        self._panels_task = Some(task);
 2449    }
 2450
 2451    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2452        self._panels_task.take()
 2453    }
 2454
 2455    pub fn user_store(&self) -> &Entity<UserStore> {
 2456        &self.app_state.user_store
 2457    }
 2458
 2459    pub fn project(&self) -> &Entity<Project> {
 2460        &self.project
 2461    }
 2462
 2463    pub fn path_style(&self, cx: &App) -> PathStyle {
 2464        self.project.read(cx).path_style(cx)
 2465    }
 2466
 2467    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2468        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2469
 2470        for pane_handle in &self.panes {
 2471            let pane = pane_handle.read(cx);
 2472
 2473            for entry in pane.activation_history() {
 2474                history.insert(
 2475                    entry.entity_id,
 2476                    history
 2477                        .get(&entry.entity_id)
 2478                        .cloned()
 2479                        .unwrap_or(0)
 2480                        .max(entry.timestamp),
 2481                );
 2482            }
 2483        }
 2484
 2485        history
 2486    }
 2487
 2488    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2489        let mut recent_item: Option<Entity<T>> = None;
 2490        let mut recent_timestamp = 0;
 2491        for pane_handle in &self.panes {
 2492            let pane = pane_handle.read(cx);
 2493            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2494                pane.items().map(|item| (item.item_id(), item)).collect();
 2495            for entry in pane.activation_history() {
 2496                if entry.timestamp > recent_timestamp
 2497                    && let Some(&item) = item_map.get(&entry.entity_id)
 2498                    && let Some(typed_item) = item.act_as::<T>(cx)
 2499                {
 2500                    recent_timestamp = entry.timestamp;
 2501                    recent_item = Some(typed_item);
 2502                }
 2503            }
 2504        }
 2505        recent_item
 2506    }
 2507
 2508    pub fn recent_navigation_history_iter(
 2509        &self,
 2510        cx: &App,
 2511    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2512        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2513        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2514
 2515        for pane in &self.panes {
 2516            let pane = pane.read(cx);
 2517
 2518            pane.nav_history()
 2519                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2520                    if let Some(fs_path) = &fs_path {
 2521                        abs_paths_opened
 2522                            .entry(fs_path.clone())
 2523                            .or_default()
 2524                            .insert(project_path.clone());
 2525                    }
 2526                    let timestamp = entry.timestamp;
 2527                    match history.entry(project_path) {
 2528                        hash_map::Entry::Occupied(mut entry) => {
 2529                            let (_, old_timestamp) = entry.get();
 2530                            if &timestamp > old_timestamp {
 2531                                entry.insert((fs_path, timestamp));
 2532                            }
 2533                        }
 2534                        hash_map::Entry::Vacant(entry) => {
 2535                            entry.insert((fs_path, timestamp));
 2536                        }
 2537                    }
 2538                });
 2539
 2540            if let Some(item) = pane.active_item()
 2541                && let Some(project_path) = item.project_path(cx)
 2542            {
 2543                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2544
 2545                if let Some(fs_path) = &fs_path {
 2546                    abs_paths_opened
 2547                        .entry(fs_path.clone())
 2548                        .or_default()
 2549                        .insert(project_path.clone());
 2550                }
 2551
 2552                history.insert(project_path, (fs_path, std::usize::MAX));
 2553            }
 2554        }
 2555
 2556        history
 2557            .into_iter()
 2558            .sorted_by_key(|(_, (_, order))| *order)
 2559            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2560            .rev()
 2561            .filter(move |(history_path, abs_path)| {
 2562                let latest_project_path_opened = abs_path
 2563                    .as_ref()
 2564                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2565                    .and_then(|project_paths| {
 2566                        project_paths
 2567                            .iter()
 2568                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2569                    });
 2570
 2571                latest_project_path_opened.is_none_or(|path| path == history_path)
 2572            })
 2573    }
 2574
 2575    pub fn recent_navigation_history(
 2576        &self,
 2577        limit: Option<usize>,
 2578        cx: &App,
 2579    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2580        self.recent_navigation_history_iter(cx)
 2581            .take(limit.unwrap_or(usize::MAX))
 2582            .collect()
 2583    }
 2584
 2585    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2586        for pane in &self.panes {
 2587            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2588        }
 2589    }
 2590
 2591    fn navigate_history(
 2592        &mut self,
 2593        pane: WeakEntity<Pane>,
 2594        mode: NavigationMode,
 2595        window: &mut Window,
 2596        cx: &mut Context<Workspace>,
 2597    ) -> Task<Result<()>> {
 2598        self.navigate_history_impl(
 2599            pane,
 2600            mode,
 2601            window,
 2602            &mut |history, cx| history.pop(mode, cx),
 2603            cx,
 2604        )
 2605    }
 2606
 2607    fn navigate_tag_history(
 2608        &mut self,
 2609        pane: WeakEntity<Pane>,
 2610        mode: TagNavigationMode,
 2611        window: &mut Window,
 2612        cx: &mut Context<Workspace>,
 2613    ) -> Task<Result<()>> {
 2614        self.navigate_history_impl(
 2615            pane,
 2616            NavigationMode::Normal,
 2617            window,
 2618            &mut |history, _cx| history.pop_tag(mode),
 2619            cx,
 2620        )
 2621    }
 2622
 2623    fn navigate_history_impl(
 2624        &mut self,
 2625        pane: WeakEntity<Pane>,
 2626        mode: NavigationMode,
 2627        window: &mut Window,
 2628        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2629        cx: &mut Context<Workspace>,
 2630    ) -> Task<Result<()>> {
 2631        let to_load = if let Some(pane) = pane.upgrade() {
 2632            pane.update(cx, |pane, cx| {
 2633                window.focus(&pane.focus_handle(cx), cx);
 2634                loop {
 2635                    // Retrieve the weak item handle from the history.
 2636                    let entry = cb(pane.nav_history_mut(), cx)?;
 2637
 2638                    // If the item is still present in this pane, then activate it.
 2639                    if let Some(index) = entry
 2640                        .item
 2641                        .upgrade()
 2642                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2643                    {
 2644                        let prev_active_item_index = pane.active_item_index();
 2645                        pane.nav_history_mut().set_mode(mode);
 2646                        pane.activate_item(index, true, true, window, cx);
 2647                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2648
 2649                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2650                        if let Some(data) = entry.data {
 2651                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2652                        }
 2653
 2654                        if navigated {
 2655                            break None;
 2656                        }
 2657                    } else {
 2658                        // If the item is no longer present in this pane, then retrieve its
 2659                        // path info in order to reopen it.
 2660                        break pane
 2661                            .nav_history()
 2662                            .path_for_item(entry.item.id())
 2663                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2664                    }
 2665                }
 2666            })
 2667        } else {
 2668            None
 2669        };
 2670
 2671        if let Some((project_path, abs_path, entry)) = to_load {
 2672            // If the item was no longer present, then load it again from its previous path, first try the local path
 2673            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2674
 2675            cx.spawn_in(window, async move  |workspace, cx| {
 2676                let open_by_project_path = open_by_project_path.await;
 2677                let mut navigated = false;
 2678                match open_by_project_path
 2679                    .with_context(|| format!("Navigating to {project_path:?}"))
 2680                {
 2681                    Ok((project_entry_id, build_item)) => {
 2682                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2683                            pane.nav_history_mut().set_mode(mode);
 2684                            pane.active_item().map(|p| p.item_id())
 2685                        })?;
 2686
 2687                        pane.update_in(cx, |pane, window, cx| {
 2688                            let item = pane.open_item(
 2689                                project_entry_id,
 2690                                project_path,
 2691                                true,
 2692                                entry.is_preview,
 2693                                true,
 2694                                None,
 2695                                window, cx,
 2696                                build_item,
 2697                            );
 2698                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2699                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2700                            if let Some(data) = entry.data {
 2701                                navigated |= item.navigate(data, window, cx);
 2702                            }
 2703                        })?;
 2704                    }
 2705                    Err(open_by_project_path_e) => {
 2706                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2707                        // and its worktree is now dropped
 2708                        if let Some(abs_path) = abs_path {
 2709                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2710                                pane.nav_history_mut().set_mode(mode);
 2711                                pane.active_item().map(|p| p.item_id())
 2712                            })?;
 2713                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2714                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2715                            })?;
 2716                            match open_by_abs_path
 2717                                .await
 2718                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2719                            {
 2720                                Ok(item) => {
 2721                                    pane.update_in(cx, |pane, window, cx| {
 2722                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2723                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2724                                        if let Some(data) = entry.data {
 2725                                            navigated |= item.navigate(data, window, cx);
 2726                                        }
 2727                                    })?;
 2728                                }
 2729                                Err(open_by_abs_path_e) => {
 2730                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2731                                }
 2732                            }
 2733                        }
 2734                    }
 2735                }
 2736
 2737                if !navigated {
 2738                    workspace
 2739                        .update_in(cx, |workspace, window, cx| {
 2740                            Self::navigate_history(workspace, pane, mode, window, cx)
 2741                        })?
 2742                        .await?;
 2743                }
 2744
 2745                Ok(())
 2746            })
 2747        } else {
 2748            Task::ready(Ok(()))
 2749        }
 2750    }
 2751
 2752    pub fn go_back(
 2753        &mut self,
 2754        pane: WeakEntity<Pane>,
 2755        window: &mut Window,
 2756        cx: &mut Context<Workspace>,
 2757    ) -> Task<Result<()>> {
 2758        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2759    }
 2760
 2761    pub fn go_forward(
 2762        &mut self,
 2763        pane: WeakEntity<Pane>,
 2764        window: &mut Window,
 2765        cx: &mut Context<Workspace>,
 2766    ) -> Task<Result<()>> {
 2767        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2768    }
 2769
 2770    pub fn reopen_closed_item(
 2771        &mut self,
 2772        window: &mut Window,
 2773        cx: &mut Context<Workspace>,
 2774    ) -> Task<Result<()>> {
 2775        self.navigate_history(
 2776            self.active_pane().downgrade(),
 2777            NavigationMode::ReopeningClosedItem,
 2778            window,
 2779            cx,
 2780        )
 2781    }
 2782
 2783    pub fn client(&self) -> &Arc<Client> {
 2784        &self.app_state.client
 2785    }
 2786
 2787    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2788        self.titlebar_item = Some(item);
 2789        cx.notify();
 2790    }
 2791
 2792    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2793        self.on_prompt_for_new_path = Some(prompt)
 2794    }
 2795
 2796    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2797        self.on_prompt_for_open_path = Some(prompt)
 2798    }
 2799
 2800    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2801        self.terminal_provider = Some(Box::new(provider));
 2802    }
 2803
 2804    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2805        self.debugger_provider = Some(Arc::new(provider));
 2806    }
 2807
 2808    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2809        self.open_in_dev_container = value;
 2810    }
 2811
 2812    pub fn open_in_dev_container(&self) -> bool {
 2813        self.open_in_dev_container
 2814    }
 2815
 2816    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2817        self._dev_container_task = Some(task);
 2818    }
 2819
 2820    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2821        self.debugger_provider.clone()
 2822    }
 2823
 2824    pub fn prompt_for_open_path(
 2825        &mut self,
 2826        path_prompt_options: PathPromptOptions,
 2827        lister: DirectoryLister,
 2828        window: &mut Window,
 2829        cx: &mut Context<Self>,
 2830    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2831        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2832            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2833            let rx = prompt(self, lister, window, cx);
 2834            self.on_prompt_for_open_path = Some(prompt);
 2835            rx
 2836        } else {
 2837            let (tx, rx) = oneshot::channel();
 2838            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2839
 2840            cx.spawn_in(window, async move |workspace, cx| {
 2841                let Ok(result) = abs_path.await else {
 2842                    return Ok(());
 2843                };
 2844
 2845                match result {
 2846                    Ok(result) => {
 2847                        tx.send(result).ok();
 2848                    }
 2849                    Err(err) => {
 2850                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2851                            workspace.show_portal_error(err.to_string(), cx);
 2852                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2853                            let rx = prompt(workspace, lister, window, cx);
 2854                            workspace.on_prompt_for_open_path = Some(prompt);
 2855                            rx
 2856                        })?;
 2857                        if let Ok(path) = rx.await {
 2858                            tx.send(path).ok();
 2859                        }
 2860                    }
 2861                };
 2862                anyhow::Ok(())
 2863            })
 2864            .detach();
 2865
 2866            rx
 2867        }
 2868    }
 2869
 2870    pub fn prompt_for_new_path(
 2871        &mut self,
 2872        lister: DirectoryLister,
 2873        suggested_name: Option<String>,
 2874        window: &mut Window,
 2875        cx: &mut Context<Self>,
 2876    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2877        if self.project.read(cx).is_via_collab()
 2878            || self.project.read(cx).is_via_remote_server()
 2879            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2880        {
 2881            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2882            let rx = prompt(self, lister, suggested_name, window, cx);
 2883            self.on_prompt_for_new_path = Some(prompt);
 2884            return rx;
 2885        }
 2886
 2887        let (tx, rx) = oneshot::channel();
 2888        cx.spawn_in(window, async move |workspace, cx| {
 2889            let abs_path = workspace.update(cx, |workspace, cx| {
 2890                let relative_to = workspace
 2891                    .most_recent_active_path(cx)
 2892                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2893                    .or_else(|| {
 2894                        let project = workspace.project.read(cx);
 2895                        project.visible_worktrees(cx).find_map(|worktree| {
 2896                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2897                        })
 2898                    })
 2899                    .or_else(std::env::home_dir)
 2900                    .unwrap_or_else(|| PathBuf::from(""));
 2901                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2902            })?;
 2903            let abs_path = match abs_path.await? {
 2904                Ok(path) => path,
 2905                Err(err) => {
 2906                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2907                        workspace.show_portal_error(err.to_string(), cx);
 2908
 2909                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2910                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2911                        workspace.on_prompt_for_new_path = Some(prompt);
 2912                        rx
 2913                    })?;
 2914                    if let Ok(path) = rx.await {
 2915                        tx.send(path).ok();
 2916                    }
 2917                    return anyhow::Ok(());
 2918                }
 2919            };
 2920
 2921            tx.send(abs_path.map(|path| vec![path])).ok();
 2922            anyhow::Ok(())
 2923        })
 2924        .detach();
 2925
 2926        rx
 2927    }
 2928
 2929    pub fn titlebar_item(&self) -> Option<AnyView> {
 2930        self.titlebar_item.clone()
 2931    }
 2932
 2933    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2934    /// When set, git-related operations should use this worktree instead of deriving
 2935    /// the active worktree from the focused file.
 2936    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2937        self.active_worktree_override
 2938    }
 2939
 2940    pub fn set_active_worktree_override(
 2941        &mut self,
 2942        worktree_id: Option<WorktreeId>,
 2943        cx: &mut Context<Self>,
 2944    ) {
 2945        self.active_worktree_override = worktree_id;
 2946        cx.notify();
 2947    }
 2948
 2949    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2950        self.active_worktree_override = None;
 2951        cx.notify();
 2952    }
 2953
 2954    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2955    ///
 2956    /// If the given workspace has a local project, then it will be passed
 2957    /// to the callback. Otherwise, a new empty window will be created.
 2958    pub fn with_local_workspace<T, F>(
 2959        &mut self,
 2960        window: &mut Window,
 2961        cx: &mut Context<Self>,
 2962        callback: F,
 2963    ) -> Task<Result<T>>
 2964    where
 2965        T: 'static,
 2966        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2967    {
 2968        if self.project.read(cx).is_local() {
 2969            Task::ready(Ok(callback(self, window, cx)))
 2970        } else {
 2971            let env = self.project.read(cx).cli_environment(cx);
 2972            let task = Self::new_local(
 2973                Vec::new(),
 2974                self.app_state.clone(),
 2975                None,
 2976                env,
 2977                None,
 2978                OpenMode::Activate,
 2979                cx,
 2980            );
 2981            cx.spawn_in(window, async move |_vh, cx| {
 2982                let OpenResult {
 2983                    window: multi_workspace_window,
 2984                    ..
 2985                } = task.await?;
 2986                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2987                    let workspace = multi_workspace.workspace().clone();
 2988                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2989                })
 2990            })
 2991        }
 2992    }
 2993
 2994    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2995    ///
 2996    /// If the given workspace has a local project, then it will be passed
 2997    /// to the callback. Otherwise, a new empty window will be created.
 2998    pub fn with_local_or_wsl_workspace<T, F>(
 2999        &mut self,
 3000        window: &mut Window,
 3001        cx: &mut Context<Self>,
 3002        callback: F,
 3003    ) -> Task<Result<T>>
 3004    where
 3005        T: 'static,
 3006        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3007    {
 3008        let project = self.project.read(cx);
 3009        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3010            Task::ready(Ok(callback(self, window, cx)))
 3011        } else {
 3012            let env = self.project.read(cx).cli_environment(cx);
 3013            let task = Self::new_local(
 3014                Vec::new(),
 3015                self.app_state.clone(),
 3016                None,
 3017                env,
 3018                None,
 3019                OpenMode::Activate,
 3020                cx,
 3021            );
 3022            cx.spawn_in(window, async move |_vh, cx| {
 3023                let OpenResult {
 3024                    window: multi_workspace_window,
 3025                    ..
 3026                } = task.await?;
 3027                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3028                    let workspace = multi_workspace.workspace().clone();
 3029                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3030                })
 3031            })
 3032        }
 3033    }
 3034
 3035    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3036        self.project.read(cx).worktrees(cx)
 3037    }
 3038
 3039    pub fn visible_worktrees<'a>(
 3040        &self,
 3041        cx: &'a App,
 3042    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3043        self.project.read(cx).visible_worktrees(cx)
 3044    }
 3045
 3046    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3047        let futures = self
 3048            .worktrees(cx)
 3049            .filter_map(|worktree| worktree.read(cx).as_local())
 3050            .map(|worktree| worktree.scan_complete())
 3051            .collect::<Vec<_>>();
 3052        async move {
 3053            for future in futures {
 3054                future.await;
 3055            }
 3056        }
 3057    }
 3058
 3059    pub fn close_global(cx: &mut App) {
 3060        cx.defer(|cx| {
 3061            cx.windows().iter().find(|window| {
 3062                window
 3063                    .update(cx, |_, window, _| {
 3064                        if window.is_window_active() {
 3065                            //This can only get called when the window's project connection has been lost
 3066                            //so we don't need to prompt the user for anything and instead just close the window
 3067                            window.remove_window();
 3068                            true
 3069                        } else {
 3070                            false
 3071                        }
 3072                    })
 3073                    .unwrap_or(false)
 3074            });
 3075        });
 3076    }
 3077
 3078    pub fn move_focused_panel_to_next_position(
 3079        &mut self,
 3080        _: &MoveFocusedPanelToNextPosition,
 3081        window: &mut Window,
 3082        cx: &mut Context<Self>,
 3083    ) {
 3084        let docks = self.all_docks();
 3085        let active_dock = docks
 3086            .into_iter()
 3087            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3088
 3089        if let Some(dock) = active_dock {
 3090            dock.update(cx, |dock, cx| {
 3091                let active_panel = dock
 3092                    .active_panel()
 3093                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3094
 3095                if let Some(panel) = active_panel {
 3096                    panel.move_to_next_position(window, cx);
 3097                }
 3098            })
 3099        }
 3100    }
 3101
 3102    pub fn prepare_to_close(
 3103        &mut self,
 3104        close_intent: CloseIntent,
 3105        window: &mut Window,
 3106        cx: &mut Context<Self>,
 3107    ) -> Task<Result<bool>> {
 3108        let active_call = self.active_global_call();
 3109
 3110        cx.spawn_in(window, async move |this, cx| {
 3111            this.update(cx, |this, _| {
 3112                if close_intent == CloseIntent::CloseWindow {
 3113                    this.removing = true;
 3114                }
 3115            })?;
 3116
 3117            let workspace_count = cx.update(|_window, cx| {
 3118                cx.windows()
 3119                    .iter()
 3120                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3121                    .count()
 3122            })?;
 3123
 3124            #[cfg(target_os = "macos")]
 3125            let save_last_workspace = false;
 3126
 3127            // On Linux and Windows, closing the last window should restore the last workspace.
 3128            #[cfg(not(target_os = "macos"))]
 3129            let save_last_workspace = {
 3130                let remaining_workspaces = cx.update(|_window, cx| {
 3131                    cx.windows()
 3132                        .iter()
 3133                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3134                        .filter_map(|multi_workspace| {
 3135                            multi_workspace
 3136                                .update(cx, |multi_workspace, _, cx| {
 3137                                    multi_workspace.workspace().read(cx).removing
 3138                                })
 3139                                .ok()
 3140                        })
 3141                        .filter(|removing| !removing)
 3142                        .count()
 3143                })?;
 3144
 3145                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3146            };
 3147
 3148            if let Some(active_call) = active_call
 3149                && workspace_count == 1
 3150                && cx
 3151                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3152                    .unwrap_or(false)
 3153            {
 3154                if close_intent == CloseIntent::CloseWindow {
 3155                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3156                    let answer = cx.update(|window, cx| {
 3157                        window.prompt(
 3158                            PromptLevel::Warning,
 3159                            "Do you want to leave the current call?",
 3160                            None,
 3161                            &["Close window and hang up", "Cancel"],
 3162                            cx,
 3163                        )
 3164                    })?;
 3165
 3166                    if answer.await.log_err() == Some(1) {
 3167                        return anyhow::Ok(false);
 3168                    } else {
 3169                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3170                            task.await.log_err();
 3171                        }
 3172                    }
 3173                }
 3174                if close_intent == CloseIntent::ReplaceWindow {
 3175                    _ = cx.update(|_window, cx| {
 3176                        let multi_workspace = cx
 3177                            .windows()
 3178                            .iter()
 3179                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3180                            .next()
 3181                            .unwrap();
 3182                        let project = multi_workspace
 3183                            .read(cx)?
 3184                            .workspace()
 3185                            .read(cx)
 3186                            .project
 3187                            .clone();
 3188                        if project.read(cx).is_shared() {
 3189                            active_call.0.unshare_project(project, cx)?;
 3190                        }
 3191                        Ok::<_, anyhow::Error>(())
 3192                    });
 3193                }
 3194            }
 3195
 3196            let save_result = this
 3197                .update_in(cx, |this, window, cx| {
 3198                    this.save_all_internal(SaveIntent::Close, window, cx)
 3199                })?
 3200                .await;
 3201
 3202            // If we're not quitting, but closing, we remove the workspace from
 3203            // the current session.
 3204            if close_intent != CloseIntent::Quit
 3205                && !save_last_workspace
 3206                && save_result.as_ref().is_ok_and(|&res| res)
 3207            {
 3208                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3209                    .await;
 3210            }
 3211
 3212            save_result
 3213        })
 3214    }
 3215
 3216    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3217        self.save_all_internal(
 3218            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3219            window,
 3220            cx,
 3221        )
 3222        .detach_and_log_err(cx);
 3223    }
 3224
 3225    fn send_keystrokes(
 3226        &mut self,
 3227        action: &SendKeystrokes,
 3228        window: &mut Window,
 3229        cx: &mut Context<Self>,
 3230    ) {
 3231        let keystrokes: Vec<Keystroke> = action
 3232            .0
 3233            .split(' ')
 3234            .flat_map(|k| Keystroke::parse(k).log_err())
 3235            .map(|k| {
 3236                cx.keyboard_mapper()
 3237                    .map_key_equivalent(k, false)
 3238                    .inner()
 3239                    .clone()
 3240            })
 3241            .collect();
 3242        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3243    }
 3244
 3245    pub fn send_keystrokes_impl(
 3246        &mut self,
 3247        keystrokes: Vec<Keystroke>,
 3248        window: &mut Window,
 3249        cx: &mut Context<Self>,
 3250    ) -> Shared<Task<()>> {
 3251        let mut state = self.dispatching_keystrokes.borrow_mut();
 3252        if !state.dispatched.insert(keystrokes.clone()) {
 3253            cx.propagate();
 3254            return state.task.clone().unwrap();
 3255        }
 3256
 3257        state.queue.extend(keystrokes);
 3258
 3259        let keystrokes = self.dispatching_keystrokes.clone();
 3260        if state.task.is_none() {
 3261            state.task = Some(
 3262                window
 3263                    .spawn(cx, async move |cx| {
 3264                        // limit to 100 keystrokes to avoid infinite recursion.
 3265                        for _ in 0..100 {
 3266                            let keystroke = {
 3267                                let mut state = keystrokes.borrow_mut();
 3268                                let Some(keystroke) = state.queue.pop_front() else {
 3269                                    state.dispatched.clear();
 3270                                    state.task.take();
 3271                                    return;
 3272                                };
 3273                                keystroke
 3274                            };
 3275                            cx.update(|window, cx| {
 3276                                let focused = window.focused(cx);
 3277                                window.dispatch_keystroke(keystroke.clone(), cx);
 3278                                if window.focused(cx) != focused {
 3279                                    // dispatch_keystroke may cause the focus to change.
 3280                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3281                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3282                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3283                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3284                                    // )
 3285                                    window.draw(cx).clear();
 3286                                }
 3287                            })
 3288                            .ok();
 3289
 3290                            // Yield between synthetic keystrokes so deferred focus and
 3291                            // other effects can settle before dispatching the next key.
 3292                            yield_now().await;
 3293                        }
 3294
 3295                        *keystrokes.borrow_mut() = Default::default();
 3296                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3297                    })
 3298                    .shared(),
 3299            );
 3300        }
 3301        state.task.clone().unwrap()
 3302    }
 3303
 3304    fn save_all_internal(
 3305        &mut self,
 3306        mut save_intent: SaveIntent,
 3307        window: &mut Window,
 3308        cx: &mut Context<Self>,
 3309    ) -> Task<Result<bool>> {
 3310        if self.project.read(cx).is_disconnected(cx) {
 3311            return Task::ready(Ok(true));
 3312        }
 3313        let dirty_items = self
 3314            .panes
 3315            .iter()
 3316            .flat_map(|pane| {
 3317                pane.read(cx).items().filter_map(|item| {
 3318                    if item.is_dirty(cx) {
 3319                        item.tab_content_text(0, cx);
 3320                        Some((pane.downgrade(), item.boxed_clone()))
 3321                    } else {
 3322                        None
 3323                    }
 3324                })
 3325            })
 3326            .collect::<Vec<_>>();
 3327
 3328        let project = self.project.clone();
 3329        cx.spawn_in(window, async move |workspace, cx| {
 3330            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3331                let (serialize_tasks, remaining_dirty_items) =
 3332                    workspace.update_in(cx, |workspace, window, cx| {
 3333                        let mut remaining_dirty_items = Vec::new();
 3334                        let mut serialize_tasks = Vec::new();
 3335                        for (pane, item) in dirty_items {
 3336                            if let Some(task) = item
 3337                                .to_serializable_item_handle(cx)
 3338                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3339                            {
 3340                                serialize_tasks.push(task);
 3341                            } else {
 3342                                remaining_dirty_items.push((pane, item));
 3343                            }
 3344                        }
 3345                        (serialize_tasks, remaining_dirty_items)
 3346                    })?;
 3347
 3348                futures::future::try_join_all(serialize_tasks).await?;
 3349
 3350                if !remaining_dirty_items.is_empty() {
 3351                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3352                }
 3353
 3354                if remaining_dirty_items.len() > 1 {
 3355                    let answer = workspace.update_in(cx, |_, window, cx| {
 3356                        let detail = Pane::file_names_for_prompt(
 3357                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3358                            cx,
 3359                        );
 3360                        window.prompt(
 3361                            PromptLevel::Warning,
 3362                            "Do you want to save all changes in the following files?",
 3363                            Some(&detail),
 3364                            &["Save all", "Discard all", "Cancel"],
 3365                            cx,
 3366                        )
 3367                    })?;
 3368                    match answer.await.log_err() {
 3369                        Some(0) => save_intent = SaveIntent::SaveAll,
 3370                        Some(1) => save_intent = SaveIntent::Skip,
 3371                        Some(2) => return Ok(false),
 3372                        _ => {}
 3373                    }
 3374                }
 3375
 3376                remaining_dirty_items
 3377            } else {
 3378                dirty_items
 3379            };
 3380
 3381            for (pane, item) in dirty_items {
 3382                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3383                    (
 3384                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3385                        item.project_entry_ids(cx),
 3386                    )
 3387                })?;
 3388                if (singleton || !project_entry_ids.is_empty())
 3389                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3390                {
 3391                    return Ok(false);
 3392                }
 3393            }
 3394            Ok(true)
 3395        })
 3396    }
 3397
 3398    pub fn open_workspace_for_paths(
 3399        &mut self,
 3400        // replace_current_window: bool,
 3401        mut open_mode: OpenMode,
 3402        paths: Vec<PathBuf>,
 3403        window: &mut Window,
 3404        cx: &mut Context<Self>,
 3405    ) -> Task<Result<Entity<Workspace>>> {
 3406        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3407        let is_remote = self.project.read(cx).is_via_collab();
 3408        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3409        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3410
 3411        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3412        if workspace_is_empty {
 3413            open_mode = OpenMode::Replace;
 3414        }
 3415
 3416        let app_state = self.app_state.clone();
 3417
 3418        cx.spawn(async move |_, cx| {
 3419            let OpenResult { workspace, .. } = cx
 3420                .update(|cx| {
 3421                    open_paths(
 3422                        &paths,
 3423                        app_state,
 3424                        OpenOptions {
 3425                            requesting_window,
 3426                            open_mode,
 3427                            ..Default::default()
 3428                        },
 3429                        cx,
 3430                    )
 3431                })
 3432                .await?;
 3433            Ok(workspace)
 3434        })
 3435    }
 3436
 3437    #[allow(clippy::type_complexity)]
 3438    pub fn open_paths(
 3439        &mut self,
 3440        mut abs_paths: Vec<PathBuf>,
 3441        options: OpenOptions,
 3442        pane: Option<WeakEntity<Pane>>,
 3443        window: &mut Window,
 3444        cx: &mut Context<Self>,
 3445    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3446        let fs = self.app_state.fs.clone();
 3447
 3448        let caller_ordered_abs_paths = abs_paths.clone();
 3449
 3450        // Sort the paths to ensure we add worktrees for parents before their children.
 3451        abs_paths.sort_unstable();
 3452        cx.spawn_in(window, async move |this, cx| {
 3453            let mut tasks = Vec::with_capacity(abs_paths.len());
 3454
 3455            for abs_path in &abs_paths {
 3456                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3457                    OpenVisible::All => Some(true),
 3458                    OpenVisible::None => Some(false),
 3459                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3460                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3461                        Some(None) => Some(true),
 3462                        None => None,
 3463                    },
 3464                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3465                        Some(Some(metadata)) => Some(metadata.is_dir),
 3466                        Some(None) => Some(false),
 3467                        None => None,
 3468                    },
 3469                };
 3470                let project_path = match visible {
 3471                    Some(visible) => match this
 3472                        .update(cx, |this, cx| {
 3473                            Workspace::project_path_for_path(
 3474                                this.project.clone(),
 3475                                abs_path,
 3476                                visible,
 3477                                cx,
 3478                            )
 3479                        })
 3480                        .log_err()
 3481                    {
 3482                        Some(project_path) => project_path.await.log_err(),
 3483                        None => None,
 3484                    },
 3485                    None => None,
 3486                };
 3487
 3488                let this = this.clone();
 3489                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3490                let fs = fs.clone();
 3491                let pane = pane.clone();
 3492                let task = cx.spawn(async move |cx| {
 3493                    let (_worktree, project_path) = project_path?;
 3494                    if fs.is_dir(&abs_path).await {
 3495                        // Opening a directory should not race to update the active entry.
 3496                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3497                        None
 3498                    } else {
 3499                        Some(
 3500                            this.update_in(cx, |this, window, cx| {
 3501                                this.open_path(
 3502                                    project_path,
 3503                                    pane,
 3504                                    options.focus.unwrap_or(true),
 3505                                    window,
 3506                                    cx,
 3507                                )
 3508                            })
 3509                            .ok()?
 3510                            .await,
 3511                        )
 3512                    }
 3513                });
 3514                tasks.push(task);
 3515            }
 3516
 3517            let results = futures::future::join_all(tasks).await;
 3518
 3519            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3520            let mut winner: Option<(PathBuf, bool)> = None;
 3521            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3522                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3523                    if !metadata.is_dir {
 3524                        winner = Some((abs_path, false));
 3525                        break;
 3526                    }
 3527                    if winner.is_none() {
 3528                        winner = Some((abs_path, true));
 3529                    }
 3530                } else if winner.is_none() {
 3531                    winner = Some((abs_path, false));
 3532                }
 3533            }
 3534
 3535            // Compute the winner entry id on the foreground thread and emit once, after all
 3536            // paths finish opening. This avoids races between concurrently-opening paths
 3537            // (directories in particular) and makes the resulting project panel selection
 3538            // deterministic.
 3539            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3540                'emit_winner: {
 3541                    let winner_abs_path: Arc<Path> =
 3542                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3543
 3544                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3545                        OpenVisible::All => true,
 3546                        OpenVisible::None => false,
 3547                        OpenVisible::OnlyFiles => !winner_is_dir,
 3548                        OpenVisible::OnlyDirectories => winner_is_dir,
 3549                    };
 3550
 3551                    let Some(worktree_task) = this
 3552                        .update(cx, |workspace, cx| {
 3553                            workspace.project.update(cx, |project, cx| {
 3554                                project.find_or_create_worktree(
 3555                                    winner_abs_path.as_ref(),
 3556                                    visible,
 3557                                    cx,
 3558                                )
 3559                            })
 3560                        })
 3561                        .ok()
 3562                    else {
 3563                        break 'emit_winner;
 3564                    };
 3565
 3566                    let Ok((worktree, _)) = worktree_task.await else {
 3567                        break 'emit_winner;
 3568                    };
 3569
 3570                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3571                        let worktree = worktree.read(cx);
 3572                        let worktree_abs_path = worktree.abs_path();
 3573                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3574                            worktree.root_entry()
 3575                        } else {
 3576                            winner_abs_path
 3577                                .strip_prefix(worktree_abs_path.as_ref())
 3578                                .ok()
 3579                                .and_then(|relative_path| {
 3580                                    let relative_path =
 3581                                        RelPath::new(relative_path, PathStyle::local())
 3582                                            .log_err()?;
 3583                                    worktree.entry_for_path(&relative_path)
 3584                                })
 3585                        }?;
 3586                        Some(entry.id)
 3587                    }) else {
 3588                        break 'emit_winner;
 3589                    };
 3590
 3591                    this.update(cx, |workspace, cx| {
 3592                        workspace.project.update(cx, |_, cx| {
 3593                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3594                        });
 3595                    })
 3596                    .ok();
 3597                }
 3598            }
 3599
 3600            results
 3601        })
 3602    }
 3603
 3604    pub fn open_resolved_path(
 3605        &mut self,
 3606        path: ResolvedPath,
 3607        window: &mut Window,
 3608        cx: &mut Context<Self>,
 3609    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3610        match path {
 3611            ResolvedPath::ProjectPath { project_path, .. } => {
 3612                self.open_path(project_path, None, true, window, cx)
 3613            }
 3614            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3615                PathBuf::from(path),
 3616                OpenOptions {
 3617                    visible: Some(OpenVisible::None),
 3618                    ..Default::default()
 3619                },
 3620                window,
 3621                cx,
 3622            ),
 3623        }
 3624    }
 3625
 3626    pub fn absolute_path_of_worktree(
 3627        &self,
 3628        worktree_id: WorktreeId,
 3629        cx: &mut Context<Self>,
 3630    ) -> Option<PathBuf> {
 3631        self.project
 3632            .read(cx)
 3633            .worktree_for_id(worktree_id, cx)
 3634            // TODO: use `abs_path` or `root_dir`
 3635            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3636    }
 3637
 3638    pub fn add_folder_to_project(
 3639        &mut self,
 3640        _: &AddFolderToProject,
 3641        window: &mut Window,
 3642        cx: &mut Context<Self>,
 3643    ) {
 3644        let project = self.project.read(cx);
 3645        if project.is_via_collab() {
 3646            self.show_error(
 3647                &anyhow!("You cannot add folders to someone else's project"),
 3648                cx,
 3649            );
 3650            return;
 3651        }
 3652        let paths = self.prompt_for_open_path(
 3653            PathPromptOptions {
 3654                files: false,
 3655                directories: true,
 3656                multiple: true,
 3657                prompt: None,
 3658            },
 3659            DirectoryLister::Project(self.project.clone()),
 3660            window,
 3661            cx,
 3662        );
 3663        cx.spawn_in(window, async move |this, cx| {
 3664            if let Some(paths) = paths.await.log_err().flatten() {
 3665                let results = this
 3666                    .update_in(cx, |this, window, cx| {
 3667                        this.open_paths(
 3668                            paths,
 3669                            OpenOptions {
 3670                                visible: Some(OpenVisible::All),
 3671                                ..Default::default()
 3672                            },
 3673                            None,
 3674                            window,
 3675                            cx,
 3676                        )
 3677                    })?
 3678                    .await;
 3679                for result in results.into_iter().flatten() {
 3680                    result.log_err();
 3681                }
 3682            }
 3683            anyhow::Ok(())
 3684        })
 3685        .detach_and_log_err(cx);
 3686    }
 3687
 3688    pub fn project_path_for_path(
 3689        project: Entity<Project>,
 3690        abs_path: &Path,
 3691        visible: bool,
 3692        cx: &mut App,
 3693    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3694        let entry = project.update(cx, |project, cx| {
 3695            project.find_or_create_worktree(abs_path, visible, cx)
 3696        });
 3697        cx.spawn(async move |cx| {
 3698            let (worktree, path) = entry.await?;
 3699            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3700            Ok((worktree, ProjectPath { worktree_id, path }))
 3701        })
 3702    }
 3703
 3704    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3705        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3706    }
 3707
 3708    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3709        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3710    }
 3711
 3712    pub fn items_of_type<'a, T: Item>(
 3713        &'a self,
 3714        cx: &'a App,
 3715    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3716        self.panes
 3717            .iter()
 3718            .flat_map(|pane| pane.read(cx).items_of_type())
 3719    }
 3720
 3721    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3722        self.active_pane().read(cx).active_item()
 3723    }
 3724
 3725    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3726        let item = self.active_item(cx)?;
 3727        item.to_any_view().downcast::<I>().ok()
 3728    }
 3729
 3730    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3731        self.active_item(cx).and_then(|item| item.project_path(cx))
 3732    }
 3733
 3734    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3735        self.recent_navigation_history_iter(cx)
 3736            .filter_map(|(path, abs_path)| {
 3737                let worktree = self
 3738                    .project
 3739                    .read(cx)
 3740                    .worktree_for_id(path.worktree_id, cx)?;
 3741                if worktree.read(cx).is_visible() {
 3742                    abs_path
 3743                } else {
 3744                    None
 3745                }
 3746            })
 3747            .next()
 3748    }
 3749
 3750    pub fn save_active_item(
 3751        &mut self,
 3752        save_intent: SaveIntent,
 3753        window: &mut Window,
 3754        cx: &mut App,
 3755    ) -> Task<Result<()>> {
 3756        let project = self.project.clone();
 3757        let pane = self.active_pane();
 3758        let item = pane.read(cx).active_item();
 3759        let pane = pane.downgrade();
 3760
 3761        window.spawn(cx, async move |cx| {
 3762            if let Some(item) = item {
 3763                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3764                    .await
 3765                    .map(|_| ())
 3766            } else {
 3767                Ok(())
 3768            }
 3769        })
 3770    }
 3771
 3772    pub fn close_inactive_items_and_panes(
 3773        &mut self,
 3774        action: &CloseInactiveTabsAndPanes,
 3775        window: &mut Window,
 3776        cx: &mut Context<Self>,
 3777    ) {
 3778        if let Some(task) = self.close_all_internal(
 3779            true,
 3780            action.save_intent.unwrap_or(SaveIntent::Close),
 3781            window,
 3782            cx,
 3783        ) {
 3784            task.detach_and_log_err(cx)
 3785        }
 3786    }
 3787
 3788    pub fn close_all_items_and_panes(
 3789        &mut self,
 3790        action: &CloseAllItemsAndPanes,
 3791        window: &mut Window,
 3792        cx: &mut Context<Self>,
 3793    ) {
 3794        if let Some(task) = self.close_all_internal(
 3795            false,
 3796            action.save_intent.unwrap_or(SaveIntent::Close),
 3797            window,
 3798            cx,
 3799        ) {
 3800            task.detach_and_log_err(cx)
 3801        }
 3802    }
 3803
 3804    /// Closes the active item across all panes.
 3805    pub fn close_item_in_all_panes(
 3806        &mut self,
 3807        action: &CloseItemInAllPanes,
 3808        window: &mut Window,
 3809        cx: &mut Context<Self>,
 3810    ) {
 3811        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3812            return;
 3813        };
 3814
 3815        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3816        let close_pinned = action.close_pinned;
 3817
 3818        if let Some(project_path) = active_item.project_path(cx) {
 3819            self.close_items_with_project_path(
 3820                &project_path,
 3821                save_intent,
 3822                close_pinned,
 3823                window,
 3824                cx,
 3825            );
 3826        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3827            let item_id = active_item.item_id();
 3828            self.active_pane().update(cx, |pane, cx| {
 3829                pane.close_item_by_id(item_id, save_intent, window, cx)
 3830                    .detach_and_log_err(cx);
 3831            });
 3832        }
 3833    }
 3834
 3835    /// Closes all items with the given project path across all panes.
 3836    pub fn close_items_with_project_path(
 3837        &mut self,
 3838        project_path: &ProjectPath,
 3839        save_intent: SaveIntent,
 3840        close_pinned: bool,
 3841        window: &mut Window,
 3842        cx: &mut Context<Self>,
 3843    ) {
 3844        let panes = self.panes().to_vec();
 3845        for pane in panes {
 3846            pane.update(cx, |pane, cx| {
 3847                pane.close_items_for_project_path(
 3848                    project_path,
 3849                    save_intent,
 3850                    close_pinned,
 3851                    window,
 3852                    cx,
 3853                )
 3854                .detach_and_log_err(cx);
 3855            });
 3856        }
 3857    }
 3858
 3859    fn close_all_internal(
 3860        &mut self,
 3861        retain_active_pane: bool,
 3862        save_intent: SaveIntent,
 3863        window: &mut Window,
 3864        cx: &mut Context<Self>,
 3865    ) -> Option<Task<Result<()>>> {
 3866        let current_pane = self.active_pane();
 3867
 3868        let mut tasks = Vec::new();
 3869
 3870        if retain_active_pane {
 3871            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3872                pane.close_other_items(
 3873                    &CloseOtherItems {
 3874                        save_intent: None,
 3875                        close_pinned: false,
 3876                    },
 3877                    None,
 3878                    window,
 3879                    cx,
 3880                )
 3881            });
 3882
 3883            tasks.push(current_pane_close);
 3884        }
 3885
 3886        for pane in self.panes() {
 3887            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3888                continue;
 3889            }
 3890
 3891            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3892                pane.close_all_items(
 3893                    &CloseAllItems {
 3894                        save_intent: Some(save_intent),
 3895                        close_pinned: false,
 3896                    },
 3897                    window,
 3898                    cx,
 3899                )
 3900            });
 3901
 3902            tasks.push(close_pane_items)
 3903        }
 3904
 3905        if tasks.is_empty() {
 3906            None
 3907        } else {
 3908            Some(cx.spawn_in(window, async move |_, _| {
 3909                for task in tasks {
 3910                    task.await?
 3911                }
 3912                Ok(())
 3913            }))
 3914        }
 3915    }
 3916
 3917    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3918        self.dock_at_position(position).read(cx).is_open()
 3919    }
 3920
 3921    pub fn toggle_dock(
 3922        &mut self,
 3923        dock_side: DockPosition,
 3924        window: &mut Window,
 3925        cx: &mut Context<Self>,
 3926    ) {
 3927        let mut focus_center = false;
 3928        let mut reveal_dock = false;
 3929
 3930        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3931        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3932
 3933        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3934            telemetry::event!(
 3935                "Panel Button Clicked",
 3936                name = panel.persistent_name(),
 3937                toggle_state = !was_visible
 3938            );
 3939        }
 3940        if was_visible {
 3941            self.save_open_dock_positions(cx);
 3942        }
 3943
 3944        let dock = self.dock_at_position(dock_side);
 3945        dock.update(cx, |dock, cx| {
 3946            dock.set_open(!was_visible, window, cx);
 3947
 3948            if dock.active_panel().is_none() {
 3949                let Some(panel_ix) = dock
 3950                    .first_enabled_panel_idx(cx)
 3951                    .log_with_level(log::Level::Info)
 3952                else {
 3953                    return;
 3954                };
 3955                dock.activate_panel(panel_ix, window, cx);
 3956            }
 3957
 3958            if let Some(active_panel) = dock.active_panel() {
 3959                if was_visible {
 3960                    if active_panel
 3961                        .panel_focus_handle(cx)
 3962                        .contains_focused(window, cx)
 3963                    {
 3964                        focus_center = true;
 3965                    }
 3966                } else {
 3967                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3968                    window.focus(focus_handle, cx);
 3969                    reveal_dock = true;
 3970                }
 3971            }
 3972        });
 3973
 3974        if reveal_dock {
 3975            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3976        }
 3977
 3978        if focus_center {
 3979            self.active_pane
 3980                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3981        }
 3982
 3983        cx.notify();
 3984        self.serialize_workspace(window, cx);
 3985    }
 3986
 3987    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3988        self.all_docks().into_iter().find(|&dock| {
 3989            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3990        })
 3991    }
 3992
 3993    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3994        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3995            self.save_open_dock_positions(cx);
 3996            dock.update(cx, |dock, cx| {
 3997                dock.set_open(false, window, cx);
 3998            });
 3999            return true;
 4000        }
 4001        false
 4002    }
 4003
 4004    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4005        self.save_open_dock_positions(cx);
 4006        for dock in self.all_docks() {
 4007            dock.update(cx, |dock, cx| {
 4008                dock.set_open(false, window, cx);
 4009            });
 4010        }
 4011
 4012        cx.focus_self(window);
 4013        cx.notify();
 4014        self.serialize_workspace(window, cx);
 4015    }
 4016
 4017    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4018        self.all_docks()
 4019            .into_iter()
 4020            .filter_map(|dock| {
 4021                let dock_ref = dock.read(cx);
 4022                if dock_ref.is_open() {
 4023                    Some(dock_ref.position())
 4024                } else {
 4025                    None
 4026                }
 4027            })
 4028            .collect()
 4029    }
 4030
 4031    /// Saves the positions of currently open docks.
 4032    ///
 4033    /// Updates `last_open_dock_positions` with positions of all currently open
 4034    /// docks, to later be restored by the 'Toggle All Docks' action.
 4035    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4036        let open_dock_positions = self.get_open_dock_positions(cx);
 4037        if !open_dock_positions.is_empty() {
 4038            self.last_open_dock_positions = open_dock_positions;
 4039        }
 4040    }
 4041
 4042    /// Toggles all docks between open and closed states.
 4043    ///
 4044    /// If any docks are open, closes all and remembers their positions. If all
 4045    /// docks are closed, restores the last remembered dock configuration.
 4046    fn toggle_all_docks(
 4047        &mut self,
 4048        _: &ToggleAllDocks,
 4049        window: &mut Window,
 4050        cx: &mut Context<Self>,
 4051    ) {
 4052        let open_dock_positions = self.get_open_dock_positions(cx);
 4053
 4054        if !open_dock_positions.is_empty() {
 4055            self.close_all_docks(window, cx);
 4056        } else if !self.last_open_dock_positions.is_empty() {
 4057            self.restore_last_open_docks(window, cx);
 4058        }
 4059    }
 4060
 4061    /// Reopens docks from the most recently remembered configuration.
 4062    ///
 4063    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4064    /// and clears the stored positions.
 4065    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4066        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4067
 4068        for position in positions_to_open {
 4069            let dock = self.dock_at_position(position);
 4070            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4071        }
 4072
 4073        cx.focus_self(window);
 4074        cx.notify();
 4075        self.serialize_workspace(window, cx);
 4076    }
 4077
 4078    /// Transfer focus to the panel of the given type.
 4079    pub fn focus_panel<T: Panel>(
 4080        &mut self,
 4081        window: &mut Window,
 4082        cx: &mut Context<Self>,
 4083    ) -> Option<Entity<T>> {
 4084        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4085        panel.to_any().downcast().ok()
 4086    }
 4087
 4088    /// Focus the panel of the given type if it isn't already focused. If it is
 4089    /// already focused, then transfer focus back to the workspace center.
 4090    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4091    /// panel when transferring focus back to the center.
 4092    pub fn toggle_panel_focus<T: Panel>(
 4093        &mut self,
 4094        window: &mut Window,
 4095        cx: &mut Context<Self>,
 4096    ) -> bool {
 4097        let mut did_focus_panel = false;
 4098        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4099            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4100            did_focus_panel
 4101        });
 4102
 4103        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4104            self.close_panel::<T>(window, cx);
 4105        }
 4106
 4107        telemetry::event!(
 4108            "Panel Button Clicked",
 4109            name = T::persistent_name(),
 4110            toggle_state = did_focus_panel
 4111        );
 4112
 4113        did_focus_panel
 4114    }
 4115
 4116    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4117        if let Some(item) = self.active_item(cx) {
 4118            item.item_focus_handle(cx).focus(window, cx);
 4119        } else {
 4120            log::error!("Could not find a focus target when switching focus to the center panes",);
 4121        }
 4122    }
 4123
 4124    pub fn activate_panel_for_proto_id(
 4125        &mut self,
 4126        panel_id: PanelId,
 4127        window: &mut Window,
 4128        cx: &mut Context<Self>,
 4129    ) -> Option<Arc<dyn PanelHandle>> {
 4130        let mut panel = None;
 4131        for dock in self.all_docks() {
 4132            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4133                panel = dock.update(cx, |dock, cx| {
 4134                    dock.activate_panel(panel_index, window, cx);
 4135                    dock.set_open(true, window, cx);
 4136                    dock.active_panel().cloned()
 4137                });
 4138                break;
 4139            }
 4140        }
 4141
 4142        if panel.is_some() {
 4143            cx.notify();
 4144            self.serialize_workspace(window, cx);
 4145        }
 4146
 4147        panel
 4148    }
 4149
 4150    /// Focus or unfocus the given panel type, depending on the given callback.
 4151    fn focus_or_unfocus_panel<T: Panel>(
 4152        &mut self,
 4153        window: &mut Window,
 4154        cx: &mut Context<Self>,
 4155        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4156    ) -> Option<Arc<dyn PanelHandle>> {
 4157        let mut result_panel = None;
 4158        let mut serialize = false;
 4159        for dock in self.all_docks() {
 4160            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4161                let mut focus_center = false;
 4162                let panel = dock.update(cx, |dock, cx| {
 4163                    dock.activate_panel(panel_index, window, cx);
 4164
 4165                    let panel = dock.active_panel().cloned();
 4166                    if let Some(panel) = panel.as_ref() {
 4167                        if should_focus(&**panel, window, cx) {
 4168                            dock.set_open(true, window, cx);
 4169                            panel.panel_focus_handle(cx).focus(window, cx);
 4170                        } else {
 4171                            focus_center = true;
 4172                        }
 4173                    }
 4174                    panel
 4175                });
 4176
 4177                if focus_center {
 4178                    self.active_pane
 4179                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4180                }
 4181
 4182                result_panel = panel;
 4183                serialize = true;
 4184                break;
 4185            }
 4186        }
 4187
 4188        if serialize {
 4189            self.serialize_workspace(window, cx);
 4190        }
 4191
 4192        cx.notify();
 4193        result_panel
 4194    }
 4195
 4196    /// Open the panel of the given type
 4197    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4198        for dock in self.all_docks() {
 4199            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4200                dock.update(cx, |dock, cx| {
 4201                    dock.activate_panel(panel_index, window, cx);
 4202                    dock.set_open(true, window, cx);
 4203                });
 4204            }
 4205        }
 4206    }
 4207
 4208    /// Open the panel of the given type, dismissing any zoomed items that
 4209    /// would obscure it (e.g. a zoomed terminal).
 4210    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4211        let dock_position = self.all_docks().iter().find_map(|dock| {
 4212            let dock = dock.read(cx);
 4213            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4214        });
 4215        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4216        self.open_panel::<T>(window, cx);
 4217    }
 4218
 4219    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4220        for dock in self.all_docks().iter() {
 4221            dock.update(cx, |dock, cx| {
 4222                if dock.panel::<T>().is_some() {
 4223                    dock.set_open(false, window, cx)
 4224                }
 4225            })
 4226        }
 4227    }
 4228
 4229    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4230        self.all_docks()
 4231            .iter()
 4232            .find_map(|dock| dock.read(cx).panel::<T>())
 4233    }
 4234
 4235    fn dismiss_zoomed_items_to_reveal(
 4236        &mut self,
 4237        dock_to_reveal: Option<DockPosition>,
 4238        window: &mut Window,
 4239        cx: &mut Context<Self>,
 4240    ) {
 4241        // If a center pane is zoomed, unzoom it.
 4242        for pane in &self.panes {
 4243            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4244                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4245            }
 4246        }
 4247
 4248        // If another dock is zoomed, hide it.
 4249        let mut focus_center = false;
 4250        for dock in self.all_docks() {
 4251            dock.update(cx, |dock, cx| {
 4252                if Some(dock.position()) != dock_to_reveal
 4253                    && let Some(panel) = dock.active_panel()
 4254                    && panel.is_zoomed(window, cx)
 4255                {
 4256                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4257                    dock.set_open(false, window, cx);
 4258                }
 4259            });
 4260        }
 4261
 4262        if focus_center {
 4263            self.active_pane
 4264                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4265        }
 4266
 4267        if self.zoomed_position != dock_to_reveal {
 4268            self.zoomed = None;
 4269            self.zoomed_position = None;
 4270            cx.emit(Event::ZoomChanged);
 4271        }
 4272
 4273        cx.notify();
 4274    }
 4275
 4276    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4277        let pane = cx.new(|cx| {
 4278            let mut pane = Pane::new(
 4279                self.weak_handle(),
 4280                self.project.clone(),
 4281                self.pane_history_timestamp.clone(),
 4282                None,
 4283                NewFile.boxed_clone(),
 4284                true,
 4285                window,
 4286                cx,
 4287            );
 4288            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4289            pane
 4290        });
 4291        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4292            .detach();
 4293        self.panes.push(pane.clone());
 4294
 4295        window.focus(&pane.focus_handle(cx), cx);
 4296
 4297        cx.emit(Event::PaneAdded(pane.clone()));
 4298        pane
 4299    }
 4300
 4301    pub fn add_item_to_center(
 4302        &mut self,
 4303        item: Box<dyn ItemHandle>,
 4304        window: &mut Window,
 4305        cx: &mut Context<Self>,
 4306    ) -> bool {
 4307        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4308            if let Some(center_pane) = center_pane.upgrade() {
 4309                center_pane.update(cx, |pane, cx| {
 4310                    pane.add_item(item, true, true, None, window, cx)
 4311                });
 4312                true
 4313            } else {
 4314                false
 4315            }
 4316        } else {
 4317            false
 4318        }
 4319    }
 4320
 4321    pub fn add_item_to_active_pane(
 4322        &mut self,
 4323        item: Box<dyn ItemHandle>,
 4324        destination_index: Option<usize>,
 4325        focus_item: bool,
 4326        window: &mut Window,
 4327        cx: &mut App,
 4328    ) {
 4329        self.add_item(
 4330            self.active_pane.clone(),
 4331            item,
 4332            destination_index,
 4333            false,
 4334            focus_item,
 4335            window,
 4336            cx,
 4337        )
 4338    }
 4339
 4340    pub fn add_item(
 4341        &mut self,
 4342        pane: Entity<Pane>,
 4343        item: Box<dyn ItemHandle>,
 4344        destination_index: Option<usize>,
 4345        activate_pane: bool,
 4346        focus_item: bool,
 4347        window: &mut Window,
 4348        cx: &mut App,
 4349    ) {
 4350        pane.update(cx, |pane, cx| {
 4351            pane.add_item(
 4352                item,
 4353                activate_pane,
 4354                focus_item,
 4355                destination_index,
 4356                window,
 4357                cx,
 4358            )
 4359        });
 4360    }
 4361
 4362    pub fn split_item(
 4363        &mut self,
 4364        split_direction: SplitDirection,
 4365        item: Box<dyn ItemHandle>,
 4366        window: &mut Window,
 4367        cx: &mut Context<Self>,
 4368    ) {
 4369        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4370        self.add_item(new_pane, item, None, true, true, window, cx);
 4371    }
 4372
 4373    pub fn open_abs_path(
 4374        &mut self,
 4375        abs_path: PathBuf,
 4376        options: OpenOptions,
 4377        window: &mut Window,
 4378        cx: &mut Context<Self>,
 4379    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4380        cx.spawn_in(window, async move |workspace, cx| {
 4381            let open_paths_task_result = workspace
 4382                .update_in(cx, |workspace, window, cx| {
 4383                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4384                })
 4385                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4386                .await;
 4387            anyhow::ensure!(
 4388                open_paths_task_result.len() == 1,
 4389                "open abs path {abs_path:?} task returned incorrect number of results"
 4390            );
 4391            match open_paths_task_result
 4392                .into_iter()
 4393                .next()
 4394                .expect("ensured single task result")
 4395            {
 4396                Some(open_result) => {
 4397                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4398                }
 4399                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4400            }
 4401        })
 4402    }
 4403
 4404    pub fn split_abs_path(
 4405        &mut self,
 4406        abs_path: PathBuf,
 4407        visible: bool,
 4408        window: &mut Window,
 4409        cx: &mut Context<Self>,
 4410    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4411        let project_path_task =
 4412            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4413        cx.spawn_in(window, async move |this, cx| {
 4414            let (_, path) = project_path_task.await?;
 4415            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4416                .await
 4417        })
 4418    }
 4419
 4420    pub fn open_path(
 4421        &mut self,
 4422        path: impl Into<ProjectPath>,
 4423        pane: Option<WeakEntity<Pane>>,
 4424        focus_item: bool,
 4425        window: &mut Window,
 4426        cx: &mut App,
 4427    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4428        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4429    }
 4430
 4431    pub fn open_path_preview(
 4432        &mut self,
 4433        path: impl Into<ProjectPath>,
 4434        pane: Option<WeakEntity<Pane>>,
 4435        focus_item: bool,
 4436        allow_preview: bool,
 4437        activate: bool,
 4438        window: &mut Window,
 4439        cx: &mut App,
 4440    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4441        let pane = pane.unwrap_or_else(|| {
 4442            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4443                self.panes
 4444                    .first()
 4445                    .expect("There must be an active pane")
 4446                    .downgrade()
 4447            })
 4448        });
 4449
 4450        let project_path = path.into();
 4451        let task = self.load_path(project_path.clone(), window, cx);
 4452        window.spawn(cx, async move |cx| {
 4453            let (project_entry_id, build_item) = task.await?;
 4454
 4455            pane.update_in(cx, |pane, window, cx| {
 4456                pane.open_item(
 4457                    project_entry_id,
 4458                    project_path,
 4459                    focus_item,
 4460                    allow_preview,
 4461                    activate,
 4462                    None,
 4463                    window,
 4464                    cx,
 4465                    build_item,
 4466                )
 4467            })
 4468        })
 4469    }
 4470
 4471    pub fn split_path(
 4472        &mut self,
 4473        path: impl Into<ProjectPath>,
 4474        window: &mut Window,
 4475        cx: &mut Context<Self>,
 4476    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4477        self.split_path_preview(path, false, None, window, cx)
 4478    }
 4479
 4480    pub fn split_path_preview(
 4481        &mut self,
 4482        path: impl Into<ProjectPath>,
 4483        allow_preview: bool,
 4484        split_direction: Option<SplitDirection>,
 4485        window: &mut Window,
 4486        cx: &mut Context<Self>,
 4487    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4488        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4489            self.panes
 4490                .first()
 4491                .expect("There must be an active pane")
 4492                .downgrade()
 4493        });
 4494
 4495        if let Member::Pane(center_pane) = &self.center.root
 4496            && center_pane.read(cx).items_len() == 0
 4497        {
 4498            return self.open_path(path, Some(pane), true, window, cx);
 4499        }
 4500
 4501        let project_path = path.into();
 4502        let task = self.load_path(project_path.clone(), window, cx);
 4503        cx.spawn_in(window, async move |this, cx| {
 4504            let (project_entry_id, build_item) = task.await?;
 4505            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4506                let pane = pane.upgrade()?;
 4507                let new_pane = this.split_pane(
 4508                    pane,
 4509                    split_direction.unwrap_or(SplitDirection::Right),
 4510                    window,
 4511                    cx,
 4512                );
 4513                new_pane.update(cx, |new_pane, cx| {
 4514                    Some(new_pane.open_item(
 4515                        project_entry_id,
 4516                        project_path,
 4517                        true,
 4518                        allow_preview,
 4519                        true,
 4520                        None,
 4521                        window,
 4522                        cx,
 4523                        build_item,
 4524                    ))
 4525                })
 4526            })
 4527            .map(|option| option.context("pane was dropped"))?
 4528        })
 4529    }
 4530
 4531    fn load_path(
 4532        &mut self,
 4533        path: ProjectPath,
 4534        window: &mut Window,
 4535        cx: &mut App,
 4536    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4537        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4538        registry.open_path(self.project(), &path, window, cx)
 4539    }
 4540
 4541    pub fn find_project_item<T>(
 4542        &self,
 4543        pane: &Entity<Pane>,
 4544        project_item: &Entity<T::Item>,
 4545        cx: &App,
 4546    ) -> Option<Entity<T>>
 4547    where
 4548        T: ProjectItem,
 4549    {
 4550        use project::ProjectItem as _;
 4551        let project_item = project_item.read(cx);
 4552        let entry_id = project_item.entry_id(cx);
 4553        let project_path = project_item.project_path(cx);
 4554
 4555        let mut item = None;
 4556        if let Some(entry_id) = entry_id {
 4557            item = pane.read(cx).item_for_entry(entry_id, cx);
 4558        }
 4559        if item.is_none()
 4560            && let Some(project_path) = project_path
 4561        {
 4562            item = pane.read(cx).item_for_path(project_path, cx);
 4563        }
 4564
 4565        item.and_then(|item| item.downcast::<T>())
 4566    }
 4567
 4568    pub fn is_project_item_open<T>(
 4569        &self,
 4570        pane: &Entity<Pane>,
 4571        project_item: &Entity<T::Item>,
 4572        cx: &App,
 4573    ) -> bool
 4574    where
 4575        T: ProjectItem,
 4576    {
 4577        self.find_project_item::<T>(pane, project_item, cx)
 4578            .is_some()
 4579    }
 4580
 4581    pub fn open_project_item<T>(
 4582        &mut self,
 4583        pane: Entity<Pane>,
 4584        project_item: Entity<T::Item>,
 4585        activate_pane: bool,
 4586        focus_item: bool,
 4587        keep_old_preview: bool,
 4588        allow_new_preview: bool,
 4589        window: &mut Window,
 4590        cx: &mut Context<Self>,
 4591    ) -> Entity<T>
 4592    where
 4593        T: ProjectItem,
 4594    {
 4595        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4596
 4597        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4598            if !keep_old_preview
 4599                && let Some(old_id) = old_item_id
 4600                && old_id != item.item_id()
 4601            {
 4602                // switching to a different item, so unpreview old active item
 4603                pane.update(cx, |pane, _| {
 4604                    pane.unpreview_item_if_preview(old_id);
 4605                });
 4606            }
 4607
 4608            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4609            if !allow_new_preview {
 4610                pane.update(cx, |pane, _| {
 4611                    pane.unpreview_item_if_preview(item.item_id());
 4612                });
 4613            }
 4614            return item;
 4615        }
 4616
 4617        let item = pane.update(cx, |pane, cx| {
 4618            cx.new(|cx| {
 4619                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4620            })
 4621        });
 4622        let mut destination_index = None;
 4623        pane.update(cx, |pane, cx| {
 4624            if !keep_old_preview && let Some(old_id) = old_item_id {
 4625                pane.unpreview_item_if_preview(old_id);
 4626            }
 4627            if allow_new_preview {
 4628                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4629            }
 4630        });
 4631
 4632        self.add_item(
 4633            pane,
 4634            Box::new(item.clone()),
 4635            destination_index,
 4636            activate_pane,
 4637            focus_item,
 4638            window,
 4639            cx,
 4640        );
 4641        item
 4642    }
 4643
 4644    pub fn open_shared_screen(
 4645        &mut self,
 4646        peer_id: PeerId,
 4647        window: &mut Window,
 4648        cx: &mut Context<Self>,
 4649    ) {
 4650        if let Some(shared_screen) =
 4651            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4652        {
 4653            self.active_pane.update(cx, |pane, cx| {
 4654                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4655            });
 4656        }
 4657    }
 4658
 4659    pub fn activate_item(
 4660        &mut self,
 4661        item: &dyn ItemHandle,
 4662        activate_pane: bool,
 4663        focus_item: bool,
 4664        window: &mut Window,
 4665        cx: &mut App,
 4666    ) -> bool {
 4667        let result = self.panes.iter().find_map(|pane| {
 4668            pane.read(cx)
 4669                .index_for_item(item)
 4670                .map(|ix| (pane.clone(), ix))
 4671        });
 4672        if let Some((pane, ix)) = result {
 4673            pane.update(cx, |pane, cx| {
 4674                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4675            });
 4676            true
 4677        } else {
 4678            false
 4679        }
 4680    }
 4681
 4682    fn activate_pane_at_index(
 4683        &mut self,
 4684        action: &ActivatePane,
 4685        window: &mut Window,
 4686        cx: &mut Context<Self>,
 4687    ) {
 4688        let panes = self.center.panes();
 4689        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4690            window.focus(&pane.focus_handle(cx), cx);
 4691        } else {
 4692            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4693                .detach();
 4694        }
 4695    }
 4696
 4697    fn move_item_to_pane_at_index(
 4698        &mut self,
 4699        action: &MoveItemToPane,
 4700        window: &mut Window,
 4701        cx: &mut Context<Self>,
 4702    ) {
 4703        let panes = self.center.panes();
 4704        let destination = match panes.get(action.destination) {
 4705            Some(&destination) => destination.clone(),
 4706            None => {
 4707                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4708                    return;
 4709                }
 4710                let direction = SplitDirection::Right;
 4711                let split_off_pane = self
 4712                    .find_pane_in_direction(direction, cx)
 4713                    .unwrap_or_else(|| self.active_pane.clone());
 4714                let new_pane = self.add_pane(window, cx);
 4715                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4716                new_pane
 4717            }
 4718        };
 4719
 4720        if action.clone {
 4721            if self
 4722                .active_pane
 4723                .read(cx)
 4724                .active_item()
 4725                .is_some_and(|item| item.can_split(cx))
 4726            {
 4727                clone_active_item(
 4728                    self.database_id(),
 4729                    &self.active_pane,
 4730                    &destination,
 4731                    action.focus,
 4732                    window,
 4733                    cx,
 4734                );
 4735                return;
 4736            }
 4737        }
 4738        move_active_item(
 4739            &self.active_pane,
 4740            &destination,
 4741            action.focus,
 4742            true,
 4743            window,
 4744            cx,
 4745        )
 4746    }
 4747
 4748    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4749        let panes = self.center.panes();
 4750        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4751            let next_ix = (ix + 1) % panes.len();
 4752            let next_pane = panes[next_ix].clone();
 4753            window.focus(&next_pane.focus_handle(cx), cx);
 4754        }
 4755    }
 4756
 4757    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4758        let panes = self.center.panes();
 4759        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4760            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4761            let prev_pane = panes[prev_ix].clone();
 4762            window.focus(&prev_pane.focus_handle(cx), cx);
 4763        }
 4764    }
 4765
 4766    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4767        let last_pane = self.center.last_pane();
 4768        window.focus(&last_pane.focus_handle(cx), cx);
 4769    }
 4770
 4771    pub fn activate_pane_in_direction(
 4772        &mut self,
 4773        direction: SplitDirection,
 4774        window: &mut Window,
 4775        cx: &mut App,
 4776    ) {
 4777        use ActivateInDirectionTarget as Target;
 4778        enum Origin {
 4779            Sidebar,
 4780            LeftDock,
 4781            RightDock,
 4782            BottomDock,
 4783            Center,
 4784        }
 4785
 4786        let origin: Origin = if self
 4787            .sidebar_focus_handle
 4788            .as_ref()
 4789            .is_some_and(|h| h.contains_focused(window, cx))
 4790        {
 4791            Origin::Sidebar
 4792        } else {
 4793            [
 4794                (&self.left_dock, Origin::LeftDock),
 4795                (&self.right_dock, Origin::RightDock),
 4796                (&self.bottom_dock, Origin::BottomDock),
 4797            ]
 4798            .into_iter()
 4799            .find_map(|(dock, origin)| {
 4800                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4801                    Some(origin)
 4802                } else {
 4803                    None
 4804                }
 4805            })
 4806            .unwrap_or(Origin::Center)
 4807        };
 4808
 4809        let get_last_active_pane = || {
 4810            let pane = self
 4811                .last_active_center_pane
 4812                .clone()
 4813                .unwrap_or_else(|| {
 4814                    self.panes
 4815                        .first()
 4816                        .expect("There must be an active pane")
 4817                        .downgrade()
 4818                })
 4819                .upgrade()?;
 4820            (pane.read(cx).items_len() != 0).then_some(pane)
 4821        };
 4822
 4823        let try_dock =
 4824            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4825
 4826        let sidebar_target = self
 4827            .sidebar_focus_handle
 4828            .as_ref()
 4829            .map(|h| Target::Sidebar(h.clone()));
 4830
 4831        let target = match (origin, direction) {
 4832            // From the sidebar, only Right navigates into the workspace.
 4833            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4834                .or_else(|| get_last_active_pane().map(Target::Pane))
 4835                .or_else(|| try_dock(&self.bottom_dock))
 4836                .or_else(|| try_dock(&self.right_dock)),
 4837
 4838            (Origin::Sidebar, _) => None,
 4839
 4840            // We're in the center, so we first try to go to a different pane,
 4841            // otherwise try to go to a dock.
 4842            (Origin::Center, direction) => {
 4843                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4844                    Some(Target::Pane(pane))
 4845                } else {
 4846                    match direction {
 4847                        SplitDirection::Up => None,
 4848                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4849                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4850                        SplitDirection::Right => try_dock(&self.right_dock),
 4851                    }
 4852                }
 4853            }
 4854
 4855            (Origin::LeftDock, SplitDirection::Right) => {
 4856                if let Some(last_active_pane) = get_last_active_pane() {
 4857                    Some(Target::Pane(last_active_pane))
 4858                } else {
 4859                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4860                }
 4861            }
 4862
 4863            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4864
 4865            (Origin::LeftDock, SplitDirection::Down)
 4866            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4867
 4868            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4869            (Origin::BottomDock, SplitDirection::Left) => {
 4870                try_dock(&self.left_dock).or(sidebar_target)
 4871            }
 4872            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4873
 4874            (Origin::RightDock, SplitDirection::Left) => {
 4875                if let Some(last_active_pane) = get_last_active_pane() {
 4876                    Some(Target::Pane(last_active_pane))
 4877                } else {
 4878                    try_dock(&self.bottom_dock)
 4879                        .or_else(|| try_dock(&self.left_dock))
 4880                        .or(sidebar_target)
 4881                }
 4882            }
 4883
 4884            _ => None,
 4885        };
 4886
 4887        match target {
 4888            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4889                let pane = pane.read(cx);
 4890                if let Some(item) = pane.active_item() {
 4891                    item.item_focus_handle(cx).focus(window, cx);
 4892                } else {
 4893                    log::error!(
 4894                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4895                    );
 4896                }
 4897            }
 4898            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4899                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4900                window.defer(cx, move |window, cx| {
 4901                    let dock = dock.read(cx);
 4902                    if let Some(panel) = dock.active_panel() {
 4903                        panel.panel_focus_handle(cx).focus(window, cx);
 4904                    } else {
 4905                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4906                    }
 4907                })
 4908            }
 4909            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4910                focus_handle.focus(window, cx);
 4911            }
 4912            None => {}
 4913        }
 4914    }
 4915
 4916    pub fn move_item_to_pane_in_direction(
 4917        &mut self,
 4918        action: &MoveItemToPaneInDirection,
 4919        window: &mut Window,
 4920        cx: &mut Context<Self>,
 4921    ) {
 4922        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4923            Some(destination) => destination,
 4924            None => {
 4925                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4926                    return;
 4927                }
 4928                let new_pane = self.add_pane(window, cx);
 4929                self.center
 4930                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4931                new_pane
 4932            }
 4933        };
 4934
 4935        if action.clone {
 4936            if self
 4937                .active_pane
 4938                .read(cx)
 4939                .active_item()
 4940                .is_some_and(|item| item.can_split(cx))
 4941            {
 4942                clone_active_item(
 4943                    self.database_id(),
 4944                    &self.active_pane,
 4945                    &destination,
 4946                    action.focus,
 4947                    window,
 4948                    cx,
 4949                );
 4950                return;
 4951            }
 4952        }
 4953        move_active_item(
 4954            &self.active_pane,
 4955            &destination,
 4956            action.focus,
 4957            true,
 4958            window,
 4959            cx,
 4960        );
 4961    }
 4962
 4963    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4964        self.center.bounding_box_for_pane(pane)
 4965    }
 4966
 4967    pub fn find_pane_in_direction(
 4968        &mut self,
 4969        direction: SplitDirection,
 4970        cx: &App,
 4971    ) -> Option<Entity<Pane>> {
 4972        self.center
 4973            .find_pane_in_direction(&self.active_pane, direction, cx)
 4974            .cloned()
 4975    }
 4976
 4977    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4978        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4979            self.center.swap(&self.active_pane, &to, cx);
 4980            cx.notify();
 4981        }
 4982    }
 4983
 4984    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4985        if self
 4986            .center
 4987            .move_to_border(&self.active_pane, direction, cx)
 4988            .unwrap()
 4989        {
 4990            cx.notify();
 4991        }
 4992    }
 4993
 4994    pub fn resize_pane(
 4995        &mut self,
 4996        axis: gpui::Axis,
 4997        amount: Pixels,
 4998        window: &mut Window,
 4999        cx: &mut Context<Self>,
 5000    ) {
 5001        let docks = self.all_docks();
 5002        let active_dock = docks
 5003            .into_iter()
 5004            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5005
 5006        if let Some(dock_entity) = active_dock {
 5007            let dock = dock_entity.read(cx);
 5008            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5009                return;
 5010            };
 5011            match dock.position() {
 5012                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5013                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5014                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5015            }
 5016        } else {
 5017            self.center
 5018                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5019        }
 5020        cx.notify();
 5021    }
 5022
 5023    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5024        self.center.reset_pane_sizes(cx);
 5025        cx.notify();
 5026    }
 5027
 5028    fn handle_pane_focused(
 5029        &mut self,
 5030        pane: Entity<Pane>,
 5031        window: &mut Window,
 5032        cx: &mut Context<Self>,
 5033    ) {
 5034        // This is explicitly hoisted out of the following check for pane identity as
 5035        // terminal panel panes are not registered as a center panes.
 5036        self.status_bar.update(cx, |status_bar, cx| {
 5037            status_bar.set_active_pane(&pane, window, cx);
 5038        });
 5039        if self.active_pane != pane {
 5040            self.set_active_pane(&pane, window, cx);
 5041        }
 5042
 5043        if self.last_active_center_pane.is_none() {
 5044            self.last_active_center_pane = Some(pane.downgrade());
 5045        }
 5046
 5047        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5048        // This prevents the dock from closing when focus events fire during window activation.
 5049        // We also preserve any dock whose active panel itself has focus — this covers
 5050        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5051        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5052            let dock_read = dock.read(cx);
 5053            if let Some(panel) = dock_read.active_panel() {
 5054                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5055                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5056                {
 5057                    return Some(dock_read.position());
 5058                }
 5059            }
 5060            None
 5061        });
 5062
 5063        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5064        if pane.read(cx).is_zoomed() {
 5065            self.zoomed = Some(pane.downgrade().into());
 5066        } else {
 5067            self.zoomed = None;
 5068        }
 5069        self.zoomed_position = None;
 5070        cx.emit(Event::ZoomChanged);
 5071        self.update_active_view_for_followers(window, cx);
 5072        pane.update(cx, |pane, _| {
 5073            pane.track_alternate_file_items();
 5074        });
 5075
 5076        cx.notify();
 5077    }
 5078
 5079    fn set_active_pane(
 5080        &mut self,
 5081        pane: &Entity<Pane>,
 5082        window: &mut Window,
 5083        cx: &mut Context<Self>,
 5084    ) {
 5085        self.active_pane = pane.clone();
 5086        self.active_item_path_changed(true, window, cx);
 5087        self.last_active_center_pane = Some(pane.downgrade());
 5088    }
 5089
 5090    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5091        self.update_active_view_for_followers(window, cx);
 5092    }
 5093
 5094    fn handle_pane_event(
 5095        &mut self,
 5096        pane: &Entity<Pane>,
 5097        event: &pane::Event,
 5098        window: &mut Window,
 5099        cx: &mut Context<Self>,
 5100    ) {
 5101        let mut serialize_workspace = true;
 5102        match event {
 5103            pane::Event::AddItem { item } => {
 5104                item.added_to_pane(self, pane.clone(), window, cx);
 5105                cx.emit(Event::ItemAdded {
 5106                    item: item.boxed_clone(),
 5107                });
 5108            }
 5109            pane::Event::Split { direction, mode } => {
 5110                match mode {
 5111                    SplitMode::ClonePane => {
 5112                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5113                            .detach();
 5114                    }
 5115                    SplitMode::EmptyPane => {
 5116                        self.split_pane(pane.clone(), *direction, window, cx);
 5117                    }
 5118                    SplitMode::MovePane => {
 5119                        self.split_and_move(pane.clone(), *direction, window, cx);
 5120                    }
 5121                };
 5122            }
 5123            pane::Event::JoinIntoNext => {
 5124                self.join_pane_into_next(pane.clone(), window, cx);
 5125            }
 5126            pane::Event::JoinAll => {
 5127                self.join_all_panes(window, cx);
 5128            }
 5129            pane::Event::Remove { focus_on_pane } => {
 5130                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5131            }
 5132            pane::Event::ActivateItem {
 5133                local,
 5134                focus_changed,
 5135            } => {
 5136                window.invalidate_character_coordinates();
 5137
 5138                pane.update(cx, |pane, _| {
 5139                    pane.track_alternate_file_items();
 5140                });
 5141                if *local {
 5142                    self.unfollow_in_pane(pane, window, cx);
 5143                }
 5144                serialize_workspace = *focus_changed || pane != self.active_pane();
 5145                if pane == self.active_pane() {
 5146                    self.active_item_path_changed(*focus_changed, window, cx);
 5147                    self.update_active_view_for_followers(window, cx);
 5148                } else if *local {
 5149                    self.set_active_pane(pane, window, cx);
 5150                }
 5151            }
 5152            pane::Event::UserSavedItem { item, save_intent } => {
 5153                cx.emit(Event::UserSavedItem {
 5154                    pane: pane.downgrade(),
 5155                    item: item.boxed_clone(),
 5156                    save_intent: *save_intent,
 5157                });
 5158                serialize_workspace = false;
 5159            }
 5160            pane::Event::ChangeItemTitle => {
 5161                if *pane == self.active_pane {
 5162                    self.active_item_path_changed(false, window, cx);
 5163                }
 5164                serialize_workspace = false;
 5165            }
 5166            pane::Event::RemovedItem { item } => {
 5167                cx.emit(Event::ActiveItemChanged);
 5168                self.update_window_edited(window, cx);
 5169                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5170                    && entry.get().entity_id() == pane.entity_id()
 5171                {
 5172                    entry.remove();
 5173                }
 5174                cx.emit(Event::ItemRemoved {
 5175                    item_id: item.item_id(),
 5176                });
 5177            }
 5178            pane::Event::Focus => {
 5179                window.invalidate_character_coordinates();
 5180                self.handle_pane_focused(pane.clone(), window, cx);
 5181            }
 5182            pane::Event::ZoomIn => {
 5183                if *pane == self.active_pane {
 5184                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5185                    if pane.read(cx).has_focus(window, cx) {
 5186                        self.zoomed = Some(pane.downgrade().into());
 5187                        self.zoomed_position = None;
 5188                        cx.emit(Event::ZoomChanged);
 5189                    }
 5190                    cx.notify();
 5191                }
 5192            }
 5193            pane::Event::ZoomOut => {
 5194                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5195                if self.zoomed_position.is_none() {
 5196                    self.zoomed = None;
 5197                    cx.emit(Event::ZoomChanged);
 5198                }
 5199                cx.notify();
 5200            }
 5201            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5202        }
 5203
 5204        if serialize_workspace {
 5205            self.serialize_workspace(window, cx);
 5206        }
 5207    }
 5208
 5209    pub fn unfollow_in_pane(
 5210        &mut self,
 5211        pane: &Entity<Pane>,
 5212        window: &mut Window,
 5213        cx: &mut Context<Workspace>,
 5214    ) -> Option<CollaboratorId> {
 5215        let leader_id = self.leader_for_pane(pane)?;
 5216        self.unfollow(leader_id, window, cx);
 5217        Some(leader_id)
 5218    }
 5219
 5220    pub fn split_pane(
 5221        &mut self,
 5222        pane_to_split: Entity<Pane>,
 5223        split_direction: SplitDirection,
 5224        window: &mut Window,
 5225        cx: &mut Context<Self>,
 5226    ) -> Entity<Pane> {
 5227        let new_pane = self.add_pane(window, cx);
 5228        self.center
 5229            .split(&pane_to_split, &new_pane, split_direction, cx);
 5230        cx.notify();
 5231        new_pane
 5232    }
 5233
 5234    pub fn split_and_move(
 5235        &mut self,
 5236        pane: Entity<Pane>,
 5237        direction: SplitDirection,
 5238        window: &mut Window,
 5239        cx: &mut Context<Self>,
 5240    ) {
 5241        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5242            return;
 5243        };
 5244        let new_pane = self.add_pane(window, cx);
 5245        new_pane.update(cx, |pane, cx| {
 5246            pane.add_item(item, true, true, None, window, cx)
 5247        });
 5248        self.center.split(&pane, &new_pane, direction, cx);
 5249        cx.notify();
 5250    }
 5251
 5252    pub fn split_and_clone(
 5253        &mut self,
 5254        pane: Entity<Pane>,
 5255        direction: SplitDirection,
 5256        window: &mut Window,
 5257        cx: &mut Context<Self>,
 5258    ) -> Task<Option<Entity<Pane>>> {
 5259        let Some(item) = pane.read(cx).active_item() else {
 5260            return Task::ready(None);
 5261        };
 5262        if !item.can_split(cx) {
 5263            return Task::ready(None);
 5264        }
 5265        let task = item.clone_on_split(self.database_id(), window, cx);
 5266        cx.spawn_in(window, async move |this, cx| {
 5267            if let Some(clone) = task.await {
 5268                this.update_in(cx, |this, window, cx| {
 5269                    let new_pane = this.add_pane(window, cx);
 5270                    let nav_history = pane.read(cx).fork_nav_history();
 5271                    new_pane.update(cx, |pane, cx| {
 5272                        pane.set_nav_history(nav_history, cx);
 5273                        pane.add_item(clone, true, true, None, window, cx)
 5274                    });
 5275                    this.center.split(&pane, &new_pane, direction, cx);
 5276                    cx.notify();
 5277                    new_pane
 5278                })
 5279                .ok()
 5280            } else {
 5281                None
 5282            }
 5283        })
 5284    }
 5285
 5286    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5287        let active_item = self.active_pane.read(cx).active_item();
 5288        for pane in &self.panes {
 5289            join_pane_into_active(&self.active_pane, pane, window, cx);
 5290        }
 5291        if let Some(active_item) = active_item {
 5292            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5293        }
 5294        cx.notify();
 5295    }
 5296
 5297    pub fn join_pane_into_next(
 5298        &mut self,
 5299        pane: Entity<Pane>,
 5300        window: &mut Window,
 5301        cx: &mut Context<Self>,
 5302    ) {
 5303        let next_pane = self
 5304            .find_pane_in_direction(SplitDirection::Right, cx)
 5305            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5306            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5307            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5308        let Some(next_pane) = next_pane else {
 5309            return;
 5310        };
 5311        move_all_items(&pane, &next_pane, window, cx);
 5312        cx.notify();
 5313    }
 5314
 5315    fn remove_pane(
 5316        &mut self,
 5317        pane: Entity<Pane>,
 5318        focus_on: Option<Entity<Pane>>,
 5319        window: &mut Window,
 5320        cx: &mut Context<Self>,
 5321    ) {
 5322        if self.center.remove(&pane, cx).unwrap() {
 5323            self.force_remove_pane(&pane, &focus_on, window, cx);
 5324            self.unfollow_in_pane(&pane, window, cx);
 5325            self.last_leaders_by_pane.remove(&pane.downgrade());
 5326            for removed_item in pane.read(cx).items() {
 5327                self.panes_by_item.remove(&removed_item.item_id());
 5328            }
 5329
 5330            cx.notify();
 5331        } else {
 5332            self.active_item_path_changed(true, window, cx);
 5333        }
 5334        cx.emit(Event::PaneRemoved);
 5335    }
 5336
 5337    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5338        &mut self.panes
 5339    }
 5340
 5341    pub fn panes(&self) -> &[Entity<Pane>] {
 5342        &self.panes
 5343    }
 5344
 5345    pub fn active_pane(&self) -> &Entity<Pane> {
 5346        &self.active_pane
 5347    }
 5348
 5349    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5350        for dock in self.all_docks() {
 5351            if dock.focus_handle(cx).contains_focused(window, cx)
 5352                && let Some(pane) = dock
 5353                    .read(cx)
 5354                    .active_panel()
 5355                    .and_then(|panel| panel.pane(cx))
 5356            {
 5357                return pane;
 5358            }
 5359        }
 5360        self.active_pane().clone()
 5361    }
 5362
 5363    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5364        self.find_pane_in_direction(SplitDirection::Right, cx)
 5365            .unwrap_or_else(|| {
 5366                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5367            })
 5368    }
 5369
 5370    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5371        self.pane_for_item_id(handle.item_id())
 5372    }
 5373
 5374    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5375        let weak_pane = self.panes_by_item.get(&item_id)?;
 5376        weak_pane.upgrade()
 5377    }
 5378
 5379    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5380        self.panes
 5381            .iter()
 5382            .find(|pane| pane.entity_id() == entity_id)
 5383            .cloned()
 5384    }
 5385
 5386    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5387        self.follower_states.retain(|leader_id, state| {
 5388            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5389                for item in state.items_by_leader_view_id.values() {
 5390                    item.view.set_leader_id(None, window, cx);
 5391                }
 5392                false
 5393            } else {
 5394                true
 5395            }
 5396        });
 5397        cx.notify();
 5398    }
 5399
 5400    pub fn start_following(
 5401        &mut self,
 5402        leader_id: impl Into<CollaboratorId>,
 5403        window: &mut Window,
 5404        cx: &mut Context<Self>,
 5405    ) -> Option<Task<Result<()>>> {
 5406        let leader_id = leader_id.into();
 5407        let pane = self.active_pane().clone();
 5408
 5409        self.last_leaders_by_pane
 5410            .insert(pane.downgrade(), leader_id);
 5411        self.unfollow(leader_id, window, cx);
 5412        self.unfollow_in_pane(&pane, window, cx);
 5413        self.follower_states.insert(
 5414            leader_id,
 5415            FollowerState {
 5416                center_pane: pane.clone(),
 5417                dock_pane: None,
 5418                active_view_id: None,
 5419                items_by_leader_view_id: Default::default(),
 5420            },
 5421        );
 5422        cx.notify();
 5423
 5424        match leader_id {
 5425            CollaboratorId::PeerId(leader_peer_id) => {
 5426                let room_id = self.active_call()?.room_id(cx)?;
 5427                let project_id = self.project.read(cx).remote_id();
 5428                let request = self.app_state.client.request(proto::Follow {
 5429                    room_id,
 5430                    project_id,
 5431                    leader_id: Some(leader_peer_id),
 5432                });
 5433
 5434                Some(cx.spawn_in(window, async move |this, cx| {
 5435                    let response = request.await?;
 5436                    this.update(cx, |this, _| {
 5437                        let state = this
 5438                            .follower_states
 5439                            .get_mut(&leader_id)
 5440                            .context("following interrupted")?;
 5441                        state.active_view_id = response
 5442                            .active_view
 5443                            .as_ref()
 5444                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5445                        anyhow::Ok(())
 5446                    })??;
 5447                    if let Some(view) = response.active_view {
 5448                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5449                    }
 5450                    this.update_in(cx, |this, window, cx| {
 5451                        this.leader_updated(leader_id, window, cx)
 5452                    })?;
 5453                    Ok(())
 5454                }))
 5455            }
 5456            CollaboratorId::Agent => {
 5457                self.leader_updated(leader_id, window, cx)?;
 5458                Some(Task::ready(Ok(())))
 5459            }
 5460        }
 5461    }
 5462
 5463    pub fn follow_next_collaborator(
 5464        &mut self,
 5465        _: &FollowNextCollaborator,
 5466        window: &mut Window,
 5467        cx: &mut Context<Self>,
 5468    ) {
 5469        let collaborators = self.project.read(cx).collaborators();
 5470        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5471            let mut collaborators = collaborators.keys().copied();
 5472            for peer_id in collaborators.by_ref() {
 5473                if CollaboratorId::PeerId(peer_id) == leader_id {
 5474                    break;
 5475                }
 5476            }
 5477            collaborators.next().map(CollaboratorId::PeerId)
 5478        } else if let Some(last_leader_id) =
 5479            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5480        {
 5481            match last_leader_id {
 5482                CollaboratorId::PeerId(peer_id) => {
 5483                    if collaborators.contains_key(peer_id) {
 5484                        Some(*last_leader_id)
 5485                    } else {
 5486                        None
 5487                    }
 5488                }
 5489                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5490            }
 5491        } else {
 5492            None
 5493        };
 5494
 5495        let pane = self.active_pane.clone();
 5496        let Some(leader_id) = next_leader_id.or_else(|| {
 5497            Some(CollaboratorId::PeerId(
 5498                collaborators.keys().copied().next()?,
 5499            ))
 5500        }) else {
 5501            return;
 5502        };
 5503        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5504            return;
 5505        }
 5506        if let Some(task) = self.start_following(leader_id, window, cx) {
 5507            task.detach_and_log_err(cx)
 5508        }
 5509    }
 5510
 5511    pub fn follow(
 5512        &mut self,
 5513        leader_id: impl Into<CollaboratorId>,
 5514        window: &mut Window,
 5515        cx: &mut Context<Self>,
 5516    ) {
 5517        let leader_id = leader_id.into();
 5518
 5519        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5520            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5521                return;
 5522            };
 5523            let Some(remote_participant) =
 5524                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5525            else {
 5526                return;
 5527            };
 5528
 5529            let project = self.project.read(cx);
 5530
 5531            let other_project_id = match remote_participant.location {
 5532                ParticipantLocation::External => None,
 5533                ParticipantLocation::UnsharedProject => None,
 5534                ParticipantLocation::SharedProject { project_id } => {
 5535                    if Some(project_id) == project.remote_id() {
 5536                        None
 5537                    } else {
 5538                        Some(project_id)
 5539                    }
 5540                }
 5541            };
 5542
 5543            // if they are active in another project, follow there.
 5544            if let Some(project_id) = other_project_id {
 5545                let app_state = self.app_state.clone();
 5546                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5547                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5548                        Some(format!("{error:#}"))
 5549                    });
 5550            }
 5551        }
 5552
 5553        // if you're already following, find the right pane and focus it.
 5554        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5555            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5556
 5557            return;
 5558        }
 5559
 5560        // Otherwise, follow.
 5561        if let Some(task) = self.start_following(leader_id, window, cx) {
 5562            task.detach_and_log_err(cx)
 5563        }
 5564    }
 5565
 5566    pub fn unfollow(
 5567        &mut self,
 5568        leader_id: impl Into<CollaboratorId>,
 5569        window: &mut Window,
 5570        cx: &mut Context<Self>,
 5571    ) -> Option<()> {
 5572        cx.notify();
 5573
 5574        let leader_id = leader_id.into();
 5575        let state = self.follower_states.remove(&leader_id)?;
 5576        for (_, item) in state.items_by_leader_view_id {
 5577            item.view.set_leader_id(None, window, cx);
 5578        }
 5579
 5580        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5581            let project_id = self.project.read(cx).remote_id();
 5582            let room_id = self.active_call()?.room_id(cx)?;
 5583            self.app_state
 5584                .client
 5585                .send(proto::Unfollow {
 5586                    room_id,
 5587                    project_id,
 5588                    leader_id: Some(leader_peer_id),
 5589                })
 5590                .log_err();
 5591        }
 5592
 5593        Some(())
 5594    }
 5595
 5596    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5597        self.follower_states.contains_key(&id.into())
 5598    }
 5599
 5600    fn active_item_path_changed(
 5601        &mut self,
 5602        focus_changed: bool,
 5603        window: &mut Window,
 5604        cx: &mut Context<Self>,
 5605    ) {
 5606        cx.emit(Event::ActiveItemChanged);
 5607        let active_entry = self.active_project_path(cx);
 5608        self.project.update(cx, |project, cx| {
 5609            project.set_active_path(active_entry.clone(), cx)
 5610        });
 5611
 5612        if focus_changed && let Some(project_path) = &active_entry {
 5613            let git_store_entity = self.project.read(cx).git_store().clone();
 5614            git_store_entity.update(cx, |git_store, cx| {
 5615                git_store.set_active_repo_for_path(project_path, cx);
 5616            });
 5617        }
 5618
 5619        self.update_window_title(window, cx);
 5620    }
 5621
 5622    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5623        let project = self.project().read(cx);
 5624        let mut title = String::new();
 5625
 5626        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5627            let name = {
 5628                let settings_location = SettingsLocation {
 5629                    worktree_id: worktree.read(cx).id(),
 5630                    path: RelPath::empty(),
 5631                };
 5632
 5633                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5634                match &settings.project_name {
 5635                    Some(name) => name.as_str(),
 5636                    None => worktree.read(cx).root_name_str(),
 5637                }
 5638            };
 5639            if i > 0 {
 5640                title.push_str(", ");
 5641            }
 5642            title.push_str(name);
 5643        }
 5644
 5645        if title.is_empty() {
 5646            title = "empty project".to_string();
 5647        }
 5648
 5649        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5650            let filename = path.path.file_name().or_else(|| {
 5651                Some(
 5652                    project
 5653                        .worktree_for_id(path.worktree_id, cx)?
 5654                        .read(cx)
 5655                        .root_name_str(),
 5656                )
 5657            });
 5658
 5659            if let Some(filename) = filename {
 5660                title.push_str("");
 5661                title.push_str(filename.as_ref());
 5662            }
 5663        }
 5664
 5665        if project.is_via_collab() {
 5666            title.push_str("");
 5667        } else if project.is_shared() {
 5668            title.push_str("");
 5669        }
 5670
 5671        if let Some(last_title) = self.last_window_title.as_ref()
 5672            && &title == last_title
 5673        {
 5674            return;
 5675        }
 5676        window.set_window_title(&title);
 5677        SystemWindowTabController::update_tab_title(
 5678            cx,
 5679            window.window_handle().window_id(),
 5680            SharedString::from(&title),
 5681        );
 5682        self.last_window_title = Some(title);
 5683    }
 5684
 5685    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5686        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5687        if is_edited != self.window_edited {
 5688            self.window_edited = is_edited;
 5689            window.set_window_edited(self.window_edited)
 5690        }
 5691    }
 5692
 5693    fn update_item_dirty_state(
 5694        &mut self,
 5695        item: &dyn ItemHandle,
 5696        window: &mut Window,
 5697        cx: &mut App,
 5698    ) {
 5699        let is_dirty = item.is_dirty(cx);
 5700        let item_id = item.item_id();
 5701        let was_dirty = self.dirty_items.contains_key(&item_id);
 5702        if is_dirty == was_dirty {
 5703            return;
 5704        }
 5705        if was_dirty {
 5706            self.dirty_items.remove(&item_id);
 5707            self.update_window_edited(window, cx);
 5708            return;
 5709        }
 5710
 5711        let workspace = self.weak_handle();
 5712        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5713            return;
 5714        };
 5715        let on_release_callback = Box::new(move |cx: &mut App| {
 5716            window_handle
 5717                .update(cx, |_, window, cx| {
 5718                    workspace
 5719                        .update(cx, |workspace, cx| {
 5720                            workspace.dirty_items.remove(&item_id);
 5721                            workspace.update_window_edited(window, cx)
 5722                        })
 5723                        .ok();
 5724                })
 5725                .ok();
 5726        });
 5727
 5728        let s = item.on_release(cx, on_release_callback);
 5729        self.dirty_items.insert(item_id, s);
 5730        self.update_window_edited(window, cx);
 5731    }
 5732
 5733    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5734        if self.notifications.is_empty() {
 5735            None
 5736        } else {
 5737            Some(
 5738                div()
 5739                    .absolute()
 5740                    .right_3()
 5741                    .bottom_3()
 5742                    .w_112()
 5743                    .h_full()
 5744                    .flex()
 5745                    .flex_col()
 5746                    .justify_end()
 5747                    .gap_2()
 5748                    .children(
 5749                        self.notifications
 5750                            .iter()
 5751                            .map(|(_, notification)| notification.clone().into_any()),
 5752                    ),
 5753            )
 5754        }
 5755    }
 5756
 5757    // RPC handlers
 5758
 5759    fn active_view_for_follower(
 5760        &self,
 5761        follower_project_id: Option<u64>,
 5762        window: &mut Window,
 5763        cx: &mut Context<Self>,
 5764    ) -> Option<proto::View> {
 5765        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5766        let item = item?;
 5767        let leader_id = self
 5768            .pane_for(&*item)
 5769            .and_then(|pane| self.leader_for_pane(&pane));
 5770        let leader_peer_id = match leader_id {
 5771            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5772            Some(CollaboratorId::Agent) | None => None,
 5773        };
 5774
 5775        let item_handle = item.to_followable_item_handle(cx)?;
 5776        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5777        let variant = item_handle.to_state_proto(window, cx)?;
 5778
 5779        if item_handle.is_project_item(window, cx)
 5780            && (follower_project_id.is_none()
 5781                || follower_project_id != self.project.read(cx).remote_id())
 5782        {
 5783            return None;
 5784        }
 5785
 5786        Some(proto::View {
 5787            id: id.to_proto(),
 5788            leader_id: leader_peer_id,
 5789            variant: Some(variant),
 5790            panel_id: panel_id.map(|id| id as i32),
 5791        })
 5792    }
 5793
 5794    fn handle_follow(
 5795        &mut self,
 5796        follower_project_id: Option<u64>,
 5797        window: &mut Window,
 5798        cx: &mut Context<Self>,
 5799    ) -> proto::FollowResponse {
 5800        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5801
 5802        cx.notify();
 5803        proto::FollowResponse {
 5804            views: active_view.iter().cloned().collect(),
 5805            active_view,
 5806        }
 5807    }
 5808
 5809    fn handle_update_followers(
 5810        &mut self,
 5811        leader_id: PeerId,
 5812        message: proto::UpdateFollowers,
 5813        _window: &mut Window,
 5814        _cx: &mut Context<Self>,
 5815    ) {
 5816        self.leader_updates_tx
 5817            .unbounded_send((leader_id, message))
 5818            .ok();
 5819    }
 5820
 5821    async fn process_leader_update(
 5822        this: &WeakEntity<Self>,
 5823        leader_id: PeerId,
 5824        update: proto::UpdateFollowers,
 5825        cx: &mut AsyncWindowContext,
 5826    ) -> Result<()> {
 5827        match update.variant.context("invalid update")? {
 5828            proto::update_followers::Variant::CreateView(view) => {
 5829                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5830                let should_add_view = this.update(cx, |this, _| {
 5831                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5832                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5833                    } else {
 5834                        anyhow::Ok(false)
 5835                    }
 5836                })??;
 5837
 5838                if should_add_view {
 5839                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5840                }
 5841            }
 5842            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5843                let should_add_view = this.update(cx, |this, _| {
 5844                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5845                        state.active_view_id = update_active_view
 5846                            .view
 5847                            .as_ref()
 5848                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5849
 5850                        if state.active_view_id.is_some_and(|view_id| {
 5851                            !state.items_by_leader_view_id.contains_key(&view_id)
 5852                        }) {
 5853                            anyhow::Ok(true)
 5854                        } else {
 5855                            anyhow::Ok(false)
 5856                        }
 5857                    } else {
 5858                        anyhow::Ok(false)
 5859                    }
 5860                })??;
 5861
 5862                if should_add_view && let Some(view) = update_active_view.view {
 5863                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5864                }
 5865            }
 5866            proto::update_followers::Variant::UpdateView(update_view) => {
 5867                let variant = update_view.variant.context("missing update view variant")?;
 5868                let id = update_view.id.context("missing update view id")?;
 5869                let mut tasks = Vec::new();
 5870                this.update_in(cx, |this, window, cx| {
 5871                    let project = this.project.clone();
 5872                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5873                        let view_id = ViewId::from_proto(id.clone())?;
 5874                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5875                            tasks.push(item.view.apply_update_proto(
 5876                                &project,
 5877                                variant.clone(),
 5878                                window,
 5879                                cx,
 5880                            ));
 5881                        }
 5882                    }
 5883                    anyhow::Ok(())
 5884                })??;
 5885                try_join_all(tasks).await.log_err();
 5886            }
 5887        }
 5888        this.update_in(cx, |this, window, cx| {
 5889            this.leader_updated(leader_id, window, cx)
 5890        })?;
 5891        Ok(())
 5892    }
 5893
 5894    async fn add_view_from_leader(
 5895        this: WeakEntity<Self>,
 5896        leader_id: PeerId,
 5897        view: &proto::View,
 5898        cx: &mut AsyncWindowContext,
 5899    ) -> Result<()> {
 5900        let this = this.upgrade().context("workspace dropped")?;
 5901
 5902        let Some(id) = view.id.clone() else {
 5903            anyhow::bail!("no id for view");
 5904        };
 5905        let id = ViewId::from_proto(id)?;
 5906        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5907
 5908        let pane = this.update(cx, |this, _cx| {
 5909            let state = this
 5910                .follower_states
 5911                .get(&leader_id.into())
 5912                .context("stopped following")?;
 5913            anyhow::Ok(state.pane().clone())
 5914        })?;
 5915        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5916            let client = this.read(cx).client().clone();
 5917            pane.items().find_map(|item| {
 5918                let item = item.to_followable_item_handle(cx)?;
 5919                if item.remote_id(&client, window, cx) == Some(id) {
 5920                    Some(item)
 5921                } else {
 5922                    None
 5923                }
 5924            })
 5925        })?;
 5926        let item = if let Some(existing_item) = existing_item {
 5927            existing_item
 5928        } else {
 5929            let variant = view.variant.clone();
 5930            anyhow::ensure!(variant.is_some(), "missing view variant");
 5931
 5932            let task = cx.update(|window, cx| {
 5933                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5934            })?;
 5935
 5936            let Some(task) = task else {
 5937                anyhow::bail!(
 5938                    "failed to construct view from leader (maybe from a different version of zed?)"
 5939                );
 5940            };
 5941
 5942            let mut new_item = task.await?;
 5943            pane.update_in(cx, |pane, window, cx| {
 5944                let mut item_to_remove = None;
 5945                for (ix, item) in pane.items().enumerate() {
 5946                    if let Some(item) = item.to_followable_item_handle(cx) {
 5947                        match new_item.dedup(item.as_ref(), window, cx) {
 5948                            Some(item::Dedup::KeepExisting) => {
 5949                                new_item =
 5950                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5951                                break;
 5952                            }
 5953                            Some(item::Dedup::ReplaceExisting) => {
 5954                                item_to_remove = Some((ix, item.item_id()));
 5955                                break;
 5956                            }
 5957                            None => {}
 5958                        }
 5959                    }
 5960                }
 5961
 5962                if let Some((ix, id)) = item_to_remove {
 5963                    pane.remove_item(id, false, false, window, cx);
 5964                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5965                }
 5966            })?;
 5967
 5968            new_item
 5969        };
 5970
 5971        this.update_in(cx, |this, window, cx| {
 5972            let state = this.follower_states.get_mut(&leader_id.into())?;
 5973            item.set_leader_id(Some(leader_id.into()), window, cx);
 5974            state.items_by_leader_view_id.insert(
 5975                id,
 5976                FollowerView {
 5977                    view: item,
 5978                    location: panel_id,
 5979                },
 5980            );
 5981
 5982            Some(())
 5983        })
 5984        .context("no follower state")?;
 5985
 5986        Ok(())
 5987    }
 5988
 5989    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5990        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5991            return;
 5992        };
 5993
 5994        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5995            let buffer_entity_id = agent_location.buffer.entity_id();
 5996            let view_id = ViewId {
 5997                creator: CollaboratorId::Agent,
 5998                id: buffer_entity_id.as_u64(),
 5999            };
 6000            follower_state.active_view_id = Some(view_id);
 6001
 6002            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6003                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6004                hash_map::Entry::Vacant(entry) => {
 6005                    let existing_view =
 6006                        follower_state
 6007                            .center_pane
 6008                            .read(cx)
 6009                            .items()
 6010                            .find_map(|item| {
 6011                                let item = item.to_followable_item_handle(cx)?;
 6012                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6013                                    && item.project_item_model_ids(cx).as_slice()
 6014                                        == [buffer_entity_id]
 6015                                {
 6016                                    Some(item)
 6017                                } else {
 6018                                    None
 6019                                }
 6020                            });
 6021                    let view = existing_view.or_else(|| {
 6022                        agent_location.buffer.upgrade().and_then(|buffer| {
 6023                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6024                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6025                            })?
 6026                            .to_followable_item_handle(cx)
 6027                        })
 6028                    });
 6029
 6030                    view.map(|view| {
 6031                        entry.insert(FollowerView {
 6032                            view,
 6033                            location: None,
 6034                        })
 6035                    })
 6036                }
 6037            };
 6038
 6039            if let Some(item) = item {
 6040                item.view
 6041                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6042                item.view
 6043                    .update_agent_location(agent_location.position, window, cx);
 6044            }
 6045        } else {
 6046            follower_state.active_view_id = None;
 6047        }
 6048
 6049        self.leader_updated(CollaboratorId::Agent, window, cx);
 6050    }
 6051
 6052    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6053        let mut is_project_item = true;
 6054        let mut update = proto::UpdateActiveView::default();
 6055        if window.is_window_active() {
 6056            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6057
 6058            if let Some(item) = active_item
 6059                && item.item_focus_handle(cx).contains_focused(window, cx)
 6060            {
 6061                let leader_id = self
 6062                    .pane_for(&*item)
 6063                    .and_then(|pane| self.leader_for_pane(&pane));
 6064                let leader_peer_id = match leader_id {
 6065                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6066                    Some(CollaboratorId::Agent) | None => None,
 6067                };
 6068
 6069                if let Some(item) = item.to_followable_item_handle(cx) {
 6070                    let id = item
 6071                        .remote_id(&self.app_state.client, window, cx)
 6072                        .map(|id| id.to_proto());
 6073
 6074                    if let Some(id) = id
 6075                        && let Some(variant) = item.to_state_proto(window, cx)
 6076                    {
 6077                        let view = Some(proto::View {
 6078                            id,
 6079                            leader_id: leader_peer_id,
 6080                            variant: Some(variant),
 6081                            panel_id: panel_id.map(|id| id as i32),
 6082                        });
 6083
 6084                        is_project_item = item.is_project_item(window, cx);
 6085                        update = proto::UpdateActiveView { view };
 6086                    };
 6087                }
 6088            }
 6089        }
 6090
 6091        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6092        if active_view_id != self.last_active_view_id.as_ref() {
 6093            self.last_active_view_id = active_view_id.cloned();
 6094            self.update_followers(
 6095                is_project_item,
 6096                proto::update_followers::Variant::UpdateActiveView(update),
 6097                window,
 6098                cx,
 6099            );
 6100        }
 6101    }
 6102
 6103    fn active_item_for_followers(
 6104        &self,
 6105        window: &mut Window,
 6106        cx: &mut App,
 6107    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6108        let mut active_item = None;
 6109        let mut panel_id = None;
 6110        for dock in self.all_docks() {
 6111            if dock.focus_handle(cx).contains_focused(window, cx)
 6112                && let Some(panel) = dock.read(cx).active_panel()
 6113                && let Some(pane) = panel.pane(cx)
 6114                && let Some(item) = pane.read(cx).active_item()
 6115            {
 6116                active_item = Some(item);
 6117                panel_id = panel.remote_id();
 6118                break;
 6119            }
 6120        }
 6121
 6122        if active_item.is_none() {
 6123            active_item = self.active_pane().read(cx).active_item();
 6124        }
 6125        (active_item, panel_id)
 6126    }
 6127
 6128    fn update_followers(
 6129        &self,
 6130        project_only: bool,
 6131        update: proto::update_followers::Variant,
 6132        _: &mut Window,
 6133        cx: &mut App,
 6134    ) -> Option<()> {
 6135        // If this update only applies to for followers in the current project,
 6136        // then skip it unless this project is shared. If it applies to all
 6137        // followers, regardless of project, then set `project_id` to none,
 6138        // indicating that it goes to all followers.
 6139        let project_id = if project_only {
 6140            Some(self.project.read(cx).remote_id()?)
 6141        } else {
 6142            None
 6143        };
 6144        self.app_state().workspace_store.update(cx, |store, cx| {
 6145            store.update_followers(project_id, update, cx)
 6146        })
 6147    }
 6148
 6149    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6150        self.follower_states.iter().find_map(|(leader_id, state)| {
 6151            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6152                Some(*leader_id)
 6153            } else {
 6154                None
 6155            }
 6156        })
 6157    }
 6158
 6159    fn leader_updated(
 6160        &mut self,
 6161        leader_id: impl Into<CollaboratorId>,
 6162        window: &mut Window,
 6163        cx: &mut Context<Self>,
 6164    ) -> Option<Box<dyn ItemHandle>> {
 6165        cx.notify();
 6166
 6167        let leader_id = leader_id.into();
 6168        let (panel_id, item) = match leader_id {
 6169            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6170            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6171        };
 6172
 6173        let state = self.follower_states.get(&leader_id)?;
 6174        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6175        let pane;
 6176        if let Some(panel_id) = panel_id {
 6177            pane = self
 6178                .activate_panel_for_proto_id(panel_id, window, cx)?
 6179                .pane(cx)?;
 6180            let state = self.follower_states.get_mut(&leader_id)?;
 6181            state.dock_pane = Some(pane.clone());
 6182        } else {
 6183            pane = state.center_pane.clone();
 6184            let state = self.follower_states.get_mut(&leader_id)?;
 6185            if let Some(dock_pane) = state.dock_pane.take() {
 6186                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6187            }
 6188        }
 6189
 6190        pane.update(cx, |pane, cx| {
 6191            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6192            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6193                pane.activate_item(index, false, false, window, cx);
 6194            } else {
 6195                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6196            }
 6197
 6198            if focus_active_item {
 6199                pane.focus_active_item(window, cx)
 6200            }
 6201        });
 6202
 6203        Some(item)
 6204    }
 6205
 6206    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6207        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6208        let active_view_id = state.active_view_id?;
 6209        Some(
 6210            state
 6211                .items_by_leader_view_id
 6212                .get(&active_view_id)?
 6213                .view
 6214                .boxed_clone(),
 6215        )
 6216    }
 6217
 6218    fn active_item_for_peer(
 6219        &self,
 6220        peer_id: PeerId,
 6221        window: &mut Window,
 6222        cx: &mut Context<Self>,
 6223    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6224        let call = self.active_call()?;
 6225        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6226        let leader_in_this_app;
 6227        let leader_in_this_project;
 6228        match participant.location {
 6229            ParticipantLocation::SharedProject { project_id } => {
 6230                leader_in_this_app = true;
 6231                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6232            }
 6233            ParticipantLocation::UnsharedProject => {
 6234                leader_in_this_app = true;
 6235                leader_in_this_project = false;
 6236            }
 6237            ParticipantLocation::External => {
 6238                leader_in_this_app = false;
 6239                leader_in_this_project = false;
 6240            }
 6241        };
 6242        let state = self.follower_states.get(&peer_id.into())?;
 6243        let mut item_to_activate = None;
 6244        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6245            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6246                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6247            {
 6248                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6249            }
 6250        } else if let Some(shared_screen) =
 6251            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6252        {
 6253            item_to_activate = Some((None, Box::new(shared_screen)));
 6254        }
 6255        item_to_activate
 6256    }
 6257
 6258    fn shared_screen_for_peer(
 6259        &self,
 6260        peer_id: PeerId,
 6261        pane: &Entity<Pane>,
 6262        window: &mut Window,
 6263        cx: &mut App,
 6264    ) -> Option<Entity<SharedScreen>> {
 6265        self.active_call()?
 6266            .create_shared_screen(peer_id, pane, window, cx)
 6267    }
 6268
 6269    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6270        if window.is_window_active() {
 6271            self.update_active_view_for_followers(window, cx);
 6272
 6273            if let Some(database_id) = self.database_id {
 6274                let db = WorkspaceDb::global(cx);
 6275                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6276                    .detach();
 6277            }
 6278        } else {
 6279            for pane in &self.panes {
 6280                pane.update(cx, |pane, cx| {
 6281                    if let Some(item) = pane.active_item() {
 6282                        item.workspace_deactivated(window, cx);
 6283                    }
 6284                    for item in pane.items() {
 6285                        if matches!(
 6286                            item.workspace_settings(cx).autosave,
 6287                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6288                        ) {
 6289                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6290                                .detach_and_log_err(cx);
 6291                        }
 6292                    }
 6293                });
 6294            }
 6295        }
 6296    }
 6297
 6298    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6299        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6300    }
 6301
 6302    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6303        self.active_call.as_ref().map(|(call, _)| call.clone())
 6304    }
 6305
 6306    fn on_active_call_event(
 6307        &mut self,
 6308        event: &ActiveCallEvent,
 6309        window: &mut Window,
 6310        cx: &mut Context<Self>,
 6311    ) {
 6312        match event {
 6313            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6314            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6315                self.leader_updated(participant_id, window, cx);
 6316            }
 6317        }
 6318    }
 6319
 6320    pub fn database_id(&self) -> Option<WorkspaceId> {
 6321        self.database_id
 6322    }
 6323
 6324    #[cfg(any(test, feature = "test-support"))]
 6325    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6326        self.database_id = Some(id);
 6327    }
 6328
 6329    pub fn session_id(&self) -> Option<String> {
 6330        self.session_id.clone()
 6331    }
 6332
 6333    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6334        let Some(display) = window.display(cx) else {
 6335            return Task::ready(());
 6336        };
 6337        let Ok(display_uuid) = display.uuid() else {
 6338            return Task::ready(());
 6339        };
 6340
 6341        let window_bounds = window.inner_window_bounds();
 6342        let database_id = self.database_id;
 6343        let has_paths = !self.root_paths(cx).is_empty();
 6344        let db = WorkspaceDb::global(cx);
 6345        let kvp = db::kvp::KeyValueStore::global(cx);
 6346
 6347        cx.background_executor().spawn(async move {
 6348            if !has_paths {
 6349                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6350                    .await
 6351                    .log_err();
 6352            }
 6353            if let Some(database_id) = database_id {
 6354                db.set_window_open_status(
 6355                    database_id,
 6356                    SerializedWindowBounds(window_bounds),
 6357                    display_uuid,
 6358                )
 6359                .await
 6360                .log_err();
 6361            } else {
 6362                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6363                    .await
 6364                    .log_err();
 6365            }
 6366        })
 6367    }
 6368
 6369    /// Bypass the 200ms serialization throttle and write workspace state to
 6370    /// the DB immediately. Returns a task the caller can await to ensure the
 6371    /// write completes. Used by the quit handler so the most recent state
 6372    /// isn't lost to a pending throttle timer when the process exits.
 6373    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6374        self._schedule_serialize_workspace.take();
 6375        self._serialize_workspace_task.take();
 6376        self.bounds_save_task_queued.take();
 6377
 6378        let bounds_task = self.save_window_bounds(window, cx);
 6379        let serialize_task = self.serialize_workspace_internal(window, cx);
 6380        cx.spawn(async move |_| {
 6381            bounds_task.await;
 6382            serialize_task.await;
 6383        })
 6384    }
 6385
 6386    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6387        let project = self.project().read(cx);
 6388        project
 6389            .visible_worktrees(cx)
 6390            .map(|worktree| worktree.read(cx).abs_path())
 6391            .collect::<Vec<_>>()
 6392    }
 6393
 6394    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 6395        let host = self.project().read(cx).remote_connection_options(cx);
 6396        let repositories = self.project().read(cx).repositories(cx);
 6397        let paths: Vec<_> = self
 6398            .root_paths(cx)
 6399            .iter()
 6400            .map(|root_path| {
 6401                repositories
 6402                    .values()
 6403                    .find(|repo| repo.read(cx).snapshot().work_directory_abs_path == *root_path)
 6404                    .map(|repo| {
 6405                        repo.read(cx)
 6406                            .snapshot()
 6407                            .original_repo_abs_path
 6408                            .to_path_buf()
 6409                    })
 6410                    .unwrap_or_else(|| root_path.to_path_buf())
 6411            })
 6412            .collect();
 6413        ProjectGroupKey::from_paths(&paths, host)
 6414    }
 6415
 6416    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6417        match member {
 6418            Member::Axis(PaneAxis { members, .. }) => {
 6419                for child in members.iter() {
 6420                    self.remove_panes(child.clone(), window, cx)
 6421                }
 6422            }
 6423            Member::Pane(pane) => {
 6424                self.force_remove_pane(&pane, &None, window, cx);
 6425            }
 6426        }
 6427    }
 6428
 6429    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6430        self.session_id.take();
 6431        self.serialize_workspace_internal(window, cx)
 6432    }
 6433
 6434    fn force_remove_pane(
 6435        &mut self,
 6436        pane: &Entity<Pane>,
 6437        focus_on: &Option<Entity<Pane>>,
 6438        window: &mut Window,
 6439        cx: &mut Context<Workspace>,
 6440    ) {
 6441        self.panes.retain(|p| p != pane);
 6442        if let Some(focus_on) = focus_on {
 6443            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6444        } else if self.active_pane() == pane {
 6445            self.panes
 6446                .last()
 6447                .unwrap()
 6448                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6449        }
 6450        if self.last_active_center_pane == Some(pane.downgrade()) {
 6451            self.last_active_center_pane = None;
 6452        }
 6453        cx.notify();
 6454    }
 6455
 6456    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6457        if self._schedule_serialize_workspace.is_none() {
 6458            self._schedule_serialize_workspace =
 6459                Some(cx.spawn_in(window, async move |this, cx| {
 6460                    cx.background_executor()
 6461                        .timer(SERIALIZATION_THROTTLE_TIME)
 6462                        .await;
 6463                    this.update_in(cx, |this, window, cx| {
 6464                        this._serialize_workspace_task =
 6465                            Some(this.serialize_workspace_internal(window, cx));
 6466                        this._schedule_serialize_workspace.take();
 6467                    })
 6468                    .log_err();
 6469                }));
 6470        }
 6471    }
 6472
 6473    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6474        let Some(database_id) = self.database_id() else {
 6475            return Task::ready(());
 6476        };
 6477
 6478        fn serialize_pane_handle(
 6479            pane_handle: &Entity<Pane>,
 6480            window: &mut Window,
 6481            cx: &mut App,
 6482        ) -> SerializedPane {
 6483            let (items, active, pinned_count) = {
 6484                let pane = pane_handle.read(cx);
 6485                let active_item_id = pane.active_item().map(|item| item.item_id());
 6486                (
 6487                    pane.items()
 6488                        .filter_map(|handle| {
 6489                            let handle = handle.to_serializable_item_handle(cx)?;
 6490
 6491                            Some(SerializedItem {
 6492                                kind: Arc::from(handle.serialized_item_kind()),
 6493                                item_id: handle.item_id().as_u64(),
 6494                                active: Some(handle.item_id()) == active_item_id,
 6495                                preview: pane.is_active_preview_item(handle.item_id()),
 6496                            })
 6497                        })
 6498                        .collect::<Vec<_>>(),
 6499                    pane.has_focus(window, cx),
 6500                    pane.pinned_count(),
 6501                )
 6502            };
 6503
 6504            SerializedPane::new(items, active, pinned_count)
 6505        }
 6506
 6507        fn build_serialized_pane_group(
 6508            pane_group: &Member,
 6509            window: &mut Window,
 6510            cx: &mut App,
 6511        ) -> SerializedPaneGroup {
 6512            match pane_group {
 6513                Member::Axis(PaneAxis {
 6514                    axis,
 6515                    members,
 6516                    flexes,
 6517                    bounding_boxes: _,
 6518                }) => SerializedPaneGroup::Group {
 6519                    axis: SerializedAxis(*axis),
 6520                    children: members
 6521                        .iter()
 6522                        .map(|member| build_serialized_pane_group(member, window, cx))
 6523                        .collect::<Vec<_>>(),
 6524                    flexes: Some(flexes.lock().clone()),
 6525                },
 6526                Member::Pane(pane_handle) => {
 6527                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6528                }
 6529            }
 6530        }
 6531
 6532        fn build_serialized_docks(
 6533            this: &Workspace,
 6534            window: &mut Window,
 6535            cx: &mut App,
 6536        ) -> DockStructure {
 6537            this.capture_dock_state(window, cx)
 6538        }
 6539
 6540        match self.workspace_location(cx) {
 6541            WorkspaceLocation::Location(location, paths) => {
 6542                let breakpoints = self.project.update(cx, |project, cx| {
 6543                    project
 6544                        .breakpoint_store()
 6545                        .read(cx)
 6546                        .all_source_breakpoints(cx)
 6547                });
 6548                let user_toolchains = self
 6549                    .project
 6550                    .read(cx)
 6551                    .user_toolchains(cx)
 6552                    .unwrap_or_default();
 6553
 6554                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6555                let docks = build_serialized_docks(self, window, cx);
 6556                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6557
 6558                let serialized_workspace = SerializedWorkspace {
 6559                    id: database_id,
 6560                    location,
 6561                    paths,
 6562                    center_group,
 6563                    window_bounds,
 6564                    display: Default::default(),
 6565                    docks,
 6566                    centered_layout: self.centered_layout,
 6567                    session_id: self.session_id.clone(),
 6568                    breakpoints,
 6569                    window_id: Some(window.window_handle().window_id().as_u64()),
 6570                    user_toolchains,
 6571                };
 6572
 6573                let db = WorkspaceDb::global(cx);
 6574                window.spawn(cx, async move |_| {
 6575                    db.save_workspace(serialized_workspace).await;
 6576                })
 6577            }
 6578            WorkspaceLocation::DetachFromSession => {
 6579                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6580                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6581                // Save dock state for empty local workspaces
 6582                let docks = build_serialized_docks(self, window, cx);
 6583                let db = WorkspaceDb::global(cx);
 6584                let kvp = db::kvp::KeyValueStore::global(cx);
 6585                window.spawn(cx, async move |_| {
 6586                    db.set_window_open_status(
 6587                        database_id,
 6588                        window_bounds,
 6589                        display.unwrap_or_default(),
 6590                    )
 6591                    .await
 6592                    .log_err();
 6593                    db.set_session_id(database_id, None).await.log_err();
 6594                    persistence::write_default_dock_state(&kvp, docks)
 6595                        .await
 6596                        .log_err();
 6597                })
 6598            }
 6599            WorkspaceLocation::None => {
 6600                // Save dock state for empty non-local workspaces
 6601                let docks = build_serialized_docks(self, window, cx);
 6602                let kvp = db::kvp::KeyValueStore::global(cx);
 6603                window.spawn(cx, async move |_| {
 6604                    persistence::write_default_dock_state(&kvp, docks)
 6605                        .await
 6606                        .log_err();
 6607                })
 6608            }
 6609        }
 6610    }
 6611
 6612    fn has_any_items_open(&self, cx: &App) -> bool {
 6613        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6614    }
 6615
 6616    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6617        let paths = PathList::new(&self.root_paths(cx));
 6618        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6619            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6620        } else if self.project.read(cx).is_local() {
 6621            if !paths.is_empty() || self.has_any_items_open(cx) {
 6622                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6623            } else {
 6624                WorkspaceLocation::DetachFromSession
 6625            }
 6626        } else {
 6627            WorkspaceLocation::None
 6628        }
 6629    }
 6630
 6631    fn update_history(&self, cx: &mut App) {
 6632        let Some(id) = self.database_id() else {
 6633            return;
 6634        };
 6635        if !self.project.read(cx).is_local() {
 6636            return;
 6637        }
 6638        if let Some(manager) = HistoryManager::global(cx) {
 6639            let paths = PathList::new(&self.root_paths(cx));
 6640            manager.update(cx, |this, cx| {
 6641                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6642            });
 6643        }
 6644    }
 6645
 6646    async fn serialize_items(
 6647        this: &WeakEntity<Self>,
 6648        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6649        cx: &mut AsyncWindowContext,
 6650    ) -> Result<()> {
 6651        const CHUNK_SIZE: usize = 200;
 6652
 6653        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6654
 6655        while let Some(items_received) = serializable_items.next().await {
 6656            let unique_items =
 6657                items_received
 6658                    .into_iter()
 6659                    .fold(HashMap::default(), |mut acc, item| {
 6660                        acc.entry(item.item_id()).or_insert(item);
 6661                        acc
 6662                    });
 6663
 6664            // We use into_iter() here so that the references to the items are moved into
 6665            // the tasks and not kept alive while we're sleeping.
 6666            for (_, item) in unique_items.into_iter() {
 6667                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6668                    item.serialize(workspace, false, window, cx)
 6669                }) {
 6670                    cx.background_spawn(async move { task.await.log_err() })
 6671                        .detach();
 6672                }
 6673            }
 6674
 6675            cx.background_executor()
 6676                .timer(SERIALIZATION_THROTTLE_TIME)
 6677                .await;
 6678        }
 6679
 6680        Ok(())
 6681    }
 6682
 6683    pub(crate) fn enqueue_item_serialization(
 6684        &mut self,
 6685        item: Box<dyn SerializableItemHandle>,
 6686    ) -> Result<()> {
 6687        self.serializable_items_tx
 6688            .unbounded_send(item)
 6689            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6690    }
 6691
 6692    pub(crate) fn load_workspace(
 6693        serialized_workspace: SerializedWorkspace,
 6694        paths_to_open: Vec<Option<ProjectPath>>,
 6695        window: &mut Window,
 6696        cx: &mut Context<Workspace>,
 6697    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6698        cx.spawn_in(window, async move |workspace, cx| {
 6699            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6700
 6701            let mut center_group = None;
 6702            let mut center_items = None;
 6703
 6704            // Traverse the splits tree and add to things
 6705            if let Some((group, active_pane, items)) = serialized_workspace
 6706                .center_group
 6707                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6708                .await
 6709            {
 6710                center_items = Some(items);
 6711                center_group = Some((group, active_pane))
 6712            }
 6713
 6714            let mut items_by_project_path = HashMap::default();
 6715            let mut item_ids_by_kind = HashMap::default();
 6716            let mut all_deserialized_items = Vec::default();
 6717            cx.update(|_, cx| {
 6718                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6719                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6720                        item_ids_by_kind
 6721                            .entry(serializable_item_handle.serialized_item_kind())
 6722                            .or_insert(Vec::new())
 6723                            .push(item.item_id().as_u64() as ItemId);
 6724                    }
 6725
 6726                    if let Some(project_path) = item.project_path(cx) {
 6727                        items_by_project_path.insert(project_path, item.clone());
 6728                    }
 6729                    all_deserialized_items.push(item);
 6730                }
 6731            })?;
 6732
 6733            let opened_items = paths_to_open
 6734                .into_iter()
 6735                .map(|path_to_open| {
 6736                    path_to_open
 6737                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6738                })
 6739                .collect::<Vec<_>>();
 6740
 6741            // Remove old panes from workspace panes list
 6742            workspace.update_in(cx, |workspace, window, cx| {
 6743                if let Some((center_group, active_pane)) = center_group {
 6744                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6745
 6746                    // Swap workspace center group
 6747                    workspace.center = PaneGroup::with_root(center_group);
 6748                    workspace.center.set_is_center(true);
 6749                    workspace.center.mark_positions(cx);
 6750
 6751                    if let Some(active_pane) = active_pane {
 6752                        workspace.set_active_pane(&active_pane, window, cx);
 6753                        cx.focus_self(window);
 6754                    } else {
 6755                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6756                    }
 6757                }
 6758
 6759                let docks = serialized_workspace.docks;
 6760
 6761                for (dock, serialized_dock) in [
 6762                    (&mut workspace.right_dock, docks.right),
 6763                    (&mut workspace.left_dock, docks.left),
 6764                    (&mut workspace.bottom_dock, docks.bottom),
 6765                ]
 6766                .iter_mut()
 6767                {
 6768                    dock.update(cx, |dock, cx| {
 6769                        dock.serialized_dock = Some(serialized_dock.clone());
 6770                        dock.restore_state(window, cx);
 6771                    });
 6772                }
 6773
 6774                cx.notify();
 6775            })?;
 6776
 6777            let _ = project
 6778                .update(cx, |project, cx| {
 6779                    project
 6780                        .breakpoint_store()
 6781                        .update(cx, |breakpoint_store, cx| {
 6782                            breakpoint_store
 6783                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6784                        })
 6785                })
 6786                .await;
 6787
 6788            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6789            // after loading the items, we might have different items and in order to avoid
 6790            // the database filling up, we delete items that haven't been loaded now.
 6791            //
 6792            // The items that have been loaded, have been saved after they've been added to the workspace.
 6793            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6794                item_ids_by_kind
 6795                    .into_iter()
 6796                    .map(|(item_kind, loaded_items)| {
 6797                        SerializableItemRegistry::cleanup(
 6798                            item_kind,
 6799                            serialized_workspace.id,
 6800                            loaded_items,
 6801                            window,
 6802                            cx,
 6803                        )
 6804                        .log_err()
 6805                    })
 6806                    .collect::<Vec<_>>()
 6807            })?;
 6808
 6809            futures::future::join_all(clean_up_tasks).await;
 6810
 6811            workspace
 6812                .update_in(cx, |workspace, window, cx| {
 6813                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6814                    workspace.serialize_workspace_internal(window, cx).detach();
 6815
 6816                    // Ensure that we mark the window as edited if we did load dirty items
 6817                    workspace.update_window_edited(window, cx);
 6818                })
 6819                .ok();
 6820
 6821            Ok(opened_items)
 6822        })
 6823    }
 6824
 6825    pub fn key_context(&self, cx: &App) -> KeyContext {
 6826        let mut context = KeyContext::new_with_defaults();
 6827        context.add("Workspace");
 6828        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6829        if let Some(status) = self
 6830            .debugger_provider
 6831            .as_ref()
 6832            .and_then(|provider| provider.active_thread_state(cx))
 6833        {
 6834            match status {
 6835                ThreadStatus::Running | ThreadStatus::Stepping => {
 6836                    context.add("debugger_running");
 6837                }
 6838                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6839                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6840            }
 6841        }
 6842
 6843        if self.left_dock.read(cx).is_open() {
 6844            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6845                context.set("left_dock", active_panel.panel_key());
 6846            }
 6847        }
 6848
 6849        if self.right_dock.read(cx).is_open() {
 6850            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6851                context.set("right_dock", active_panel.panel_key());
 6852            }
 6853        }
 6854
 6855        if self.bottom_dock.read(cx).is_open() {
 6856            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6857                context.set("bottom_dock", active_panel.panel_key());
 6858            }
 6859        }
 6860
 6861        context
 6862    }
 6863
 6864    /// Multiworkspace uses this to add workspace action handling to itself
 6865    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6866        self.add_workspace_actions_listeners(div, window, cx)
 6867            .on_action(cx.listener(
 6868                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6869                    for action in &action_sequence.0 {
 6870                        window.dispatch_action(action.boxed_clone(), cx);
 6871                    }
 6872                },
 6873            ))
 6874            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6875            .on_action(cx.listener(Self::close_all_items_and_panes))
 6876            .on_action(cx.listener(Self::close_item_in_all_panes))
 6877            .on_action(cx.listener(Self::save_all))
 6878            .on_action(cx.listener(Self::send_keystrokes))
 6879            .on_action(cx.listener(Self::add_folder_to_project))
 6880            .on_action(cx.listener(Self::follow_next_collaborator))
 6881            .on_action(cx.listener(Self::activate_pane_at_index))
 6882            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6883            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6884            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6885            .on_action(cx.listener(Self::toggle_theme_mode))
 6886            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6887                let pane = workspace.active_pane().clone();
 6888                workspace.unfollow_in_pane(&pane, window, cx);
 6889            }))
 6890            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6891                workspace
 6892                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6893                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6894            }))
 6895            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6896                workspace
 6897                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6898                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6899            }))
 6900            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6901                workspace
 6902                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6903                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6904            }))
 6905            .on_action(
 6906                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6907                    workspace.activate_previous_pane(window, cx)
 6908                }),
 6909            )
 6910            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6911                workspace.activate_next_pane(window, cx)
 6912            }))
 6913            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6914                workspace.activate_last_pane(window, cx)
 6915            }))
 6916            .on_action(
 6917                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6918                    workspace.activate_next_window(cx)
 6919                }),
 6920            )
 6921            .on_action(
 6922                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6923                    workspace.activate_previous_window(cx)
 6924                }),
 6925            )
 6926            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6927                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6928            }))
 6929            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6930                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6931            }))
 6932            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6933                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6934            }))
 6935            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6936                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6937            }))
 6938            .on_action(cx.listener(
 6939                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6940                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6941                },
 6942            ))
 6943            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6944                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6945            }))
 6946            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6947                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6948            }))
 6949            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6950                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6951            }))
 6952            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6953                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6954            }))
 6955            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6956                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6957                    SplitDirection::Down,
 6958                    SplitDirection::Up,
 6959                    SplitDirection::Right,
 6960                    SplitDirection::Left,
 6961                ];
 6962                for dir in DIRECTION_PRIORITY {
 6963                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6964                        workspace.swap_pane_in_direction(dir, cx);
 6965                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6966                        break;
 6967                    }
 6968                }
 6969            }))
 6970            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6971                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6972            }))
 6973            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6974                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6975            }))
 6976            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6977                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6978            }))
 6979            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6980                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6981            }))
 6982            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6983                this.toggle_dock(DockPosition::Left, window, cx);
 6984            }))
 6985            .on_action(cx.listener(
 6986                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6987                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6988                },
 6989            ))
 6990            .on_action(cx.listener(
 6991                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6992                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6993                },
 6994            ))
 6995            .on_action(cx.listener(
 6996                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6997                    if !workspace.close_active_dock(window, cx) {
 6998                        cx.propagate();
 6999                    }
 7000                },
 7001            ))
 7002            .on_action(
 7003                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7004                    workspace.close_all_docks(window, cx);
 7005                }),
 7006            )
 7007            .on_action(cx.listener(Self::toggle_all_docks))
 7008            .on_action(cx.listener(
 7009                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7010                    workspace.clear_all_notifications(cx);
 7011                },
 7012            ))
 7013            .on_action(cx.listener(
 7014                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7015                    workspace.clear_navigation_history(window, cx);
 7016                },
 7017            ))
 7018            .on_action(cx.listener(
 7019                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7020                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7021                        workspace.suppress_notification(&notification_id, cx);
 7022                    }
 7023                },
 7024            ))
 7025            .on_action(cx.listener(
 7026                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7027                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7028                },
 7029            ))
 7030            .on_action(
 7031                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7032                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7033                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7034                            trusted_worktrees.clear_trusted_paths()
 7035                        });
 7036                        let db = WorkspaceDb::global(cx);
 7037                        cx.spawn(async move |_, cx| {
 7038                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7039                                cx.update(|cx| reload(cx));
 7040                            }
 7041                        })
 7042                        .detach();
 7043                    }
 7044                }),
 7045            )
 7046            .on_action(cx.listener(
 7047                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7048                    workspace.reopen_closed_item(window, cx).detach();
 7049                },
 7050            ))
 7051            .on_action(cx.listener(
 7052                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7053                    for dock in workspace.all_docks() {
 7054                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7055                            let panel = dock.read(cx).active_panel().cloned();
 7056                            if let Some(panel) = panel {
 7057                                dock.update(cx, |dock, cx| {
 7058                                    dock.set_panel_size_state(
 7059                                        panel.as_ref(),
 7060                                        dock::PanelSizeState::default(),
 7061                                        cx,
 7062                                    );
 7063                                });
 7064                            }
 7065                            return;
 7066                        }
 7067                    }
 7068                },
 7069            ))
 7070            .on_action(cx.listener(
 7071                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7072                    for dock in workspace.all_docks() {
 7073                        let panel = dock.read(cx).visible_panel().cloned();
 7074                        if let Some(panel) = panel {
 7075                            dock.update(cx, |dock, cx| {
 7076                                dock.set_panel_size_state(
 7077                                    panel.as_ref(),
 7078                                    dock::PanelSizeState::default(),
 7079                                    cx,
 7080                                );
 7081                            });
 7082                        }
 7083                    }
 7084                },
 7085            ))
 7086            .on_action(cx.listener(
 7087                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7088                    adjust_active_dock_size_by_px(
 7089                        px_with_ui_font_fallback(act.px, cx),
 7090                        workspace,
 7091                        window,
 7092                        cx,
 7093                    );
 7094                },
 7095            ))
 7096            .on_action(cx.listener(
 7097                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7098                    adjust_active_dock_size_by_px(
 7099                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7100                        workspace,
 7101                        window,
 7102                        cx,
 7103                    );
 7104                },
 7105            ))
 7106            .on_action(cx.listener(
 7107                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7108                    adjust_open_docks_size_by_px(
 7109                        px_with_ui_font_fallback(act.px, cx),
 7110                        workspace,
 7111                        window,
 7112                        cx,
 7113                    );
 7114                },
 7115            ))
 7116            .on_action(cx.listener(
 7117                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7118                    adjust_open_docks_size_by_px(
 7119                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7120                        workspace,
 7121                        window,
 7122                        cx,
 7123                    );
 7124                },
 7125            ))
 7126            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7127            .on_action(cx.listener(
 7128                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7129                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7130                        let dock = active_dock.read(cx);
 7131                        if let Some(active_panel) = dock.active_panel() {
 7132                            if active_panel.pane(cx).is_none() {
 7133                                let mut recent_pane: Option<Entity<Pane>> = None;
 7134                                let mut recent_timestamp = 0;
 7135                                for pane_handle in workspace.panes() {
 7136                                    let pane = pane_handle.read(cx);
 7137                                    for entry in pane.activation_history() {
 7138                                        if entry.timestamp > recent_timestamp {
 7139                                            recent_timestamp = entry.timestamp;
 7140                                            recent_pane = Some(pane_handle.clone());
 7141                                        }
 7142                                    }
 7143                                }
 7144
 7145                                if let Some(pane) = recent_pane {
 7146                                    let wrap_around = action.wrap_around;
 7147                                    pane.update(cx, |pane, cx| {
 7148                                        let current_index = pane.active_item_index();
 7149                                        let items_len = pane.items_len();
 7150                                        if items_len > 0 {
 7151                                            let next_index = if current_index + 1 < items_len {
 7152                                                current_index + 1
 7153                                            } else if wrap_around {
 7154                                                0
 7155                                            } else {
 7156                                                return;
 7157                                            };
 7158                                            pane.activate_item(
 7159                                                next_index, false, false, window, cx,
 7160                                            );
 7161                                        }
 7162                                    });
 7163                                    return;
 7164                                }
 7165                            }
 7166                        }
 7167                    }
 7168                    cx.propagate();
 7169                },
 7170            ))
 7171            .on_action(cx.listener(
 7172                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7173                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7174                        let dock = active_dock.read(cx);
 7175                        if let Some(active_panel) = dock.active_panel() {
 7176                            if active_panel.pane(cx).is_none() {
 7177                                let mut recent_pane: Option<Entity<Pane>> = None;
 7178                                let mut recent_timestamp = 0;
 7179                                for pane_handle in workspace.panes() {
 7180                                    let pane = pane_handle.read(cx);
 7181                                    for entry in pane.activation_history() {
 7182                                        if entry.timestamp > recent_timestamp {
 7183                                            recent_timestamp = entry.timestamp;
 7184                                            recent_pane = Some(pane_handle.clone());
 7185                                        }
 7186                                    }
 7187                                }
 7188
 7189                                if let Some(pane) = recent_pane {
 7190                                    let wrap_around = action.wrap_around;
 7191                                    pane.update(cx, |pane, cx| {
 7192                                        let current_index = pane.active_item_index();
 7193                                        let items_len = pane.items_len();
 7194                                        if items_len > 0 {
 7195                                            let prev_index = if current_index > 0 {
 7196                                                current_index - 1
 7197                                            } else if wrap_around {
 7198                                                items_len.saturating_sub(1)
 7199                                            } else {
 7200                                                return;
 7201                                            };
 7202                                            pane.activate_item(
 7203                                                prev_index, false, false, window, cx,
 7204                                            );
 7205                                        }
 7206                                    });
 7207                                    return;
 7208                                }
 7209                            }
 7210                        }
 7211                    }
 7212                    cx.propagate();
 7213                },
 7214            ))
 7215            .on_action(cx.listener(
 7216                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7217                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7218                        let dock = active_dock.read(cx);
 7219                        if let Some(active_panel) = dock.active_panel() {
 7220                            if active_panel.pane(cx).is_none() {
 7221                                let active_pane = workspace.active_pane().clone();
 7222                                active_pane.update(cx, |pane, cx| {
 7223                                    pane.close_active_item(action, window, cx)
 7224                                        .detach_and_log_err(cx);
 7225                                });
 7226                                return;
 7227                            }
 7228                        }
 7229                    }
 7230                    cx.propagate();
 7231                },
 7232            ))
 7233            .on_action(
 7234                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7235                    let pane = workspace.active_pane().clone();
 7236                    if let Some(item) = pane.read(cx).active_item() {
 7237                        item.toggle_read_only(window, cx);
 7238                    }
 7239                }),
 7240            )
 7241            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7242                workspace.focus_center_pane(window, cx);
 7243            }))
 7244            .on_action(cx.listener(Workspace::cancel))
 7245    }
 7246
 7247    #[cfg(any(test, feature = "test-support"))]
 7248    pub fn set_random_database_id(&mut self) {
 7249        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7250    }
 7251
 7252    #[cfg(any(test, feature = "test-support"))]
 7253    pub(crate) fn test_new(
 7254        project: Entity<Project>,
 7255        window: &mut Window,
 7256        cx: &mut Context<Self>,
 7257    ) -> Self {
 7258        use node_runtime::NodeRuntime;
 7259        use session::Session;
 7260
 7261        let client = project.read(cx).client();
 7262        let user_store = project.read(cx).user_store();
 7263        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7264        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7265        window.activate_window();
 7266        let app_state = Arc::new(AppState {
 7267            languages: project.read(cx).languages().clone(),
 7268            workspace_store,
 7269            client,
 7270            user_store,
 7271            fs: project.read(cx).fs().clone(),
 7272            build_window_options: |_, _| Default::default(),
 7273            node_runtime: NodeRuntime::unavailable(),
 7274            session,
 7275        });
 7276        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7277        workspace
 7278            .active_pane
 7279            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7280        workspace
 7281    }
 7282
 7283    pub fn register_action<A: Action>(
 7284        &mut self,
 7285        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7286    ) -> &mut Self {
 7287        let callback = Arc::new(callback);
 7288
 7289        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7290            let callback = callback.clone();
 7291            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7292                (callback)(workspace, event, window, cx)
 7293            }))
 7294        }));
 7295        self
 7296    }
 7297    pub fn register_action_renderer(
 7298        &mut self,
 7299        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7300    ) -> &mut Self {
 7301        self.workspace_actions.push(Box::new(callback));
 7302        self
 7303    }
 7304
 7305    fn add_workspace_actions_listeners(
 7306        &self,
 7307        mut div: Div,
 7308        window: &mut Window,
 7309        cx: &mut Context<Self>,
 7310    ) -> Div {
 7311        for action in self.workspace_actions.iter() {
 7312            div = (action)(div, self, window, cx)
 7313        }
 7314        div
 7315    }
 7316
 7317    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7318        self.modal_layer.read(cx).has_active_modal()
 7319    }
 7320
 7321    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7322        self.modal_layer
 7323            .read(cx)
 7324            .is_active_modal_command_palette(cx)
 7325    }
 7326
 7327    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7328        self.modal_layer.read(cx).active_modal()
 7329    }
 7330
 7331    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7332    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7333    /// If no modal is active, the new modal will be shown.
 7334    ///
 7335    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7336    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7337    /// will not be shown.
 7338    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7339    where
 7340        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7341    {
 7342        self.modal_layer.update(cx, |modal_layer, cx| {
 7343            modal_layer.toggle_modal(window, cx, build)
 7344        })
 7345    }
 7346
 7347    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7348        self.modal_layer
 7349            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7350    }
 7351
 7352    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7353        self.toast_layer
 7354            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7355    }
 7356
 7357    pub fn toggle_centered_layout(
 7358        &mut self,
 7359        _: &ToggleCenteredLayout,
 7360        _: &mut Window,
 7361        cx: &mut Context<Self>,
 7362    ) {
 7363        self.centered_layout = !self.centered_layout;
 7364        if let Some(database_id) = self.database_id() {
 7365            let db = WorkspaceDb::global(cx);
 7366            let centered_layout = self.centered_layout;
 7367            cx.background_spawn(async move {
 7368                db.set_centered_layout(database_id, centered_layout).await
 7369            })
 7370            .detach_and_log_err(cx);
 7371        }
 7372        cx.notify();
 7373    }
 7374
 7375    fn adjust_padding(padding: Option<f32>) -> f32 {
 7376        padding
 7377            .unwrap_or(CenteredPaddingSettings::default().0)
 7378            .clamp(
 7379                CenteredPaddingSettings::MIN_PADDING,
 7380                CenteredPaddingSettings::MAX_PADDING,
 7381            )
 7382    }
 7383
 7384    fn render_dock(
 7385        &self,
 7386        position: DockPosition,
 7387        dock: &Entity<Dock>,
 7388        window: &mut Window,
 7389        cx: &mut App,
 7390    ) -> Option<Div> {
 7391        if self.zoomed_position == Some(position) {
 7392            return None;
 7393        }
 7394
 7395        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7396            let pane = panel.pane(cx)?;
 7397            let follower_states = &self.follower_states;
 7398            leader_border_for_pane(follower_states, &pane, window, cx)
 7399        });
 7400
 7401        let mut container = div()
 7402            .flex()
 7403            .overflow_hidden()
 7404            .flex_none()
 7405            .child(dock.clone())
 7406            .children(leader_border);
 7407
 7408        // Apply sizing only when the dock is open. When closed the dock is still
 7409        // included in the element tree so its focus handle remains mounted — without
 7410        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7411        let dock = dock.read(cx);
 7412        if let Some(panel) = dock.visible_panel() {
 7413            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7414            if position.axis() == Axis::Horizontal {
 7415                let use_flexible = panel.has_flexible_size(window, cx);
 7416                let flex_grow = if use_flexible {
 7417                    size_state
 7418                        .and_then(|state| state.flex)
 7419                        .or_else(|| self.default_dock_flex(position))
 7420                } else {
 7421                    None
 7422                };
 7423                if let Some(grow) = flex_grow {
 7424                    let grow = grow.max(0.001);
 7425                    let style = container.style();
 7426                    style.flex_grow = Some(grow);
 7427                    style.flex_shrink = Some(1.0);
 7428                    style.flex_basis = Some(relative(0.).into());
 7429                } else {
 7430                    let size = size_state
 7431                        .and_then(|state| state.size)
 7432                        .unwrap_or_else(|| panel.default_size(window, cx));
 7433                    container = container.w(size);
 7434                }
 7435            } else {
 7436                let size = size_state
 7437                    .and_then(|state| state.size)
 7438                    .unwrap_or_else(|| panel.default_size(window, cx));
 7439                container = container.h(size);
 7440            }
 7441        }
 7442
 7443        Some(container)
 7444    }
 7445
 7446    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7447        window
 7448            .root::<MultiWorkspace>()
 7449            .flatten()
 7450            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7451    }
 7452
 7453    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7454        self.zoomed.as_ref()
 7455    }
 7456
 7457    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7458        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7459            return;
 7460        };
 7461        let windows = cx.windows();
 7462        let next_window =
 7463            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7464                || {
 7465                    windows
 7466                        .iter()
 7467                        .cycle()
 7468                        .skip_while(|window| window.window_id() != current_window_id)
 7469                        .nth(1)
 7470                },
 7471            );
 7472
 7473        if let Some(window) = next_window {
 7474            window
 7475                .update(cx, |_, window, _| window.activate_window())
 7476                .ok();
 7477        }
 7478    }
 7479
 7480    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7481        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7482            return;
 7483        };
 7484        let windows = cx.windows();
 7485        let prev_window =
 7486            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7487                || {
 7488                    windows
 7489                        .iter()
 7490                        .rev()
 7491                        .cycle()
 7492                        .skip_while(|window| window.window_id() != current_window_id)
 7493                        .nth(1)
 7494                },
 7495            );
 7496
 7497        if let Some(window) = prev_window {
 7498            window
 7499                .update(cx, |_, window, _| window.activate_window())
 7500                .ok();
 7501        }
 7502    }
 7503
 7504    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7505        if cx.stop_active_drag(window) {
 7506        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7507            dismiss_app_notification(&notification_id, cx);
 7508        } else {
 7509            cx.propagate();
 7510        }
 7511    }
 7512
 7513    fn resize_dock(
 7514        &mut self,
 7515        dock_pos: DockPosition,
 7516        new_size: Pixels,
 7517        window: &mut Window,
 7518        cx: &mut Context<Self>,
 7519    ) {
 7520        match dock_pos {
 7521            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7522            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7523            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7524        }
 7525    }
 7526
 7527    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7528        let workspace_width = self.bounds.size.width;
 7529        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7530
 7531        self.right_dock.read_with(cx, |right_dock, cx| {
 7532            let right_dock_size = right_dock
 7533                .stored_active_panel_size(window, cx)
 7534                .unwrap_or(Pixels::ZERO);
 7535            if right_dock_size + size > workspace_width {
 7536                size = workspace_width - right_dock_size
 7537            }
 7538        });
 7539
 7540        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7541        self.left_dock.update(cx, |left_dock, cx| {
 7542            if WorkspaceSettings::get_global(cx)
 7543                .resize_all_panels_in_dock
 7544                .contains(&DockPosition::Left)
 7545            {
 7546                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7547            } else {
 7548                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7549            }
 7550        });
 7551    }
 7552
 7553    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7554        let workspace_width = self.bounds.size.width;
 7555        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7556        self.left_dock.read_with(cx, |left_dock, cx| {
 7557            let left_dock_size = left_dock
 7558                .stored_active_panel_size(window, cx)
 7559                .unwrap_or(Pixels::ZERO);
 7560            if left_dock_size + size > workspace_width {
 7561                size = workspace_width - left_dock_size
 7562            }
 7563        });
 7564        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7565        self.right_dock.update(cx, |right_dock, cx| {
 7566            if WorkspaceSettings::get_global(cx)
 7567                .resize_all_panels_in_dock
 7568                .contains(&DockPosition::Right)
 7569            {
 7570                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7571            } else {
 7572                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7573            }
 7574        });
 7575    }
 7576
 7577    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7578        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7579        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7580            if WorkspaceSettings::get_global(cx)
 7581                .resize_all_panels_in_dock
 7582                .contains(&DockPosition::Bottom)
 7583            {
 7584                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7585            } else {
 7586                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7587            }
 7588        });
 7589    }
 7590
 7591    fn toggle_edit_predictions_all_files(
 7592        &mut self,
 7593        _: &ToggleEditPrediction,
 7594        _window: &mut Window,
 7595        cx: &mut Context<Self>,
 7596    ) {
 7597        let fs = self.project().read(cx).fs().clone();
 7598        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7599        update_settings_file(fs, cx, move |file, _| {
 7600            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7601        });
 7602    }
 7603
 7604    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7605        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7606        let next_mode = match current_mode {
 7607            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7608                theme_settings::ThemeAppearanceMode::Dark
 7609            }
 7610            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7611                theme_settings::ThemeAppearanceMode::Light
 7612            }
 7613            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7614                match cx.theme().appearance() {
 7615                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7616                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7617                }
 7618            }
 7619        };
 7620
 7621        let fs = self.project().read(cx).fs().clone();
 7622        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7623            theme_settings::set_mode(settings, next_mode);
 7624        });
 7625    }
 7626
 7627    pub fn show_worktree_trust_security_modal(
 7628        &mut self,
 7629        toggle: bool,
 7630        window: &mut Window,
 7631        cx: &mut Context<Self>,
 7632    ) {
 7633        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7634            if toggle {
 7635                security_modal.update(cx, |security_modal, cx| {
 7636                    security_modal.dismiss(cx);
 7637                })
 7638            } else {
 7639                security_modal.update(cx, |security_modal, cx| {
 7640                    security_modal.refresh_restricted_paths(cx);
 7641                });
 7642            }
 7643        } else {
 7644            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7645                .map(|trusted_worktrees| {
 7646                    trusted_worktrees
 7647                        .read(cx)
 7648                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7649                })
 7650                .unwrap_or(false);
 7651            if has_restricted_worktrees {
 7652                let project = self.project().read(cx);
 7653                let remote_host = project
 7654                    .remote_connection_options(cx)
 7655                    .map(RemoteHostLocation::from);
 7656                let worktree_store = project.worktree_store().downgrade();
 7657                self.toggle_modal(window, cx, |_, cx| {
 7658                    SecurityModal::new(worktree_store, remote_host, cx)
 7659                });
 7660            }
 7661        }
 7662    }
 7663}
 7664
 7665pub trait AnyActiveCall {
 7666    fn entity(&self) -> AnyEntity;
 7667    fn is_in_room(&self, _: &App) -> bool;
 7668    fn room_id(&self, _: &App) -> Option<u64>;
 7669    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7670    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7671    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7672    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7673    fn is_sharing_project(&self, _: &App) -> bool;
 7674    fn has_remote_participants(&self, _: &App) -> bool;
 7675    fn local_participant_is_guest(&self, _: &App) -> bool;
 7676    fn client(&self, _: &App) -> Arc<Client>;
 7677    fn share_on_join(&self, _: &App) -> bool;
 7678    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7679    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7680    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7681    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7682    fn join_project(
 7683        &self,
 7684        _: u64,
 7685        _: Arc<LanguageRegistry>,
 7686        _: Arc<dyn Fs>,
 7687        _: &mut App,
 7688    ) -> Task<Result<Entity<Project>>>;
 7689    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7690    fn subscribe(
 7691        &self,
 7692        _: &mut Window,
 7693        _: &mut Context<Workspace>,
 7694        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7695    ) -> Subscription;
 7696    fn create_shared_screen(
 7697        &self,
 7698        _: PeerId,
 7699        _: &Entity<Pane>,
 7700        _: &mut Window,
 7701        _: &mut App,
 7702    ) -> Option<Entity<SharedScreen>>;
 7703}
 7704
 7705#[derive(Clone)]
 7706pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7707impl Global for GlobalAnyActiveCall {}
 7708
 7709impl GlobalAnyActiveCall {
 7710    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7711        cx.try_global()
 7712    }
 7713
 7714    pub(crate) fn global(cx: &App) -> &Self {
 7715        cx.global()
 7716    }
 7717}
 7718
 7719pub fn merge_conflict_notification_id() -> NotificationId {
 7720    struct MergeConflictNotification;
 7721    NotificationId::unique::<MergeConflictNotification>()
 7722}
 7723
 7724/// Workspace-local view of a remote participant's location.
 7725#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7726pub enum ParticipantLocation {
 7727    SharedProject { project_id: u64 },
 7728    UnsharedProject,
 7729    External,
 7730}
 7731
 7732impl ParticipantLocation {
 7733    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7734        match location
 7735            .and_then(|l| l.variant)
 7736            .context("participant location was not provided")?
 7737        {
 7738            proto::participant_location::Variant::SharedProject(project) => {
 7739                Ok(Self::SharedProject {
 7740                    project_id: project.id,
 7741                })
 7742            }
 7743            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7744            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7745        }
 7746    }
 7747}
 7748/// Workspace-local view of a remote collaborator's state.
 7749/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7750#[derive(Clone)]
 7751pub struct RemoteCollaborator {
 7752    pub user: Arc<User>,
 7753    pub peer_id: PeerId,
 7754    pub location: ParticipantLocation,
 7755    pub participant_index: ParticipantIndex,
 7756}
 7757
 7758pub enum ActiveCallEvent {
 7759    ParticipantLocationChanged { participant_id: PeerId },
 7760    RemoteVideoTracksChanged { participant_id: PeerId },
 7761}
 7762
 7763fn leader_border_for_pane(
 7764    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7765    pane: &Entity<Pane>,
 7766    _: &Window,
 7767    cx: &App,
 7768) -> Option<Div> {
 7769    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7770        if state.pane() == pane {
 7771            Some((*leader_id, state))
 7772        } else {
 7773            None
 7774        }
 7775    })?;
 7776
 7777    let mut leader_color = match leader_id {
 7778        CollaboratorId::PeerId(leader_peer_id) => {
 7779            let leader = GlobalAnyActiveCall::try_global(cx)?
 7780                .0
 7781                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7782
 7783            cx.theme()
 7784                .players()
 7785                .color_for_participant(leader.participant_index.0)
 7786                .cursor
 7787        }
 7788        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7789    };
 7790    leader_color.fade_out(0.3);
 7791    Some(
 7792        div()
 7793            .absolute()
 7794            .size_full()
 7795            .left_0()
 7796            .top_0()
 7797            .border_2()
 7798            .border_color(leader_color),
 7799    )
 7800}
 7801
 7802fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7803    ZED_WINDOW_POSITION
 7804        .zip(*ZED_WINDOW_SIZE)
 7805        .map(|(position, size)| Bounds {
 7806            origin: position,
 7807            size,
 7808        })
 7809}
 7810
 7811fn open_items(
 7812    serialized_workspace: Option<SerializedWorkspace>,
 7813    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7814    window: &mut Window,
 7815    cx: &mut Context<Workspace>,
 7816) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7817    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7818        Workspace::load_workspace(
 7819            serialized_workspace,
 7820            project_paths_to_open
 7821                .iter()
 7822                .map(|(_, project_path)| project_path)
 7823                .cloned()
 7824                .collect(),
 7825            window,
 7826            cx,
 7827        )
 7828    });
 7829
 7830    cx.spawn_in(window, async move |workspace, cx| {
 7831        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7832
 7833        if let Some(restored_items) = restored_items {
 7834            let restored_items = restored_items.await?;
 7835
 7836            let restored_project_paths = restored_items
 7837                .iter()
 7838                .filter_map(|item| {
 7839                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7840                        .ok()
 7841                        .flatten()
 7842                })
 7843                .collect::<HashSet<_>>();
 7844
 7845            for restored_item in restored_items {
 7846                opened_items.push(restored_item.map(Ok));
 7847            }
 7848
 7849            project_paths_to_open
 7850                .iter_mut()
 7851                .for_each(|(_, project_path)| {
 7852                    if let Some(project_path_to_open) = project_path
 7853                        && restored_project_paths.contains(project_path_to_open)
 7854                    {
 7855                        *project_path = None;
 7856                    }
 7857                });
 7858        } else {
 7859            for _ in 0..project_paths_to_open.len() {
 7860                opened_items.push(None);
 7861            }
 7862        }
 7863        assert!(opened_items.len() == project_paths_to_open.len());
 7864
 7865        let tasks =
 7866            project_paths_to_open
 7867                .into_iter()
 7868                .enumerate()
 7869                .map(|(ix, (abs_path, project_path))| {
 7870                    let workspace = workspace.clone();
 7871                    cx.spawn(async move |cx| {
 7872                        let file_project_path = project_path?;
 7873                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7874                            workspace.project().update(cx, |project, cx| {
 7875                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7876                            })
 7877                        });
 7878
 7879                        // We only want to open file paths here. If one of the items
 7880                        // here is a directory, it was already opened further above
 7881                        // with a `find_or_create_worktree`.
 7882                        if let Ok(task) = abs_path_task
 7883                            && task.await.is_none_or(|p| p.is_file())
 7884                        {
 7885                            return Some((
 7886                                ix,
 7887                                workspace
 7888                                    .update_in(cx, |workspace, window, cx| {
 7889                                        workspace.open_path(
 7890                                            file_project_path,
 7891                                            None,
 7892                                            true,
 7893                                            window,
 7894                                            cx,
 7895                                        )
 7896                                    })
 7897                                    .log_err()?
 7898                                    .await,
 7899                            ));
 7900                        }
 7901                        None
 7902                    })
 7903                });
 7904
 7905        let tasks = tasks.collect::<Vec<_>>();
 7906
 7907        let tasks = futures::future::join_all(tasks);
 7908        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7909            opened_items[ix] = Some(path_open_result);
 7910        }
 7911
 7912        Ok(opened_items)
 7913    })
 7914}
 7915
 7916#[derive(Clone)]
 7917enum ActivateInDirectionTarget {
 7918    Pane(Entity<Pane>),
 7919    Dock(Entity<Dock>),
 7920    Sidebar(FocusHandle),
 7921}
 7922
 7923fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7924    window
 7925        .update(cx, |multi_workspace, _, cx| {
 7926            let workspace = multi_workspace.workspace().clone();
 7927            workspace.update(cx, |workspace, cx| {
 7928                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7929                    struct DatabaseFailedNotification;
 7930
 7931                    workspace.show_notification(
 7932                        NotificationId::unique::<DatabaseFailedNotification>(),
 7933                        cx,
 7934                        |cx| {
 7935                            cx.new(|cx| {
 7936                                MessageNotification::new("Failed to load the database file.", cx)
 7937                                    .primary_message("File an Issue")
 7938                                    .primary_icon(IconName::Plus)
 7939                                    .primary_on_click(|window, cx| {
 7940                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7941                                    })
 7942                            })
 7943                        },
 7944                    );
 7945                }
 7946            });
 7947        })
 7948        .log_err();
 7949}
 7950
 7951fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7952    if val == 0 {
 7953        ThemeSettings::get_global(cx).ui_font_size(cx)
 7954    } else {
 7955        px(val as f32)
 7956    }
 7957}
 7958
 7959fn adjust_active_dock_size_by_px(
 7960    px: Pixels,
 7961    workspace: &mut Workspace,
 7962    window: &mut Window,
 7963    cx: &mut Context<Workspace>,
 7964) {
 7965    let Some(active_dock) = workspace
 7966        .all_docks()
 7967        .into_iter()
 7968        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7969    else {
 7970        return;
 7971    };
 7972    let dock = active_dock.read(cx);
 7973    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7974        return;
 7975    };
 7976    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7977}
 7978
 7979fn adjust_open_docks_size_by_px(
 7980    px: Pixels,
 7981    workspace: &mut Workspace,
 7982    window: &mut Window,
 7983    cx: &mut Context<Workspace>,
 7984) {
 7985    let docks = workspace
 7986        .all_docks()
 7987        .into_iter()
 7988        .filter_map(|dock_entity| {
 7989            let dock = dock_entity.read(cx);
 7990            if dock.is_open() {
 7991                let dock_pos = dock.position();
 7992                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7993                Some((dock_pos, panel_size + px))
 7994            } else {
 7995                None
 7996            }
 7997        })
 7998        .collect::<Vec<_>>();
 7999
 8000    for (position, new_size) in docks {
 8001        workspace.resize_dock(position, new_size, window, cx);
 8002    }
 8003}
 8004
 8005impl Focusable for Workspace {
 8006    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8007        self.active_pane.focus_handle(cx)
 8008    }
 8009}
 8010
 8011#[derive(Clone)]
 8012struct DraggedDock(DockPosition);
 8013
 8014impl Render for DraggedDock {
 8015    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8016        gpui::Empty
 8017    }
 8018}
 8019
 8020impl Render for Workspace {
 8021    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8022        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8023        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8024            log::info!("Rendered first frame");
 8025        }
 8026
 8027        let centered_layout = self.centered_layout
 8028            && self.center.panes().len() == 1
 8029            && self.active_item(cx).is_some();
 8030        let render_padding = |size| {
 8031            (size > 0.0).then(|| {
 8032                div()
 8033                    .h_full()
 8034                    .w(relative(size))
 8035                    .bg(cx.theme().colors().editor_background)
 8036                    .border_color(cx.theme().colors().pane_group_border)
 8037            })
 8038        };
 8039        let paddings = if centered_layout {
 8040            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8041            (
 8042                render_padding(Self::adjust_padding(
 8043                    settings.left_padding.map(|padding| padding.0),
 8044                )),
 8045                render_padding(Self::adjust_padding(
 8046                    settings.right_padding.map(|padding| padding.0),
 8047                )),
 8048            )
 8049        } else {
 8050            (None, None)
 8051        };
 8052        let ui_font = theme_settings::setup_ui_font(window, cx);
 8053
 8054        let theme = cx.theme().clone();
 8055        let colors = theme.colors();
 8056        let notification_entities = self
 8057            .notifications
 8058            .iter()
 8059            .map(|(_, notification)| notification.entity_id())
 8060            .collect::<Vec<_>>();
 8061        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8062
 8063        div()
 8064            .relative()
 8065            .size_full()
 8066            .flex()
 8067            .flex_col()
 8068            .font(ui_font)
 8069            .gap_0()
 8070                .justify_start()
 8071                .items_start()
 8072                .text_color(colors.text)
 8073                .overflow_hidden()
 8074                .children(self.titlebar_item.clone())
 8075                .on_modifiers_changed(move |_, _, cx| {
 8076                    for &id in &notification_entities {
 8077                        cx.notify(id);
 8078                    }
 8079                })
 8080                .child(
 8081                    div()
 8082                        .size_full()
 8083                        .relative()
 8084                        .flex_1()
 8085                        .flex()
 8086                        .flex_col()
 8087                        .child(
 8088                            div()
 8089                                .id("workspace")
 8090                                .bg(colors.background)
 8091                                .relative()
 8092                                .flex_1()
 8093                                .w_full()
 8094                                .flex()
 8095                                .flex_col()
 8096                                .overflow_hidden()
 8097                                .border_t_1()
 8098                                .border_b_1()
 8099                                .border_color(colors.border)
 8100                                .child({
 8101                                    let this = cx.entity();
 8102                                    canvas(
 8103                                        move |bounds, window, cx| {
 8104                                            this.update(cx, |this, cx| {
 8105                                                let bounds_changed = this.bounds != bounds;
 8106                                                this.bounds = bounds;
 8107
 8108                                                if bounds_changed {
 8109                                                    this.left_dock.update(cx, |dock, cx| {
 8110                                                        dock.clamp_panel_size(
 8111                                                            bounds.size.width,
 8112                                                            window,
 8113                                                            cx,
 8114                                                        )
 8115                                                    });
 8116
 8117                                                    this.right_dock.update(cx, |dock, cx| {
 8118                                                        dock.clamp_panel_size(
 8119                                                            bounds.size.width,
 8120                                                            window,
 8121                                                            cx,
 8122                                                        )
 8123                                                    });
 8124
 8125                                                    this.bottom_dock.update(cx, |dock, cx| {
 8126                                                        dock.clamp_panel_size(
 8127                                                            bounds.size.height,
 8128                                                            window,
 8129                                                            cx,
 8130                                                        )
 8131                                                    });
 8132                                                }
 8133                                            })
 8134                                        },
 8135                                        |_, _, _, _| {},
 8136                                    )
 8137                                    .absolute()
 8138                                    .size_full()
 8139                                })
 8140                                .when(self.zoomed.is_none(), |this| {
 8141                                    this.on_drag_move(cx.listener(
 8142                                        move |workspace,
 8143                                              e: &DragMoveEvent<DraggedDock>,
 8144                                              window,
 8145                                              cx| {
 8146                                            if workspace.previous_dock_drag_coordinates
 8147                                                != Some(e.event.position)
 8148                                            {
 8149                                                workspace.previous_dock_drag_coordinates =
 8150                                                    Some(e.event.position);
 8151
 8152                                                match e.drag(cx).0 {
 8153                                                    DockPosition::Left => {
 8154                                                        workspace.resize_left_dock(
 8155                                                            e.event.position.x
 8156                                                                - workspace.bounds.left(),
 8157                                                            window,
 8158                                                            cx,
 8159                                                        );
 8160                                                    }
 8161                                                    DockPosition::Right => {
 8162                                                        workspace.resize_right_dock(
 8163                                                            workspace.bounds.right()
 8164                                                                - e.event.position.x,
 8165                                                            window,
 8166                                                            cx,
 8167                                                        );
 8168                                                    }
 8169                                                    DockPosition::Bottom => {
 8170                                                        workspace.resize_bottom_dock(
 8171                                                            workspace.bounds.bottom()
 8172                                                                - e.event.position.y,
 8173                                                            window,
 8174                                                            cx,
 8175                                                        );
 8176                                                    }
 8177                                                };
 8178                                                workspace.serialize_workspace(window, cx);
 8179                                            }
 8180                                        },
 8181                                    ))
 8182
 8183                                })
 8184                                .child({
 8185                                    match bottom_dock_layout {
 8186                                        BottomDockLayout::Full => div()
 8187                                            .flex()
 8188                                            .flex_col()
 8189                                            .h_full()
 8190                                            .child(
 8191                                                div()
 8192                                                    .flex()
 8193                                                    .flex_row()
 8194                                                    .flex_1()
 8195                                                    .overflow_hidden()
 8196                                                    .children(self.render_dock(
 8197                                                        DockPosition::Left,
 8198                                                        &self.left_dock,
 8199                                                        window,
 8200                                                        cx,
 8201                                                    ))
 8202
 8203                                                    .child(
 8204                                                        div()
 8205                                                            .flex()
 8206                                                            .flex_col()
 8207                                                            .flex_1()
 8208                                                            .overflow_hidden()
 8209                                                            .child(
 8210                                                                h_flex()
 8211                                                                    .flex_1()
 8212                                                                    .when_some(
 8213                                                                        paddings.0,
 8214                                                                        |this, p| {
 8215                                                                            this.child(
 8216                                                                                p.border_r_1(),
 8217                                                                            )
 8218                                                                        },
 8219                                                                    )
 8220                                                                    .child(self.center.render(
 8221                                                                        self.zoomed.as_ref(),
 8222                                                                        &PaneRenderContext {
 8223                                                                            follower_states:
 8224                                                                                &self.follower_states,
 8225                                                                            active_call: self.active_call(),
 8226                                                                            active_pane: &self.active_pane,
 8227                                                                            app_state: &self.app_state,
 8228                                                                            project: &self.project,
 8229                                                                            workspace: &self.weak_self,
 8230                                                                        },
 8231                                                                        window,
 8232                                                                        cx,
 8233                                                                    ))
 8234                                                                    .when_some(
 8235                                                                        paddings.1,
 8236                                                                        |this, p| {
 8237                                                                            this.child(
 8238                                                                                p.border_l_1(),
 8239                                                                            )
 8240                                                                        },
 8241                                                                    ),
 8242                                                            ),
 8243                                                    )
 8244
 8245                                                    .children(self.render_dock(
 8246                                                        DockPosition::Right,
 8247                                                        &self.right_dock,
 8248                                                        window,
 8249                                                        cx,
 8250                                                    )),
 8251                                            )
 8252                                            .child(div().w_full().children(self.render_dock(
 8253                                                DockPosition::Bottom,
 8254                                                &self.bottom_dock,
 8255                                                window,
 8256                                                cx
 8257                                            ))),
 8258
 8259                                        BottomDockLayout::LeftAligned => div()
 8260                                            .flex()
 8261                                            .flex_row()
 8262                                            .h_full()
 8263                                            .child(
 8264                                                div()
 8265                                                    .flex()
 8266                                                    .flex_col()
 8267                                                    .flex_1()
 8268                                                    .h_full()
 8269                                                    .child(
 8270                                                        div()
 8271                                                            .flex()
 8272                                                            .flex_row()
 8273                                                            .flex_1()
 8274                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8275
 8276                                                            .child(
 8277                                                                div()
 8278                                                                    .flex()
 8279                                                                    .flex_col()
 8280                                                                    .flex_1()
 8281                                                                    .overflow_hidden()
 8282                                                                    .child(
 8283                                                                        h_flex()
 8284                                                                            .flex_1()
 8285                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8286                                                                            .child(self.center.render(
 8287                                                                                self.zoomed.as_ref(),
 8288                                                                                &PaneRenderContext {
 8289                                                                                    follower_states:
 8290                                                                                        &self.follower_states,
 8291                                                                                    active_call: self.active_call(),
 8292                                                                                    active_pane: &self.active_pane,
 8293                                                                                    app_state: &self.app_state,
 8294                                                                                    project: &self.project,
 8295                                                                                    workspace: &self.weak_self,
 8296                                                                                },
 8297                                                                                window,
 8298                                                                                cx,
 8299                                                                            ))
 8300                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8301                                                                    )
 8302                                                            )
 8303
 8304                                                    )
 8305                                                    .child(
 8306                                                        div()
 8307                                                            .w_full()
 8308                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8309                                                    ),
 8310                                            )
 8311                                            .children(self.render_dock(
 8312                                                DockPosition::Right,
 8313                                                &self.right_dock,
 8314                                                window,
 8315                                                cx,
 8316                                            )),
 8317                                        BottomDockLayout::RightAligned => div()
 8318                                            .flex()
 8319                                            .flex_row()
 8320                                            .h_full()
 8321                                            .children(self.render_dock(
 8322                                                DockPosition::Left,
 8323                                                &self.left_dock,
 8324                                                window,
 8325                                                cx,
 8326                                            ))
 8327
 8328                                            .child(
 8329                                                div()
 8330                                                    .flex()
 8331                                                    .flex_col()
 8332                                                    .flex_1()
 8333                                                    .h_full()
 8334                                                    .child(
 8335                                                        div()
 8336                                                            .flex()
 8337                                                            .flex_row()
 8338                                                            .flex_1()
 8339                                                            .child(
 8340                                                                div()
 8341                                                                    .flex()
 8342                                                                    .flex_col()
 8343                                                                    .flex_1()
 8344                                                                    .overflow_hidden()
 8345                                                                    .child(
 8346                                                                        h_flex()
 8347                                                                            .flex_1()
 8348                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8349                                                                            .child(self.center.render(
 8350                                                                                self.zoomed.as_ref(),
 8351                                                                                &PaneRenderContext {
 8352                                                                                    follower_states:
 8353                                                                                        &self.follower_states,
 8354                                                                                    active_call: self.active_call(),
 8355                                                                                    active_pane: &self.active_pane,
 8356                                                                                    app_state: &self.app_state,
 8357                                                                                    project: &self.project,
 8358                                                                                    workspace: &self.weak_self,
 8359                                                                                },
 8360                                                                                window,
 8361                                                                                cx,
 8362                                                                            ))
 8363                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8364                                                                    )
 8365                                                            )
 8366
 8367                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8368                                                    )
 8369                                                    .child(
 8370                                                        div()
 8371                                                            .w_full()
 8372                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8373                                                    ),
 8374                                            ),
 8375                                        BottomDockLayout::Contained => div()
 8376                                            .flex()
 8377                                            .flex_row()
 8378                                            .h_full()
 8379                                            .children(self.render_dock(
 8380                                                DockPosition::Left,
 8381                                                &self.left_dock,
 8382                                                window,
 8383                                                cx,
 8384                                            ))
 8385
 8386                                            .child(
 8387                                                div()
 8388                                                    .flex()
 8389                                                    .flex_col()
 8390                                                    .flex_1()
 8391                                                    .overflow_hidden()
 8392                                                    .child(
 8393                                                        h_flex()
 8394                                                            .flex_1()
 8395                                                            .when_some(paddings.0, |this, p| {
 8396                                                                this.child(p.border_r_1())
 8397                                                            })
 8398                                                            .child(self.center.render(
 8399                                                                self.zoomed.as_ref(),
 8400                                                                &PaneRenderContext {
 8401                                                                    follower_states:
 8402                                                                        &self.follower_states,
 8403                                                                    active_call: self.active_call(),
 8404                                                                    active_pane: &self.active_pane,
 8405                                                                    app_state: &self.app_state,
 8406                                                                    project: &self.project,
 8407                                                                    workspace: &self.weak_self,
 8408                                                                },
 8409                                                                window,
 8410                                                                cx,
 8411                                                            ))
 8412                                                            .when_some(paddings.1, |this, p| {
 8413                                                                this.child(p.border_l_1())
 8414                                                            }),
 8415                                                    )
 8416                                                    .children(self.render_dock(
 8417                                                        DockPosition::Bottom,
 8418                                                        &self.bottom_dock,
 8419                                                        window,
 8420                                                        cx,
 8421                                                    )),
 8422                                            )
 8423
 8424                                            .children(self.render_dock(
 8425                                                DockPosition::Right,
 8426                                                &self.right_dock,
 8427                                                window,
 8428                                                cx,
 8429                                            )),
 8430                                    }
 8431                                })
 8432                                .children(self.zoomed.as_ref().and_then(|view| {
 8433                                    let zoomed_view = view.upgrade()?;
 8434                                    let div = div()
 8435                                        .occlude()
 8436                                        .absolute()
 8437                                        .overflow_hidden()
 8438                                        .border_color(colors.border)
 8439                                        .bg(colors.background)
 8440                                        .child(zoomed_view)
 8441                                        .inset_0()
 8442                                        .shadow_lg();
 8443
 8444                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8445                                       return Some(div);
 8446                                    }
 8447
 8448                                    Some(match self.zoomed_position {
 8449                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8450                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8451                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8452                                        None => {
 8453                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8454                                        }
 8455                                    })
 8456                                }))
 8457                                .children(self.render_notifications(window, cx)),
 8458                        )
 8459                        .when(self.status_bar_visible(cx), |parent| {
 8460                            parent.child(self.status_bar.clone())
 8461                        })
 8462                        .child(self.toast_layer.clone()),
 8463                )
 8464    }
 8465}
 8466
 8467impl WorkspaceStore {
 8468    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8469        Self {
 8470            workspaces: Default::default(),
 8471            _subscriptions: vec![
 8472                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8473                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8474            ],
 8475            client,
 8476        }
 8477    }
 8478
 8479    pub fn update_followers(
 8480        &self,
 8481        project_id: Option<u64>,
 8482        update: proto::update_followers::Variant,
 8483        cx: &App,
 8484    ) -> Option<()> {
 8485        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8486        let room_id = active_call.0.room_id(cx)?;
 8487        self.client
 8488            .send(proto::UpdateFollowers {
 8489                room_id,
 8490                project_id,
 8491                variant: Some(update),
 8492            })
 8493            .log_err()
 8494    }
 8495
 8496    pub async fn handle_follow(
 8497        this: Entity<Self>,
 8498        envelope: TypedEnvelope<proto::Follow>,
 8499        mut cx: AsyncApp,
 8500    ) -> Result<proto::FollowResponse> {
 8501        this.update(&mut cx, |this, cx| {
 8502            let follower = Follower {
 8503                project_id: envelope.payload.project_id,
 8504                peer_id: envelope.original_sender_id()?,
 8505            };
 8506
 8507            let mut response = proto::FollowResponse::default();
 8508
 8509            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8510                let Some(workspace) = weak_workspace.upgrade() else {
 8511                    return false;
 8512                };
 8513                window_handle
 8514                    .update(cx, |_, window, cx| {
 8515                        workspace.update(cx, |workspace, cx| {
 8516                            let handler_response =
 8517                                workspace.handle_follow(follower.project_id, window, cx);
 8518                            if let Some(active_view) = handler_response.active_view
 8519                                && workspace.project.read(cx).remote_id() == follower.project_id
 8520                            {
 8521                                response.active_view = Some(active_view)
 8522                            }
 8523                        });
 8524                    })
 8525                    .is_ok()
 8526            });
 8527
 8528            Ok(response)
 8529        })
 8530    }
 8531
 8532    async fn handle_update_followers(
 8533        this: Entity<Self>,
 8534        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8535        mut cx: AsyncApp,
 8536    ) -> Result<()> {
 8537        let leader_id = envelope.original_sender_id()?;
 8538        let update = envelope.payload;
 8539
 8540        this.update(&mut cx, |this, cx| {
 8541            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8542                let Some(workspace) = weak_workspace.upgrade() else {
 8543                    return false;
 8544                };
 8545                window_handle
 8546                    .update(cx, |_, window, cx| {
 8547                        workspace.update(cx, |workspace, cx| {
 8548                            let project_id = workspace.project.read(cx).remote_id();
 8549                            if update.project_id != project_id && update.project_id.is_some() {
 8550                                return;
 8551                            }
 8552                            workspace.handle_update_followers(
 8553                                leader_id,
 8554                                update.clone(),
 8555                                window,
 8556                                cx,
 8557                            );
 8558                        });
 8559                    })
 8560                    .is_ok()
 8561            });
 8562            Ok(())
 8563        })
 8564    }
 8565
 8566    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8567        self.workspaces.iter().map(|(_, weak)| weak)
 8568    }
 8569
 8570    pub fn workspaces_with_windows(
 8571        &self,
 8572    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8573        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8574    }
 8575}
 8576
 8577impl ViewId {
 8578    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8579        Ok(Self {
 8580            creator: message
 8581                .creator
 8582                .map(CollaboratorId::PeerId)
 8583                .context("creator is missing")?,
 8584            id: message.id,
 8585        })
 8586    }
 8587
 8588    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8589        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8590            Some(proto::ViewId {
 8591                creator: Some(peer_id),
 8592                id: self.id,
 8593            })
 8594        } else {
 8595            None
 8596        }
 8597    }
 8598}
 8599
 8600impl FollowerState {
 8601    fn pane(&self) -> &Entity<Pane> {
 8602        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8603    }
 8604}
 8605
 8606pub trait WorkspaceHandle {
 8607    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8608}
 8609
 8610impl WorkspaceHandle for Entity<Workspace> {
 8611    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8612        self.read(cx)
 8613            .worktrees(cx)
 8614            .flat_map(|worktree| {
 8615                let worktree_id = worktree.read(cx).id();
 8616                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8617                    worktree_id,
 8618                    path: f.path.clone(),
 8619                })
 8620            })
 8621            .collect::<Vec<_>>()
 8622    }
 8623}
 8624
 8625pub async fn last_opened_workspace_location(
 8626    db: &WorkspaceDb,
 8627    fs: &dyn fs::Fs,
 8628) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8629    db.last_workspace(fs)
 8630        .await
 8631        .log_err()
 8632        .flatten()
 8633        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8634}
 8635
 8636pub async fn last_session_workspace_locations(
 8637    db: &WorkspaceDb,
 8638    last_session_id: &str,
 8639    last_session_window_stack: Option<Vec<WindowId>>,
 8640    fs: &dyn fs::Fs,
 8641) -> Option<Vec<SessionWorkspace>> {
 8642    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8643        .await
 8644        .log_err()
 8645}
 8646
 8647pub struct MultiWorkspaceRestoreResult {
 8648    pub window_handle: WindowHandle<MultiWorkspace>,
 8649    pub errors: Vec<anyhow::Error>,
 8650}
 8651
 8652pub async fn restore_multiworkspace(
 8653    multi_workspace: SerializedMultiWorkspace,
 8654    app_state: Arc<AppState>,
 8655    cx: &mut AsyncApp,
 8656) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8657    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8658    let mut group_iter = workspaces.into_iter();
 8659    let first = group_iter
 8660        .next()
 8661        .context("window group must not be empty")?;
 8662
 8663    let window_handle = if first.paths.is_empty() {
 8664        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8665            .await?
 8666    } else {
 8667        let OpenResult { window, .. } = cx
 8668            .update(|cx| {
 8669                Workspace::new_local(
 8670                    first.paths.paths().to_vec(),
 8671                    app_state.clone(),
 8672                    None,
 8673                    None,
 8674                    None,
 8675                    OpenMode::Activate,
 8676                    cx,
 8677                )
 8678            })
 8679            .await?;
 8680        window
 8681    };
 8682
 8683    let mut errors = Vec::new();
 8684
 8685    for session_workspace in group_iter {
 8686        let error = if session_workspace.paths.is_empty() {
 8687            cx.update(|cx| {
 8688                open_workspace_by_id(
 8689                    session_workspace.workspace_id,
 8690                    app_state.clone(),
 8691                    Some(window_handle),
 8692                    cx,
 8693                )
 8694            })
 8695            .await
 8696            .err()
 8697        } else {
 8698            cx.update(|cx| {
 8699                Workspace::new_local(
 8700                    session_workspace.paths.paths().to_vec(),
 8701                    app_state.clone(),
 8702                    Some(window_handle),
 8703                    None,
 8704                    None,
 8705                    OpenMode::Add,
 8706                    cx,
 8707                )
 8708            })
 8709            .await
 8710            .err()
 8711        };
 8712
 8713        if let Some(error) = error {
 8714            errors.push(error);
 8715        }
 8716    }
 8717
 8718    if let Some(target_id) = state.active_workspace_id {
 8719        window_handle
 8720            .update(cx, |multi_workspace, window, cx| {
 8721                let target_workspace = multi_workspace
 8722                    .workspaces()
 8723                    .find(|ws| ws.read(cx).database_id() == Some(target_id));
 8724                if let Some(workspace) = target_workspace {
 8725                    multi_workspace.activate(workspace, window, cx);
 8726                }
 8727            })
 8728            .ok();
 8729    } else {
 8730        window_handle
 8731            .update(cx, |multi_workspace, window, cx| {
 8732                let first_workspace = multi_workspace.workspaces().next();
 8733                if let Some(workspace) = first_workspace {
 8734                    multi_workspace.activate(workspace, window, cx);
 8735                }
 8736            })
 8737            .ok();
 8738    }
 8739
 8740    if state.sidebar_open {
 8741        window_handle
 8742            .update(cx, |multi_workspace, _, cx| {
 8743                multi_workspace.open_sidebar(cx);
 8744            })
 8745            .ok();
 8746    }
 8747
 8748    if let Some(sidebar_state) = &state.sidebar_state {
 8749        let sidebar_state = sidebar_state.clone();
 8750        window_handle
 8751            .update(cx, |multi_workspace, window, cx| {
 8752                if let Some(sidebar) = multi_workspace.sidebar() {
 8753                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8754                }
 8755                multi_workspace.serialize(cx);
 8756            })
 8757            .ok();
 8758    }
 8759
 8760    window_handle
 8761        .update(cx, |_, window, _cx| {
 8762            window.activate_window();
 8763        })
 8764        .ok();
 8765
 8766    Ok(MultiWorkspaceRestoreResult {
 8767        window_handle,
 8768        errors,
 8769    })
 8770}
 8771
 8772actions!(
 8773    collab,
 8774    [
 8775        /// Opens the channel notes for the current call.
 8776        ///
 8777        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8778        /// channel in the collab panel.
 8779        ///
 8780        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8781        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8782        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8783        OpenChannelNotes,
 8784        /// Mutes your microphone.
 8785        Mute,
 8786        /// Deafens yourself (mute both microphone and speakers).
 8787        Deafen,
 8788        /// Leaves the current call.
 8789        LeaveCall,
 8790        /// Shares the current project with collaborators.
 8791        ShareProject,
 8792        /// Shares your screen with collaborators.
 8793        ScreenShare,
 8794        /// Copies the current room name and session id for debugging purposes.
 8795        CopyRoomId,
 8796    ]
 8797);
 8798
 8799/// Opens the channel notes for a specific channel by its ID.
 8800#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8801#[action(namespace = collab)]
 8802#[serde(deny_unknown_fields)]
 8803pub struct OpenChannelNotesById {
 8804    pub channel_id: u64,
 8805}
 8806
 8807actions!(
 8808    zed,
 8809    [
 8810        /// Opens the Zed log file.
 8811        OpenLog,
 8812        /// Reveals the Zed log file in the system file manager.
 8813        RevealLogInFileManager
 8814    ]
 8815);
 8816
 8817async fn join_channel_internal(
 8818    channel_id: ChannelId,
 8819    app_state: &Arc<AppState>,
 8820    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8821    requesting_workspace: Option<WeakEntity<Workspace>>,
 8822    active_call: &dyn AnyActiveCall,
 8823    cx: &mut AsyncApp,
 8824) -> Result<bool> {
 8825    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8826        if !active_call.is_in_room(cx) {
 8827            return (false, false);
 8828        }
 8829
 8830        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8831        let should_prompt = active_call.is_sharing_project(cx)
 8832            && active_call.has_remote_participants(cx)
 8833            && !already_in_channel;
 8834        (should_prompt, already_in_channel)
 8835    });
 8836
 8837    if already_in_channel {
 8838        let task = cx.update(|cx| {
 8839            if let Some((project, host)) = active_call.most_active_project(cx) {
 8840                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8841            } else {
 8842                None
 8843            }
 8844        });
 8845        if let Some(task) = task {
 8846            task.await?;
 8847        }
 8848        return anyhow::Ok(true);
 8849    }
 8850
 8851    if should_prompt {
 8852        if let Some(multi_workspace) = requesting_window {
 8853            let answer = multi_workspace
 8854                .update(cx, |_, window, cx| {
 8855                    window.prompt(
 8856                        PromptLevel::Warning,
 8857                        "Do you want to switch channels?",
 8858                        Some("Leaving this call will unshare your current project."),
 8859                        &["Yes, Join Channel", "Cancel"],
 8860                        cx,
 8861                    )
 8862                })?
 8863                .await;
 8864
 8865            if answer == Ok(1) {
 8866                return Ok(false);
 8867            }
 8868        } else {
 8869            return Ok(false);
 8870        }
 8871    }
 8872
 8873    let client = cx.update(|cx| active_call.client(cx));
 8874
 8875    let mut client_status = client.status();
 8876
 8877    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8878    'outer: loop {
 8879        let Some(status) = client_status.recv().await else {
 8880            anyhow::bail!("error connecting");
 8881        };
 8882
 8883        match status {
 8884            Status::Connecting
 8885            | Status::Authenticating
 8886            | Status::Authenticated
 8887            | Status::Reconnecting
 8888            | Status::Reauthenticating
 8889            | Status::Reauthenticated => continue,
 8890            Status::Connected { .. } => break 'outer,
 8891            Status::SignedOut | Status::AuthenticationError => {
 8892                return Err(ErrorCode::SignedOut.into());
 8893            }
 8894            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8895            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8896                return Err(ErrorCode::Disconnected.into());
 8897            }
 8898        }
 8899    }
 8900
 8901    let joined = cx
 8902        .update(|cx| active_call.join_channel(channel_id, cx))
 8903        .await?;
 8904
 8905    if !joined {
 8906        return anyhow::Ok(true);
 8907    }
 8908
 8909    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8910
 8911    let task = cx.update(|cx| {
 8912        if let Some((project, host)) = active_call.most_active_project(cx) {
 8913            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8914        }
 8915
 8916        // If you are the first to join a channel, see if you should share your project.
 8917        if !active_call.has_remote_participants(cx)
 8918            && !active_call.local_participant_is_guest(cx)
 8919            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8920        {
 8921            let project = workspace.update(cx, |workspace, cx| {
 8922                let project = workspace.project.read(cx);
 8923
 8924                if !active_call.share_on_join(cx) {
 8925                    return None;
 8926                }
 8927
 8928                if (project.is_local() || project.is_via_remote_server())
 8929                    && project.visible_worktrees(cx).any(|tree| {
 8930                        tree.read(cx)
 8931                            .root_entry()
 8932                            .is_some_and(|entry| entry.is_dir())
 8933                    })
 8934                {
 8935                    Some(workspace.project.clone())
 8936                } else {
 8937                    None
 8938                }
 8939            });
 8940            if let Some(project) = project {
 8941                let share_task = active_call.share_project(project, cx);
 8942                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8943                    share_task.await?;
 8944                    Ok(())
 8945                }));
 8946            }
 8947        }
 8948
 8949        None
 8950    });
 8951    if let Some(task) = task {
 8952        task.await?;
 8953        return anyhow::Ok(true);
 8954    }
 8955    anyhow::Ok(false)
 8956}
 8957
 8958pub fn join_channel(
 8959    channel_id: ChannelId,
 8960    app_state: Arc<AppState>,
 8961    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8962    requesting_workspace: Option<WeakEntity<Workspace>>,
 8963    cx: &mut App,
 8964) -> Task<Result<()>> {
 8965    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8966    cx.spawn(async move |cx| {
 8967        let result = join_channel_internal(
 8968            channel_id,
 8969            &app_state,
 8970            requesting_window,
 8971            requesting_workspace,
 8972            &*active_call.0,
 8973            cx,
 8974        )
 8975        .await;
 8976
 8977        // join channel succeeded, and opened a window
 8978        if matches!(result, Ok(true)) {
 8979            return anyhow::Ok(());
 8980        }
 8981
 8982        // find an existing workspace to focus and show call controls
 8983        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8984        if active_window.is_none() {
 8985            // no open workspaces, make one to show the error in (blergh)
 8986            let OpenResult {
 8987                window: window_handle,
 8988                ..
 8989            } = cx
 8990                .update(|cx| {
 8991                    Workspace::new_local(
 8992                        vec![],
 8993                        app_state.clone(),
 8994                        requesting_window,
 8995                        None,
 8996                        None,
 8997                        OpenMode::Activate,
 8998                        cx,
 8999                    )
 9000                })
 9001                .await?;
 9002
 9003            window_handle
 9004                .update(cx, |_, window, _cx| {
 9005                    window.activate_window();
 9006                })
 9007                .ok();
 9008
 9009            if result.is_ok() {
 9010                cx.update(|cx| {
 9011                    cx.dispatch_action(&OpenChannelNotes);
 9012                });
 9013            }
 9014
 9015            active_window = Some(window_handle);
 9016        }
 9017
 9018        if let Err(err) = result {
 9019            log::error!("failed to join channel: {}", err);
 9020            if let Some(active_window) = active_window {
 9021                active_window
 9022                    .update(cx, |_, window, cx| {
 9023                        let detail: SharedString = match err.error_code() {
 9024                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9025                            ErrorCode::UpgradeRequired => concat!(
 9026                                "Your are running an unsupported version of Zed. ",
 9027                                "Please update to continue."
 9028                            )
 9029                            .into(),
 9030                            ErrorCode::NoSuchChannel => concat!(
 9031                                "No matching channel was found. ",
 9032                                "Please check the link and try again."
 9033                            )
 9034                            .into(),
 9035                            ErrorCode::Forbidden => concat!(
 9036                                "This channel is private, and you do not have access. ",
 9037                                "Please ask someone to add you and try again."
 9038                            )
 9039                            .into(),
 9040                            ErrorCode::Disconnected => {
 9041                                "Please check your internet connection and try again.".into()
 9042                            }
 9043                            _ => format!("{}\n\nPlease try again.", err).into(),
 9044                        };
 9045                        window.prompt(
 9046                            PromptLevel::Critical,
 9047                            "Failed to join channel",
 9048                            Some(&detail),
 9049                            &["Ok"],
 9050                            cx,
 9051                        )
 9052                    })?
 9053                    .await
 9054                    .ok();
 9055            }
 9056        }
 9057
 9058        // return ok, we showed the error to the user.
 9059        anyhow::Ok(())
 9060    })
 9061}
 9062
 9063pub async fn get_any_active_multi_workspace(
 9064    app_state: Arc<AppState>,
 9065    mut cx: AsyncApp,
 9066) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9067    // find an existing workspace to focus and show call controls
 9068    let active_window = activate_any_workspace_window(&mut cx);
 9069    if active_window.is_none() {
 9070        cx.update(|cx| {
 9071            Workspace::new_local(
 9072                vec![],
 9073                app_state.clone(),
 9074                None,
 9075                None,
 9076                None,
 9077                OpenMode::Activate,
 9078                cx,
 9079            )
 9080        })
 9081        .await?;
 9082    }
 9083    activate_any_workspace_window(&mut cx).context("could not open zed")
 9084}
 9085
 9086fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9087    cx.update(|cx| {
 9088        if let Some(workspace_window) = cx
 9089            .active_window()
 9090            .and_then(|window| window.downcast::<MultiWorkspace>())
 9091        {
 9092            return Some(workspace_window);
 9093        }
 9094
 9095        for window in cx.windows() {
 9096            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9097                workspace_window
 9098                    .update(cx, |_, window, _| window.activate_window())
 9099                    .ok();
 9100                return Some(workspace_window);
 9101            }
 9102        }
 9103        None
 9104    })
 9105}
 9106
 9107pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9108    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9109}
 9110
 9111pub fn workspace_windows_for_location(
 9112    serialized_location: &SerializedWorkspaceLocation,
 9113    cx: &App,
 9114) -> Vec<WindowHandle<MultiWorkspace>> {
 9115    cx.windows()
 9116        .into_iter()
 9117        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9118        .filter(|multi_workspace| {
 9119            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9120                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9121                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9122                }
 9123                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9124                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9125                    a.distro_name == b.distro_name
 9126                }
 9127                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9128                    a.container_id == b.container_id
 9129                }
 9130                #[cfg(any(test, feature = "test-support"))]
 9131                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9132                    a.id == b.id
 9133                }
 9134                _ => false,
 9135            };
 9136
 9137            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9138                multi_workspace.workspaces().any(|workspace| {
 9139                    match workspace.read(cx).workspace_location(cx) {
 9140                        WorkspaceLocation::Location(location, _) => {
 9141                            match (&location, serialized_location) {
 9142                                (
 9143                                    SerializedWorkspaceLocation::Local,
 9144                                    SerializedWorkspaceLocation::Local,
 9145                                ) => true,
 9146                                (
 9147                                    SerializedWorkspaceLocation::Remote(a),
 9148                                    SerializedWorkspaceLocation::Remote(b),
 9149                                ) => same_host(a, b),
 9150                                _ => false,
 9151                            }
 9152                        }
 9153                        _ => false,
 9154                    }
 9155                })
 9156            })
 9157        })
 9158        .collect()
 9159}
 9160
 9161pub async fn find_existing_workspace(
 9162    abs_paths: &[PathBuf],
 9163    open_options: &OpenOptions,
 9164    location: &SerializedWorkspaceLocation,
 9165    cx: &mut AsyncApp,
 9166) -> (
 9167    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9168    OpenVisible,
 9169) {
 9170    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9171    let mut open_visible = OpenVisible::All;
 9172    let mut best_match = None;
 9173
 9174    if open_options.open_new_workspace != Some(true) {
 9175        cx.update(|cx| {
 9176            for window in workspace_windows_for_location(location, cx) {
 9177                if let Ok(multi_workspace) = window.read(cx) {
 9178                    for workspace in multi_workspace.workspaces() {
 9179                        let project = workspace.read(cx).project.read(cx);
 9180                        let m = project.visibility_for_paths(
 9181                            abs_paths,
 9182                            open_options.open_new_workspace == None,
 9183                            cx,
 9184                        );
 9185                        if m > best_match {
 9186                            existing = Some((window, workspace.clone()));
 9187                            best_match = m;
 9188                        } else if best_match.is_none()
 9189                            && open_options.open_new_workspace == Some(false)
 9190                        {
 9191                            existing = Some((window, workspace.clone()))
 9192                        }
 9193                    }
 9194                }
 9195            }
 9196        });
 9197
 9198        let all_paths_are_files = existing
 9199            .as_ref()
 9200            .and_then(|(_, target_workspace)| {
 9201                cx.update(|cx| {
 9202                    let workspace = target_workspace.read(cx);
 9203                    let project = workspace.project.read(cx);
 9204                    let path_style = workspace.path_style(cx);
 9205                    Some(!abs_paths.iter().any(|path| {
 9206                        let path = util::paths::SanitizedPath::new(path);
 9207                        project.worktrees(cx).any(|worktree| {
 9208                            let worktree = worktree.read(cx);
 9209                            let abs_path = worktree.abs_path();
 9210                            path_style
 9211                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9212                                .and_then(|rel| worktree.entry_for_path(&rel))
 9213                                .is_some_and(|e| e.is_dir())
 9214                        })
 9215                    }))
 9216                })
 9217            })
 9218            .unwrap_or(false);
 9219
 9220        if open_options.open_new_workspace.is_none()
 9221            && existing.is_some()
 9222            && open_options.wait
 9223            && all_paths_are_files
 9224        {
 9225            cx.update(|cx| {
 9226                let windows = workspace_windows_for_location(location, cx);
 9227                let window = cx
 9228                    .active_window()
 9229                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9230                    .filter(|window| windows.contains(window))
 9231                    .or_else(|| windows.into_iter().next());
 9232                if let Some(window) = window {
 9233                    if let Ok(multi_workspace) = window.read(cx) {
 9234                        let active_workspace = multi_workspace.workspace().clone();
 9235                        existing = Some((window, active_workspace));
 9236                        open_visible = OpenVisible::None;
 9237                    }
 9238                }
 9239            });
 9240        }
 9241    }
 9242    (existing, open_visible)
 9243}
 9244
 9245#[derive(Default, Clone)]
 9246pub struct OpenOptions {
 9247    pub visible: Option<OpenVisible>,
 9248    pub focus: Option<bool>,
 9249    pub open_new_workspace: Option<bool>,
 9250    pub wait: bool,
 9251    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9252    pub open_mode: OpenMode,
 9253    pub env: Option<HashMap<String, String>>,
 9254    pub open_in_dev_container: bool,
 9255}
 9256
 9257/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9258/// or [`Workspace::open_workspace_for_paths`].
 9259pub struct OpenResult {
 9260    pub window: WindowHandle<MultiWorkspace>,
 9261    pub workspace: Entity<Workspace>,
 9262    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9263}
 9264
 9265/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9266pub fn open_workspace_by_id(
 9267    workspace_id: WorkspaceId,
 9268    app_state: Arc<AppState>,
 9269    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9270    cx: &mut App,
 9271) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9272    let project_handle = Project::local(
 9273        app_state.client.clone(),
 9274        app_state.node_runtime.clone(),
 9275        app_state.user_store.clone(),
 9276        app_state.languages.clone(),
 9277        app_state.fs.clone(),
 9278        None,
 9279        project::LocalProjectFlags {
 9280            init_worktree_trust: true,
 9281            ..project::LocalProjectFlags::default()
 9282        },
 9283        cx,
 9284    );
 9285
 9286    let db = WorkspaceDb::global(cx);
 9287    let kvp = db::kvp::KeyValueStore::global(cx);
 9288    cx.spawn(async move |cx| {
 9289        let serialized_workspace = db
 9290            .workspace_for_id(workspace_id)
 9291            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9292
 9293        let centered_layout = serialized_workspace.centered_layout;
 9294
 9295        let (window, workspace) = if let Some(window) = requesting_window {
 9296            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9297                let workspace = cx.new(|cx| {
 9298                    let mut workspace = Workspace::new(
 9299                        Some(workspace_id),
 9300                        project_handle.clone(),
 9301                        app_state.clone(),
 9302                        window,
 9303                        cx,
 9304                    );
 9305                    workspace.centered_layout = centered_layout;
 9306                    workspace
 9307                });
 9308                multi_workspace.add(workspace.clone(), &*window, cx);
 9309                workspace
 9310            })?;
 9311            (window, workspace)
 9312        } else {
 9313            let window_bounds_override = window_bounds_env_override();
 9314
 9315            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9316                (Some(WindowBounds::Windowed(bounds)), None)
 9317            } else if let Some(display) = serialized_workspace.display
 9318                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9319            {
 9320                (Some(bounds.0), Some(display))
 9321            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9322                (Some(bounds), Some(display))
 9323            } else {
 9324                (None, None)
 9325            };
 9326
 9327            let options = cx.update(|cx| {
 9328                let mut options = (app_state.build_window_options)(display, cx);
 9329                options.window_bounds = window_bounds;
 9330                options
 9331            });
 9332
 9333            let window = cx.open_window(options, {
 9334                let app_state = app_state.clone();
 9335                let project_handle = project_handle.clone();
 9336                move |window, cx| {
 9337                    let workspace = cx.new(|cx| {
 9338                        let mut workspace = Workspace::new(
 9339                            Some(workspace_id),
 9340                            project_handle,
 9341                            app_state,
 9342                            window,
 9343                            cx,
 9344                        );
 9345                        workspace.centered_layout = centered_layout;
 9346                        workspace
 9347                    });
 9348                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9349                }
 9350            })?;
 9351
 9352            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9353                multi_workspace.workspace().clone()
 9354            })?;
 9355
 9356            (window, workspace)
 9357        };
 9358
 9359        notify_if_database_failed(window, cx);
 9360
 9361        // Restore items from the serialized workspace
 9362        window
 9363            .update(cx, |_, window, cx| {
 9364                workspace.update(cx, |_workspace, cx| {
 9365                    open_items(Some(serialized_workspace), vec![], window, cx)
 9366                })
 9367            })?
 9368            .await?;
 9369
 9370        window.update(cx, |_, window, cx| {
 9371            workspace.update(cx, |workspace, cx| {
 9372                workspace.serialize_workspace(window, cx);
 9373            });
 9374        })?;
 9375
 9376        Ok(window)
 9377    })
 9378}
 9379
 9380#[allow(clippy::type_complexity)]
 9381pub fn open_paths(
 9382    abs_paths: &[PathBuf],
 9383    app_state: Arc<AppState>,
 9384    open_options: OpenOptions,
 9385    cx: &mut App,
 9386) -> Task<anyhow::Result<OpenResult>> {
 9387    let abs_paths = abs_paths.to_vec();
 9388    #[cfg(target_os = "windows")]
 9389    let wsl_path = abs_paths
 9390        .iter()
 9391        .find_map(|p| util::paths::WslPath::from_path(p));
 9392
 9393    cx.spawn(async move |cx| {
 9394        let (mut existing, mut open_visible) = find_existing_workspace(
 9395            &abs_paths,
 9396            &open_options,
 9397            &SerializedWorkspaceLocation::Local,
 9398            cx,
 9399        )
 9400        .await;
 9401
 9402        // Fallback: if no workspace contains the paths and all paths are files,
 9403        // prefer an existing local workspace window (active window first).
 9404        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9405            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9406            let all_metadatas = futures::future::join_all(all_paths)
 9407                .await
 9408                .into_iter()
 9409                .filter_map(|result| result.ok().flatten())
 9410                .collect::<Vec<_>>();
 9411
 9412            if all_metadatas.iter().all(|file| !file.is_dir) {
 9413                cx.update(|cx| {
 9414                    let windows = workspace_windows_for_location(
 9415                        &SerializedWorkspaceLocation::Local,
 9416                        cx,
 9417                    );
 9418                    let window = cx
 9419                        .active_window()
 9420                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9421                        .filter(|window| windows.contains(window))
 9422                        .or_else(|| windows.into_iter().next());
 9423                    if let Some(window) = window {
 9424                        if let Ok(multi_workspace) = window.read(cx) {
 9425                            let active_workspace = multi_workspace.workspace().clone();
 9426                            existing = Some((window, active_workspace));
 9427                            open_visible = OpenVisible::None;
 9428                        }
 9429                    }
 9430                });
 9431            }
 9432        }
 9433
 9434        let open_in_dev_container = open_options.open_in_dev_container;
 9435
 9436        let result = if let Some((existing, target_workspace)) = existing {
 9437            let open_task = existing
 9438                .update(cx, |multi_workspace, window, cx| {
 9439                    window.activate_window();
 9440                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9441                    target_workspace.update(cx, |workspace, cx| {
 9442                        if open_in_dev_container {
 9443                            workspace.set_open_in_dev_container(true);
 9444                        }
 9445                        workspace.open_paths(
 9446                            abs_paths,
 9447                            OpenOptions {
 9448                                visible: Some(open_visible),
 9449                                ..Default::default()
 9450                            },
 9451                            None,
 9452                            window,
 9453                            cx,
 9454                        )
 9455                    })
 9456                })?
 9457                .await;
 9458
 9459            _ = existing.update(cx, |multi_workspace, _, cx| {
 9460                let workspace = multi_workspace.workspace().clone();
 9461                workspace.update(cx, |workspace, cx| {
 9462                    for item in open_task.iter().flatten() {
 9463                        if let Err(e) = item {
 9464                            workspace.show_error(&e, cx);
 9465                        }
 9466                    }
 9467                });
 9468            });
 9469
 9470            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9471        } else {
 9472            let init = if open_in_dev_container {
 9473                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9474                    workspace.set_open_in_dev_container(true);
 9475                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9476            } else {
 9477                None
 9478            };
 9479            let result = cx
 9480                .update(move |cx| {
 9481                    Workspace::new_local(
 9482                        abs_paths,
 9483                        app_state.clone(),
 9484                        open_options.requesting_window,
 9485                        open_options.env,
 9486                        init,
 9487                        open_options.open_mode,
 9488                        cx,
 9489                    )
 9490                })
 9491                .await;
 9492
 9493            if let Ok(ref result) = result {
 9494                result.window
 9495                    .update(cx, |_, window, _cx| {
 9496                        window.activate_window();
 9497                    })
 9498                    .log_err();
 9499            }
 9500
 9501            result
 9502        };
 9503
 9504        #[cfg(target_os = "windows")]
 9505        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9506            && let Ok(ref result) = result
 9507        {
 9508            result.window
 9509                .update(cx, move |multi_workspace, _window, cx| {
 9510                    struct OpenInWsl;
 9511                    let workspace = multi_workspace.workspace().clone();
 9512                    workspace.update(cx, |workspace, cx| {
 9513                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9514                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9515                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9516                            cx.new(move |cx| {
 9517                                MessageNotification::new(msg, cx)
 9518                                    .primary_message("Open in WSL")
 9519                                    .primary_icon(IconName::FolderOpen)
 9520                                    .primary_on_click(move |window, cx| {
 9521                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9522                                                distro: remote::WslConnectionOptions {
 9523                                                        distro_name: distro.clone(),
 9524                                                    user: None,
 9525                                                },
 9526                                                paths: vec![path.clone().into()],
 9527                                            }), cx)
 9528                                    })
 9529                            })
 9530                        });
 9531                    });
 9532                })
 9533                .unwrap();
 9534        };
 9535        result
 9536    })
 9537}
 9538
 9539pub fn open_new(
 9540    open_options: OpenOptions,
 9541    app_state: Arc<AppState>,
 9542    cx: &mut App,
 9543    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9544) -> Task<anyhow::Result<()>> {
 9545    let addition = open_options.open_mode;
 9546    let task = Workspace::new_local(
 9547        Vec::new(),
 9548        app_state,
 9549        open_options.requesting_window,
 9550        open_options.env,
 9551        Some(Box::new(init)),
 9552        addition,
 9553        cx,
 9554    );
 9555    cx.spawn(async move |cx| {
 9556        let OpenResult { window, .. } = task.await?;
 9557        window
 9558            .update(cx, |_, window, _cx| {
 9559                window.activate_window();
 9560            })
 9561            .ok();
 9562        Ok(())
 9563    })
 9564}
 9565
 9566pub fn create_and_open_local_file(
 9567    path: &'static Path,
 9568    window: &mut Window,
 9569    cx: &mut Context<Workspace>,
 9570    default_content: impl 'static + Send + FnOnce() -> Rope,
 9571) -> Task<Result<Box<dyn ItemHandle>>> {
 9572    cx.spawn_in(window, async move |workspace, cx| {
 9573        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9574        if !fs.is_file(path).await {
 9575            fs.create_file(path, Default::default()).await?;
 9576            fs.save(path, &default_content(), Default::default())
 9577                .await?;
 9578        }
 9579
 9580        workspace
 9581            .update_in(cx, |workspace, window, cx| {
 9582                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9583                    let path = workspace
 9584                        .project
 9585                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9586                    cx.spawn_in(window, async move |workspace, cx| {
 9587                        let path = path.await?;
 9588
 9589                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9590
 9591                        let mut items = workspace
 9592                            .update_in(cx, |workspace, window, cx| {
 9593                                workspace.open_paths(
 9594                                    vec![path.to_path_buf()],
 9595                                    OpenOptions {
 9596                                        visible: Some(OpenVisible::None),
 9597                                        ..Default::default()
 9598                                    },
 9599                                    None,
 9600                                    window,
 9601                                    cx,
 9602                                )
 9603                            })?
 9604                            .await;
 9605                        let item = items.pop().flatten();
 9606                        item.with_context(|| format!("path {path:?} is not a file"))?
 9607                    })
 9608                })
 9609            })?
 9610            .await?
 9611            .await
 9612    })
 9613}
 9614
 9615pub fn open_remote_project_with_new_connection(
 9616    window: WindowHandle<MultiWorkspace>,
 9617    remote_connection: Arc<dyn RemoteConnection>,
 9618    cancel_rx: oneshot::Receiver<()>,
 9619    delegate: Arc<dyn RemoteClientDelegate>,
 9620    app_state: Arc<AppState>,
 9621    paths: Vec<PathBuf>,
 9622    cx: &mut App,
 9623) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9624    cx.spawn(async move |cx| {
 9625        let (workspace_id, serialized_workspace) =
 9626            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9627                .await?;
 9628
 9629        let session = match cx
 9630            .update(|cx| {
 9631                remote::RemoteClient::new(
 9632                    ConnectionIdentifier::Workspace(workspace_id.0),
 9633                    remote_connection,
 9634                    cancel_rx,
 9635                    delegate,
 9636                    cx,
 9637                )
 9638            })
 9639            .await?
 9640        {
 9641            Some(result) => result,
 9642            None => return Ok(Vec::new()),
 9643        };
 9644
 9645        let project = cx.update(|cx| {
 9646            project::Project::remote(
 9647                session,
 9648                app_state.client.clone(),
 9649                app_state.node_runtime.clone(),
 9650                app_state.user_store.clone(),
 9651                app_state.languages.clone(),
 9652                app_state.fs.clone(),
 9653                true,
 9654                cx,
 9655            )
 9656        });
 9657
 9658        open_remote_project_inner(
 9659            project,
 9660            paths,
 9661            workspace_id,
 9662            serialized_workspace,
 9663            app_state,
 9664            window,
 9665            cx,
 9666        )
 9667        .await
 9668    })
 9669}
 9670
 9671pub fn open_remote_project_with_existing_connection(
 9672    connection_options: RemoteConnectionOptions,
 9673    project: Entity<Project>,
 9674    paths: Vec<PathBuf>,
 9675    app_state: Arc<AppState>,
 9676    window: WindowHandle<MultiWorkspace>,
 9677    cx: &mut AsyncApp,
 9678) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9679    cx.spawn(async move |cx| {
 9680        let (workspace_id, serialized_workspace) =
 9681            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9682
 9683        open_remote_project_inner(
 9684            project,
 9685            paths,
 9686            workspace_id,
 9687            serialized_workspace,
 9688            app_state,
 9689            window,
 9690            cx,
 9691        )
 9692        .await
 9693    })
 9694}
 9695
 9696async fn open_remote_project_inner(
 9697    project: Entity<Project>,
 9698    paths: Vec<PathBuf>,
 9699    workspace_id: WorkspaceId,
 9700    serialized_workspace: Option<SerializedWorkspace>,
 9701    app_state: Arc<AppState>,
 9702    window: WindowHandle<MultiWorkspace>,
 9703    cx: &mut AsyncApp,
 9704) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9705    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9706    let toolchains = db.toolchains(workspace_id).await?;
 9707    for (toolchain, worktree_path, path) in toolchains {
 9708        project
 9709            .update(cx, |this, cx| {
 9710                let Some(worktree_id) =
 9711                    this.find_worktree(&worktree_path, cx)
 9712                        .and_then(|(worktree, rel_path)| {
 9713                            if rel_path.is_empty() {
 9714                                Some(worktree.read(cx).id())
 9715                            } else {
 9716                                None
 9717                            }
 9718                        })
 9719                else {
 9720                    return Task::ready(None);
 9721                };
 9722
 9723                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9724            })
 9725            .await;
 9726    }
 9727    let mut project_paths_to_open = vec![];
 9728    let mut project_path_errors = vec![];
 9729
 9730    for path in paths {
 9731        let result = cx
 9732            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9733            .await;
 9734        match result {
 9735            Ok((_, project_path)) => {
 9736                project_paths_to_open.push((path.clone(), Some(project_path)));
 9737            }
 9738            Err(error) => {
 9739                project_path_errors.push(error);
 9740            }
 9741        };
 9742    }
 9743
 9744    if project_paths_to_open.is_empty() {
 9745        return Err(project_path_errors.pop().context("no paths given")?);
 9746    }
 9747
 9748    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9749        telemetry::event!("SSH Project Opened");
 9750
 9751        let new_workspace = cx.new(|cx| {
 9752            let mut workspace =
 9753                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9754            workspace.update_history(cx);
 9755
 9756            if let Some(ref serialized) = serialized_workspace {
 9757                workspace.centered_layout = serialized.centered_layout;
 9758            }
 9759
 9760            workspace
 9761        });
 9762
 9763        multi_workspace.activate(new_workspace.clone(), window, cx);
 9764        new_workspace
 9765    })?;
 9766
 9767    let items = window
 9768        .update(cx, |_, window, cx| {
 9769            window.activate_window();
 9770            workspace.update(cx, |_workspace, cx| {
 9771                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9772            })
 9773        })?
 9774        .await?;
 9775
 9776    workspace.update(cx, |workspace, cx| {
 9777        for error in project_path_errors {
 9778            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9779                if let Some(path) = error.error_tag("path") {
 9780                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9781                }
 9782            } else {
 9783                workspace.show_error(&error, cx)
 9784            }
 9785        }
 9786    });
 9787
 9788    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9789}
 9790
 9791fn deserialize_remote_project(
 9792    connection_options: RemoteConnectionOptions,
 9793    paths: Vec<PathBuf>,
 9794    cx: &AsyncApp,
 9795) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9796    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9797    cx.background_spawn(async move {
 9798        let remote_connection_id = db
 9799            .get_or_create_remote_connection(connection_options)
 9800            .await?;
 9801
 9802        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9803
 9804        let workspace_id = if let Some(workspace_id) =
 9805            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9806        {
 9807            workspace_id
 9808        } else {
 9809            db.next_id().await?
 9810        };
 9811
 9812        Ok((workspace_id, serialized_workspace))
 9813    })
 9814}
 9815
 9816pub fn join_in_room_project(
 9817    project_id: u64,
 9818    follow_user_id: u64,
 9819    app_state: Arc<AppState>,
 9820    cx: &mut App,
 9821) -> Task<Result<()>> {
 9822    let windows = cx.windows();
 9823    cx.spawn(async move |cx| {
 9824        let existing_window_and_workspace: Option<(
 9825            WindowHandle<MultiWorkspace>,
 9826            Entity<Workspace>,
 9827        )> = windows.into_iter().find_map(|window_handle| {
 9828            window_handle
 9829                .downcast::<MultiWorkspace>()
 9830                .and_then(|window_handle| {
 9831                    window_handle
 9832                        .update(cx, |multi_workspace, _window, cx| {
 9833                            for workspace in multi_workspace.workspaces() {
 9834                                if workspace.read(cx).project().read(cx).remote_id()
 9835                                    == Some(project_id)
 9836                                {
 9837                                    return Some((window_handle, workspace.clone()));
 9838                                }
 9839                            }
 9840                            None
 9841                        })
 9842                        .unwrap_or(None)
 9843                })
 9844        });
 9845
 9846        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9847            existing_window_and_workspace
 9848        {
 9849            existing_window
 9850                .update(cx, |multi_workspace, window, cx| {
 9851                    multi_workspace.activate(target_workspace, window, cx);
 9852                })
 9853                .ok();
 9854            existing_window
 9855        } else {
 9856            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9857            let project = cx
 9858                .update(|cx| {
 9859                    active_call.0.join_project(
 9860                        project_id,
 9861                        app_state.languages.clone(),
 9862                        app_state.fs.clone(),
 9863                        cx,
 9864                    )
 9865                })
 9866                .await?;
 9867
 9868            let window_bounds_override = window_bounds_env_override();
 9869            cx.update(|cx| {
 9870                let mut options = (app_state.build_window_options)(None, cx);
 9871                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9872                cx.open_window(options, |window, cx| {
 9873                    let workspace = cx.new(|cx| {
 9874                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9875                    });
 9876                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9877                })
 9878            })?
 9879        };
 9880
 9881        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9882            cx.activate(true);
 9883            window.activate_window();
 9884
 9885            // We set the active workspace above, so this is the correct workspace.
 9886            let workspace = multi_workspace.workspace().clone();
 9887            workspace.update(cx, |workspace, cx| {
 9888                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9889                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9890                    .or_else(|| {
 9891                        // If we couldn't follow the given user, follow the host instead.
 9892                        let collaborator = workspace
 9893                            .project()
 9894                            .read(cx)
 9895                            .collaborators()
 9896                            .values()
 9897                            .find(|collaborator| collaborator.is_host)?;
 9898                        Some(collaborator.peer_id)
 9899                    });
 9900
 9901                if let Some(follow_peer_id) = follow_peer_id {
 9902                    workspace.follow(follow_peer_id, window, cx);
 9903                }
 9904            });
 9905        })?;
 9906
 9907        anyhow::Ok(())
 9908    })
 9909}
 9910
 9911pub fn reload(cx: &mut App) {
 9912    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9913    let mut workspace_windows = cx
 9914        .windows()
 9915        .into_iter()
 9916        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9917        .collect::<Vec<_>>();
 9918
 9919    // If multiple windows have unsaved changes, and need a save prompt,
 9920    // prompt in the active window before switching to a different window.
 9921    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9922
 9923    let mut prompt = None;
 9924    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9925        prompt = window
 9926            .update(cx, |_, window, cx| {
 9927                window.prompt(
 9928                    PromptLevel::Info,
 9929                    "Are you sure you want to restart?",
 9930                    None,
 9931                    &["Restart", "Cancel"],
 9932                    cx,
 9933                )
 9934            })
 9935            .ok();
 9936    }
 9937
 9938    cx.spawn(async move |cx| {
 9939        if let Some(prompt) = prompt {
 9940            let answer = prompt.await?;
 9941            if answer != 0 {
 9942                return anyhow::Ok(());
 9943            }
 9944        }
 9945
 9946        // If the user cancels any save prompt, then keep the app open.
 9947        for window in workspace_windows {
 9948            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9949                let workspace = multi_workspace.workspace().clone();
 9950                workspace.update(cx, |workspace, cx| {
 9951                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9952                })
 9953            }) && !should_close.await?
 9954            {
 9955                return anyhow::Ok(());
 9956            }
 9957        }
 9958        cx.update(|cx| cx.restart());
 9959        anyhow::Ok(())
 9960    })
 9961    .detach_and_log_err(cx);
 9962}
 9963
 9964fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9965    let mut parts = value.split(',');
 9966    let x: usize = parts.next()?.parse().ok()?;
 9967    let y: usize = parts.next()?.parse().ok()?;
 9968    Some(point(px(x as f32), px(y as f32)))
 9969}
 9970
 9971fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9972    let mut parts = value.split(',');
 9973    let width: usize = parts.next()?.parse().ok()?;
 9974    let height: usize = parts.next()?.parse().ok()?;
 9975    Some(size(px(width as f32), px(height as f32)))
 9976}
 9977
 9978/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9979/// appropriate.
 9980///
 9981/// The `border_radius_tiling` parameter allows overriding which corners get
 9982/// rounded, independently of the actual window tiling state. This is used
 9983/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9984/// we want square corners on the left (so the sidebar appears flush with the
 9985/// window edge) but we still need the shadow padding for proper visual
 9986/// appearance. Unlike actual window tiling, this only affects border radius -
 9987/// not padding or shadows.
 9988pub fn client_side_decorations(
 9989    element: impl IntoElement,
 9990    window: &mut Window,
 9991    cx: &mut App,
 9992    border_radius_tiling: Tiling,
 9993) -> Stateful<Div> {
 9994    const BORDER_SIZE: Pixels = px(1.0);
 9995    let decorations = window.window_decorations();
 9996    let tiling = match decorations {
 9997        Decorations::Server => Tiling::default(),
 9998        Decorations::Client { tiling } => tiling,
 9999    };
10000
10001    match decorations {
10002        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10003        Decorations::Server => window.set_client_inset(px(0.0)),
10004    }
10005
10006    struct GlobalResizeEdge(ResizeEdge);
10007    impl Global for GlobalResizeEdge {}
10008
10009    div()
10010        .id("window-backdrop")
10011        .bg(transparent_black())
10012        .map(|div| match decorations {
10013            Decorations::Server => div,
10014            Decorations::Client { .. } => div
10015                .when(
10016                    !(tiling.top
10017                        || tiling.right
10018                        || border_radius_tiling.top
10019                        || border_radius_tiling.right),
10020                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10021                )
10022                .when(
10023                    !(tiling.top
10024                        || tiling.left
10025                        || border_radius_tiling.top
10026                        || border_radius_tiling.left),
10027                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10028                )
10029                .when(
10030                    !(tiling.bottom
10031                        || tiling.right
10032                        || border_radius_tiling.bottom
10033                        || border_radius_tiling.right),
10034                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10035                )
10036                .when(
10037                    !(tiling.bottom
10038                        || tiling.left
10039                        || border_radius_tiling.bottom
10040                        || border_radius_tiling.left),
10041                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10042                )
10043                .when(!tiling.top, |div| {
10044                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10045                })
10046                .when(!tiling.bottom, |div| {
10047                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10048                })
10049                .when(!tiling.left, |div| {
10050                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10051                })
10052                .when(!tiling.right, |div| {
10053                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10054                })
10055                .on_mouse_move(move |e, window, cx| {
10056                    let size = window.window_bounds().get_bounds().size;
10057                    let pos = e.position;
10058
10059                    let new_edge =
10060                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10061
10062                    let edge = cx.try_global::<GlobalResizeEdge>();
10063                    if new_edge != edge.map(|edge| edge.0) {
10064                        window
10065                            .window_handle()
10066                            .update(cx, |workspace, _, cx| {
10067                                cx.notify(workspace.entity_id());
10068                            })
10069                            .ok();
10070                    }
10071                })
10072                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10073                    let size = window.window_bounds().get_bounds().size;
10074                    let pos = e.position;
10075
10076                    let edge = match resize_edge(
10077                        pos,
10078                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10079                        size,
10080                        tiling,
10081                    ) {
10082                        Some(value) => value,
10083                        None => return,
10084                    };
10085
10086                    window.start_window_resize(edge);
10087                }),
10088        })
10089        .size_full()
10090        .child(
10091            div()
10092                .cursor(CursorStyle::Arrow)
10093                .map(|div| match decorations {
10094                    Decorations::Server => div,
10095                    Decorations::Client { .. } => div
10096                        .border_color(cx.theme().colors().border)
10097                        .when(
10098                            !(tiling.top
10099                                || tiling.right
10100                                || border_radius_tiling.top
10101                                || border_radius_tiling.right),
10102                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10103                        )
10104                        .when(
10105                            !(tiling.top
10106                                || tiling.left
10107                                || border_radius_tiling.top
10108                                || border_radius_tiling.left),
10109                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10110                        )
10111                        .when(
10112                            !(tiling.bottom
10113                                || tiling.right
10114                                || border_radius_tiling.bottom
10115                                || border_radius_tiling.right),
10116                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10117                        )
10118                        .when(
10119                            !(tiling.bottom
10120                                || tiling.left
10121                                || border_radius_tiling.bottom
10122                                || border_radius_tiling.left),
10123                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10124                        )
10125                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10126                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10127                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10128                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10129                        .when(!tiling.is_tiled(), |div| {
10130                            div.shadow(vec![gpui::BoxShadow {
10131                                color: Hsla {
10132                                    h: 0.,
10133                                    s: 0.,
10134                                    l: 0.,
10135                                    a: 0.4,
10136                                },
10137                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10138                                spread_radius: px(0.),
10139                                offset: point(px(0.0), px(0.0)),
10140                            }])
10141                        }),
10142                })
10143                .on_mouse_move(|_e, _, cx| {
10144                    cx.stop_propagation();
10145                })
10146                .size_full()
10147                .child(element),
10148        )
10149        .map(|div| match decorations {
10150            Decorations::Server => div,
10151            Decorations::Client { tiling, .. } => div.child(
10152                canvas(
10153                    |_bounds, window, _| {
10154                        window.insert_hitbox(
10155                            Bounds::new(
10156                                point(px(0.0), px(0.0)),
10157                                window.window_bounds().get_bounds().size,
10158                            ),
10159                            HitboxBehavior::Normal,
10160                        )
10161                    },
10162                    move |_bounds, hitbox, window, cx| {
10163                        let mouse = window.mouse_position();
10164                        let size = window.window_bounds().get_bounds().size;
10165                        let Some(edge) =
10166                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10167                        else {
10168                            return;
10169                        };
10170                        cx.set_global(GlobalResizeEdge(edge));
10171                        window.set_cursor_style(
10172                            match edge {
10173                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10174                                ResizeEdge::Left | ResizeEdge::Right => {
10175                                    CursorStyle::ResizeLeftRight
10176                                }
10177                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10178                                    CursorStyle::ResizeUpLeftDownRight
10179                                }
10180                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10181                                    CursorStyle::ResizeUpRightDownLeft
10182                                }
10183                            },
10184                            &hitbox,
10185                        );
10186                    },
10187                )
10188                .size_full()
10189                .absolute(),
10190            ),
10191        })
10192}
10193
10194fn resize_edge(
10195    pos: Point<Pixels>,
10196    shadow_size: Pixels,
10197    window_size: Size<Pixels>,
10198    tiling: Tiling,
10199) -> Option<ResizeEdge> {
10200    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10201    if bounds.contains(&pos) {
10202        return None;
10203    }
10204
10205    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10206    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10207    if !tiling.top && top_left_bounds.contains(&pos) {
10208        return Some(ResizeEdge::TopLeft);
10209    }
10210
10211    let top_right_bounds = Bounds::new(
10212        Point::new(window_size.width - corner_size.width, px(0.)),
10213        corner_size,
10214    );
10215    if !tiling.top && top_right_bounds.contains(&pos) {
10216        return Some(ResizeEdge::TopRight);
10217    }
10218
10219    let bottom_left_bounds = Bounds::new(
10220        Point::new(px(0.), window_size.height - corner_size.height),
10221        corner_size,
10222    );
10223    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10224        return Some(ResizeEdge::BottomLeft);
10225    }
10226
10227    let bottom_right_bounds = Bounds::new(
10228        Point::new(
10229            window_size.width - corner_size.width,
10230            window_size.height - corner_size.height,
10231        ),
10232        corner_size,
10233    );
10234    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10235        return Some(ResizeEdge::BottomRight);
10236    }
10237
10238    if !tiling.top && pos.y < shadow_size {
10239        Some(ResizeEdge::Top)
10240    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10241        Some(ResizeEdge::Bottom)
10242    } else if !tiling.left && pos.x < shadow_size {
10243        Some(ResizeEdge::Left)
10244    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10245        Some(ResizeEdge::Right)
10246    } else {
10247        None
10248    }
10249}
10250
10251fn join_pane_into_active(
10252    active_pane: &Entity<Pane>,
10253    pane: &Entity<Pane>,
10254    window: &mut Window,
10255    cx: &mut App,
10256) {
10257    if pane == active_pane {
10258    } else if pane.read(cx).items_len() == 0 {
10259        pane.update(cx, |_, cx| {
10260            cx.emit(pane::Event::Remove {
10261                focus_on_pane: None,
10262            });
10263        })
10264    } else {
10265        move_all_items(pane, active_pane, window, cx);
10266    }
10267}
10268
10269fn move_all_items(
10270    from_pane: &Entity<Pane>,
10271    to_pane: &Entity<Pane>,
10272    window: &mut Window,
10273    cx: &mut App,
10274) {
10275    let destination_is_different = from_pane != to_pane;
10276    let mut moved_items = 0;
10277    for (item_ix, item_handle) in from_pane
10278        .read(cx)
10279        .items()
10280        .enumerate()
10281        .map(|(ix, item)| (ix, item.clone()))
10282        .collect::<Vec<_>>()
10283    {
10284        let ix = item_ix - moved_items;
10285        if destination_is_different {
10286            // Close item from previous pane
10287            from_pane.update(cx, |source, cx| {
10288                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10289            });
10290            moved_items += 1;
10291        }
10292
10293        // This automatically removes duplicate items in the pane
10294        to_pane.update(cx, |destination, cx| {
10295            destination.add_item(item_handle, true, true, None, window, cx);
10296            window.focus(&destination.focus_handle(cx), cx)
10297        });
10298    }
10299}
10300
10301pub fn move_item(
10302    source: &Entity<Pane>,
10303    destination: &Entity<Pane>,
10304    item_id_to_move: EntityId,
10305    destination_index: usize,
10306    activate: bool,
10307    window: &mut Window,
10308    cx: &mut App,
10309) {
10310    let Some((item_ix, item_handle)) = source
10311        .read(cx)
10312        .items()
10313        .enumerate()
10314        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10315        .map(|(ix, item)| (ix, item.clone()))
10316    else {
10317        // Tab was closed during drag
10318        return;
10319    };
10320
10321    if source != destination {
10322        // Close item from previous pane
10323        source.update(cx, |source, cx| {
10324            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10325        });
10326    }
10327
10328    // This automatically removes duplicate items in the pane
10329    destination.update(cx, |destination, cx| {
10330        destination.add_item_inner(
10331            item_handle,
10332            activate,
10333            activate,
10334            activate,
10335            Some(destination_index),
10336            window,
10337            cx,
10338        );
10339        if activate {
10340            window.focus(&destination.focus_handle(cx), cx)
10341        }
10342    });
10343}
10344
10345pub fn move_active_item(
10346    source: &Entity<Pane>,
10347    destination: &Entity<Pane>,
10348    focus_destination: bool,
10349    close_if_empty: bool,
10350    window: &mut Window,
10351    cx: &mut App,
10352) {
10353    if source == destination {
10354        return;
10355    }
10356    let Some(active_item) = source.read(cx).active_item() else {
10357        return;
10358    };
10359    source.update(cx, |source_pane, cx| {
10360        let item_id = active_item.item_id();
10361        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10362        destination.update(cx, |target_pane, cx| {
10363            target_pane.add_item(
10364                active_item,
10365                focus_destination,
10366                focus_destination,
10367                Some(target_pane.items_len()),
10368                window,
10369                cx,
10370            );
10371        });
10372    });
10373}
10374
10375pub fn clone_active_item(
10376    workspace_id: Option<WorkspaceId>,
10377    source: &Entity<Pane>,
10378    destination: &Entity<Pane>,
10379    focus_destination: bool,
10380    window: &mut Window,
10381    cx: &mut App,
10382) {
10383    if source == destination {
10384        return;
10385    }
10386    let Some(active_item) = source.read(cx).active_item() else {
10387        return;
10388    };
10389    if !active_item.can_split(cx) {
10390        return;
10391    }
10392    let destination = destination.downgrade();
10393    let task = active_item.clone_on_split(workspace_id, window, cx);
10394    window
10395        .spawn(cx, async move |cx| {
10396            let Some(clone) = task.await else {
10397                return;
10398            };
10399            destination
10400                .update_in(cx, |target_pane, window, cx| {
10401                    target_pane.add_item(
10402                        clone,
10403                        focus_destination,
10404                        focus_destination,
10405                        Some(target_pane.items_len()),
10406                        window,
10407                        cx,
10408                    );
10409                })
10410                .log_err();
10411        })
10412        .detach();
10413}
10414
10415#[derive(Debug)]
10416pub struct WorkspacePosition {
10417    pub window_bounds: Option<WindowBounds>,
10418    pub display: Option<Uuid>,
10419    pub centered_layout: bool,
10420}
10421
10422pub fn remote_workspace_position_from_db(
10423    connection_options: RemoteConnectionOptions,
10424    paths_to_open: &[PathBuf],
10425    cx: &App,
10426) -> Task<Result<WorkspacePosition>> {
10427    let paths = paths_to_open.to_vec();
10428    let db = WorkspaceDb::global(cx);
10429    let kvp = db::kvp::KeyValueStore::global(cx);
10430
10431    cx.background_spawn(async move {
10432        let remote_connection_id = db
10433            .get_or_create_remote_connection(connection_options)
10434            .await
10435            .context("fetching serialized ssh project")?;
10436        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10437
10438        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10439            (Some(WindowBounds::Windowed(bounds)), None)
10440        } else {
10441            let restorable_bounds = serialized_workspace
10442                .as_ref()
10443                .and_then(|workspace| {
10444                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10445                })
10446                .or_else(|| persistence::read_default_window_bounds(&kvp));
10447
10448            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10449                (Some(serialized_bounds), Some(serialized_display))
10450            } else {
10451                (None, None)
10452            }
10453        };
10454
10455        let centered_layout = serialized_workspace
10456            .as_ref()
10457            .map(|w| w.centered_layout)
10458            .unwrap_or(false);
10459
10460        Ok(WorkspacePosition {
10461            window_bounds,
10462            display,
10463            centered_layout,
10464        })
10465    })
10466}
10467
10468pub fn with_active_or_new_workspace(
10469    cx: &mut App,
10470    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10471) {
10472    match cx
10473        .active_window()
10474        .and_then(|w| w.downcast::<MultiWorkspace>())
10475    {
10476        Some(multi_workspace) => {
10477            cx.defer(move |cx| {
10478                multi_workspace
10479                    .update(cx, |multi_workspace, window, cx| {
10480                        let workspace = multi_workspace.workspace().clone();
10481                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10482                    })
10483                    .log_err();
10484            });
10485        }
10486        None => {
10487            let app_state = AppState::global(cx);
10488            open_new(
10489                OpenOptions::default(),
10490                app_state,
10491                cx,
10492                move |workspace, window, cx| f(workspace, window, cx),
10493            )
10494            .detach_and_log_err(cx);
10495        }
10496    }
10497}
10498
10499/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10500/// key. This migration path only runs once per panel per workspace.
10501fn load_legacy_panel_size(
10502    panel_key: &str,
10503    dock_position: DockPosition,
10504    workspace: &Workspace,
10505    cx: &mut App,
10506) -> Option<Pixels> {
10507    #[derive(Deserialize)]
10508    struct LegacyPanelState {
10509        #[serde(default)]
10510        width: Option<Pixels>,
10511        #[serde(default)]
10512        height: Option<Pixels>,
10513    }
10514
10515    let workspace_id = workspace
10516        .database_id()
10517        .map(|id| i64::from(id).to_string())
10518        .or_else(|| workspace.session_id())?;
10519
10520    let legacy_key = match panel_key {
10521        "ProjectPanel" => {
10522            format!("{}-{:?}", "ProjectPanel", workspace_id)
10523        }
10524        "OutlinePanel" => {
10525            format!("{}-{:?}", "OutlinePanel", workspace_id)
10526        }
10527        "GitPanel" => {
10528            format!("{}-{:?}", "GitPanel", workspace_id)
10529        }
10530        "TerminalPanel" => {
10531            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10532        }
10533        _ => return None,
10534    };
10535
10536    let kvp = db::kvp::KeyValueStore::global(cx);
10537    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10538    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10539    let size = match dock_position {
10540        DockPosition::Bottom => state.height,
10541        DockPosition::Left | DockPosition::Right => state.width,
10542    }?;
10543
10544    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10545        .detach_and_log_err(cx);
10546
10547    Some(size)
10548}
10549
10550#[cfg(test)]
10551mod tests {
10552    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10553
10554    use super::*;
10555    use crate::{
10556        dock::{PanelEvent, test::TestPanel},
10557        item::{
10558            ItemBufferKind, ItemEvent,
10559            test::{TestItem, TestProjectItem},
10560        },
10561    };
10562    use fs::FakeFs;
10563    use gpui::{
10564        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10565        UpdateGlobal, VisualTestContext, px,
10566    };
10567    use project::{Project, ProjectEntryId};
10568    use serde_json::json;
10569    use settings::SettingsStore;
10570    use util::path;
10571    use util::rel_path::rel_path;
10572
10573    #[gpui::test]
10574    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10575        init_test(cx);
10576
10577        let fs = FakeFs::new(cx.executor());
10578        let project = Project::test(fs, [], cx).await;
10579        let (workspace, cx) =
10580            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10581
10582        // Adding an item with no ambiguity renders the tab without detail.
10583        let item1 = cx.new(|cx| {
10584            let mut item = TestItem::new(cx);
10585            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10586            item
10587        });
10588        workspace.update_in(cx, |workspace, window, cx| {
10589            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10590        });
10591        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10592
10593        // Adding an item that creates ambiguity increases the level of detail on
10594        // both tabs.
10595        let item2 = cx.new_window_entity(|_window, cx| {
10596            let mut item = TestItem::new(cx);
10597            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10598            item
10599        });
10600        workspace.update_in(cx, |workspace, window, cx| {
10601            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10602        });
10603        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10604        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10605
10606        // Adding an item that creates ambiguity increases the level of detail only
10607        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10608        // we stop at the highest detail available.
10609        let item3 = cx.new(|cx| {
10610            let mut item = TestItem::new(cx);
10611            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10612            item
10613        });
10614        workspace.update_in(cx, |workspace, window, cx| {
10615            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10616        });
10617        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10618        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10619        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10620    }
10621
10622    #[gpui::test]
10623    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10624        init_test(cx);
10625
10626        let fs = FakeFs::new(cx.executor());
10627        fs.insert_tree(
10628            "/root1",
10629            json!({
10630                "one.txt": "",
10631                "two.txt": "",
10632            }),
10633        )
10634        .await;
10635        fs.insert_tree(
10636            "/root2",
10637            json!({
10638                "three.txt": "",
10639            }),
10640        )
10641        .await;
10642
10643        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10644        let (workspace, cx) =
10645            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10646        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10647        let worktree_id = project.update(cx, |project, cx| {
10648            project.worktrees(cx).next().unwrap().read(cx).id()
10649        });
10650
10651        let item1 = cx.new(|cx| {
10652            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10653        });
10654        let item2 = cx.new(|cx| {
10655            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10656        });
10657
10658        // Add an item to an empty pane
10659        workspace.update_in(cx, |workspace, window, cx| {
10660            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10661        });
10662        project.update(cx, |project, cx| {
10663            assert_eq!(
10664                project.active_entry(),
10665                project
10666                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10667                    .map(|e| e.id)
10668            );
10669        });
10670        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10671
10672        // Add a second item to a non-empty pane
10673        workspace.update_in(cx, |workspace, window, cx| {
10674            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10675        });
10676        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10677        project.update(cx, |project, cx| {
10678            assert_eq!(
10679                project.active_entry(),
10680                project
10681                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10682                    .map(|e| e.id)
10683            );
10684        });
10685
10686        // Close the active item
10687        pane.update_in(cx, |pane, window, cx| {
10688            pane.close_active_item(&Default::default(), window, cx)
10689        })
10690        .await
10691        .unwrap();
10692        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10693        project.update(cx, |project, cx| {
10694            assert_eq!(
10695                project.active_entry(),
10696                project
10697                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10698                    .map(|e| e.id)
10699            );
10700        });
10701
10702        // Add a project folder
10703        project
10704            .update(cx, |project, cx| {
10705                project.find_or_create_worktree("root2", true, cx)
10706            })
10707            .await
10708            .unwrap();
10709        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10710
10711        // Remove a project folder
10712        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10713        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10714    }
10715
10716    #[gpui::test]
10717    async fn test_close_window(cx: &mut TestAppContext) {
10718        init_test(cx);
10719
10720        let fs = FakeFs::new(cx.executor());
10721        fs.insert_tree("/root", json!({ "one": "" })).await;
10722
10723        let project = Project::test(fs, ["root".as_ref()], cx).await;
10724        let (workspace, cx) =
10725            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10726
10727        // When there are no dirty items, there's nothing to do.
10728        let item1 = cx.new(TestItem::new);
10729        workspace.update_in(cx, |w, window, cx| {
10730            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10731        });
10732        let task = workspace.update_in(cx, |w, window, cx| {
10733            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10734        });
10735        assert!(task.await.unwrap());
10736
10737        // When there are dirty untitled items, prompt to save each one. If the user
10738        // cancels any prompt, then abort.
10739        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10740        let item3 = cx.new(|cx| {
10741            TestItem::new(cx)
10742                .with_dirty(true)
10743                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10744        });
10745        workspace.update_in(cx, |w, window, cx| {
10746            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10747            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10748        });
10749        let task = workspace.update_in(cx, |w, window, cx| {
10750            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10751        });
10752        cx.executor().run_until_parked();
10753        cx.simulate_prompt_answer("Cancel"); // cancel save all
10754        cx.executor().run_until_parked();
10755        assert!(!cx.has_pending_prompt());
10756        assert!(!task.await.unwrap());
10757    }
10758
10759    #[gpui::test]
10760    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10761        init_test(cx);
10762
10763        let fs = FakeFs::new(cx.executor());
10764        fs.insert_tree("/root", json!({ "one": "" })).await;
10765
10766        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10767        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10768        let multi_workspace_handle =
10769            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10770        cx.run_until_parked();
10771
10772        let workspace_a = multi_workspace_handle
10773            .read_with(cx, |mw, _| mw.workspace().clone())
10774            .unwrap();
10775
10776        let workspace_b = multi_workspace_handle
10777            .update(cx, |mw, window, cx| {
10778                mw.test_add_workspace(project_b, window, cx)
10779            })
10780            .unwrap();
10781
10782        // Activate workspace A
10783        multi_workspace_handle
10784            .update(cx, |mw, window, cx| {
10785                let workspace = mw
10786                    .workspaces()
10787                    .nth(0)
10788                    .expect("no workspace at index 0")
10789                    .clone();
10790                mw.activate(workspace, window, cx);
10791            })
10792            .unwrap();
10793
10794        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10795
10796        // Workspace A has a clean item
10797        let item_a = cx.new(TestItem::new);
10798        workspace_a.update_in(cx, |w, window, cx| {
10799            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10800        });
10801
10802        // Workspace B has a dirty item
10803        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10804        workspace_b.update_in(cx, |w, window, cx| {
10805            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10806        });
10807
10808        // Verify workspace A is active
10809        multi_workspace_handle
10810            .read_with(cx, |mw, _| {
10811                assert_eq!(
10812                    mw.workspaces()
10813                        .position(|workspace| workspace == mw.active_workspace()),
10814                    Some(0)
10815                );
10816            })
10817            .unwrap();
10818
10819        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10820        multi_workspace_handle
10821            .update(cx, |mw, window, cx| {
10822                mw.close_window(&CloseWindow, window, cx);
10823            })
10824            .unwrap();
10825        cx.run_until_parked();
10826
10827        // Workspace B should now be active since it has dirty items that need attention
10828        multi_workspace_handle
10829            .read_with(cx, |mw, _| {
10830                assert_eq!(
10831                    mw.workspaces()
10832                        .position(|workspace| workspace == mw.active_workspace()),
10833                    Some(1),
10834                    "workspace B should be activated when it prompts"
10835                );
10836            })
10837            .unwrap();
10838
10839        // User cancels the save prompt from workspace B
10840        cx.simulate_prompt_answer("Cancel");
10841        cx.run_until_parked();
10842
10843        // Window should still exist because workspace B's close was cancelled
10844        assert!(
10845            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10846            "window should still exist after cancelling one workspace's close"
10847        );
10848    }
10849
10850    #[gpui::test]
10851    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10852        init_test(cx);
10853
10854        // Register TestItem as a serializable item
10855        cx.update(|cx| {
10856            register_serializable_item::<TestItem>(cx);
10857        });
10858
10859        let fs = FakeFs::new(cx.executor());
10860        fs.insert_tree("/root", json!({ "one": "" })).await;
10861
10862        let project = Project::test(fs, ["root".as_ref()], cx).await;
10863        let (workspace, cx) =
10864            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10865
10866        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10867        let item1 = cx.new(|cx| {
10868            TestItem::new(cx)
10869                .with_dirty(true)
10870                .with_serialize(|| Some(Task::ready(Ok(()))))
10871        });
10872        let item2 = cx.new(|cx| {
10873            TestItem::new(cx)
10874                .with_dirty(true)
10875                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10876                .with_serialize(|| Some(Task::ready(Ok(()))))
10877        });
10878        workspace.update_in(cx, |w, window, cx| {
10879            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10880            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10881        });
10882        let task = workspace.update_in(cx, |w, window, cx| {
10883            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10884        });
10885        assert!(task.await.unwrap());
10886    }
10887
10888    #[gpui::test]
10889    async fn test_close_pane_items(cx: &mut TestAppContext) {
10890        init_test(cx);
10891
10892        let fs = FakeFs::new(cx.executor());
10893
10894        let project = Project::test(fs, None, cx).await;
10895        let (workspace, cx) =
10896            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10897
10898        let item1 = cx.new(|cx| {
10899            TestItem::new(cx)
10900                .with_dirty(true)
10901                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10902        });
10903        let item2 = cx.new(|cx| {
10904            TestItem::new(cx)
10905                .with_dirty(true)
10906                .with_conflict(true)
10907                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10908        });
10909        let item3 = cx.new(|cx| {
10910            TestItem::new(cx)
10911                .with_dirty(true)
10912                .with_conflict(true)
10913                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10914        });
10915        let item4 = cx.new(|cx| {
10916            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10917                let project_item = TestProjectItem::new_untitled(cx);
10918                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10919                project_item
10920            }])
10921        });
10922        let pane = workspace.update_in(cx, |workspace, window, cx| {
10923            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10924            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10925            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10926            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10927            workspace.active_pane().clone()
10928        });
10929
10930        let close_items = pane.update_in(cx, |pane, window, cx| {
10931            pane.activate_item(1, true, true, window, cx);
10932            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10933            let item1_id = item1.item_id();
10934            let item3_id = item3.item_id();
10935            let item4_id = item4.item_id();
10936            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10937                [item1_id, item3_id, item4_id].contains(&id)
10938            })
10939        });
10940        cx.executor().run_until_parked();
10941
10942        assert!(cx.has_pending_prompt());
10943        cx.simulate_prompt_answer("Save all");
10944
10945        cx.executor().run_until_parked();
10946
10947        // Item 1 is saved. There's a prompt to save item 3.
10948        pane.update(cx, |pane, cx| {
10949            assert_eq!(item1.read(cx).save_count, 1);
10950            assert_eq!(item1.read(cx).save_as_count, 0);
10951            assert_eq!(item1.read(cx).reload_count, 0);
10952            assert_eq!(pane.items_len(), 3);
10953            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10954        });
10955        assert!(cx.has_pending_prompt());
10956
10957        // Cancel saving item 3.
10958        cx.simulate_prompt_answer("Discard");
10959        cx.executor().run_until_parked();
10960
10961        // Item 3 is reloaded. There's a prompt to save item 4.
10962        pane.update(cx, |pane, cx| {
10963            assert_eq!(item3.read(cx).save_count, 0);
10964            assert_eq!(item3.read(cx).save_as_count, 0);
10965            assert_eq!(item3.read(cx).reload_count, 1);
10966            assert_eq!(pane.items_len(), 2);
10967            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10968        });
10969
10970        // There's a prompt for a path for item 4.
10971        cx.simulate_new_path_selection(|_| Some(Default::default()));
10972        close_items.await.unwrap();
10973
10974        // The requested items are closed.
10975        pane.update(cx, |pane, cx| {
10976            assert_eq!(item4.read(cx).save_count, 0);
10977            assert_eq!(item4.read(cx).save_as_count, 1);
10978            assert_eq!(item4.read(cx).reload_count, 0);
10979            assert_eq!(pane.items_len(), 1);
10980            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10981        });
10982    }
10983
10984    #[gpui::test]
10985    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10986        init_test(cx);
10987
10988        let fs = FakeFs::new(cx.executor());
10989        let project = Project::test(fs, [], cx).await;
10990        let (workspace, cx) =
10991            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10992
10993        // Create several workspace items with single project entries, and two
10994        // workspace items with multiple project entries.
10995        let single_entry_items = (0..=4)
10996            .map(|project_entry_id| {
10997                cx.new(|cx| {
10998                    TestItem::new(cx)
10999                        .with_dirty(true)
11000                        .with_project_items(&[dirty_project_item(
11001                            project_entry_id,
11002                            &format!("{project_entry_id}.txt"),
11003                            cx,
11004                        )])
11005                })
11006            })
11007            .collect::<Vec<_>>();
11008        let item_2_3 = cx.new(|cx| {
11009            TestItem::new(cx)
11010                .with_dirty(true)
11011                .with_buffer_kind(ItemBufferKind::Multibuffer)
11012                .with_project_items(&[
11013                    single_entry_items[2].read(cx).project_items[0].clone(),
11014                    single_entry_items[3].read(cx).project_items[0].clone(),
11015                ])
11016        });
11017        let item_3_4 = cx.new(|cx| {
11018            TestItem::new(cx)
11019                .with_dirty(true)
11020                .with_buffer_kind(ItemBufferKind::Multibuffer)
11021                .with_project_items(&[
11022                    single_entry_items[3].read(cx).project_items[0].clone(),
11023                    single_entry_items[4].read(cx).project_items[0].clone(),
11024                ])
11025        });
11026
11027        // Create two panes that contain the following project entries:
11028        //   left pane:
11029        //     multi-entry items:   (2, 3)
11030        //     single-entry items:  0, 2, 3, 4
11031        //   right pane:
11032        //     single-entry items:  4, 1
11033        //     multi-entry items:   (3, 4)
11034        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11035            let left_pane = workspace.active_pane().clone();
11036            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11037            workspace.add_item_to_active_pane(
11038                single_entry_items[0].boxed_clone(),
11039                None,
11040                true,
11041                window,
11042                cx,
11043            );
11044            workspace.add_item_to_active_pane(
11045                single_entry_items[2].boxed_clone(),
11046                None,
11047                true,
11048                window,
11049                cx,
11050            );
11051            workspace.add_item_to_active_pane(
11052                single_entry_items[3].boxed_clone(),
11053                None,
11054                true,
11055                window,
11056                cx,
11057            );
11058            workspace.add_item_to_active_pane(
11059                single_entry_items[4].boxed_clone(),
11060                None,
11061                true,
11062                window,
11063                cx,
11064            );
11065
11066            let right_pane =
11067                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11068
11069            let boxed_clone = single_entry_items[1].boxed_clone();
11070            let right_pane = window.spawn(cx, async move |cx| {
11071                right_pane.await.inspect(|right_pane| {
11072                    right_pane
11073                        .update_in(cx, |pane, window, cx| {
11074                            pane.add_item(boxed_clone, true, true, None, window, cx);
11075                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11076                        })
11077                        .unwrap();
11078                })
11079            });
11080
11081            (left_pane, right_pane)
11082        });
11083        let right_pane = right_pane.await.unwrap();
11084        cx.focus(&right_pane);
11085
11086        let close = right_pane.update_in(cx, |pane, window, cx| {
11087            pane.close_all_items(&CloseAllItems::default(), window, cx)
11088                .unwrap()
11089        });
11090        cx.executor().run_until_parked();
11091
11092        let msg = cx.pending_prompt().unwrap().0;
11093        assert!(msg.contains("1.txt"));
11094        assert!(!msg.contains("2.txt"));
11095        assert!(!msg.contains("3.txt"));
11096        assert!(!msg.contains("4.txt"));
11097
11098        // With best-effort close, cancelling item 1 keeps it open but items 4
11099        // and (3,4) still close since their entries exist in left pane.
11100        cx.simulate_prompt_answer("Cancel");
11101        close.await;
11102
11103        right_pane.read_with(cx, |pane, _| {
11104            assert_eq!(pane.items_len(), 1);
11105        });
11106
11107        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11108        left_pane
11109            .update_in(cx, |left_pane, window, cx| {
11110                left_pane.close_item_by_id(
11111                    single_entry_items[3].entity_id(),
11112                    SaveIntent::Skip,
11113                    window,
11114                    cx,
11115                )
11116            })
11117            .await
11118            .unwrap();
11119
11120        let close = left_pane.update_in(cx, |pane, window, cx| {
11121            pane.close_all_items(&CloseAllItems::default(), window, cx)
11122                .unwrap()
11123        });
11124        cx.executor().run_until_parked();
11125
11126        let details = cx.pending_prompt().unwrap().1;
11127        assert!(details.contains("0.txt"));
11128        assert!(details.contains("3.txt"));
11129        assert!(details.contains("4.txt"));
11130        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11131        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11132        // assert!(!details.contains("2.txt"));
11133
11134        cx.simulate_prompt_answer("Save all");
11135        cx.executor().run_until_parked();
11136        close.await;
11137
11138        left_pane.read_with(cx, |pane, _| {
11139            assert_eq!(pane.items_len(), 0);
11140        });
11141    }
11142
11143    #[gpui::test]
11144    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11145        init_test(cx);
11146
11147        let fs = FakeFs::new(cx.executor());
11148        let project = Project::test(fs, [], cx).await;
11149        let (workspace, cx) =
11150            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11151        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11152
11153        let item = cx.new(|cx| {
11154            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11155        });
11156        let item_id = item.entity_id();
11157        workspace.update_in(cx, |workspace, window, cx| {
11158            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11159        });
11160
11161        // Autosave on window change.
11162        item.update(cx, |item, cx| {
11163            SettingsStore::update_global(cx, |settings, cx| {
11164                settings.update_user_settings(cx, |settings| {
11165                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11166                })
11167            });
11168            item.is_dirty = true;
11169        });
11170
11171        // Deactivating the window saves the file.
11172        cx.deactivate_window();
11173        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11174
11175        // Re-activating the window doesn't save the file.
11176        cx.update(|window, _| window.activate_window());
11177        cx.executor().run_until_parked();
11178        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11179
11180        // Autosave on focus change.
11181        item.update_in(cx, |item, window, cx| {
11182            cx.focus_self(window);
11183            SettingsStore::update_global(cx, |settings, cx| {
11184                settings.update_user_settings(cx, |settings| {
11185                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11186                })
11187            });
11188            item.is_dirty = true;
11189        });
11190        // Blurring the item saves the file.
11191        item.update_in(cx, |_, window, _| window.blur());
11192        cx.executor().run_until_parked();
11193        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11194
11195        // Deactivating the window still saves the file.
11196        item.update_in(cx, |item, window, cx| {
11197            cx.focus_self(window);
11198            item.is_dirty = true;
11199        });
11200        cx.deactivate_window();
11201        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11202
11203        // Autosave after delay.
11204        item.update(cx, |item, cx| {
11205            SettingsStore::update_global(cx, |settings, cx| {
11206                settings.update_user_settings(cx, |settings| {
11207                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11208                        milliseconds: 500.into(),
11209                    });
11210                })
11211            });
11212            item.is_dirty = true;
11213            cx.emit(ItemEvent::Edit);
11214        });
11215
11216        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11217        cx.executor().advance_clock(Duration::from_millis(250));
11218        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11219
11220        // After delay expires, the file is saved.
11221        cx.executor().advance_clock(Duration::from_millis(250));
11222        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11223
11224        // Autosave after delay, should save earlier than delay if tab is closed
11225        item.update(cx, |item, cx| {
11226            item.is_dirty = true;
11227            cx.emit(ItemEvent::Edit);
11228        });
11229        cx.executor().advance_clock(Duration::from_millis(250));
11230        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11231
11232        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11233        pane.update_in(cx, |pane, window, cx| {
11234            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11235        })
11236        .await
11237        .unwrap();
11238        assert!(!cx.has_pending_prompt());
11239        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11240
11241        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11242        workspace.update_in(cx, |workspace, window, cx| {
11243            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11244        });
11245        item.update_in(cx, |item, _window, cx| {
11246            item.is_dirty = true;
11247            for project_item in &mut item.project_items {
11248                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11249            }
11250        });
11251        cx.run_until_parked();
11252        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11253
11254        // Autosave on focus change, ensuring closing the tab counts as such.
11255        item.update(cx, |item, cx| {
11256            SettingsStore::update_global(cx, |settings, cx| {
11257                settings.update_user_settings(cx, |settings| {
11258                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11259                })
11260            });
11261            item.is_dirty = true;
11262            for project_item in &mut item.project_items {
11263                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11264            }
11265        });
11266
11267        pane.update_in(cx, |pane, window, cx| {
11268            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11269        })
11270        .await
11271        .unwrap();
11272        assert!(!cx.has_pending_prompt());
11273        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11274
11275        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11276        workspace.update_in(cx, |workspace, window, cx| {
11277            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11278        });
11279        item.update_in(cx, |item, window, cx| {
11280            item.project_items[0].update(cx, |item, _| {
11281                item.entry_id = None;
11282            });
11283            item.is_dirty = true;
11284            window.blur();
11285        });
11286        cx.run_until_parked();
11287        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11288
11289        // Ensure autosave is prevented for deleted files also when closing the buffer.
11290        let _close_items = pane.update_in(cx, |pane, window, cx| {
11291            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11292        });
11293        cx.run_until_parked();
11294        assert!(cx.has_pending_prompt());
11295        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11296    }
11297
11298    #[gpui::test]
11299    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11300        init_test(cx);
11301
11302        let fs = FakeFs::new(cx.executor());
11303        let project = Project::test(fs, [], cx).await;
11304        let (workspace, cx) =
11305            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11306
11307        // Create a multibuffer-like item with two child focus handles,
11308        // simulating individual buffer editors within a multibuffer.
11309        let item = cx.new(|cx| {
11310            TestItem::new(cx)
11311                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11312                .with_child_focus_handles(2, cx)
11313        });
11314        workspace.update_in(cx, |workspace, window, cx| {
11315            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11316        });
11317
11318        // Set autosave to OnFocusChange and focus the first child handle,
11319        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11320        item.update_in(cx, |item, window, cx| {
11321            SettingsStore::update_global(cx, |settings, cx| {
11322                settings.update_user_settings(cx, |settings| {
11323                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11324                })
11325            });
11326            item.is_dirty = true;
11327            window.focus(&item.child_focus_handles[0], cx);
11328        });
11329        cx.executor().run_until_parked();
11330        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11331
11332        // Moving focus from one child to another within the same item should
11333        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11334        item.update_in(cx, |item, window, cx| {
11335            window.focus(&item.child_focus_handles[1], cx);
11336        });
11337        cx.executor().run_until_parked();
11338        item.read_with(cx, |item, _| {
11339            assert_eq!(
11340                item.save_count, 0,
11341                "Switching focus between children within the same item should not autosave"
11342            );
11343        });
11344
11345        // Blurring the item saves the file. This is the core regression scenario:
11346        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11347        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11348        // the leaf is always a child focus handle, so `on_blur` never detected
11349        // focus leaving the item.
11350        item.update_in(cx, |_, window, _| window.blur());
11351        cx.executor().run_until_parked();
11352        item.read_with(cx, |item, _| {
11353            assert_eq!(
11354                item.save_count, 1,
11355                "Blurring should trigger autosave when focus was on a child of the item"
11356            );
11357        });
11358
11359        // Deactivating the window should also trigger autosave when a child of
11360        // the multibuffer item currently owns focus.
11361        item.update_in(cx, |item, window, cx| {
11362            item.is_dirty = true;
11363            window.focus(&item.child_focus_handles[0], cx);
11364        });
11365        cx.executor().run_until_parked();
11366        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11367
11368        cx.deactivate_window();
11369        item.read_with(cx, |item, _| {
11370            assert_eq!(
11371                item.save_count, 2,
11372                "Deactivating window should trigger autosave when focus was on a child"
11373            );
11374        });
11375    }
11376
11377    #[gpui::test]
11378    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11379        init_test(cx);
11380
11381        let fs = FakeFs::new(cx.executor());
11382
11383        let project = Project::test(fs, [], cx).await;
11384        let (workspace, cx) =
11385            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11386
11387        let item = cx.new(|cx| {
11388            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11389        });
11390        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11391        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11392        let toolbar_notify_count = Rc::new(RefCell::new(0));
11393
11394        workspace.update_in(cx, |workspace, window, cx| {
11395            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11396            let toolbar_notification_count = toolbar_notify_count.clone();
11397            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11398                *toolbar_notification_count.borrow_mut() += 1
11399            })
11400            .detach();
11401        });
11402
11403        pane.read_with(cx, |pane, _| {
11404            assert!(!pane.can_navigate_backward());
11405            assert!(!pane.can_navigate_forward());
11406        });
11407
11408        item.update_in(cx, |item, _, cx| {
11409            item.set_state("one".to_string(), cx);
11410        });
11411
11412        // Toolbar must be notified to re-render the navigation buttons
11413        assert_eq!(*toolbar_notify_count.borrow(), 1);
11414
11415        pane.read_with(cx, |pane, _| {
11416            assert!(pane.can_navigate_backward());
11417            assert!(!pane.can_navigate_forward());
11418        });
11419
11420        workspace
11421            .update_in(cx, |workspace, window, cx| {
11422                workspace.go_back(pane.downgrade(), window, cx)
11423            })
11424            .await
11425            .unwrap();
11426
11427        assert_eq!(*toolbar_notify_count.borrow(), 2);
11428        pane.read_with(cx, |pane, _| {
11429            assert!(!pane.can_navigate_backward());
11430            assert!(pane.can_navigate_forward());
11431        });
11432    }
11433
11434    /// Tests that the navigation history deduplicates entries for the same item.
11435    ///
11436    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11437    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11438    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11439    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11440    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11441    ///
11442    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11443    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11444    #[gpui::test]
11445    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11446        init_test(cx);
11447
11448        let fs = FakeFs::new(cx.executor());
11449        let project = Project::test(fs, [], cx).await;
11450        let (workspace, cx) =
11451            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11452
11453        let item_a = cx.new(|cx| {
11454            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11455        });
11456        let item_b = cx.new(|cx| {
11457            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11458        });
11459        let item_c = cx.new(|cx| {
11460            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11461        });
11462
11463        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11464
11465        workspace.update_in(cx, |workspace, window, cx| {
11466            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11467            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11468            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11469        });
11470
11471        workspace.update_in(cx, |workspace, window, cx| {
11472            workspace.activate_item(&item_a, false, false, window, cx);
11473        });
11474        cx.run_until_parked();
11475
11476        workspace.update_in(cx, |workspace, window, cx| {
11477            workspace.activate_item(&item_b, false, false, window, cx);
11478        });
11479        cx.run_until_parked();
11480
11481        workspace.update_in(cx, |workspace, window, cx| {
11482            workspace.activate_item(&item_a, false, false, window, cx);
11483        });
11484        cx.run_until_parked();
11485
11486        workspace.update_in(cx, |workspace, window, cx| {
11487            workspace.activate_item(&item_b, false, false, window, cx);
11488        });
11489        cx.run_until_parked();
11490
11491        workspace.update_in(cx, |workspace, window, cx| {
11492            workspace.activate_item(&item_a, false, false, window, cx);
11493        });
11494        cx.run_until_parked();
11495
11496        workspace.update_in(cx, |workspace, window, cx| {
11497            workspace.activate_item(&item_b, false, false, window, cx);
11498        });
11499        cx.run_until_parked();
11500
11501        workspace.update_in(cx, |workspace, window, cx| {
11502            workspace.activate_item(&item_c, false, false, window, cx);
11503        });
11504        cx.run_until_parked();
11505
11506        let backward_count = pane.read_with(cx, |pane, cx| {
11507            let mut count = 0;
11508            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11509                count += 1;
11510            });
11511            count
11512        });
11513        assert!(
11514            backward_count <= 4,
11515            "Should have at most 4 entries, got {}",
11516            backward_count
11517        );
11518
11519        workspace
11520            .update_in(cx, |workspace, window, cx| {
11521                workspace.go_back(pane.downgrade(), window, cx)
11522            })
11523            .await
11524            .unwrap();
11525
11526        let active_item = workspace.read_with(cx, |workspace, cx| {
11527            workspace.active_item(cx).unwrap().item_id()
11528        });
11529        assert_eq!(
11530            active_item,
11531            item_b.entity_id(),
11532            "After first go_back, should be at item B"
11533        );
11534
11535        workspace
11536            .update_in(cx, |workspace, window, cx| {
11537                workspace.go_back(pane.downgrade(), window, cx)
11538            })
11539            .await
11540            .unwrap();
11541
11542        let active_item = workspace.read_with(cx, |workspace, cx| {
11543            workspace.active_item(cx).unwrap().item_id()
11544        });
11545        assert_eq!(
11546            active_item,
11547            item_a.entity_id(),
11548            "After second go_back, should be at item A"
11549        );
11550
11551        pane.read_with(cx, |pane, _| {
11552            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11553        });
11554    }
11555
11556    #[gpui::test]
11557    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11558        init_test(cx);
11559        let fs = FakeFs::new(cx.executor());
11560        let project = Project::test(fs, [], cx).await;
11561        let (multi_workspace, cx) =
11562            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11563        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11564
11565        workspace.update_in(cx, |workspace, window, cx| {
11566            let first_item = cx.new(|cx| {
11567                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11568            });
11569            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11570            workspace.split_pane(
11571                workspace.active_pane().clone(),
11572                SplitDirection::Right,
11573                window,
11574                cx,
11575            );
11576            workspace.split_pane(
11577                workspace.active_pane().clone(),
11578                SplitDirection::Right,
11579                window,
11580                cx,
11581            );
11582        });
11583
11584        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11585            let panes = workspace.center.panes();
11586            assert!(panes.len() >= 2);
11587            (
11588                panes.first().expect("at least one pane").entity_id(),
11589                panes.last().expect("at least one pane").entity_id(),
11590            )
11591        });
11592
11593        workspace.update_in(cx, |workspace, window, cx| {
11594            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11595        });
11596        workspace.update(cx, |workspace, _| {
11597            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11598            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11599        });
11600
11601        cx.dispatch_action(ActivateLastPane);
11602
11603        workspace.update(cx, |workspace, _| {
11604            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11605        });
11606    }
11607
11608    #[gpui::test]
11609    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11610        init_test(cx);
11611        let fs = FakeFs::new(cx.executor());
11612
11613        let project = Project::test(fs, [], cx).await;
11614        let (workspace, cx) =
11615            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11616
11617        let panel = workspace.update_in(cx, |workspace, window, cx| {
11618            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11619            workspace.add_panel(panel.clone(), window, cx);
11620
11621            workspace
11622                .right_dock()
11623                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11624
11625            panel
11626        });
11627
11628        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11629        pane.update_in(cx, |pane, window, cx| {
11630            let item = cx.new(TestItem::new);
11631            pane.add_item(Box::new(item), true, true, None, window, cx);
11632        });
11633
11634        // Transfer focus from center to panel
11635        workspace.update_in(cx, |workspace, window, cx| {
11636            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11637        });
11638
11639        workspace.update_in(cx, |workspace, window, cx| {
11640            assert!(workspace.right_dock().read(cx).is_open());
11641            assert!(!panel.is_zoomed(window, cx));
11642            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11643        });
11644
11645        // Transfer focus from panel to center
11646        workspace.update_in(cx, |workspace, window, cx| {
11647            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11648        });
11649
11650        workspace.update_in(cx, |workspace, window, cx| {
11651            assert!(workspace.right_dock().read(cx).is_open());
11652            assert!(!panel.is_zoomed(window, cx));
11653            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11654            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11655        });
11656
11657        // Close the dock
11658        workspace.update_in(cx, |workspace, window, cx| {
11659            workspace.toggle_dock(DockPosition::Right, window, cx);
11660        });
11661
11662        workspace.update_in(cx, |workspace, window, cx| {
11663            assert!(!workspace.right_dock().read(cx).is_open());
11664            assert!(!panel.is_zoomed(window, cx));
11665            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11666            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11667        });
11668
11669        // Open the dock
11670        workspace.update_in(cx, |workspace, window, cx| {
11671            workspace.toggle_dock(DockPosition::Right, window, cx);
11672        });
11673
11674        workspace.update_in(cx, |workspace, window, cx| {
11675            assert!(workspace.right_dock().read(cx).is_open());
11676            assert!(!panel.is_zoomed(window, cx));
11677            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11678        });
11679
11680        // Focus and zoom panel
11681        panel.update_in(cx, |panel, window, cx| {
11682            cx.focus_self(window);
11683            panel.set_zoomed(true, window, cx)
11684        });
11685
11686        workspace.update_in(cx, |workspace, window, cx| {
11687            assert!(workspace.right_dock().read(cx).is_open());
11688            assert!(panel.is_zoomed(window, cx));
11689            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11690        });
11691
11692        // Transfer focus to the center closes the dock
11693        workspace.update_in(cx, |workspace, window, cx| {
11694            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11695        });
11696
11697        workspace.update_in(cx, |workspace, window, cx| {
11698            assert!(!workspace.right_dock().read(cx).is_open());
11699            assert!(panel.is_zoomed(window, cx));
11700            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11701        });
11702
11703        // Transferring focus back to the panel keeps it zoomed
11704        workspace.update_in(cx, |workspace, window, cx| {
11705            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11706        });
11707
11708        workspace.update_in(cx, |workspace, window, cx| {
11709            assert!(workspace.right_dock().read(cx).is_open());
11710            assert!(panel.is_zoomed(window, cx));
11711            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11712        });
11713
11714        // Close the dock while it is zoomed
11715        workspace.update_in(cx, |workspace, window, cx| {
11716            workspace.toggle_dock(DockPosition::Right, 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!(workspace.zoomed.is_none());
11723            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11724        });
11725
11726        // Opening the dock, when it's zoomed, retains focus
11727        workspace.update_in(cx, |workspace, window, cx| {
11728            workspace.toggle_dock(DockPosition::Right, window, cx)
11729        });
11730
11731        workspace.update_in(cx, |workspace, window, cx| {
11732            assert!(workspace.right_dock().read(cx).is_open());
11733            assert!(panel.is_zoomed(window, cx));
11734            assert!(workspace.zoomed.is_some());
11735            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11736        });
11737
11738        // Unzoom and close the panel, zoom the active pane.
11739        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11740        workspace.update_in(cx, |workspace, window, cx| {
11741            workspace.toggle_dock(DockPosition::Right, window, cx)
11742        });
11743        pane.update_in(cx, |pane, window, cx| {
11744            pane.toggle_zoom(&Default::default(), window, cx)
11745        });
11746
11747        // Opening a dock unzooms the pane.
11748        workspace.update_in(cx, |workspace, window, cx| {
11749            workspace.toggle_dock(DockPosition::Right, window, cx)
11750        });
11751        workspace.update_in(cx, |workspace, window, cx| {
11752            let pane = pane.read(cx);
11753            assert!(!pane.is_zoomed());
11754            assert!(!pane.focus_handle(cx).is_focused(window));
11755            assert!(workspace.right_dock().read(cx).is_open());
11756            assert!(workspace.zoomed.is_none());
11757        });
11758    }
11759
11760    #[gpui::test]
11761    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11762        init_test(cx);
11763        let fs = FakeFs::new(cx.executor());
11764
11765        let project = Project::test(fs, [], cx).await;
11766        let (workspace, cx) =
11767            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11768
11769        let panel = workspace.update_in(cx, |workspace, window, cx| {
11770            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11771            workspace.add_panel(panel.clone(), window, cx);
11772            panel
11773        });
11774
11775        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11776        pane.update_in(cx, |pane, window, cx| {
11777            let item = cx.new(TestItem::new);
11778            pane.add_item(Box::new(item), true, true, None, window, cx);
11779        });
11780
11781        // Enable close_panel_on_toggle
11782        cx.update_global(|store: &mut SettingsStore, cx| {
11783            store.update_user_settings(cx, |settings| {
11784                settings.workspace.close_panel_on_toggle = Some(true);
11785            });
11786        });
11787
11788        // Panel starts closed. Toggling should open and focus it.
11789        workspace.update_in(cx, |workspace, window, cx| {
11790            assert!(!workspace.right_dock().read(cx).is_open());
11791            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11792        });
11793
11794        workspace.update_in(cx, |workspace, window, cx| {
11795            assert!(
11796                workspace.right_dock().read(cx).is_open(),
11797                "Dock should be open after toggling from center"
11798            );
11799            assert!(
11800                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11801                "Panel should be focused after toggling from center"
11802            );
11803        });
11804
11805        // Panel is open and focused. Toggling should close the panel and
11806        // return focus to the center.
11807        workspace.update_in(cx, |workspace, window, cx| {
11808            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11809        });
11810
11811        workspace.update_in(cx, |workspace, window, cx| {
11812            assert!(
11813                !workspace.right_dock().read(cx).is_open(),
11814                "Dock should be closed after toggling from focused panel"
11815            );
11816            assert!(
11817                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11818                "Panel should not be focused after toggling from focused panel"
11819            );
11820        });
11821
11822        // Open the dock and focus something else so the panel is open but not
11823        // focused. Toggling should focus the panel (not close it).
11824        workspace.update_in(cx, |workspace, window, cx| {
11825            workspace
11826                .right_dock()
11827                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11828            window.focus(&pane.read(cx).focus_handle(cx), cx);
11829        });
11830
11831        workspace.update_in(cx, |workspace, window, cx| {
11832            assert!(workspace.right_dock().read(cx).is_open());
11833            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11834            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11835        });
11836
11837        workspace.update_in(cx, |workspace, window, cx| {
11838            assert!(
11839                workspace.right_dock().read(cx).is_open(),
11840                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11841            );
11842            assert!(
11843                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11844                "Panel should be focused after toggling an open-but-unfocused panel"
11845            );
11846        });
11847
11848        // Now disable the setting and verify the original behavior: toggling
11849        // from a focused panel moves focus to center but leaves the dock open.
11850        cx.update_global(|store: &mut SettingsStore, cx| {
11851            store.update_user_settings(cx, |settings| {
11852                settings.workspace.close_panel_on_toggle = Some(false);
11853            });
11854        });
11855
11856        workspace.update_in(cx, |workspace, window, cx| {
11857            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11858        });
11859
11860        workspace.update_in(cx, |workspace, window, cx| {
11861            assert!(
11862                workspace.right_dock().read(cx).is_open(),
11863                "Dock should remain open when setting is disabled"
11864            );
11865            assert!(
11866                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11867                "Panel should not be focused after toggling with setting disabled"
11868            );
11869        });
11870    }
11871
11872    #[gpui::test]
11873    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11874        init_test(cx);
11875        let fs = FakeFs::new(cx.executor());
11876
11877        let project = Project::test(fs, [], cx).await;
11878        let (workspace, cx) =
11879            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11880
11881        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11882            workspace.active_pane().clone()
11883        });
11884
11885        // Add an item to the pane so it can be zoomed
11886        workspace.update_in(cx, |workspace, window, cx| {
11887            let item = cx.new(TestItem::new);
11888            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11889        });
11890
11891        // Initially not zoomed
11892        workspace.update_in(cx, |workspace, _window, cx| {
11893            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11894            assert!(
11895                workspace.zoomed.is_none(),
11896                "Workspace should track no zoomed pane"
11897            );
11898            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11899        });
11900
11901        // Zoom In
11902        pane.update_in(cx, |pane, window, cx| {
11903            pane.zoom_in(&crate::ZoomIn, window, cx);
11904        });
11905
11906        workspace.update_in(cx, |workspace, window, cx| {
11907            assert!(
11908                pane.read(cx).is_zoomed(),
11909                "Pane should be zoomed after ZoomIn"
11910            );
11911            assert!(
11912                workspace.zoomed.is_some(),
11913                "Workspace should track the zoomed pane"
11914            );
11915            assert!(
11916                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11917                "ZoomIn should focus the pane"
11918            );
11919        });
11920
11921        // Zoom In again is a no-op
11922        pane.update_in(cx, |pane, window, cx| {
11923            pane.zoom_in(&crate::ZoomIn, window, cx);
11924        });
11925
11926        workspace.update_in(cx, |workspace, window, cx| {
11927            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11928            assert!(
11929                workspace.zoomed.is_some(),
11930                "Workspace still tracks zoomed pane"
11931            );
11932            assert!(
11933                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11934                "Pane remains focused after repeated ZoomIn"
11935            );
11936        });
11937
11938        // Zoom Out
11939        pane.update_in(cx, |pane, window, cx| {
11940            pane.zoom_out(&crate::ZoomOut, window, cx);
11941        });
11942
11943        workspace.update_in(cx, |workspace, _window, cx| {
11944            assert!(
11945                !pane.read(cx).is_zoomed(),
11946                "Pane should unzoom after ZoomOut"
11947            );
11948            assert!(
11949                workspace.zoomed.is_none(),
11950                "Workspace clears zoom tracking after ZoomOut"
11951            );
11952        });
11953
11954        // Zoom Out again is a no-op
11955        pane.update_in(cx, |pane, window, cx| {
11956            pane.zoom_out(&crate::ZoomOut, window, cx);
11957        });
11958
11959        workspace.update_in(cx, |workspace, _window, cx| {
11960            assert!(
11961                !pane.read(cx).is_zoomed(),
11962                "Second ZoomOut keeps pane unzoomed"
11963            );
11964            assert!(
11965                workspace.zoomed.is_none(),
11966                "Workspace remains without zoomed pane"
11967            );
11968        });
11969    }
11970
11971    #[gpui::test]
11972    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11973        init_test(cx);
11974        let fs = FakeFs::new(cx.executor());
11975
11976        let project = Project::test(fs, [], cx).await;
11977        let (workspace, cx) =
11978            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11979        workspace.update_in(cx, |workspace, window, cx| {
11980            // Open two docks
11981            let left_dock = workspace.dock_at_position(DockPosition::Left);
11982            let right_dock = workspace.dock_at_position(DockPosition::Right);
11983
11984            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11985            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11986
11987            assert!(left_dock.read(cx).is_open());
11988            assert!(right_dock.read(cx).is_open());
11989        });
11990
11991        workspace.update_in(cx, |workspace, window, cx| {
11992            // Toggle all docks - should close both
11993            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11994
11995            let left_dock = workspace.dock_at_position(DockPosition::Left);
11996            let right_dock = workspace.dock_at_position(DockPosition::Right);
11997            assert!(!left_dock.read(cx).is_open());
11998            assert!(!right_dock.read(cx).is_open());
11999        });
12000
12001        workspace.update_in(cx, |workspace, window, cx| {
12002            // Toggle again - should reopen both
12003            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12004
12005            let left_dock = workspace.dock_at_position(DockPosition::Left);
12006            let right_dock = workspace.dock_at_position(DockPosition::Right);
12007            assert!(left_dock.read(cx).is_open());
12008            assert!(right_dock.read(cx).is_open());
12009        });
12010    }
12011
12012    #[gpui::test]
12013    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12014        init_test(cx);
12015        let fs = FakeFs::new(cx.executor());
12016
12017        let project = Project::test(fs, [], cx).await;
12018        let (workspace, cx) =
12019            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12020        workspace.update_in(cx, |workspace, window, cx| {
12021            // Open two docks
12022            let left_dock = workspace.dock_at_position(DockPosition::Left);
12023            let right_dock = workspace.dock_at_position(DockPosition::Right);
12024
12025            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12026            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12027
12028            assert!(left_dock.read(cx).is_open());
12029            assert!(right_dock.read(cx).is_open());
12030        });
12031
12032        workspace.update_in(cx, |workspace, window, cx| {
12033            // Close them manually
12034            workspace.toggle_dock(DockPosition::Left, window, cx);
12035            workspace.toggle_dock(DockPosition::Right, window, cx);
12036
12037            let left_dock = workspace.dock_at_position(DockPosition::Left);
12038            let right_dock = workspace.dock_at_position(DockPosition::Right);
12039            assert!(!left_dock.read(cx).is_open());
12040            assert!(!right_dock.read(cx).is_open());
12041        });
12042
12043        workspace.update_in(cx, |workspace, window, cx| {
12044            // Toggle all docks - only last closed (right dock) should reopen
12045            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12046
12047            let left_dock = workspace.dock_at_position(DockPosition::Left);
12048            let right_dock = workspace.dock_at_position(DockPosition::Right);
12049            assert!(!left_dock.read(cx).is_open());
12050            assert!(right_dock.read(cx).is_open());
12051        });
12052    }
12053
12054    #[gpui::test]
12055    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12056        init_test(cx);
12057        let fs = FakeFs::new(cx.executor());
12058        let project = Project::test(fs, [], cx).await;
12059        let (multi_workspace, cx) =
12060            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12061        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12062
12063        // Open two docks (left and right) with one panel each
12064        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12065            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12066            workspace.add_panel(left_panel.clone(), window, cx);
12067
12068            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12069            workspace.add_panel(right_panel.clone(), window, cx);
12070
12071            workspace.toggle_dock(DockPosition::Left, window, cx);
12072            workspace.toggle_dock(DockPosition::Right, window, cx);
12073
12074            // Verify initial state
12075            assert!(
12076                workspace.left_dock().read(cx).is_open(),
12077                "Left dock should be open"
12078            );
12079            assert_eq!(
12080                workspace
12081                    .left_dock()
12082                    .read(cx)
12083                    .visible_panel()
12084                    .unwrap()
12085                    .panel_id(),
12086                left_panel.panel_id(),
12087                "Left panel should be visible in left dock"
12088            );
12089            assert!(
12090                workspace.right_dock().read(cx).is_open(),
12091                "Right dock should be open"
12092            );
12093            assert_eq!(
12094                workspace
12095                    .right_dock()
12096                    .read(cx)
12097                    .visible_panel()
12098                    .unwrap()
12099                    .panel_id(),
12100                right_panel.panel_id(),
12101                "Right panel should be visible in right dock"
12102            );
12103            assert!(
12104                !workspace.bottom_dock().read(cx).is_open(),
12105                "Bottom dock should be closed"
12106            );
12107
12108            (left_panel, right_panel)
12109        });
12110
12111        // Focus the left panel and move it to the next position (bottom dock)
12112        workspace.update_in(cx, |workspace, window, cx| {
12113            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12114            assert!(
12115                left_panel.read(cx).focus_handle(cx).is_focused(window),
12116                "Left panel should be focused"
12117            );
12118        });
12119
12120        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12121
12122        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12123        workspace.update(cx, |workspace, cx| {
12124            assert!(
12125                !workspace.left_dock().read(cx).is_open(),
12126                "Left dock should be closed"
12127            );
12128            assert!(
12129                workspace.bottom_dock().read(cx).is_open(),
12130                "Bottom dock should now be open"
12131            );
12132            assert_eq!(
12133                left_panel.read(cx).position,
12134                DockPosition::Bottom,
12135                "Left panel should now be in the bottom dock"
12136            );
12137            assert_eq!(
12138                workspace
12139                    .bottom_dock()
12140                    .read(cx)
12141                    .visible_panel()
12142                    .unwrap()
12143                    .panel_id(),
12144                left_panel.panel_id(),
12145                "Left panel should be the visible panel in the bottom dock"
12146            );
12147        });
12148
12149        // Toggle all docks off
12150        workspace.update_in(cx, |workspace, window, cx| {
12151            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12152            assert!(
12153                !workspace.left_dock().read(cx).is_open(),
12154                "Left dock should be closed"
12155            );
12156            assert!(
12157                !workspace.right_dock().read(cx).is_open(),
12158                "Right dock should be closed"
12159            );
12160            assert!(
12161                !workspace.bottom_dock().read(cx).is_open(),
12162                "Bottom dock should be closed"
12163            );
12164        });
12165
12166        // Toggle all docks back on and verify positions are restored
12167        workspace.update_in(cx, |workspace, window, cx| {
12168            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12169            assert!(
12170                !workspace.left_dock().read(cx).is_open(),
12171                "Left dock should remain closed"
12172            );
12173            assert!(
12174                workspace.right_dock().read(cx).is_open(),
12175                "Right dock should remain open"
12176            );
12177            assert!(
12178                workspace.bottom_dock().read(cx).is_open(),
12179                "Bottom dock should remain open"
12180            );
12181            assert_eq!(
12182                left_panel.read(cx).position,
12183                DockPosition::Bottom,
12184                "Left panel should remain in the bottom dock"
12185            );
12186            assert_eq!(
12187                right_panel.read(cx).position,
12188                DockPosition::Right,
12189                "Right panel should remain in the right dock"
12190            );
12191            assert_eq!(
12192                workspace
12193                    .bottom_dock()
12194                    .read(cx)
12195                    .visible_panel()
12196                    .unwrap()
12197                    .panel_id(),
12198                left_panel.panel_id(),
12199                "Left panel should be the visible panel in the right dock"
12200            );
12201        });
12202    }
12203
12204    #[gpui::test]
12205    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12206        init_test(cx);
12207
12208        let fs = FakeFs::new(cx.executor());
12209
12210        let project = Project::test(fs, None, cx).await;
12211        let (workspace, cx) =
12212            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12213
12214        // Let's arrange the panes like this:
12215        //
12216        // +-----------------------+
12217        // |         top           |
12218        // +------+--------+-------+
12219        // | left | center | right |
12220        // +------+--------+-------+
12221        // |        bottom         |
12222        // +-----------------------+
12223
12224        let top_item = cx.new(|cx| {
12225            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12226        });
12227        let bottom_item = cx.new(|cx| {
12228            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12229        });
12230        let left_item = cx.new(|cx| {
12231            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12232        });
12233        let right_item = cx.new(|cx| {
12234            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12235        });
12236        let center_item = cx.new(|cx| {
12237            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12238        });
12239
12240        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12241            let top_pane_id = workspace.active_pane().entity_id();
12242            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12243            workspace.split_pane(
12244                workspace.active_pane().clone(),
12245                SplitDirection::Down,
12246                window,
12247                cx,
12248            );
12249            top_pane_id
12250        });
12251        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12252            let bottom_pane_id = workspace.active_pane().entity_id();
12253            workspace.add_item_to_active_pane(
12254                Box::new(bottom_item.clone()),
12255                None,
12256                false,
12257                window,
12258                cx,
12259            );
12260            workspace.split_pane(
12261                workspace.active_pane().clone(),
12262                SplitDirection::Up,
12263                window,
12264                cx,
12265            );
12266            bottom_pane_id
12267        });
12268        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12269            let left_pane_id = workspace.active_pane().entity_id();
12270            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12271            workspace.split_pane(
12272                workspace.active_pane().clone(),
12273                SplitDirection::Right,
12274                window,
12275                cx,
12276            );
12277            left_pane_id
12278        });
12279        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12280            let right_pane_id = workspace.active_pane().entity_id();
12281            workspace.add_item_to_active_pane(
12282                Box::new(right_item.clone()),
12283                None,
12284                false,
12285                window,
12286                cx,
12287            );
12288            workspace.split_pane(
12289                workspace.active_pane().clone(),
12290                SplitDirection::Left,
12291                window,
12292                cx,
12293            );
12294            right_pane_id
12295        });
12296        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12297            let center_pane_id = workspace.active_pane().entity_id();
12298            workspace.add_item_to_active_pane(
12299                Box::new(center_item.clone()),
12300                None,
12301                false,
12302                window,
12303                cx,
12304            );
12305            center_pane_id
12306        });
12307        cx.executor().run_until_parked();
12308
12309        workspace.update_in(cx, |workspace, window, cx| {
12310            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12311
12312            // Join into next from center pane into right
12313            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12314        });
12315
12316        workspace.update_in(cx, |workspace, window, cx| {
12317            let active_pane = workspace.active_pane();
12318            assert_eq!(right_pane_id, active_pane.entity_id());
12319            assert_eq!(2, active_pane.read(cx).items_len());
12320            let item_ids_in_pane =
12321                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12322            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12323            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12324
12325            // Join into next from right pane into bottom
12326            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12327        });
12328
12329        workspace.update_in(cx, |workspace, window, cx| {
12330            let active_pane = workspace.active_pane();
12331            assert_eq!(bottom_pane_id, active_pane.entity_id());
12332            assert_eq!(3, active_pane.read(cx).items_len());
12333            let item_ids_in_pane =
12334                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12335            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12336            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12337            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12338
12339            // Join into next from bottom pane into left
12340            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12341        });
12342
12343        workspace.update_in(cx, |workspace, window, cx| {
12344            let active_pane = workspace.active_pane();
12345            assert_eq!(left_pane_id, active_pane.entity_id());
12346            assert_eq!(4, active_pane.read(cx).items_len());
12347            let item_ids_in_pane =
12348                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12349            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12350            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12351            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12352            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12353
12354            // Join into next from left pane into top
12355            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12356        });
12357
12358        workspace.update_in(cx, |workspace, window, cx| {
12359            let active_pane = workspace.active_pane();
12360            assert_eq!(top_pane_id, active_pane.entity_id());
12361            assert_eq!(5, active_pane.read(cx).items_len());
12362            let item_ids_in_pane =
12363                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12364            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12365            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12366            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12367            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12368            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12369
12370            // Single pane left: no-op
12371            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12372        });
12373
12374        workspace.update(cx, |workspace, _cx| {
12375            let active_pane = workspace.active_pane();
12376            assert_eq!(top_pane_id, active_pane.entity_id());
12377        });
12378    }
12379
12380    fn add_an_item_to_active_pane(
12381        cx: &mut VisualTestContext,
12382        workspace: &Entity<Workspace>,
12383        item_id: u64,
12384    ) -> Entity<TestItem> {
12385        let item = cx.new(|cx| {
12386            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12387                item_id,
12388                "item{item_id}.txt",
12389                cx,
12390            )])
12391        });
12392        workspace.update_in(cx, |workspace, window, cx| {
12393            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12394        });
12395        item
12396    }
12397
12398    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12399        workspace.update_in(cx, |workspace, window, cx| {
12400            workspace.split_pane(
12401                workspace.active_pane().clone(),
12402                SplitDirection::Right,
12403                window,
12404                cx,
12405            )
12406        })
12407    }
12408
12409    #[gpui::test]
12410    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12411        init_test(cx);
12412        let fs = FakeFs::new(cx.executor());
12413        let project = Project::test(fs, None, cx).await;
12414        let (workspace, cx) =
12415            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12416
12417        add_an_item_to_active_pane(cx, &workspace, 1);
12418        split_pane(cx, &workspace);
12419        add_an_item_to_active_pane(cx, &workspace, 2);
12420        split_pane(cx, &workspace); // empty pane
12421        split_pane(cx, &workspace);
12422        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12423
12424        cx.executor().run_until_parked();
12425
12426        workspace.update(cx, |workspace, cx| {
12427            let num_panes = workspace.panes().len();
12428            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12429            let active_item = workspace
12430                .active_pane()
12431                .read(cx)
12432                .active_item()
12433                .expect("item is in focus");
12434
12435            assert_eq!(num_panes, 4);
12436            assert_eq!(num_items_in_current_pane, 1);
12437            assert_eq!(active_item.item_id(), last_item.item_id());
12438        });
12439
12440        workspace.update_in(cx, |workspace, window, cx| {
12441            workspace.join_all_panes(window, cx);
12442        });
12443
12444        workspace.update(cx, |workspace, cx| {
12445            let num_panes = workspace.panes().len();
12446            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12447            let active_item = workspace
12448                .active_pane()
12449                .read(cx)
12450                .active_item()
12451                .expect("item is in focus");
12452
12453            assert_eq!(num_panes, 1);
12454            assert_eq!(num_items_in_current_pane, 3);
12455            assert_eq!(active_item.item_id(), last_item.item_id());
12456        });
12457    }
12458
12459    #[gpui::test]
12460    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12461        init_test(cx);
12462        let fs = FakeFs::new(cx.executor());
12463
12464        let project = Project::test(fs, [], cx).await;
12465        let (multi_workspace, cx) =
12466            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12467        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12468
12469        workspace.update(cx, |workspace, _cx| {
12470            workspace.bounds.size.width = px(800.);
12471        });
12472
12473        workspace.update_in(cx, |workspace, window, cx| {
12474            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12475            workspace.add_panel(panel, window, cx);
12476            workspace.toggle_dock(DockPosition::Right, window, cx);
12477        });
12478
12479        let (panel, resized_width, ratio_basis_width) =
12480            workspace.update_in(cx, |workspace, window, cx| {
12481                let item = cx.new(|cx| {
12482                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12483                });
12484                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12485
12486                let dock = workspace.right_dock().read(cx);
12487                let workspace_width = workspace.bounds.size.width;
12488                let initial_width = workspace
12489                    .dock_size(&dock, window, cx)
12490                    .expect("flexible dock should have an initial width");
12491
12492                assert_eq!(initial_width, workspace_width / 2.);
12493
12494                workspace.resize_right_dock(px(300.), window, cx);
12495
12496                let dock = workspace.right_dock().read(cx);
12497                let resized_width = workspace
12498                    .dock_size(&dock, window, cx)
12499                    .expect("flexible dock should keep its resized width");
12500
12501                assert_eq!(resized_width, px(300.));
12502
12503                let panel = workspace
12504                    .right_dock()
12505                    .read(cx)
12506                    .visible_panel()
12507                    .expect("flexible dock should have a visible panel")
12508                    .panel_id();
12509
12510                (panel, resized_width, workspace_width)
12511            });
12512
12513        workspace.update_in(cx, |workspace, window, cx| {
12514            workspace.toggle_dock(DockPosition::Right, window, cx);
12515            workspace.toggle_dock(DockPosition::Right, window, cx);
12516
12517            let dock = workspace.right_dock().read(cx);
12518            let reopened_width = workspace
12519                .dock_size(&dock, window, cx)
12520                .expect("flexible dock should restore when reopened");
12521
12522            assert_eq!(reopened_width, resized_width);
12523
12524            let right_dock = workspace.right_dock().read(cx);
12525            let flexible_panel = right_dock
12526                .visible_panel()
12527                .expect("flexible dock should still have a visible panel");
12528            assert_eq!(flexible_panel.panel_id(), panel);
12529            assert_eq!(
12530                right_dock
12531                    .stored_panel_size_state(flexible_panel.as_ref())
12532                    .and_then(|size_state| size_state.flex),
12533                Some(
12534                    resized_width.to_f64() as f32
12535                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12536                )
12537            );
12538        });
12539
12540        workspace.update_in(cx, |workspace, window, cx| {
12541            workspace.split_pane(
12542                workspace.active_pane().clone(),
12543                SplitDirection::Right,
12544                window,
12545                cx,
12546            );
12547
12548            let dock = workspace.right_dock().read(cx);
12549            let split_width = workspace
12550                .dock_size(&dock, window, cx)
12551                .expect("flexible dock should keep its user-resized proportion");
12552
12553            assert_eq!(split_width, px(300.));
12554
12555            workspace.bounds.size.width = px(1600.);
12556
12557            let dock = workspace.right_dock().read(cx);
12558            let resized_window_width = workspace
12559                .dock_size(&dock, window, cx)
12560                .expect("flexible dock should preserve proportional size on window resize");
12561
12562            assert_eq!(
12563                resized_window_width,
12564                workspace.bounds.size.width
12565                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12566            );
12567        });
12568    }
12569
12570    #[gpui::test]
12571    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12572        init_test(cx);
12573        let fs = FakeFs::new(cx.executor());
12574
12575        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12576        {
12577            let project = Project::test(fs.clone(), [], cx).await;
12578            let (multi_workspace, cx) =
12579                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12580            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12581
12582            workspace.update(cx, |workspace, _cx| {
12583                workspace.set_random_database_id();
12584                workspace.bounds.size.width = px(800.);
12585            });
12586
12587            let panel = workspace.update_in(cx, |workspace, window, cx| {
12588                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12589                workspace.add_panel(panel.clone(), window, cx);
12590                workspace.toggle_dock(DockPosition::Left, window, cx);
12591                panel
12592            });
12593
12594            workspace.update_in(cx, |workspace, window, cx| {
12595                workspace.resize_left_dock(px(350.), window, cx);
12596            });
12597
12598            cx.run_until_parked();
12599
12600            let persisted = workspace.read_with(cx, |workspace, cx| {
12601                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12602            });
12603            assert_eq!(
12604                persisted.and_then(|s| s.size),
12605                Some(px(350.)),
12606                "fixed-width panel size should be persisted to KVP"
12607            );
12608
12609            // Remove the panel and re-add a fresh instance with the same key.
12610            // The new instance should have its size state restored from KVP.
12611            workspace.update_in(cx, |workspace, window, cx| {
12612                workspace.remove_panel(&panel, window, cx);
12613            });
12614
12615            workspace.update_in(cx, |workspace, window, cx| {
12616                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12617                workspace.add_panel(new_panel, window, cx);
12618
12619                let left_dock = workspace.left_dock().read(cx);
12620                let size_state = left_dock
12621                    .panel::<TestPanel>()
12622                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12623                assert_eq!(
12624                    size_state.and_then(|s| s.size),
12625                    Some(px(350.)),
12626                    "re-added fixed-width panel should restore persisted size from KVP"
12627                );
12628            });
12629        }
12630
12631        // Flexible panel: both pixel size and ratio are persisted and restored.
12632        {
12633            let project = Project::test(fs.clone(), [], cx).await;
12634            let (multi_workspace, cx) =
12635                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12636            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12637
12638            workspace.update(cx, |workspace, _cx| {
12639                workspace.set_random_database_id();
12640                workspace.bounds.size.width = px(800.);
12641            });
12642
12643            let panel = workspace.update_in(cx, |workspace, window, cx| {
12644                let item = cx.new(|cx| {
12645                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12646                });
12647                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12648
12649                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12650                workspace.add_panel(panel.clone(), window, cx);
12651                workspace.toggle_dock(DockPosition::Right, window, cx);
12652                panel
12653            });
12654
12655            workspace.update_in(cx, |workspace, window, cx| {
12656                workspace.resize_right_dock(px(300.), window, cx);
12657            });
12658
12659            cx.run_until_parked();
12660
12661            let persisted = workspace
12662                .read_with(cx, |workspace, cx| {
12663                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12664                })
12665                .expect("flexible panel state should be persisted to KVP");
12666            assert_eq!(
12667                persisted.size, None,
12668                "flexible panel should not persist a redundant pixel size"
12669            );
12670            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12671
12672            // Remove the panel and re-add: both size and ratio should be restored.
12673            workspace.update_in(cx, |workspace, window, cx| {
12674                workspace.remove_panel(&panel, window, cx);
12675            });
12676
12677            workspace.update_in(cx, |workspace, window, cx| {
12678                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12679                workspace.add_panel(new_panel, window, cx);
12680
12681                let right_dock = workspace.right_dock().read(cx);
12682                let size_state = right_dock
12683                    .panel::<TestPanel>()
12684                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12685                    .expect("re-added flexible panel should have restored size state from KVP");
12686                assert_eq!(
12687                    size_state.size, None,
12688                    "re-added flexible panel should not have a persisted pixel size"
12689                );
12690                assert_eq!(
12691                    size_state.flex,
12692                    Some(original_ratio),
12693                    "re-added flexible panel should restore persisted flex"
12694                );
12695            });
12696        }
12697    }
12698
12699    #[gpui::test]
12700    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12701        init_test(cx);
12702        let fs = FakeFs::new(cx.executor());
12703
12704        let project = Project::test(fs, [], cx).await;
12705        let (multi_workspace, cx) =
12706            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12707        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12708
12709        workspace.update(cx, |workspace, _cx| {
12710            workspace.bounds.size.width = px(900.);
12711        });
12712
12713        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12714        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12715        // and the center pane each take half the workspace width.
12716        workspace.update_in(cx, |workspace, window, cx| {
12717            let item = cx.new(|cx| {
12718                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12719            });
12720            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12721
12722            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12723            workspace.add_panel(panel, window, cx);
12724            workspace.toggle_dock(DockPosition::Left, window, cx);
12725
12726            let left_dock = workspace.left_dock().read(cx);
12727            let left_width = workspace
12728                .dock_size(&left_dock, window, cx)
12729                .expect("left dock should have an active panel");
12730
12731            assert_eq!(
12732                left_width,
12733                workspace.bounds.size.width / 2.,
12734                "flexible left panel should split evenly with the center pane"
12735            );
12736        });
12737
12738        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12739        // change horizontal width fractions, so the flexible panel stays at the same
12740        // width as each half of the split.
12741        workspace.update_in(cx, |workspace, window, cx| {
12742            workspace.split_pane(
12743                workspace.active_pane().clone(),
12744                SplitDirection::Down,
12745                window,
12746                cx,
12747            );
12748
12749            let left_dock = workspace.left_dock().read(cx);
12750            let left_width = workspace
12751                .dock_size(&left_dock, window, cx)
12752                .expect("left dock should still have an active panel after vertical split");
12753
12754            assert_eq!(
12755                left_width,
12756                workspace.bounds.size.width / 2.,
12757                "flexible left panel width should match each vertically-split pane"
12758            );
12759        });
12760
12761        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12762        // size reduces the available width, so the flexible left panel and the center
12763        // panes all shrink proportionally to accommodate it.
12764        workspace.update_in(cx, |workspace, window, cx| {
12765            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12766            workspace.add_panel(panel, window, cx);
12767            workspace.toggle_dock(DockPosition::Right, window, cx);
12768
12769            let right_dock = workspace.right_dock().read(cx);
12770            let right_width = workspace
12771                .dock_size(&right_dock, window, cx)
12772                .expect("right dock should have an active panel");
12773
12774            let left_dock = workspace.left_dock().read(cx);
12775            let left_width = workspace
12776                .dock_size(&left_dock, window, cx)
12777                .expect("left dock should still have an active panel");
12778
12779            let available_width = workspace.bounds.size.width - right_width;
12780            assert_eq!(
12781                left_width,
12782                available_width / 2.,
12783                "flexible left panel should shrink proportionally as the right dock takes space"
12784            );
12785        });
12786
12787        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12788        // flex sizing and the workspace width is divided among left-flex, center
12789        // (implicit flex 1.0), and right-flex.
12790        workspace.update_in(cx, |workspace, window, cx| {
12791            let right_dock = workspace.right_dock().clone();
12792            let right_panel = right_dock
12793                .read(cx)
12794                .visible_panel()
12795                .expect("right dock should have a visible panel")
12796                .clone();
12797            workspace.toggle_dock_panel_flexible_size(
12798                &right_dock,
12799                right_panel.as_ref(),
12800                window,
12801                cx,
12802            );
12803
12804            let right_dock = right_dock.read(cx);
12805            let right_panel = right_dock
12806                .visible_panel()
12807                .expect("right dock should still have a visible panel");
12808            assert!(
12809                right_panel.has_flexible_size(window, cx),
12810                "right panel should now be flexible"
12811            );
12812
12813            let right_size_state = right_dock
12814                .stored_panel_size_state(right_panel.as_ref())
12815                .expect("right panel should have a stored size state after toggling");
12816            let right_flex = right_size_state
12817                .flex
12818                .expect("right panel should have a flex value after toggling");
12819
12820            let left_dock = workspace.left_dock().read(cx);
12821            let left_width = workspace
12822                .dock_size(&left_dock, window, cx)
12823                .expect("left dock should still have an active panel");
12824            let right_width = workspace
12825                .dock_size(&right_dock, window, cx)
12826                .expect("right dock should still have an active panel");
12827
12828            let left_flex = workspace
12829                .default_dock_flex(DockPosition::Left)
12830                .expect("left dock should have a default flex");
12831
12832            let total_flex = left_flex + 1.0 + right_flex;
12833            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12834            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12835            assert_eq!(
12836                left_width, expected_left,
12837                "flexible left panel should share workspace width via flex ratios"
12838            );
12839            assert_eq!(
12840                right_width, expected_right,
12841                "flexible right panel should share workspace width via flex ratios"
12842            );
12843        });
12844    }
12845
12846    struct TestModal(FocusHandle);
12847
12848    impl TestModal {
12849        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12850            Self(cx.focus_handle())
12851        }
12852    }
12853
12854    impl EventEmitter<DismissEvent> for TestModal {}
12855
12856    impl Focusable for TestModal {
12857        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12858            self.0.clone()
12859        }
12860    }
12861
12862    impl ModalView for TestModal {}
12863
12864    impl Render for TestModal {
12865        fn render(
12866            &mut self,
12867            _window: &mut Window,
12868            _cx: &mut Context<TestModal>,
12869        ) -> impl IntoElement {
12870            div().track_focus(&self.0)
12871        }
12872    }
12873
12874    #[gpui::test]
12875    async fn test_panels(cx: &mut gpui::TestAppContext) {
12876        init_test(cx);
12877        let fs = FakeFs::new(cx.executor());
12878
12879        let project = Project::test(fs, [], cx).await;
12880        let (multi_workspace, cx) =
12881            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12882        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12883
12884        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12885            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12886            workspace.add_panel(panel_1.clone(), window, cx);
12887            workspace.toggle_dock(DockPosition::Left, window, cx);
12888            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12889            workspace.add_panel(panel_2.clone(), window, cx);
12890            workspace.toggle_dock(DockPosition::Right, window, cx);
12891
12892            let left_dock = workspace.left_dock();
12893            assert_eq!(
12894                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12895                panel_1.panel_id()
12896            );
12897            assert_eq!(
12898                workspace.dock_size(&left_dock.read(cx), window, cx),
12899                Some(px(300.))
12900            );
12901
12902            workspace.resize_left_dock(px(1337.), window, cx);
12903            assert_eq!(
12904                workspace
12905                    .right_dock()
12906                    .read(cx)
12907                    .visible_panel()
12908                    .unwrap()
12909                    .panel_id(),
12910                panel_2.panel_id(),
12911            );
12912
12913            (panel_1, panel_2)
12914        });
12915
12916        // Move panel_1 to the right
12917        panel_1.update_in(cx, |panel_1, window, cx| {
12918            panel_1.set_position(DockPosition::Right, window, cx)
12919        });
12920
12921        workspace.update_in(cx, |workspace, window, cx| {
12922            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12923            // Since it was the only panel on the left, the left dock should now be closed.
12924            assert!(!workspace.left_dock().read(cx).is_open());
12925            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12926            let right_dock = workspace.right_dock();
12927            assert_eq!(
12928                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12929                panel_1.panel_id()
12930            );
12931            assert_eq!(
12932                right_dock
12933                    .read(cx)
12934                    .active_panel_size()
12935                    .unwrap()
12936                    .size
12937                    .unwrap(),
12938                px(1337.)
12939            );
12940
12941            // Now we move panel_2 to the left
12942            panel_2.set_position(DockPosition::Left, window, cx);
12943        });
12944
12945        workspace.update(cx, |workspace, cx| {
12946            // Since panel_2 was not visible on the right, we don't open the left dock.
12947            assert!(!workspace.left_dock().read(cx).is_open());
12948            // And the right dock is unaffected in its displaying of panel_1
12949            assert!(workspace.right_dock().read(cx).is_open());
12950            assert_eq!(
12951                workspace
12952                    .right_dock()
12953                    .read(cx)
12954                    .visible_panel()
12955                    .unwrap()
12956                    .panel_id(),
12957                panel_1.panel_id(),
12958            );
12959        });
12960
12961        // Move panel_1 back to the left
12962        panel_1.update_in(cx, |panel_1, window, cx| {
12963            panel_1.set_position(DockPosition::Left, window, cx)
12964        });
12965
12966        workspace.update_in(cx, |workspace, window, cx| {
12967            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12968            let left_dock = workspace.left_dock();
12969            assert!(left_dock.read(cx).is_open());
12970            assert_eq!(
12971                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12972                panel_1.panel_id()
12973            );
12974            assert_eq!(
12975                workspace.dock_size(&left_dock.read(cx), window, cx),
12976                Some(px(1337.))
12977            );
12978            // And the right dock should be closed as it no longer has any panels.
12979            assert!(!workspace.right_dock().read(cx).is_open());
12980
12981            // Now we move panel_1 to the bottom
12982            panel_1.set_position(DockPosition::Bottom, window, cx);
12983        });
12984
12985        workspace.update_in(cx, |workspace, window, cx| {
12986            // Since panel_1 was visible on the left, we close the left dock.
12987            assert!(!workspace.left_dock().read(cx).is_open());
12988            // The bottom dock is sized based on the panel's default size,
12989            // since the panel orientation changed from vertical to horizontal.
12990            let bottom_dock = workspace.bottom_dock();
12991            assert_eq!(
12992                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12993                Some(px(300.))
12994            );
12995            // Close bottom dock and move panel_1 back to the left.
12996            bottom_dock.update(cx, |bottom_dock, cx| {
12997                bottom_dock.set_open(false, window, cx)
12998            });
12999            panel_1.set_position(DockPosition::Left, window, cx);
13000        });
13001
13002        // Emit activated event on panel 1
13003        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13004
13005        // Now the left dock is open and panel_1 is active and focused.
13006        workspace.update_in(cx, |workspace, window, cx| {
13007            let left_dock = workspace.left_dock();
13008            assert!(left_dock.read(cx).is_open());
13009            assert_eq!(
13010                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13011                panel_1.panel_id(),
13012            );
13013            assert!(panel_1.focus_handle(cx).is_focused(window));
13014        });
13015
13016        // Emit closed event on panel 2, which is not active
13017        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13018
13019        // Wo don't close the left dock, because panel_2 wasn't the active panel
13020        workspace.update(cx, |workspace, cx| {
13021            let left_dock = workspace.left_dock();
13022            assert!(left_dock.read(cx).is_open());
13023            assert_eq!(
13024                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13025                panel_1.panel_id(),
13026            );
13027        });
13028
13029        // Emitting a ZoomIn event shows the panel as zoomed.
13030        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13031        workspace.read_with(cx, |workspace, _| {
13032            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13033            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13034        });
13035
13036        // Move panel to another dock while it is zoomed
13037        panel_1.update_in(cx, |panel, window, cx| {
13038            panel.set_position(DockPosition::Right, window, cx)
13039        });
13040        workspace.read_with(cx, |workspace, _| {
13041            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13042
13043            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13044        });
13045
13046        // This is a helper for getting a:
13047        // - valid focus on an element,
13048        // - that isn't a part of the panes and panels system of the Workspace,
13049        // - and doesn't trigger the 'on_focus_lost' API.
13050        let focus_other_view = {
13051            let workspace = workspace.clone();
13052            move |cx: &mut VisualTestContext| {
13053                workspace.update_in(cx, |workspace, window, cx| {
13054                    if workspace.active_modal::<TestModal>(cx).is_some() {
13055                        workspace.toggle_modal(window, cx, TestModal::new);
13056                        workspace.toggle_modal(window, cx, TestModal::new);
13057                    } else {
13058                        workspace.toggle_modal(window, cx, TestModal::new);
13059                    }
13060                })
13061            }
13062        };
13063
13064        // If focus is transferred to another view that's not a panel or another pane, we still show
13065        // the panel as zoomed.
13066        focus_other_view(cx);
13067        workspace.read_with(cx, |workspace, _| {
13068            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13069            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13070        });
13071
13072        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13073        workspace.update_in(cx, |_workspace, window, cx| {
13074            cx.focus_self(window);
13075        });
13076        workspace.read_with(cx, |workspace, _| {
13077            assert_eq!(workspace.zoomed, None);
13078            assert_eq!(workspace.zoomed_position, None);
13079        });
13080
13081        // If focus is transferred again to another view that's not a panel or a pane, we won't
13082        // show the panel as zoomed because it wasn't zoomed before.
13083        focus_other_view(cx);
13084        workspace.read_with(cx, |workspace, _| {
13085            assert_eq!(workspace.zoomed, None);
13086            assert_eq!(workspace.zoomed_position, None);
13087        });
13088
13089        // When the panel is activated, it is zoomed again.
13090        cx.dispatch_action(ToggleRightDock);
13091        workspace.read_with(cx, |workspace, _| {
13092            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13093            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13094        });
13095
13096        // Emitting a ZoomOut event unzooms the panel.
13097        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13098        workspace.read_with(cx, |workspace, _| {
13099            assert_eq!(workspace.zoomed, None);
13100            assert_eq!(workspace.zoomed_position, None);
13101        });
13102
13103        // Emit closed event on panel 1, which is active
13104        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13105
13106        // Now the left dock is closed, because panel_1 was the active panel
13107        workspace.update(cx, |workspace, cx| {
13108            let right_dock = workspace.right_dock();
13109            assert!(!right_dock.read(cx).is_open());
13110        });
13111    }
13112
13113    #[gpui::test]
13114    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13115        init_test(cx);
13116
13117        let fs = FakeFs::new(cx.background_executor.clone());
13118        let project = Project::test(fs, [], cx).await;
13119        let (workspace, cx) =
13120            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13121        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13122
13123        let dirty_regular_buffer = cx.new(|cx| {
13124            TestItem::new(cx)
13125                .with_dirty(true)
13126                .with_label("1.txt")
13127                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13128        });
13129        let dirty_regular_buffer_2 = cx.new(|cx| {
13130            TestItem::new(cx)
13131                .with_dirty(true)
13132                .with_label("2.txt")
13133                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13134        });
13135        let dirty_multi_buffer_with_both = cx.new(|cx| {
13136            TestItem::new(cx)
13137                .with_dirty(true)
13138                .with_buffer_kind(ItemBufferKind::Multibuffer)
13139                .with_label("Fake Project Search")
13140                .with_project_items(&[
13141                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13142                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13143                ])
13144        });
13145        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13146        workspace.update_in(cx, |workspace, window, cx| {
13147            workspace.add_item(
13148                pane.clone(),
13149                Box::new(dirty_regular_buffer.clone()),
13150                None,
13151                false,
13152                false,
13153                window,
13154                cx,
13155            );
13156            workspace.add_item(
13157                pane.clone(),
13158                Box::new(dirty_regular_buffer_2.clone()),
13159                None,
13160                false,
13161                false,
13162                window,
13163                cx,
13164            );
13165            workspace.add_item(
13166                pane.clone(),
13167                Box::new(dirty_multi_buffer_with_both.clone()),
13168                None,
13169                false,
13170                false,
13171                window,
13172                cx,
13173            );
13174        });
13175
13176        pane.update_in(cx, |pane, window, cx| {
13177            pane.activate_item(2, true, true, window, cx);
13178            assert_eq!(
13179                pane.active_item().unwrap().item_id(),
13180                multi_buffer_with_both_files_id,
13181                "Should select the multi buffer in the pane"
13182            );
13183        });
13184        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13185            pane.close_other_items(
13186                &CloseOtherItems {
13187                    save_intent: Some(SaveIntent::Save),
13188                    close_pinned: true,
13189                },
13190                None,
13191                window,
13192                cx,
13193            )
13194        });
13195        cx.background_executor.run_until_parked();
13196        assert!(!cx.has_pending_prompt());
13197        close_all_but_multi_buffer_task
13198            .await
13199            .expect("Closing all buffers but the multi buffer failed");
13200        pane.update(cx, |pane, cx| {
13201            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13202            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13203            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13204            assert_eq!(pane.items_len(), 1);
13205            assert_eq!(
13206                pane.active_item().unwrap().item_id(),
13207                multi_buffer_with_both_files_id,
13208                "Should have only the multi buffer left in the pane"
13209            );
13210            assert!(
13211                dirty_multi_buffer_with_both.read(cx).is_dirty,
13212                "The multi buffer containing the unsaved buffer should still be dirty"
13213            );
13214        });
13215
13216        dirty_regular_buffer.update(cx, |buffer, cx| {
13217            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13218        });
13219
13220        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13221            pane.close_active_item(
13222                &CloseActiveItem {
13223                    save_intent: Some(SaveIntent::Close),
13224                    close_pinned: false,
13225                },
13226                window,
13227                cx,
13228            )
13229        });
13230        cx.background_executor.run_until_parked();
13231        assert!(
13232            cx.has_pending_prompt(),
13233            "Dirty multi buffer should prompt a save dialog"
13234        );
13235        cx.simulate_prompt_answer("Save");
13236        cx.background_executor.run_until_parked();
13237        close_multi_buffer_task
13238            .await
13239            .expect("Closing the multi buffer failed");
13240        pane.update(cx, |pane, cx| {
13241            assert_eq!(
13242                dirty_multi_buffer_with_both.read(cx).save_count,
13243                1,
13244                "Multi buffer item should get be saved"
13245            );
13246            // Test impl does not save inner items, so we do not assert them
13247            assert_eq!(
13248                pane.items_len(),
13249                0,
13250                "No more items should be left in the pane"
13251            );
13252            assert!(pane.active_item().is_none());
13253        });
13254    }
13255
13256    #[gpui::test]
13257    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13258        cx: &mut TestAppContext,
13259    ) {
13260        init_test(cx);
13261
13262        let fs = FakeFs::new(cx.background_executor.clone());
13263        let project = Project::test(fs, [], cx).await;
13264        let (workspace, cx) =
13265            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13266        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13267
13268        let dirty_regular_buffer = cx.new(|cx| {
13269            TestItem::new(cx)
13270                .with_dirty(true)
13271                .with_label("1.txt")
13272                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13273        });
13274        let dirty_regular_buffer_2 = cx.new(|cx| {
13275            TestItem::new(cx)
13276                .with_dirty(true)
13277                .with_label("2.txt")
13278                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13279        });
13280        let clear_regular_buffer = cx.new(|cx| {
13281            TestItem::new(cx)
13282                .with_label("3.txt")
13283                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13284        });
13285
13286        let dirty_multi_buffer_with_both = cx.new(|cx| {
13287            TestItem::new(cx)
13288                .with_dirty(true)
13289                .with_buffer_kind(ItemBufferKind::Multibuffer)
13290                .with_label("Fake Project Search")
13291                .with_project_items(&[
13292                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13293                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13294                    clear_regular_buffer.read(cx).project_items[0].clone(),
13295                ])
13296        });
13297        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13298        workspace.update_in(cx, |workspace, window, cx| {
13299            workspace.add_item(
13300                pane.clone(),
13301                Box::new(dirty_regular_buffer.clone()),
13302                None,
13303                false,
13304                false,
13305                window,
13306                cx,
13307            );
13308            workspace.add_item(
13309                pane.clone(),
13310                Box::new(dirty_multi_buffer_with_both.clone()),
13311                None,
13312                false,
13313                false,
13314                window,
13315                cx,
13316            );
13317        });
13318
13319        pane.update_in(cx, |pane, window, cx| {
13320            pane.activate_item(1, true, true, window, cx);
13321            assert_eq!(
13322                pane.active_item().unwrap().item_id(),
13323                multi_buffer_with_both_files_id,
13324                "Should select the multi buffer in the pane"
13325            );
13326        });
13327        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13328            pane.close_active_item(
13329                &CloseActiveItem {
13330                    save_intent: None,
13331                    close_pinned: false,
13332                },
13333                window,
13334                cx,
13335            )
13336        });
13337        cx.background_executor.run_until_parked();
13338        assert!(
13339            cx.has_pending_prompt(),
13340            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13341        );
13342    }
13343
13344    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13345    /// closed when they are deleted from disk.
13346    #[gpui::test]
13347    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13348        init_test(cx);
13349
13350        // Enable the close_on_disk_deletion setting
13351        cx.update_global(|store: &mut SettingsStore, cx| {
13352            store.update_user_settings(cx, |settings| {
13353                settings.workspace.close_on_file_delete = Some(true);
13354            });
13355        });
13356
13357        let fs = FakeFs::new(cx.background_executor.clone());
13358        let project = Project::test(fs, [], cx).await;
13359        let (workspace, cx) =
13360            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13361        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13362
13363        // Create a test item that simulates a file
13364        let item = cx.new(|cx| {
13365            TestItem::new(cx)
13366                .with_label("test.txt")
13367                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13368        });
13369
13370        // Add item to workspace
13371        workspace.update_in(cx, |workspace, window, cx| {
13372            workspace.add_item(
13373                pane.clone(),
13374                Box::new(item.clone()),
13375                None,
13376                false,
13377                false,
13378                window,
13379                cx,
13380            );
13381        });
13382
13383        // Verify the item is in the pane
13384        pane.read_with(cx, |pane, _| {
13385            assert_eq!(pane.items().count(), 1);
13386        });
13387
13388        // Simulate file deletion by setting the item's deleted state
13389        item.update(cx, |item, _| {
13390            item.set_has_deleted_file(true);
13391        });
13392
13393        // Emit UpdateTab event to trigger the close behavior
13394        cx.run_until_parked();
13395        item.update(cx, |_, cx| {
13396            cx.emit(ItemEvent::UpdateTab);
13397        });
13398
13399        // Allow the close operation to complete
13400        cx.run_until_parked();
13401
13402        // Verify the item was automatically closed
13403        pane.read_with(cx, |pane, _| {
13404            assert_eq!(
13405                pane.items().count(),
13406                0,
13407                "Item should be automatically closed when file is deleted"
13408            );
13409        });
13410    }
13411
13412    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13413    /// open with a strikethrough when they are deleted from disk.
13414    #[gpui::test]
13415    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13416        init_test(cx);
13417
13418        // Ensure close_on_disk_deletion is disabled (default)
13419        cx.update_global(|store: &mut SettingsStore, cx| {
13420            store.update_user_settings(cx, |settings| {
13421                settings.workspace.close_on_file_delete = Some(false);
13422            });
13423        });
13424
13425        let fs = FakeFs::new(cx.background_executor.clone());
13426        let project = Project::test(fs, [], cx).await;
13427        let (workspace, cx) =
13428            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13429        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13430
13431        // Create a test item that simulates a file
13432        let item = cx.new(|cx| {
13433            TestItem::new(cx)
13434                .with_label("test.txt")
13435                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13436        });
13437
13438        // Add item to workspace
13439        workspace.update_in(cx, |workspace, window, cx| {
13440            workspace.add_item(
13441                pane.clone(),
13442                Box::new(item.clone()),
13443                None,
13444                false,
13445                false,
13446                window,
13447                cx,
13448            );
13449        });
13450
13451        // Verify the item is in the pane
13452        pane.read_with(cx, |pane, _| {
13453            assert_eq!(pane.items().count(), 1);
13454        });
13455
13456        // Simulate file deletion
13457        item.update(cx, |item, _| {
13458            item.set_has_deleted_file(true);
13459        });
13460
13461        // Emit UpdateTab event
13462        cx.run_until_parked();
13463        item.update(cx, |_, cx| {
13464            cx.emit(ItemEvent::UpdateTab);
13465        });
13466
13467        // Allow any potential close operation to complete
13468        cx.run_until_parked();
13469
13470        // Verify the item remains open (with strikethrough)
13471        pane.read_with(cx, |pane, _| {
13472            assert_eq!(
13473                pane.items().count(),
13474                1,
13475                "Item should remain open when close_on_disk_deletion is disabled"
13476            );
13477        });
13478
13479        // Verify the item shows as deleted
13480        item.read_with(cx, |item, _| {
13481            assert!(
13482                item.has_deleted_file,
13483                "Item should be marked as having deleted file"
13484            );
13485        });
13486    }
13487
13488    /// Tests that dirty files are not automatically closed when deleted from disk,
13489    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13490    /// unsaved changes without being prompted.
13491    #[gpui::test]
13492    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13493        init_test(cx);
13494
13495        // Enable the close_on_file_delete setting
13496        cx.update_global(|store: &mut SettingsStore, cx| {
13497            store.update_user_settings(cx, |settings| {
13498                settings.workspace.close_on_file_delete = Some(true);
13499            });
13500        });
13501
13502        let fs = FakeFs::new(cx.background_executor.clone());
13503        let project = Project::test(fs, [], cx).await;
13504        let (workspace, cx) =
13505            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13506        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13507
13508        // Create a dirty test item
13509        let item = cx.new(|cx| {
13510            TestItem::new(cx)
13511                .with_dirty(true)
13512                .with_label("test.txt")
13513                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13514        });
13515
13516        // Add item to workspace
13517        workspace.update_in(cx, |workspace, window, cx| {
13518            workspace.add_item(
13519                pane.clone(),
13520                Box::new(item.clone()),
13521                None,
13522                false,
13523                false,
13524                window,
13525                cx,
13526            );
13527        });
13528
13529        // Simulate file deletion
13530        item.update(cx, |item, _| {
13531            item.set_has_deleted_file(true);
13532        });
13533
13534        // Emit UpdateTab event to trigger the close behavior
13535        cx.run_until_parked();
13536        item.update(cx, |_, cx| {
13537            cx.emit(ItemEvent::UpdateTab);
13538        });
13539
13540        // Allow any potential close operation to complete
13541        cx.run_until_parked();
13542
13543        // Verify the item remains open (dirty files are not auto-closed)
13544        pane.read_with(cx, |pane, _| {
13545            assert_eq!(
13546                pane.items().count(),
13547                1,
13548                "Dirty items should not be automatically closed even when file is deleted"
13549            );
13550        });
13551
13552        // Verify the item is marked as deleted and still dirty
13553        item.read_with(cx, |item, _| {
13554            assert!(
13555                item.has_deleted_file,
13556                "Item should be marked as having deleted file"
13557            );
13558            assert!(item.is_dirty, "Item should still be dirty");
13559        });
13560    }
13561
13562    /// Tests that navigation history is cleaned up when files are auto-closed
13563    /// due to deletion from disk.
13564    #[gpui::test]
13565    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13566        init_test(cx);
13567
13568        // Enable the close_on_file_delete setting
13569        cx.update_global(|store: &mut SettingsStore, cx| {
13570            store.update_user_settings(cx, |settings| {
13571                settings.workspace.close_on_file_delete = Some(true);
13572            });
13573        });
13574
13575        let fs = FakeFs::new(cx.background_executor.clone());
13576        let project = Project::test(fs, [], cx).await;
13577        let (workspace, cx) =
13578            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13579        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13580
13581        // Create test items
13582        let item1 = cx.new(|cx| {
13583            TestItem::new(cx)
13584                .with_label("test1.txt")
13585                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13586        });
13587        let item1_id = item1.item_id();
13588
13589        let item2 = cx.new(|cx| {
13590            TestItem::new(cx)
13591                .with_label("test2.txt")
13592                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13593        });
13594
13595        // Add items to workspace
13596        workspace.update_in(cx, |workspace, window, cx| {
13597            workspace.add_item(
13598                pane.clone(),
13599                Box::new(item1.clone()),
13600                None,
13601                false,
13602                false,
13603                window,
13604                cx,
13605            );
13606            workspace.add_item(
13607                pane.clone(),
13608                Box::new(item2.clone()),
13609                None,
13610                false,
13611                false,
13612                window,
13613                cx,
13614            );
13615        });
13616
13617        // Activate item1 to ensure it gets navigation entries
13618        pane.update_in(cx, |pane, window, cx| {
13619            pane.activate_item(0, true, true, window, cx);
13620        });
13621
13622        // Switch to item2 and back to create navigation history
13623        pane.update_in(cx, |pane, window, cx| {
13624            pane.activate_item(1, true, true, window, cx);
13625        });
13626        cx.run_until_parked();
13627
13628        pane.update_in(cx, |pane, window, cx| {
13629            pane.activate_item(0, true, true, window, cx);
13630        });
13631        cx.run_until_parked();
13632
13633        // Simulate file deletion for item1
13634        item1.update(cx, |item, _| {
13635            item.set_has_deleted_file(true);
13636        });
13637
13638        // Emit UpdateTab event to trigger the close behavior
13639        item1.update(cx, |_, cx| {
13640            cx.emit(ItemEvent::UpdateTab);
13641        });
13642        cx.run_until_parked();
13643
13644        // Verify item1 was closed
13645        pane.read_with(cx, |pane, _| {
13646            assert_eq!(
13647                pane.items().count(),
13648                1,
13649                "Should have 1 item remaining after auto-close"
13650            );
13651        });
13652
13653        // Check navigation history after close
13654        let has_item = pane.read_with(cx, |pane, cx| {
13655            let mut has_item = false;
13656            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13657                if entry.item.id() == item1_id {
13658                    has_item = true;
13659                }
13660            });
13661            has_item
13662        });
13663
13664        assert!(
13665            !has_item,
13666            "Navigation history should not contain closed item entries"
13667        );
13668    }
13669
13670    #[gpui::test]
13671    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13672        cx: &mut TestAppContext,
13673    ) {
13674        init_test(cx);
13675
13676        let fs = FakeFs::new(cx.background_executor.clone());
13677        let project = Project::test(fs, [], cx).await;
13678        let (workspace, cx) =
13679            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13680        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13681
13682        let dirty_regular_buffer = cx.new(|cx| {
13683            TestItem::new(cx)
13684                .with_dirty(true)
13685                .with_label("1.txt")
13686                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13687        });
13688        let dirty_regular_buffer_2 = cx.new(|cx| {
13689            TestItem::new(cx)
13690                .with_dirty(true)
13691                .with_label("2.txt")
13692                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13693        });
13694        let clear_regular_buffer = cx.new(|cx| {
13695            TestItem::new(cx)
13696                .with_label("3.txt")
13697                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13698        });
13699
13700        let dirty_multi_buffer = cx.new(|cx| {
13701            TestItem::new(cx)
13702                .with_dirty(true)
13703                .with_buffer_kind(ItemBufferKind::Multibuffer)
13704                .with_label("Fake Project Search")
13705                .with_project_items(&[
13706                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13707                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13708                    clear_regular_buffer.read(cx).project_items[0].clone(),
13709                ])
13710        });
13711        workspace.update_in(cx, |workspace, window, cx| {
13712            workspace.add_item(
13713                pane.clone(),
13714                Box::new(dirty_regular_buffer.clone()),
13715                None,
13716                false,
13717                false,
13718                window,
13719                cx,
13720            );
13721            workspace.add_item(
13722                pane.clone(),
13723                Box::new(dirty_regular_buffer_2.clone()),
13724                None,
13725                false,
13726                false,
13727                window,
13728                cx,
13729            );
13730            workspace.add_item(
13731                pane.clone(),
13732                Box::new(dirty_multi_buffer.clone()),
13733                None,
13734                false,
13735                false,
13736                window,
13737                cx,
13738            );
13739        });
13740
13741        pane.update_in(cx, |pane, window, cx| {
13742            pane.activate_item(2, true, true, window, cx);
13743            assert_eq!(
13744                pane.active_item().unwrap().item_id(),
13745                dirty_multi_buffer.item_id(),
13746                "Should select the multi buffer in the pane"
13747            );
13748        });
13749        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13750            pane.close_active_item(
13751                &CloseActiveItem {
13752                    save_intent: None,
13753                    close_pinned: false,
13754                },
13755                window,
13756                cx,
13757            )
13758        });
13759        cx.background_executor.run_until_parked();
13760        assert!(
13761            !cx.has_pending_prompt(),
13762            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13763        );
13764        close_multi_buffer_task
13765            .await
13766            .expect("Closing multi buffer failed");
13767        pane.update(cx, |pane, cx| {
13768            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13769            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13770            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13771            assert_eq!(
13772                pane.items()
13773                    .map(|item| item.item_id())
13774                    .sorted()
13775                    .collect::<Vec<_>>(),
13776                vec![
13777                    dirty_regular_buffer.item_id(),
13778                    dirty_regular_buffer_2.item_id(),
13779                ],
13780                "Should have no multi buffer left in the pane"
13781            );
13782            assert!(dirty_regular_buffer.read(cx).is_dirty);
13783            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13784        });
13785    }
13786
13787    #[gpui::test]
13788    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13789        init_test(cx);
13790        let fs = FakeFs::new(cx.executor());
13791        let project = Project::test(fs, [], cx).await;
13792        let (multi_workspace, cx) =
13793            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13794        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13795
13796        // Add a new panel to the right dock, opening the dock and setting the
13797        // focus to the new panel.
13798        let panel = workspace.update_in(cx, |workspace, window, cx| {
13799            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13800            workspace.add_panel(panel.clone(), window, cx);
13801
13802            workspace
13803                .right_dock()
13804                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13805
13806            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13807
13808            panel
13809        });
13810
13811        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13812        // panel to the next valid position which, in this case, is the left
13813        // dock.
13814        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13815        workspace.update(cx, |workspace, cx| {
13816            assert!(workspace.left_dock().read(cx).is_open());
13817            assert_eq!(panel.read(cx).position, DockPosition::Left);
13818        });
13819
13820        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13821        // panel to the next valid position which, in this case, is the bottom
13822        // dock.
13823        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13824        workspace.update(cx, |workspace, cx| {
13825            assert!(workspace.bottom_dock().read(cx).is_open());
13826            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13827        });
13828
13829        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13830        // around moving the panel to its initial position, the right dock.
13831        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13832        workspace.update(cx, |workspace, cx| {
13833            assert!(workspace.right_dock().read(cx).is_open());
13834            assert_eq!(panel.read(cx).position, DockPosition::Right);
13835        });
13836
13837        // Remove focus from the panel, ensuring that, if the panel is not
13838        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13839        // the panel's position, so the panel is still in the right dock.
13840        workspace.update_in(cx, |workspace, window, cx| {
13841            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13842        });
13843
13844        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13845        workspace.update(cx, |workspace, cx| {
13846            assert!(workspace.right_dock().read(cx).is_open());
13847            assert_eq!(panel.read(cx).position, DockPosition::Right);
13848        });
13849    }
13850
13851    #[gpui::test]
13852    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13853        init_test(cx);
13854
13855        let fs = FakeFs::new(cx.executor());
13856        let project = Project::test(fs, [], cx).await;
13857        let (workspace, cx) =
13858            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13859
13860        let item_1 = cx.new(|cx| {
13861            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13862        });
13863        workspace.update_in(cx, |workspace, window, cx| {
13864            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13865            workspace.move_item_to_pane_in_direction(
13866                &MoveItemToPaneInDirection {
13867                    direction: SplitDirection::Right,
13868                    focus: true,
13869                    clone: false,
13870                },
13871                window,
13872                cx,
13873            );
13874            workspace.move_item_to_pane_at_index(
13875                &MoveItemToPane {
13876                    destination: 3,
13877                    focus: true,
13878                    clone: false,
13879                },
13880                window,
13881                cx,
13882            );
13883
13884            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13885            assert_eq!(
13886                pane_items_paths(&workspace.active_pane, cx),
13887                vec!["first.txt".to_string()],
13888                "Single item was not moved anywhere"
13889            );
13890        });
13891
13892        let item_2 = cx.new(|cx| {
13893            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13894        });
13895        workspace.update_in(cx, |workspace, window, cx| {
13896            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13897            assert_eq!(
13898                pane_items_paths(&workspace.panes[0], cx),
13899                vec!["first.txt".to_string(), "second.txt".to_string()],
13900            );
13901            workspace.move_item_to_pane_in_direction(
13902                &MoveItemToPaneInDirection {
13903                    direction: SplitDirection::Right,
13904                    focus: true,
13905                    clone: false,
13906                },
13907                window,
13908                cx,
13909            );
13910
13911            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13912            assert_eq!(
13913                pane_items_paths(&workspace.panes[0], cx),
13914                vec!["first.txt".to_string()],
13915                "After moving, one item should be left in the original pane"
13916            );
13917            assert_eq!(
13918                pane_items_paths(&workspace.panes[1], cx),
13919                vec!["second.txt".to_string()],
13920                "New item should have been moved to the new pane"
13921            );
13922        });
13923
13924        let item_3 = cx.new(|cx| {
13925            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13926        });
13927        workspace.update_in(cx, |workspace, window, cx| {
13928            let original_pane = workspace.panes[0].clone();
13929            workspace.set_active_pane(&original_pane, window, cx);
13930            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13931            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13932            assert_eq!(
13933                pane_items_paths(&workspace.active_pane, cx),
13934                vec!["first.txt".to_string(), "third.txt".to_string()],
13935                "New pane should be ready to move one item out"
13936            );
13937
13938            workspace.move_item_to_pane_at_index(
13939                &MoveItemToPane {
13940                    destination: 3,
13941                    focus: true,
13942                    clone: false,
13943                },
13944                window,
13945                cx,
13946            );
13947            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13948            assert_eq!(
13949                pane_items_paths(&workspace.active_pane, cx),
13950                vec!["first.txt".to_string()],
13951                "After moving, one item should be left in the original pane"
13952            );
13953            assert_eq!(
13954                pane_items_paths(&workspace.panes[1], cx),
13955                vec!["second.txt".to_string()],
13956                "Previously created pane should be unchanged"
13957            );
13958            assert_eq!(
13959                pane_items_paths(&workspace.panes[2], cx),
13960                vec!["third.txt".to_string()],
13961                "New item should have been moved to the new pane"
13962            );
13963        });
13964    }
13965
13966    #[gpui::test]
13967    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13968        init_test(cx);
13969
13970        let fs = FakeFs::new(cx.executor());
13971        let project = Project::test(fs, [], cx).await;
13972        let (workspace, cx) =
13973            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13974
13975        let item_1 = cx.new(|cx| {
13976            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13977        });
13978        workspace.update_in(cx, |workspace, window, cx| {
13979            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13980            workspace.move_item_to_pane_in_direction(
13981                &MoveItemToPaneInDirection {
13982                    direction: SplitDirection::Right,
13983                    focus: true,
13984                    clone: true,
13985                },
13986                window,
13987                cx,
13988            );
13989        });
13990        cx.run_until_parked();
13991        workspace.update_in(cx, |workspace, window, cx| {
13992            workspace.move_item_to_pane_at_index(
13993                &MoveItemToPane {
13994                    destination: 3,
13995                    focus: true,
13996                    clone: true,
13997                },
13998                window,
13999                cx,
14000            );
14001        });
14002        cx.run_until_parked();
14003
14004        workspace.update(cx, |workspace, cx| {
14005            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14006            for pane in workspace.panes() {
14007                assert_eq!(
14008                    pane_items_paths(pane, cx),
14009                    vec!["first.txt".to_string()],
14010                    "Single item exists in all panes"
14011                );
14012            }
14013        });
14014
14015        // verify that the active pane has been updated after waiting for the
14016        // pane focus event to fire and resolve
14017        workspace.read_with(cx, |workspace, _app| {
14018            assert_eq!(
14019                workspace.active_pane(),
14020                &workspace.panes[2],
14021                "The third pane should be the active one: {:?}",
14022                workspace.panes
14023            );
14024        })
14025    }
14026
14027    #[gpui::test]
14028    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14029        init_test(cx);
14030
14031        let fs = FakeFs::new(cx.executor());
14032        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14033
14034        let project = Project::test(fs, ["root".as_ref()], cx).await;
14035        let (workspace, cx) =
14036            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14037
14038        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14039        // Add item to pane A with project path
14040        let item_a = cx.new(|cx| {
14041            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14042        });
14043        workspace.update_in(cx, |workspace, window, cx| {
14044            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14045        });
14046
14047        // Split to create pane B
14048        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14049            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14050        });
14051
14052        // Add item with SAME project path to pane B, and pin it
14053        let item_b = cx.new(|cx| {
14054            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14055        });
14056        pane_b.update_in(cx, |pane, window, cx| {
14057            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14058            pane.set_pinned_count(1);
14059        });
14060
14061        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14062        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14063
14064        // close_pinned: false should only close the unpinned copy
14065        workspace.update_in(cx, |workspace, window, cx| {
14066            workspace.close_item_in_all_panes(
14067                &CloseItemInAllPanes {
14068                    save_intent: Some(SaveIntent::Close),
14069                    close_pinned: false,
14070                },
14071                window,
14072                cx,
14073            )
14074        });
14075        cx.executor().run_until_parked();
14076
14077        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14078        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14079        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14080        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14081
14082        // Split again, seeing as closing the previous item also closed its
14083        // pane, so only pane remains, which does not allow us to properly test
14084        // that both items close when `close_pinned: true`.
14085        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14086            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14087        });
14088
14089        // Add an item with the same project path to pane C so that
14090        // close_item_in_all_panes can determine what to close across all panes
14091        // (it reads the active item from the active pane, and split_pane
14092        // creates an empty pane).
14093        let item_c = cx.new(|cx| {
14094            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14095        });
14096        pane_c.update_in(cx, |pane, window, cx| {
14097            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14098        });
14099
14100        // close_pinned: true should close the pinned copy too
14101        workspace.update_in(cx, |workspace, window, cx| {
14102            let panes_count = workspace.panes().len();
14103            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14104
14105            workspace.close_item_in_all_panes(
14106                &CloseItemInAllPanes {
14107                    save_intent: Some(SaveIntent::Close),
14108                    close_pinned: true,
14109                },
14110                window,
14111                cx,
14112            )
14113        });
14114        cx.executor().run_until_parked();
14115
14116        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14117        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14118        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14119        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14120    }
14121
14122    mod register_project_item_tests {
14123
14124        use super::*;
14125
14126        // View
14127        struct TestPngItemView {
14128            focus_handle: FocusHandle,
14129        }
14130        // Model
14131        struct TestPngItem {}
14132
14133        impl project::ProjectItem for TestPngItem {
14134            fn try_open(
14135                _project: &Entity<Project>,
14136                path: &ProjectPath,
14137                cx: &mut App,
14138            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14139                if path.path.extension().unwrap() == "png" {
14140                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14141                } else {
14142                    None
14143                }
14144            }
14145
14146            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14147                None
14148            }
14149
14150            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14151                None
14152            }
14153
14154            fn is_dirty(&self) -> bool {
14155                false
14156            }
14157        }
14158
14159        impl Item for TestPngItemView {
14160            type Event = ();
14161            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14162                "".into()
14163            }
14164        }
14165        impl EventEmitter<()> for TestPngItemView {}
14166        impl Focusable for TestPngItemView {
14167            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14168                self.focus_handle.clone()
14169            }
14170        }
14171
14172        impl Render for TestPngItemView {
14173            fn render(
14174                &mut self,
14175                _window: &mut Window,
14176                _cx: &mut Context<Self>,
14177            ) -> impl IntoElement {
14178                Empty
14179            }
14180        }
14181
14182        impl ProjectItem for TestPngItemView {
14183            type Item = TestPngItem;
14184
14185            fn for_project_item(
14186                _project: Entity<Project>,
14187                _pane: Option<&Pane>,
14188                _item: Entity<Self::Item>,
14189                _: &mut Window,
14190                cx: &mut Context<Self>,
14191            ) -> Self
14192            where
14193                Self: Sized,
14194            {
14195                Self {
14196                    focus_handle: cx.focus_handle(),
14197                }
14198            }
14199        }
14200
14201        // View
14202        struct TestIpynbItemView {
14203            focus_handle: FocusHandle,
14204        }
14205        // Model
14206        struct TestIpynbItem {}
14207
14208        impl project::ProjectItem for TestIpynbItem {
14209            fn try_open(
14210                _project: &Entity<Project>,
14211                path: &ProjectPath,
14212                cx: &mut App,
14213            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14214                if path.path.extension().unwrap() == "ipynb" {
14215                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14216                } else {
14217                    None
14218                }
14219            }
14220
14221            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14222                None
14223            }
14224
14225            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14226                None
14227            }
14228
14229            fn is_dirty(&self) -> bool {
14230                false
14231            }
14232        }
14233
14234        impl Item for TestIpynbItemView {
14235            type Event = ();
14236            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14237                "".into()
14238            }
14239        }
14240        impl EventEmitter<()> for TestIpynbItemView {}
14241        impl Focusable for TestIpynbItemView {
14242            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14243                self.focus_handle.clone()
14244            }
14245        }
14246
14247        impl Render for TestIpynbItemView {
14248            fn render(
14249                &mut self,
14250                _window: &mut Window,
14251                _cx: &mut Context<Self>,
14252            ) -> impl IntoElement {
14253                Empty
14254            }
14255        }
14256
14257        impl ProjectItem for TestIpynbItemView {
14258            type Item = TestIpynbItem;
14259
14260            fn for_project_item(
14261                _project: Entity<Project>,
14262                _pane: Option<&Pane>,
14263                _item: Entity<Self::Item>,
14264                _: &mut Window,
14265                cx: &mut Context<Self>,
14266            ) -> Self
14267            where
14268                Self: Sized,
14269            {
14270                Self {
14271                    focus_handle: cx.focus_handle(),
14272                }
14273            }
14274        }
14275
14276        struct TestAlternatePngItemView {
14277            focus_handle: FocusHandle,
14278        }
14279
14280        impl Item for TestAlternatePngItemView {
14281            type Event = ();
14282            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14283                "".into()
14284            }
14285        }
14286
14287        impl EventEmitter<()> for TestAlternatePngItemView {}
14288        impl Focusable for TestAlternatePngItemView {
14289            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14290                self.focus_handle.clone()
14291            }
14292        }
14293
14294        impl Render for TestAlternatePngItemView {
14295            fn render(
14296                &mut self,
14297                _window: &mut Window,
14298                _cx: &mut Context<Self>,
14299            ) -> impl IntoElement {
14300                Empty
14301            }
14302        }
14303
14304        impl ProjectItem for TestAlternatePngItemView {
14305            type Item = TestPngItem;
14306
14307            fn for_project_item(
14308                _project: Entity<Project>,
14309                _pane: Option<&Pane>,
14310                _item: Entity<Self::Item>,
14311                _: &mut Window,
14312                cx: &mut Context<Self>,
14313            ) -> Self
14314            where
14315                Self: Sized,
14316            {
14317                Self {
14318                    focus_handle: cx.focus_handle(),
14319                }
14320            }
14321        }
14322
14323        #[gpui::test]
14324        async fn test_register_project_item(cx: &mut TestAppContext) {
14325            init_test(cx);
14326
14327            cx.update(|cx| {
14328                register_project_item::<TestPngItemView>(cx);
14329                register_project_item::<TestIpynbItemView>(cx);
14330            });
14331
14332            let fs = FakeFs::new(cx.executor());
14333            fs.insert_tree(
14334                "/root1",
14335                json!({
14336                    "one.png": "BINARYDATAHERE",
14337                    "two.ipynb": "{ totally a notebook }",
14338                    "three.txt": "editing text, sure why not?"
14339                }),
14340            )
14341            .await;
14342
14343            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14344            let (workspace, cx) =
14345                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14346
14347            let worktree_id = project.update(cx, |project, cx| {
14348                project.worktrees(cx).next().unwrap().read(cx).id()
14349            });
14350
14351            let handle = workspace
14352                .update_in(cx, |workspace, window, cx| {
14353                    let project_path = (worktree_id, rel_path("one.png"));
14354                    workspace.open_path(project_path, None, true, window, cx)
14355                })
14356                .await
14357                .unwrap();
14358
14359            // Now we can check if the handle we got back errored or not
14360            assert_eq!(
14361                handle.to_any_view().entity_type(),
14362                TypeId::of::<TestPngItemView>()
14363            );
14364
14365            let handle = workspace
14366                .update_in(cx, |workspace, window, cx| {
14367                    let project_path = (worktree_id, rel_path("two.ipynb"));
14368                    workspace.open_path(project_path, None, true, window, cx)
14369                })
14370                .await
14371                .unwrap();
14372
14373            assert_eq!(
14374                handle.to_any_view().entity_type(),
14375                TypeId::of::<TestIpynbItemView>()
14376            );
14377
14378            let handle = workspace
14379                .update_in(cx, |workspace, window, cx| {
14380                    let project_path = (worktree_id, rel_path("three.txt"));
14381                    workspace.open_path(project_path, None, true, window, cx)
14382                })
14383                .await;
14384            assert!(handle.is_err());
14385        }
14386
14387        #[gpui::test]
14388        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14389            init_test(cx);
14390
14391            cx.update(|cx| {
14392                register_project_item::<TestPngItemView>(cx);
14393                register_project_item::<TestAlternatePngItemView>(cx);
14394            });
14395
14396            let fs = FakeFs::new(cx.executor());
14397            fs.insert_tree(
14398                "/root1",
14399                json!({
14400                    "one.png": "BINARYDATAHERE",
14401                    "two.ipynb": "{ totally a notebook }",
14402                    "three.txt": "editing text, sure why not?"
14403                }),
14404            )
14405            .await;
14406            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14407            let (workspace, cx) =
14408                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14409            let worktree_id = project.update(cx, |project, cx| {
14410                project.worktrees(cx).next().unwrap().read(cx).id()
14411            });
14412
14413            let handle = workspace
14414                .update_in(cx, |workspace, window, cx| {
14415                    let project_path = (worktree_id, rel_path("one.png"));
14416                    workspace.open_path(project_path, None, true, window, cx)
14417                })
14418                .await
14419                .unwrap();
14420
14421            // This _must_ be the second item registered
14422            assert_eq!(
14423                handle.to_any_view().entity_type(),
14424                TypeId::of::<TestAlternatePngItemView>()
14425            );
14426
14427            let handle = workspace
14428                .update_in(cx, |workspace, window, cx| {
14429                    let project_path = (worktree_id, rel_path("three.txt"));
14430                    workspace.open_path(project_path, None, true, window, cx)
14431                })
14432                .await;
14433            assert!(handle.is_err());
14434        }
14435    }
14436
14437    #[gpui::test]
14438    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14439        init_test(cx);
14440
14441        let fs = FakeFs::new(cx.executor());
14442        let project = Project::test(fs, [], cx).await;
14443        let (workspace, _cx) =
14444            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14445
14446        // Test with status bar shown (default)
14447        workspace.read_with(cx, |workspace, cx| {
14448            let visible = workspace.status_bar_visible(cx);
14449            assert!(visible, "Status bar should be visible by default");
14450        });
14451
14452        // Test with status bar hidden
14453        cx.update_global(|store: &mut SettingsStore, cx| {
14454            store.update_user_settings(cx, |settings| {
14455                settings.status_bar.get_or_insert_default().show = Some(false);
14456            });
14457        });
14458
14459        workspace.read_with(cx, |workspace, cx| {
14460            let visible = workspace.status_bar_visible(cx);
14461            assert!(!visible, "Status bar should be hidden when show is false");
14462        });
14463
14464        // Test with status bar shown explicitly
14465        cx.update_global(|store: &mut SettingsStore, cx| {
14466            store.update_user_settings(cx, |settings| {
14467                settings.status_bar.get_or_insert_default().show = Some(true);
14468            });
14469        });
14470
14471        workspace.read_with(cx, |workspace, cx| {
14472            let visible = workspace.status_bar_visible(cx);
14473            assert!(visible, "Status bar should be visible when show is true");
14474        });
14475    }
14476
14477    #[gpui::test]
14478    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14479        init_test(cx);
14480
14481        let fs = FakeFs::new(cx.executor());
14482        let project = Project::test(fs, [], cx).await;
14483        let (multi_workspace, cx) =
14484            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14485        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14486        let panel = workspace.update_in(cx, |workspace, window, cx| {
14487            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14488            workspace.add_panel(panel.clone(), window, cx);
14489
14490            workspace
14491                .right_dock()
14492                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14493
14494            panel
14495        });
14496
14497        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14498        let item_a = cx.new(TestItem::new);
14499        let item_b = cx.new(TestItem::new);
14500        let item_a_id = item_a.entity_id();
14501        let item_b_id = item_b.entity_id();
14502
14503        pane.update_in(cx, |pane, window, cx| {
14504            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14505            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14506        });
14507
14508        pane.read_with(cx, |pane, _| {
14509            assert_eq!(pane.items_len(), 2);
14510            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14511        });
14512
14513        workspace.update_in(cx, |workspace, window, cx| {
14514            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14515        });
14516
14517        workspace.update_in(cx, |_, window, cx| {
14518            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14519        });
14520
14521        // Assert that the `pane::CloseActiveItem` action is handled at the
14522        // workspace level when one of the dock panels is focused and, in that
14523        // case, the center pane's active item is closed but the focus is not
14524        // moved.
14525        cx.dispatch_action(pane::CloseActiveItem::default());
14526        cx.run_until_parked();
14527
14528        pane.read_with(cx, |pane, _| {
14529            assert_eq!(pane.items_len(), 1);
14530            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14531        });
14532
14533        workspace.update_in(cx, |workspace, window, cx| {
14534            assert!(workspace.right_dock().read(cx).is_open());
14535            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14536        });
14537    }
14538
14539    #[gpui::test]
14540    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14541        init_test(cx);
14542        let fs = FakeFs::new(cx.executor());
14543
14544        let project_a = Project::test(fs.clone(), [], cx).await;
14545        let project_b = Project::test(fs, [], cx).await;
14546
14547        let multi_workspace_handle =
14548            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14549        cx.run_until_parked();
14550
14551        let workspace_a = multi_workspace_handle
14552            .read_with(cx, |mw, _| mw.workspace().clone())
14553            .unwrap();
14554
14555        let _workspace_b = multi_workspace_handle
14556            .update(cx, |mw, window, cx| {
14557                mw.test_add_workspace(project_b, window, cx)
14558            })
14559            .unwrap();
14560
14561        // Switch to workspace A
14562        multi_workspace_handle
14563            .update(cx, |mw, window, cx| {
14564                let workspace = mw.workspaces().next().expect("no workspace").clone();
14565                mw.activate(workspace, window, cx);
14566            })
14567            .unwrap();
14568
14569        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14570
14571        // Add a panel to workspace A's right dock and open the dock
14572        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14573            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14574            workspace.add_panel(panel.clone(), window, cx);
14575            workspace
14576                .right_dock()
14577                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14578            panel
14579        });
14580
14581        // Focus the panel through the workspace (matching existing test pattern)
14582        workspace_a.update_in(cx, |workspace, window, cx| {
14583            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14584        });
14585
14586        // Zoom the panel
14587        panel.update_in(cx, |panel, window, cx| {
14588            panel.set_zoomed(true, window, cx);
14589        });
14590
14591        // Verify the panel is zoomed and the dock is open
14592        workspace_a.update_in(cx, |workspace, window, cx| {
14593            assert!(
14594                workspace.right_dock().read(cx).is_open(),
14595                "dock should be open before switch"
14596            );
14597            assert!(
14598                panel.is_zoomed(window, cx),
14599                "panel should be zoomed before switch"
14600            );
14601            assert!(
14602                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14603                "panel should be focused before switch"
14604            );
14605        });
14606
14607        // Switch to workspace B
14608        multi_workspace_handle
14609            .update(cx, |mw, window, cx| {
14610                let workspace = mw
14611                    .workspaces()
14612                    .nth(1)
14613                    .expect("no workspace at index 1")
14614                    .clone();
14615                mw.activate(workspace, window, cx);
14616            })
14617            .unwrap();
14618        cx.run_until_parked();
14619
14620        // Switch back to workspace A
14621        multi_workspace_handle
14622            .update(cx, |mw, window, cx| {
14623                let workspace = mw
14624                    .workspaces()
14625                    .nth(0)
14626                    .expect("no workspace at index 0")
14627                    .clone();
14628                mw.activate(workspace, window, cx);
14629            })
14630            .unwrap();
14631        cx.run_until_parked();
14632
14633        // Verify the panel is still zoomed and the dock is still open
14634        workspace_a.update_in(cx, |workspace, window, cx| {
14635            assert!(
14636                workspace.right_dock().read(cx).is_open(),
14637                "dock should still be open after switching back"
14638            );
14639            assert!(
14640                panel.is_zoomed(window, cx),
14641                "panel should still be zoomed after switching back"
14642            );
14643        });
14644    }
14645
14646    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14647        pane.read(cx)
14648            .items()
14649            .flat_map(|item| {
14650                item.project_paths(cx)
14651                    .into_iter()
14652                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14653            })
14654            .collect()
14655    }
14656
14657    pub fn init_test(cx: &mut TestAppContext) {
14658        cx.update(|cx| {
14659            let settings_store = SettingsStore::test(cx);
14660            cx.set_global(settings_store);
14661            cx.set_global(db::AppDatabase::test_new());
14662            theme_settings::init(theme::LoadThemes::JustBase, cx);
14663        });
14664    }
14665
14666    #[gpui::test]
14667    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14668        use settings::{ThemeName, ThemeSelection};
14669        use theme::SystemAppearance;
14670        use zed_actions::theme::ToggleMode;
14671
14672        init_test(cx);
14673
14674        let fs = FakeFs::new(cx.executor());
14675        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14676
14677        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14678            .await;
14679
14680        // Build a test project and workspace view so the test can invoke
14681        // the workspace action handler the same way the UI would.
14682        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14683        let (workspace, cx) =
14684            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14685
14686        // Seed the settings file with a plain static light theme so the
14687        // first toggle always starts from a known persisted state.
14688        workspace.update_in(cx, |_workspace, _window, cx| {
14689            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14690            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14691                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14692            });
14693        });
14694        cx.executor().advance_clock(Duration::from_millis(200));
14695        cx.run_until_parked();
14696
14697        // Confirm the initial persisted settings contain the static theme
14698        // we just wrote before any toggling happens.
14699        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14700        assert!(settings_text.contains(r#""theme": "One Light""#));
14701
14702        // Toggle once. This should migrate the persisted theme settings
14703        // into light/dark slots and enable system mode.
14704        workspace.update_in(cx, |workspace, window, cx| {
14705            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14706        });
14707        cx.executor().advance_clock(Duration::from_millis(200));
14708        cx.run_until_parked();
14709
14710        // 1. Static -> Dynamic
14711        // this assertion checks theme changed from static to dynamic.
14712        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14713        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14714        assert_eq!(
14715            parsed["theme"],
14716            serde_json::json!({
14717                "mode": "system",
14718                "light": "One Light",
14719                "dark": "One Dark"
14720            })
14721        );
14722
14723        // 2. Toggle again, suppose it will change the mode to light
14724        workspace.update_in(cx, |workspace, window, cx| {
14725            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14726        });
14727        cx.executor().advance_clock(Duration::from_millis(200));
14728        cx.run_until_parked();
14729
14730        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14731        assert!(settings_text.contains(r#""mode": "light""#));
14732    }
14733
14734    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14735        let item = TestProjectItem::new(id, path, cx);
14736        item.update(cx, |item, _| {
14737            item.is_dirty = true;
14738        });
14739        item
14740    }
14741
14742    #[gpui::test]
14743    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14744        cx: &mut gpui::TestAppContext,
14745    ) {
14746        init_test(cx);
14747        let fs = FakeFs::new(cx.executor());
14748
14749        let project = Project::test(fs, [], cx).await;
14750        let (workspace, cx) =
14751            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14752
14753        let panel = workspace.update_in(cx, |workspace, window, cx| {
14754            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14755            workspace.add_panel(panel.clone(), window, cx);
14756            workspace
14757                .right_dock()
14758                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14759            panel
14760        });
14761
14762        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14763        pane.update_in(cx, |pane, window, cx| {
14764            let item = cx.new(TestItem::new);
14765            pane.add_item(Box::new(item), true, true, None, window, cx);
14766        });
14767
14768        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14769        // mirrors the real-world flow and avoids side effects from directly
14770        // focusing the panel while the center pane is active.
14771        workspace.update_in(cx, |workspace, window, cx| {
14772            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14773        });
14774
14775        panel.update_in(cx, |panel, window, cx| {
14776            panel.set_zoomed(true, window, cx);
14777        });
14778
14779        workspace.update_in(cx, |workspace, window, cx| {
14780            assert!(workspace.right_dock().read(cx).is_open());
14781            assert!(panel.is_zoomed(window, cx));
14782            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14783        });
14784
14785        // Simulate a spurious pane::Event::Focus on the center pane while the
14786        // panel still has focus. This mirrors what happens during macOS window
14787        // activation: the center pane fires a focus event even though actual
14788        // focus remains on the dock panel.
14789        pane.update_in(cx, |_, _, cx| {
14790            cx.emit(pane::Event::Focus);
14791        });
14792
14793        // The dock must remain open because the panel had focus at the time the
14794        // event was processed. Before the fix, dock_to_preserve was None for
14795        // panels that don't implement pane(), causing the dock to close.
14796        workspace.update_in(cx, |workspace, window, cx| {
14797            assert!(
14798                workspace.right_dock().read(cx).is_open(),
14799                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14800            );
14801            assert!(panel.is_zoomed(window, cx));
14802        });
14803    }
14804
14805    #[gpui::test]
14806    async fn test_panels_stay_open_after_position_change_and_settings_update(
14807        cx: &mut gpui::TestAppContext,
14808    ) {
14809        init_test(cx);
14810        let fs = FakeFs::new(cx.executor());
14811        let project = Project::test(fs, [], cx).await;
14812        let (workspace, cx) =
14813            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14814
14815        // Add two panels to the left dock and open it.
14816        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14817            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14818            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14819            workspace.add_panel(panel_a.clone(), window, cx);
14820            workspace.add_panel(panel_b.clone(), window, cx);
14821            workspace.left_dock().update(cx, |dock, cx| {
14822                dock.set_open(true, window, cx);
14823                dock.activate_panel(0, window, cx);
14824            });
14825            (panel_a, panel_b)
14826        });
14827
14828        workspace.update_in(cx, |workspace, _, cx| {
14829            assert!(workspace.left_dock().read(cx).is_open());
14830        });
14831
14832        // Simulate a feature flag changing default dock positions: both panels
14833        // move from Left to Right.
14834        workspace.update_in(cx, |_workspace, _window, cx| {
14835            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14836            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14837            cx.update_global::<SettingsStore, _>(|_, _| {});
14838        });
14839
14840        // Both panels should now be in the right dock.
14841        workspace.update_in(cx, |workspace, _, cx| {
14842            let right_dock = workspace.right_dock().read(cx);
14843            assert_eq!(right_dock.panels_len(), 2);
14844        });
14845
14846        // Open the right dock and activate panel_b (simulating the user
14847        // opening the panel after it moved).
14848        workspace.update_in(cx, |workspace, window, cx| {
14849            workspace.right_dock().update(cx, |dock, cx| {
14850                dock.set_open(true, window, cx);
14851                dock.activate_panel(1, window, cx);
14852            });
14853        });
14854
14855        // Now trigger another SettingsStore change
14856        workspace.update_in(cx, |_workspace, _window, cx| {
14857            cx.update_global::<SettingsStore, _>(|_, _| {});
14858        });
14859
14860        workspace.update_in(cx, |workspace, _, cx| {
14861            assert!(
14862                workspace.right_dock().read(cx).is_open(),
14863                "Right dock should still be open after a settings change"
14864            );
14865            assert_eq!(
14866                workspace.right_dock().read(cx).panels_len(),
14867                2,
14868                "Both panels should still be in the right dock"
14869            );
14870        });
14871    }
14872}