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, ProjectGroupKey, Sidebar, SidebarEvent,
   35    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    _panels_task: Option<Task<Result<()>>>,
 1349    sidebar_focus_handle: Option<FocusHandle>,
 1350    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1351}
 1352
 1353impl EventEmitter<Event> for Workspace {}
 1354
 1355#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1356pub struct ViewId {
 1357    pub creator: CollaboratorId,
 1358    pub id: u64,
 1359}
 1360
 1361pub struct FollowerState {
 1362    center_pane: Entity<Pane>,
 1363    dock_pane: Option<Entity<Pane>>,
 1364    active_view_id: Option<ViewId>,
 1365    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1366}
 1367
 1368struct FollowerView {
 1369    view: Box<dyn FollowableItemHandle>,
 1370    location: Option<proto::PanelId>,
 1371}
 1372
 1373#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1374pub enum OpenMode {
 1375    /// Open the workspace in a new window.
 1376    NewWindow,
 1377    /// Add to the window's multi workspace without activating it (used during deserialization).
 1378    Add,
 1379    /// Add to the window's multi workspace and activate it.
 1380    #[default]
 1381    Activate,
 1382    /// Replace the currently active workspace, and any of it's linked workspaces
 1383    Replace,
 1384}
 1385
 1386impl Workspace {
 1387    pub fn new(
 1388        workspace_id: Option<WorkspaceId>,
 1389        project: Entity<Project>,
 1390        app_state: Arc<AppState>,
 1391        window: &mut Window,
 1392        cx: &mut Context<Self>,
 1393    ) -> Self {
 1394        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1395            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1396                if let TrustedWorktreesEvent::Trusted(..) = e {
 1397                    // Do not persist auto trusted worktrees
 1398                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1399                        worktrees_store.update(cx, |worktrees_store, cx| {
 1400                            worktrees_store.schedule_serialization(
 1401                                cx,
 1402                                |new_trusted_worktrees, cx| {
 1403                                    let timeout =
 1404                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1405                                    let db = WorkspaceDb::global(cx);
 1406                                    cx.background_spawn(async move {
 1407                                        timeout.await;
 1408                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1409                                            .await
 1410                                            .log_err();
 1411                                    })
 1412                                },
 1413                            )
 1414                        });
 1415                    }
 1416                }
 1417            })
 1418            .detach();
 1419
 1420            cx.observe_global::<SettingsStore>(|_, cx| {
 1421                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1422                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1423                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1424                            trusted_worktrees.auto_trust_all(cx);
 1425                        })
 1426                    }
 1427                }
 1428            })
 1429            .detach();
 1430        }
 1431
 1432        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1433            match event {
 1434                project::Event::RemoteIdChanged(_) => {
 1435                    this.update_window_title(window, cx);
 1436                }
 1437
 1438                project::Event::CollaboratorLeft(peer_id) => {
 1439                    this.collaborator_left(*peer_id, window, cx);
 1440                }
 1441
 1442                &project::Event::WorktreeRemoved(_) => {
 1443                    this.update_window_title(window, cx);
 1444                    this.serialize_workspace(window, cx);
 1445                    this.update_history(cx);
 1446                }
 1447
 1448                &project::Event::WorktreeAdded(id) => {
 1449                    this.update_window_title(window, cx);
 1450                    if this
 1451                        .project()
 1452                        .read(cx)
 1453                        .worktree_for_id(id, cx)
 1454                        .is_some_and(|wt| wt.read(cx).is_visible())
 1455                    {
 1456                        this.serialize_workspace(window, cx);
 1457                        this.update_history(cx);
 1458                    }
 1459                }
 1460                project::Event::WorktreeUpdatedEntries(..) => {
 1461                    this.update_window_title(window, cx);
 1462                    this.serialize_workspace(window, cx);
 1463                }
 1464
 1465                project::Event::DisconnectedFromHost => {
 1466                    this.update_window_edited(window, cx);
 1467                    let leaders_to_unfollow =
 1468                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1469                    for leader_id in leaders_to_unfollow {
 1470                        this.unfollow(leader_id, window, cx);
 1471                    }
 1472                }
 1473
 1474                project::Event::DisconnectedFromRemote {
 1475                    server_not_running: _,
 1476                } => {
 1477                    this.update_window_edited(window, cx);
 1478                }
 1479
 1480                project::Event::Closed => {
 1481                    window.remove_window();
 1482                }
 1483
 1484                project::Event::DeletedEntry(_, entry_id) => {
 1485                    for pane in this.panes.iter() {
 1486                        pane.update(cx, |pane, cx| {
 1487                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1488                        });
 1489                    }
 1490                }
 1491
 1492                project::Event::Toast {
 1493                    notification_id,
 1494                    message,
 1495                    link,
 1496                } => this.show_notification(
 1497                    NotificationId::named(notification_id.clone()),
 1498                    cx,
 1499                    |cx| {
 1500                        let mut notification = MessageNotification::new(message.clone(), cx);
 1501                        if let Some(link) = link {
 1502                            notification = notification
 1503                                .more_info_message(link.label)
 1504                                .more_info_url(link.url);
 1505                        }
 1506
 1507                        cx.new(|_| notification)
 1508                    },
 1509                ),
 1510
 1511                project::Event::HideToast { notification_id } => {
 1512                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1513                }
 1514
 1515                project::Event::LanguageServerPrompt(request) => {
 1516                    struct LanguageServerPrompt;
 1517
 1518                    this.show_notification(
 1519                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1520                        cx,
 1521                        |cx| {
 1522                            cx.new(|cx| {
 1523                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1524                            })
 1525                        },
 1526                    );
 1527                }
 1528
 1529                project::Event::AgentLocationChanged => {
 1530                    this.handle_agent_location_changed(window, cx)
 1531                }
 1532
 1533                _ => {}
 1534            }
 1535            cx.notify()
 1536        })
 1537        .detach();
 1538
 1539        cx.subscribe_in(
 1540            &project.read(cx).breakpoint_store(),
 1541            window,
 1542            |workspace, _, event, window, cx| match event {
 1543                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1544                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1545                    workspace.serialize_workspace(window, cx);
 1546                }
 1547                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1548            },
 1549        )
 1550        .detach();
 1551        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1552            cx.subscribe_in(
 1553                &toolchain_store,
 1554                window,
 1555                |workspace, _, event, window, cx| match event {
 1556                    ToolchainStoreEvent::CustomToolchainsModified => {
 1557                        workspace.serialize_workspace(window, cx);
 1558                    }
 1559                    _ => {}
 1560                },
 1561            )
 1562            .detach();
 1563        }
 1564
 1565        cx.on_focus_lost(window, |this, window, cx| {
 1566            let focus_handle = this.focus_handle(cx);
 1567            window.focus(&focus_handle, cx);
 1568        })
 1569        .detach();
 1570
 1571        let weak_handle = cx.entity().downgrade();
 1572        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1573
 1574        let center_pane = cx.new(|cx| {
 1575            let mut center_pane = Pane::new(
 1576                weak_handle.clone(),
 1577                project.clone(),
 1578                pane_history_timestamp.clone(),
 1579                None,
 1580                NewFile.boxed_clone(),
 1581                true,
 1582                window,
 1583                cx,
 1584            );
 1585            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1586            center_pane.set_should_display_welcome_page(true);
 1587            center_pane
 1588        });
 1589        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1590            .detach();
 1591
 1592        window.focus(&center_pane.focus_handle(cx), cx);
 1593
 1594        cx.emit(Event::PaneAdded(center_pane.clone()));
 1595
 1596        let any_window_handle = window.window_handle();
 1597        app_state.workspace_store.update(cx, |store, _| {
 1598            store
 1599                .workspaces
 1600                .insert((any_window_handle, weak_handle.clone()));
 1601        });
 1602
 1603        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1604        let mut connection_status = app_state.client.status();
 1605        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1606            current_user.next().await;
 1607            connection_status.next().await;
 1608            let mut stream =
 1609                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1610
 1611            while stream.recv().await.is_some() {
 1612                this.update(cx, |_, cx| cx.notify())?;
 1613            }
 1614            anyhow::Ok(())
 1615        });
 1616
 1617        // All leader updates are enqueued and then processed in a single task, so
 1618        // that each asynchronous operation can be run in order.
 1619        let (leader_updates_tx, mut leader_updates_rx) =
 1620            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1621        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1622            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1623                Self::process_leader_update(&this, leader_id, update, cx)
 1624                    .await
 1625                    .log_err();
 1626            }
 1627
 1628            Ok(())
 1629        });
 1630
 1631        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1632        let modal_layer = cx.new(|_| ModalLayer::new());
 1633        let toast_layer = cx.new(|_| ToastLayer::new());
 1634        cx.subscribe(
 1635            &modal_layer,
 1636            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1637                cx.emit(Event::ModalOpened);
 1638            },
 1639        )
 1640        .detach();
 1641
 1642        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1643        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1644        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1645        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1646        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1647        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1648        let multi_workspace = window
 1649            .root::<MultiWorkspace>()
 1650            .flatten()
 1651            .map(|mw| mw.downgrade());
 1652        let status_bar = cx.new(|cx| {
 1653            let mut status_bar =
 1654                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1655            status_bar.add_left_item(left_dock_buttons, window, cx);
 1656            status_bar.add_right_item(right_dock_buttons, window, cx);
 1657            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1658            status_bar
 1659        });
 1660
 1661        let session_id = app_state.session.read(cx).id().to_owned();
 1662
 1663        let mut active_call = None;
 1664        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1665            let subscriptions =
 1666                vec![
 1667                    call.0
 1668                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1669                ];
 1670            active_call = Some((call, subscriptions));
 1671        }
 1672
 1673        let (serializable_items_tx, serializable_items_rx) =
 1674            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1675        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1676            Self::serialize_items(&this, serializable_items_rx, cx).await
 1677        });
 1678
 1679        let subscriptions = vec![
 1680            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1681            cx.observe_window_bounds(window, move |this, window, cx| {
 1682                if this.bounds_save_task_queued.is_some() {
 1683                    return;
 1684                }
 1685                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1686                    cx.background_executor()
 1687                        .timer(Duration::from_millis(100))
 1688                        .await;
 1689                    this.update_in(cx, |this, window, cx| {
 1690                        this.save_window_bounds(window, cx).detach();
 1691                        this.bounds_save_task_queued.take();
 1692                    })
 1693                    .ok();
 1694                }));
 1695                cx.notify();
 1696            }),
 1697            cx.observe_window_appearance(window, |_, window, cx| {
 1698                let window_appearance = window.appearance();
 1699
 1700                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1701
 1702                theme_settings::reload_theme(cx);
 1703                theme_settings::reload_icon_theme(cx);
 1704            }),
 1705            cx.on_release({
 1706                let weak_handle = weak_handle.clone();
 1707                move |this, cx| {
 1708                    this.app_state.workspace_store.update(cx, move |store, _| {
 1709                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1710                    })
 1711                }
 1712            }),
 1713        ];
 1714
 1715        cx.defer_in(window, move |this, window, cx| {
 1716            this.update_window_title(window, cx);
 1717            this.show_initial_notifications(cx);
 1718        });
 1719
 1720        let mut center = PaneGroup::new(center_pane.clone());
 1721        center.set_is_center(true);
 1722        center.mark_positions(cx);
 1723
 1724        Workspace {
 1725            weak_self: weak_handle.clone(),
 1726            zoomed: None,
 1727            zoomed_position: None,
 1728            previous_dock_drag_coordinates: None,
 1729            center,
 1730            panes: vec![center_pane.clone()],
 1731            panes_by_item: Default::default(),
 1732            active_pane: center_pane.clone(),
 1733            last_active_center_pane: Some(center_pane.downgrade()),
 1734            last_active_view_id: None,
 1735            status_bar,
 1736            modal_layer,
 1737            toast_layer,
 1738            titlebar_item: None,
 1739            active_worktree_override: None,
 1740            notifications: Notifications::default(),
 1741            suppressed_notifications: HashSet::default(),
 1742            left_dock,
 1743            bottom_dock,
 1744            right_dock,
 1745            _panels_task: None,
 1746            project: project.clone(),
 1747            follower_states: Default::default(),
 1748            last_leaders_by_pane: Default::default(),
 1749            dispatching_keystrokes: Default::default(),
 1750            window_edited: false,
 1751            last_window_title: None,
 1752            dirty_items: Default::default(),
 1753            active_call,
 1754            database_id: workspace_id,
 1755            app_state,
 1756            _observe_current_user,
 1757            _apply_leader_updates,
 1758            _schedule_serialize_workspace: None,
 1759            _serialize_workspace_task: None,
 1760            _schedule_serialize_ssh_paths: None,
 1761            leader_updates_tx,
 1762            _subscriptions: subscriptions,
 1763            pane_history_timestamp,
 1764            workspace_actions: Default::default(),
 1765            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1766            bounds: Default::default(),
 1767            centered_layout: false,
 1768            bounds_save_task_queued: None,
 1769            on_prompt_for_new_path: None,
 1770            on_prompt_for_open_path: None,
 1771            terminal_provider: None,
 1772            debugger_provider: None,
 1773            serializable_items_tx,
 1774            _items_serializer,
 1775            session_id: Some(session_id),
 1776
 1777            scheduled_tasks: Vec::new(),
 1778            last_open_dock_positions: Vec::new(),
 1779            removing: false,
 1780            sidebar_focus_handle: None,
 1781            multi_workspace,
 1782        }
 1783    }
 1784
 1785    pub fn new_local(
 1786        abs_paths: Vec<PathBuf>,
 1787        app_state: Arc<AppState>,
 1788        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1789        env: Option<HashMap<String, String>>,
 1790        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1791        open_mode: OpenMode,
 1792        cx: &mut App,
 1793    ) -> Task<anyhow::Result<OpenResult>> {
 1794        let project_handle = Project::local(
 1795            app_state.client.clone(),
 1796            app_state.node_runtime.clone(),
 1797            app_state.user_store.clone(),
 1798            app_state.languages.clone(),
 1799            app_state.fs.clone(),
 1800            env,
 1801            Default::default(),
 1802            cx,
 1803        );
 1804
 1805        let db = WorkspaceDb::global(cx);
 1806        let kvp = db::kvp::KeyValueStore::global(cx);
 1807        cx.spawn(async move |cx| {
 1808            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1809            for path in abs_paths.into_iter() {
 1810                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1811                    paths_to_open.push(canonical)
 1812                } else {
 1813                    paths_to_open.push(path)
 1814                }
 1815            }
 1816
 1817            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1818
 1819            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1820                paths_to_open = paths.ordered_paths().cloned().collect();
 1821                if !paths.is_lexicographically_ordered() {
 1822                    project_handle.update(cx, |project, cx| {
 1823                        project.set_worktrees_reordered(true, cx);
 1824                    });
 1825                }
 1826            }
 1827
 1828            // Get project paths for all of the abs_paths
 1829            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1830                Vec::with_capacity(paths_to_open.len());
 1831
 1832            for path in paths_to_open.into_iter() {
 1833                if let Some((_, project_entry)) = cx
 1834                    .update(|cx| {
 1835                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1836                    })
 1837                    .await
 1838                    .log_err()
 1839                {
 1840                    project_paths.push((path, Some(project_entry)));
 1841                } else {
 1842                    project_paths.push((path, None));
 1843                }
 1844            }
 1845
 1846            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1847                serialized_workspace.id
 1848            } else {
 1849                db.next_id().await.unwrap_or_else(|_| Default::default())
 1850            };
 1851
 1852            let toolchains = db.toolchains(workspace_id).await?;
 1853
 1854            for (toolchain, worktree_path, path) in toolchains {
 1855                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1856                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1857                    this.find_worktree(&worktree_path, cx)
 1858                        .and_then(|(worktree, rel_path)| {
 1859                            if rel_path.is_empty() {
 1860                                Some(worktree.read(cx).id())
 1861                            } else {
 1862                                None
 1863                            }
 1864                        })
 1865                }) else {
 1866                    // We did not find a worktree with a given path, but that's whatever.
 1867                    continue;
 1868                };
 1869                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1870                    continue;
 1871                }
 1872
 1873                project_handle
 1874                    .update(cx, |this, cx| {
 1875                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1876                    })
 1877                    .await;
 1878            }
 1879            if let Some(workspace) = serialized_workspace.as_ref() {
 1880                project_handle.update(cx, |this, cx| {
 1881                    for (scope, toolchains) in &workspace.user_toolchains {
 1882                        for toolchain in toolchains {
 1883                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1884                        }
 1885                    }
 1886                });
 1887            }
 1888
 1889            let window_to_replace = match open_mode {
 1890                OpenMode::NewWindow => None,
 1891                _ => requesting_window,
 1892            };
 1893
 1894            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1895                if let Some(window) = window_to_replace {
 1896                    let centered_layout = serialized_workspace
 1897                        .as_ref()
 1898                        .map(|w| w.centered_layout)
 1899                        .unwrap_or(false);
 1900
 1901                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1902                        let workspace = cx.new(|cx| {
 1903                            let mut workspace = Workspace::new(
 1904                                Some(workspace_id),
 1905                                project_handle.clone(),
 1906                                app_state.clone(),
 1907                                window,
 1908                                cx,
 1909                            );
 1910
 1911                            workspace.centered_layout = centered_layout;
 1912
 1913                            // Call init callback to add items before window renders
 1914                            if let Some(init) = init {
 1915                                init(&mut workspace, window, cx);
 1916                            }
 1917
 1918                            workspace
 1919                        });
 1920                        match open_mode {
 1921                            OpenMode::Replace => {
 1922                                multi_workspace.replace(workspace.clone(), &*window, cx);
 1923                            }
 1924                            OpenMode::Activate => {
 1925                                multi_workspace.activate(workspace.clone(), window, cx);
 1926                            }
 1927                            OpenMode::Add => {
 1928                                multi_workspace.add(workspace.clone(), &*window, cx);
 1929                            }
 1930                            OpenMode::NewWindow => {
 1931                                unreachable!()
 1932                            }
 1933                        }
 1934                        workspace
 1935                    })?;
 1936                    (window, workspace)
 1937                } else {
 1938                    let window_bounds_override = window_bounds_env_override();
 1939
 1940                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1941                        (Some(WindowBounds::Windowed(bounds)), None)
 1942                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1943                        && let Some(display) = workspace.display
 1944                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1945                    {
 1946                        // Reopening an existing workspace - restore its saved bounds
 1947                        (Some(bounds.0), Some(display))
 1948                    } else if let Some((display, bounds)) =
 1949                        persistence::read_default_window_bounds(&kvp)
 1950                    {
 1951                        // New or empty workspace - use the last known window bounds
 1952                        (Some(bounds), Some(display))
 1953                    } else {
 1954                        // New window - let GPUI's default_bounds() handle cascading
 1955                        (None, None)
 1956                    };
 1957
 1958                    // Use the serialized workspace to construct the new window
 1959                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1960                    options.window_bounds = window_bounds;
 1961                    let centered_layout = serialized_workspace
 1962                        .as_ref()
 1963                        .map(|w| w.centered_layout)
 1964                        .unwrap_or(false);
 1965                    let window = cx.open_window(options, {
 1966                        let app_state = app_state.clone();
 1967                        let project_handle = project_handle.clone();
 1968                        move |window, cx| {
 1969                            let workspace = cx.new(|cx| {
 1970                                let mut workspace = Workspace::new(
 1971                                    Some(workspace_id),
 1972                                    project_handle,
 1973                                    app_state,
 1974                                    window,
 1975                                    cx,
 1976                                );
 1977                                workspace.centered_layout = centered_layout;
 1978
 1979                                // Call init callback to add items before window renders
 1980                                if let Some(init) = init {
 1981                                    init(&mut workspace, window, cx);
 1982                                }
 1983
 1984                                workspace
 1985                            });
 1986                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1987                        }
 1988                    })?;
 1989                    let workspace =
 1990                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1991                            multi_workspace.workspace().clone()
 1992                        })?;
 1993                    (window, workspace)
 1994                };
 1995
 1996            notify_if_database_failed(window, cx);
 1997            // Check if this is an empty workspace (no paths to open)
 1998            // An empty workspace is one where project_paths is empty
 1999            let is_empty_workspace = project_paths.is_empty();
 2000            // Check if serialized workspace has paths before it's moved
 2001            let serialized_workspace_has_paths = serialized_workspace
 2002                .as_ref()
 2003                .map(|ws| !ws.paths.is_empty())
 2004                .unwrap_or(false);
 2005
 2006            let opened_items = window
 2007                .update(cx, |_, window, cx| {
 2008                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2009                        open_items(serialized_workspace, project_paths, window, cx)
 2010                    })
 2011                })?
 2012                .await
 2013                .unwrap_or_default();
 2014
 2015            // Restore default dock state for empty workspaces
 2016            // Only restore if:
 2017            // 1. This is an empty workspace (no paths), AND
 2018            // 2. The serialized workspace either doesn't exist or has no paths
 2019            if is_empty_workspace && !serialized_workspace_has_paths {
 2020                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2021                    window
 2022                        .update(cx, |_, window, cx| {
 2023                            workspace.update(cx, |workspace, cx| {
 2024                                for (dock, serialized_dock) in [
 2025                                    (&workspace.right_dock, &default_docks.right),
 2026                                    (&workspace.left_dock, &default_docks.left),
 2027                                    (&workspace.bottom_dock, &default_docks.bottom),
 2028                                ] {
 2029                                    dock.update(cx, |dock, cx| {
 2030                                        dock.serialized_dock = Some(serialized_dock.clone());
 2031                                        dock.restore_state(window, cx);
 2032                                    });
 2033                                }
 2034                                cx.notify();
 2035                            });
 2036                        })
 2037                        .log_err();
 2038                }
 2039            }
 2040
 2041            window
 2042                .update(cx, |_, _window, cx| {
 2043                    workspace.update(cx, |this: &mut Workspace, cx| {
 2044                        this.update_history(cx);
 2045                    });
 2046                })
 2047                .log_err();
 2048            Ok(OpenResult {
 2049                window,
 2050                workspace,
 2051                opened_items,
 2052            })
 2053        })
 2054    }
 2055
 2056    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2057        self.weak_self.clone()
 2058    }
 2059
 2060    pub fn left_dock(&self) -> &Entity<Dock> {
 2061        &self.left_dock
 2062    }
 2063
 2064    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2065        &self.bottom_dock
 2066    }
 2067
 2068    pub fn set_bottom_dock_layout(
 2069        &mut self,
 2070        layout: BottomDockLayout,
 2071        window: &mut Window,
 2072        cx: &mut Context<Self>,
 2073    ) {
 2074        let fs = self.project().read(cx).fs();
 2075        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2076            content.workspace.bottom_dock_layout = Some(layout);
 2077        });
 2078
 2079        cx.notify();
 2080        self.serialize_workspace(window, cx);
 2081    }
 2082
 2083    pub fn right_dock(&self) -> &Entity<Dock> {
 2084        &self.right_dock
 2085    }
 2086
 2087    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2088        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2089    }
 2090
 2091    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2092        let left_dock = self.left_dock.read(cx);
 2093        let left_visible = left_dock.is_open();
 2094        let left_active_panel = left_dock
 2095            .active_panel()
 2096            .map(|panel| panel.persistent_name().to_string());
 2097        // `zoomed_position` is kept in sync with individual panel zoom state
 2098        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2099        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2100
 2101        let right_dock = self.right_dock.read(cx);
 2102        let right_visible = right_dock.is_open();
 2103        let right_active_panel = right_dock
 2104            .active_panel()
 2105            .map(|panel| panel.persistent_name().to_string());
 2106        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2107
 2108        let bottom_dock = self.bottom_dock.read(cx);
 2109        let bottom_visible = bottom_dock.is_open();
 2110        let bottom_active_panel = bottom_dock
 2111            .active_panel()
 2112            .map(|panel| panel.persistent_name().to_string());
 2113        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2114
 2115        DockStructure {
 2116            left: DockData {
 2117                visible: left_visible,
 2118                active_panel: left_active_panel,
 2119                zoom: left_dock_zoom,
 2120            },
 2121            right: DockData {
 2122                visible: right_visible,
 2123                active_panel: right_active_panel,
 2124                zoom: right_dock_zoom,
 2125            },
 2126            bottom: DockData {
 2127                visible: bottom_visible,
 2128                active_panel: bottom_active_panel,
 2129                zoom: bottom_dock_zoom,
 2130            },
 2131        }
 2132    }
 2133
 2134    pub fn set_dock_structure(
 2135        &self,
 2136        docks: DockStructure,
 2137        window: &mut Window,
 2138        cx: &mut Context<Self>,
 2139    ) {
 2140        for (dock, data) in [
 2141            (&self.left_dock, docks.left),
 2142            (&self.bottom_dock, docks.bottom),
 2143            (&self.right_dock, docks.right),
 2144        ] {
 2145            dock.update(cx, |dock, cx| {
 2146                dock.serialized_dock = Some(data);
 2147                dock.restore_state(window, cx);
 2148            });
 2149        }
 2150    }
 2151
 2152    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2153        self.items(cx)
 2154            .filter_map(|item| {
 2155                let project_path = item.project_path(cx)?;
 2156                self.project.read(cx).absolute_path(&project_path, cx)
 2157            })
 2158            .collect()
 2159    }
 2160
 2161    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2162        match position {
 2163            DockPosition::Left => &self.left_dock,
 2164            DockPosition::Bottom => &self.bottom_dock,
 2165            DockPosition::Right => &self.right_dock,
 2166        }
 2167    }
 2168
 2169    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2170        self.all_docks().into_iter().find_map(|dock| {
 2171            let dock = dock.read(cx);
 2172            dock.has_agent_panel(cx).then_some(dock.position())
 2173        })
 2174    }
 2175
 2176    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2177        self.all_docks().into_iter().find_map(|dock| {
 2178            let dock = dock.read(cx);
 2179            let panel = dock.panel::<T>()?;
 2180            dock.stored_panel_size_state(&panel)
 2181        })
 2182    }
 2183
 2184    pub fn persisted_panel_size_state(
 2185        &self,
 2186        panel_key: &'static str,
 2187        cx: &App,
 2188    ) -> Option<dock::PanelSizeState> {
 2189        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2190    }
 2191
 2192    pub fn persist_panel_size_state(
 2193        &self,
 2194        panel_key: &str,
 2195        size_state: dock::PanelSizeState,
 2196        cx: &mut App,
 2197    ) {
 2198        let Some(workspace_id) = self
 2199            .database_id()
 2200            .map(|id| i64::from(id).to_string())
 2201            .or(self.session_id())
 2202        else {
 2203            return;
 2204        };
 2205
 2206        let kvp = db::kvp::KeyValueStore::global(cx);
 2207        let panel_key = panel_key.to_string();
 2208        cx.background_spawn(async move {
 2209            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2210            scope
 2211                .write(
 2212                    format!("{workspace_id}:{panel_key}"),
 2213                    serde_json::to_string(&size_state)?,
 2214                )
 2215                .await
 2216        })
 2217        .detach_and_log_err(cx);
 2218    }
 2219
 2220    pub fn set_panel_size_state<T: Panel>(
 2221        &mut self,
 2222        size_state: dock::PanelSizeState,
 2223        window: &mut Window,
 2224        cx: &mut Context<Self>,
 2225    ) -> bool {
 2226        let Some(panel) = self.panel::<T>(cx) else {
 2227            return false;
 2228        };
 2229
 2230        let dock = self.dock_at_position(panel.position(window, cx));
 2231        let did_set = dock.update(cx, |dock, cx| {
 2232            dock.set_panel_size_state(&panel, size_state, cx)
 2233        });
 2234
 2235        if did_set {
 2236            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2237        }
 2238
 2239        did_set
 2240    }
 2241
 2242    pub fn toggle_dock_panel_flexible_size(
 2243        &self,
 2244        dock: &Entity<Dock>,
 2245        panel: &dyn PanelHandle,
 2246        window: &mut Window,
 2247        cx: &mut App,
 2248    ) {
 2249        let position = dock.read(cx).position();
 2250        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2251        let current_flex =
 2252            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2253        dock.update(cx, |dock, cx| {
 2254            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2255        });
 2256    }
 2257
 2258    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2259        let panel = dock.active_panel()?;
 2260        let size_state = dock
 2261            .stored_panel_size_state(panel.as_ref())
 2262            .unwrap_or_default();
 2263        let position = dock.position();
 2264
 2265        let use_flex = panel.has_flexible_size(window, cx);
 2266
 2267        if position.axis() == Axis::Horizontal
 2268            && use_flex
 2269            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2270        {
 2271            let workspace_width = self.bounds.size.width;
 2272            if workspace_width <= Pixels::ZERO {
 2273                return None;
 2274            }
 2275            let flex = flex.max(0.001);
 2276            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2277            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2278                // Both docks are flex items sharing the full workspace width.
 2279                let total_flex = flex + 1.0 + opposite_flex;
 2280                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2281            } else {
 2282                // Opposite dock is fixed-width; flex items share (W - fixed).
 2283                let opposite_fixed = opposite
 2284                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2285                    .unwrap_or_default();
 2286                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2287                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2288            }
 2289        }
 2290
 2291        Some(
 2292            size_state
 2293                .size
 2294                .unwrap_or_else(|| panel.default_size(window, cx)),
 2295        )
 2296    }
 2297
 2298    pub fn dock_flex_for_size(
 2299        &self,
 2300        position: DockPosition,
 2301        size: Pixels,
 2302        window: &Window,
 2303        cx: &App,
 2304    ) -> Option<f32> {
 2305        if position.axis() != Axis::Horizontal {
 2306            return None;
 2307        }
 2308
 2309        let workspace_width = self.bounds.size.width;
 2310        if workspace_width <= Pixels::ZERO {
 2311            return None;
 2312        }
 2313
 2314        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2315        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2316            let size = size.clamp(px(0.), workspace_width - px(1.));
 2317            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2318        } else {
 2319            let opposite_width = opposite
 2320                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2321                .unwrap_or_default();
 2322            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2323            let remaining = (available - size).max(px(1.));
 2324            Some((size / remaining).max(0.0))
 2325        }
 2326    }
 2327
 2328    fn opposite_dock_panel_and_size_state(
 2329        &self,
 2330        position: DockPosition,
 2331        window: &Window,
 2332        cx: &App,
 2333    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2334        let opposite_position = match position {
 2335            DockPosition::Left => DockPosition::Right,
 2336            DockPosition::Right => DockPosition::Left,
 2337            DockPosition::Bottom => return None,
 2338        };
 2339
 2340        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2341        let panel = opposite_dock.visible_panel()?;
 2342        let mut size_state = opposite_dock
 2343            .stored_panel_size_state(panel.as_ref())
 2344            .unwrap_or_default();
 2345        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2346            size_state.flex = self.default_dock_flex(opposite_position);
 2347        }
 2348        Some((panel.clone(), size_state))
 2349    }
 2350
 2351    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2352        if position.axis() != Axis::Horizontal {
 2353            return None;
 2354        }
 2355
 2356        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2357        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2358    }
 2359
 2360    pub fn is_edited(&self) -> bool {
 2361        self.window_edited
 2362    }
 2363
 2364    pub fn add_panel<T: Panel>(
 2365        &mut self,
 2366        panel: Entity<T>,
 2367        window: &mut Window,
 2368        cx: &mut Context<Self>,
 2369    ) {
 2370        let focus_handle = panel.panel_focus_handle(cx);
 2371        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2372            .detach();
 2373
 2374        let dock_position = panel.position(window, cx);
 2375        let dock = self.dock_at_position(dock_position);
 2376        let any_panel = panel.to_any();
 2377        let persisted_size_state =
 2378            self.persisted_panel_size_state(T::panel_key(), cx)
 2379                .or_else(|| {
 2380                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2381                        let state = dock::PanelSizeState {
 2382                            size: Some(size),
 2383                            flex: None,
 2384                        };
 2385                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2386                        state
 2387                    })
 2388                });
 2389
 2390        dock.update(cx, |dock, cx| {
 2391            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2392            if let Some(size_state) = persisted_size_state {
 2393                dock.set_panel_size_state(&panel, size_state, cx);
 2394            }
 2395            index
 2396        });
 2397
 2398        cx.emit(Event::PanelAdded(any_panel));
 2399    }
 2400
 2401    pub fn remove_panel<T: Panel>(
 2402        &mut self,
 2403        panel: &Entity<T>,
 2404        window: &mut Window,
 2405        cx: &mut Context<Self>,
 2406    ) {
 2407        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2408            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2409        }
 2410    }
 2411
 2412    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2413        &self.status_bar
 2414    }
 2415
 2416    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2417        self.sidebar_focus_handle = handle;
 2418    }
 2419
 2420    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2421        StatusBarSettings::get_global(cx).show
 2422    }
 2423
 2424    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2425        self.multi_workspace.as_ref()
 2426    }
 2427
 2428    pub fn set_multi_workspace(
 2429        &mut self,
 2430        multi_workspace: WeakEntity<MultiWorkspace>,
 2431        cx: &mut App,
 2432    ) {
 2433        self.status_bar.update(cx, |status_bar, cx| {
 2434            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2435        });
 2436        self.multi_workspace = Some(multi_workspace);
 2437    }
 2438
 2439    pub fn app_state(&self) -> &Arc<AppState> {
 2440        &self.app_state
 2441    }
 2442
 2443    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2444        self._panels_task = Some(task);
 2445    }
 2446
 2447    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2448        self._panels_task.take()
 2449    }
 2450
 2451    pub fn user_store(&self) -> &Entity<UserStore> {
 2452        &self.app_state.user_store
 2453    }
 2454
 2455    pub fn project(&self) -> &Entity<Project> {
 2456        &self.project
 2457    }
 2458
 2459    pub fn path_style(&self, cx: &App) -> PathStyle {
 2460        self.project.read(cx).path_style(cx)
 2461    }
 2462
 2463    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2464        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2465
 2466        for pane_handle in &self.panes {
 2467            let pane = pane_handle.read(cx);
 2468
 2469            for entry in pane.activation_history() {
 2470                history.insert(
 2471                    entry.entity_id,
 2472                    history
 2473                        .get(&entry.entity_id)
 2474                        .cloned()
 2475                        .unwrap_or(0)
 2476                        .max(entry.timestamp),
 2477                );
 2478            }
 2479        }
 2480
 2481        history
 2482    }
 2483
 2484    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2485        let mut recent_item: Option<Entity<T>> = None;
 2486        let mut recent_timestamp = 0;
 2487        for pane_handle in &self.panes {
 2488            let pane = pane_handle.read(cx);
 2489            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2490                pane.items().map(|item| (item.item_id(), item)).collect();
 2491            for entry in pane.activation_history() {
 2492                if entry.timestamp > recent_timestamp
 2493                    && let Some(&item) = item_map.get(&entry.entity_id)
 2494                    && let Some(typed_item) = item.act_as::<T>(cx)
 2495                {
 2496                    recent_timestamp = entry.timestamp;
 2497                    recent_item = Some(typed_item);
 2498                }
 2499            }
 2500        }
 2501        recent_item
 2502    }
 2503
 2504    pub fn recent_navigation_history_iter(
 2505        &self,
 2506        cx: &App,
 2507    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2508        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2509        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2510
 2511        for pane in &self.panes {
 2512            let pane = pane.read(cx);
 2513
 2514            pane.nav_history()
 2515                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2516                    if let Some(fs_path) = &fs_path {
 2517                        abs_paths_opened
 2518                            .entry(fs_path.clone())
 2519                            .or_default()
 2520                            .insert(project_path.clone());
 2521                    }
 2522                    let timestamp = entry.timestamp;
 2523                    match history.entry(project_path) {
 2524                        hash_map::Entry::Occupied(mut entry) => {
 2525                            let (_, old_timestamp) = entry.get();
 2526                            if &timestamp > old_timestamp {
 2527                                entry.insert((fs_path, timestamp));
 2528                            }
 2529                        }
 2530                        hash_map::Entry::Vacant(entry) => {
 2531                            entry.insert((fs_path, timestamp));
 2532                        }
 2533                    }
 2534                });
 2535
 2536            if let Some(item) = pane.active_item()
 2537                && let Some(project_path) = item.project_path(cx)
 2538            {
 2539                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2540
 2541                if let Some(fs_path) = &fs_path {
 2542                    abs_paths_opened
 2543                        .entry(fs_path.clone())
 2544                        .or_default()
 2545                        .insert(project_path.clone());
 2546                }
 2547
 2548                history.insert(project_path, (fs_path, std::usize::MAX));
 2549            }
 2550        }
 2551
 2552        history
 2553            .into_iter()
 2554            .sorted_by_key(|(_, (_, order))| *order)
 2555            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2556            .rev()
 2557            .filter(move |(history_path, abs_path)| {
 2558                let latest_project_path_opened = abs_path
 2559                    .as_ref()
 2560                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2561                    .and_then(|project_paths| {
 2562                        project_paths
 2563                            .iter()
 2564                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2565                    });
 2566
 2567                latest_project_path_opened.is_none_or(|path| path == history_path)
 2568            })
 2569    }
 2570
 2571    pub fn recent_navigation_history(
 2572        &self,
 2573        limit: Option<usize>,
 2574        cx: &App,
 2575    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2576        self.recent_navigation_history_iter(cx)
 2577            .take(limit.unwrap_or(usize::MAX))
 2578            .collect()
 2579    }
 2580
 2581    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2582        for pane in &self.panes {
 2583            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2584        }
 2585    }
 2586
 2587    fn navigate_history(
 2588        &mut self,
 2589        pane: WeakEntity<Pane>,
 2590        mode: NavigationMode,
 2591        window: &mut Window,
 2592        cx: &mut Context<Workspace>,
 2593    ) -> Task<Result<()>> {
 2594        self.navigate_history_impl(
 2595            pane,
 2596            mode,
 2597            window,
 2598            &mut |history, cx| history.pop(mode, cx),
 2599            cx,
 2600        )
 2601    }
 2602
 2603    fn navigate_tag_history(
 2604        &mut self,
 2605        pane: WeakEntity<Pane>,
 2606        mode: TagNavigationMode,
 2607        window: &mut Window,
 2608        cx: &mut Context<Workspace>,
 2609    ) -> Task<Result<()>> {
 2610        self.navigate_history_impl(
 2611            pane,
 2612            NavigationMode::Normal,
 2613            window,
 2614            &mut |history, _cx| history.pop_tag(mode),
 2615            cx,
 2616        )
 2617    }
 2618
 2619    fn navigate_history_impl(
 2620        &mut self,
 2621        pane: WeakEntity<Pane>,
 2622        mode: NavigationMode,
 2623        window: &mut Window,
 2624        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2625        cx: &mut Context<Workspace>,
 2626    ) -> Task<Result<()>> {
 2627        let to_load = if let Some(pane) = pane.upgrade() {
 2628            pane.update(cx, |pane, cx| {
 2629                window.focus(&pane.focus_handle(cx), cx);
 2630                loop {
 2631                    // Retrieve the weak item handle from the history.
 2632                    let entry = cb(pane.nav_history_mut(), cx)?;
 2633
 2634                    // If the item is still present in this pane, then activate it.
 2635                    if let Some(index) = entry
 2636                        .item
 2637                        .upgrade()
 2638                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2639                    {
 2640                        let prev_active_item_index = pane.active_item_index();
 2641                        pane.nav_history_mut().set_mode(mode);
 2642                        pane.activate_item(index, true, true, window, cx);
 2643                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2644
 2645                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2646                        if let Some(data) = entry.data {
 2647                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2648                        }
 2649
 2650                        if navigated {
 2651                            break None;
 2652                        }
 2653                    } else {
 2654                        // If the item is no longer present in this pane, then retrieve its
 2655                        // path info in order to reopen it.
 2656                        break pane
 2657                            .nav_history()
 2658                            .path_for_item(entry.item.id())
 2659                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2660                    }
 2661                }
 2662            })
 2663        } else {
 2664            None
 2665        };
 2666
 2667        if let Some((project_path, abs_path, entry)) = to_load {
 2668            // If the item was no longer present, then load it again from its previous path, first try the local path
 2669            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2670
 2671            cx.spawn_in(window, async move  |workspace, cx| {
 2672                let open_by_project_path = open_by_project_path.await;
 2673                let mut navigated = false;
 2674                match open_by_project_path
 2675                    .with_context(|| format!("Navigating to {project_path:?}"))
 2676                {
 2677                    Ok((project_entry_id, build_item)) => {
 2678                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2679                            pane.nav_history_mut().set_mode(mode);
 2680                            pane.active_item().map(|p| p.item_id())
 2681                        })?;
 2682
 2683                        pane.update_in(cx, |pane, window, cx| {
 2684                            let item = pane.open_item(
 2685                                project_entry_id,
 2686                                project_path,
 2687                                true,
 2688                                entry.is_preview,
 2689                                true,
 2690                                None,
 2691                                window, cx,
 2692                                build_item,
 2693                            );
 2694                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2695                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2696                            if let Some(data) = entry.data {
 2697                                navigated |= item.navigate(data, window, cx);
 2698                            }
 2699                        })?;
 2700                    }
 2701                    Err(open_by_project_path_e) => {
 2702                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2703                        // and its worktree is now dropped
 2704                        if let Some(abs_path) = abs_path {
 2705                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2706                                pane.nav_history_mut().set_mode(mode);
 2707                                pane.active_item().map(|p| p.item_id())
 2708                            })?;
 2709                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2710                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2711                            })?;
 2712                            match open_by_abs_path
 2713                                .await
 2714                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2715                            {
 2716                                Ok(item) => {
 2717                                    pane.update_in(cx, |pane, window, cx| {
 2718                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2719                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2720                                        if let Some(data) = entry.data {
 2721                                            navigated |= item.navigate(data, window, cx);
 2722                                        }
 2723                                    })?;
 2724                                }
 2725                                Err(open_by_abs_path_e) => {
 2726                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2727                                }
 2728                            }
 2729                        }
 2730                    }
 2731                }
 2732
 2733                if !navigated {
 2734                    workspace
 2735                        .update_in(cx, |workspace, window, cx| {
 2736                            Self::navigate_history(workspace, pane, mode, window, cx)
 2737                        })?
 2738                        .await?;
 2739                }
 2740
 2741                Ok(())
 2742            })
 2743        } else {
 2744            Task::ready(Ok(()))
 2745        }
 2746    }
 2747
 2748    pub fn go_back(
 2749        &mut self,
 2750        pane: WeakEntity<Pane>,
 2751        window: &mut Window,
 2752        cx: &mut Context<Workspace>,
 2753    ) -> Task<Result<()>> {
 2754        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2755    }
 2756
 2757    pub fn go_forward(
 2758        &mut self,
 2759        pane: WeakEntity<Pane>,
 2760        window: &mut Window,
 2761        cx: &mut Context<Workspace>,
 2762    ) -> Task<Result<()>> {
 2763        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2764    }
 2765
 2766    pub fn reopen_closed_item(
 2767        &mut self,
 2768        window: &mut Window,
 2769        cx: &mut Context<Workspace>,
 2770    ) -> Task<Result<()>> {
 2771        self.navigate_history(
 2772            self.active_pane().downgrade(),
 2773            NavigationMode::ReopeningClosedItem,
 2774            window,
 2775            cx,
 2776        )
 2777    }
 2778
 2779    pub fn client(&self) -> &Arc<Client> {
 2780        &self.app_state.client
 2781    }
 2782
 2783    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2784        self.titlebar_item = Some(item);
 2785        cx.notify();
 2786    }
 2787
 2788    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2789        self.on_prompt_for_new_path = Some(prompt)
 2790    }
 2791
 2792    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2793        self.on_prompt_for_open_path = Some(prompt)
 2794    }
 2795
 2796    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2797        self.terminal_provider = Some(Box::new(provider));
 2798    }
 2799
 2800    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2801        self.debugger_provider = Some(Arc::new(provider));
 2802    }
 2803
 2804    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2805        self.debugger_provider.clone()
 2806    }
 2807
 2808    pub fn prompt_for_open_path(
 2809        &mut self,
 2810        path_prompt_options: PathPromptOptions,
 2811        lister: DirectoryLister,
 2812        window: &mut Window,
 2813        cx: &mut Context<Self>,
 2814    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2815        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2816            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2817            let rx = prompt(self, lister, window, cx);
 2818            self.on_prompt_for_open_path = Some(prompt);
 2819            rx
 2820        } else {
 2821            let (tx, rx) = oneshot::channel();
 2822            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2823
 2824            cx.spawn_in(window, async move |workspace, cx| {
 2825                let Ok(result) = abs_path.await else {
 2826                    return Ok(());
 2827                };
 2828
 2829                match result {
 2830                    Ok(result) => {
 2831                        tx.send(result).ok();
 2832                    }
 2833                    Err(err) => {
 2834                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2835                            workspace.show_portal_error(err.to_string(), cx);
 2836                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2837                            let rx = prompt(workspace, lister, window, cx);
 2838                            workspace.on_prompt_for_open_path = Some(prompt);
 2839                            rx
 2840                        })?;
 2841                        if let Ok(path) = rx.await {
 2842                            tx.send(path).ok();
 2843                        }
 2844                    }
 2845                };
 2846                anyhow::Ok(())
 2847            })
 2848            .detach();
 2849
 2850            rx
 2851        }
 2852    }
 2853
 2854    pub fn prompt_for_new_path(
 2855        &mut self,
 2856        lister: DirectoryLister,
 2857        suggested_name: Option<String>,
 2858        window: &mut Window,
 2859        cx: &mut Context<Self>,
 2860    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2861        if self.project.read(cx).is_via_collab()
 2862            || self.project.read(cx).is_via_remote_server()
 2863            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2864        {
 2865            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2866            let rx = prompt(self, lister, suggested_name, window, cx);
 2867            self.on_prompt_for_new_path = Some(prompt);
 2868            return rx;
 2869        }
 2870
 2871        let (tx, rx) = oneshot::channel();
 2872        cx.spawn_in(window, async move |workspace, cx| {
 2873            let abs_path = workspace.update(cx, |workspace, cx| {
 2874                let relative_to = workspace
 2875                    .most_recent_active_path(cx)
 2876                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2877                    .or_else(|| {
 2878                        let project = workspace.project.read(cx);
 2879                        project.visible_worktrees(cx).find_map(|worktree| {
 2880                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2881                        })
 2882                    })
 2883                    .or_else(std::env::home_dir)
 2884                    .unwrap_or_else(|| PathBuf::from(""));
 2885                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2886            })?;
 2887            let abs_path = match abs_path.await? {
 2888                Ok(path) => path,
 2889                Err(err) => {
 2890                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2891                        workspace.show_portal_error(err.to_string(), cx);
 2892
 2893                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2894                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2895                        workspace.on_prompt_for_new_path = Some(prompt);
 2896                        rx
 2897                    })?;
 2898                    if let Ok(path) = rx.await {
 2899                        tx.send(path).ok();
 2900                    }
 2901                    return anyhow::Ok(());
 2902                }
 2903            };
 2904
 2905            tx.send(abs_path.map(|path| vec![path])).ok();
 2906            anyhow::Ok(())
 2907        })
 2908        .detach();
 2909
 2910        rx
 2911    }
 2912
 2913    pub fn titlebar_item(&self) -> Option<AnyView> {
 2914        self.titlebar_item.clone()
 2915    }
 2916
 2917    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2918    /// When set, git-related operations should use this worktree instead of deriving
 2919    /// the active worktree from the focused file.
 2920    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2921        self.active_worktree_override
 2922    }
 2923
 2924    pub fn set_active_worktree_override(
 2925        &mut self,
 2926        worktree_id: Option<WorktreeId>,
 2927        cx: &mut Context<Self>,
 2928    ) {
 2929        self.active_worktree_override = worktree_id;
 2930        cx.notify();
 2931    }
 2932
 2933    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2934        self.active_worktree_override = None;
 2935        cx.notify();
 2936    }
 2937
 2938    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2939    ///
 2940    /// If the given workspace has a local project, then it will be passed
 2941    /// to the callback. Otherwise, a new empty window will be created.
 2942    pub fn with_local_workspace<T, F>(
 2943        &mut self,
 2944        window: &mut Window,
 2945        cx: &mut Context<Self>,
 2946        callback: F,
 2947    ) -> Task<Result<T>>
 2948    where
 2949        T: 'static,
 2950        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2951    {
 2952        if self.project.read(cx).is_local() {
 2953            Task::ready(Ok(callback(self, window, cx)))
 2954        } else {
 2955            let env = self.project.read(cx).cli_environment(cx);
 2956            let task = Self::new_local(
 2957                Vec::new(),
 2958                self.app_state.clone(),
 2959                None,
 2960                env,
 2961                None,
 2962                OpenMode::Activate,
 2963                cx,
 2964            );
 2965            cx.spawn_in(window, async move |_vh, cx| {
 2966                let OpenResult {
 2967                    window: multi_workspace_window,
 2968                    ..
 2969                } = task.await?;
 2970                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2971                    let workspace = multi_workspace.workspace().clone();
 2972                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2973                })
 2974            })
 2975        }
 2976    }
 2977
 2978    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2979    ///
 2980    /// If the given workspace has a local project, then it will be passed
 2981    /// to the callback. Otherwise, a new empty window will be created.
 2982    pub fn with_local_or_wsl_workspace<T, F>(
 2983        &mut self,
 2984        window: &mut Window,
 2985        cx: &mut Context<Self>,
 2986        callback: F,
 2987    ) -> Task<Result<T>>
 2988    where
 2989        T: 'static,
 2990        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2991    {
 2992        let project = self.project.read(cx);
 2993        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2994            Task::ready(Ok(callback(self, window, cx)))
 2995        } else {
 2996            let env = self.project.read(cx).cli_environment(cx);
 2997            let task = Self::new_local(
 2998                Vec::new(),
 2999                self.app_state.clone(),
 3000                None,
 3001                env,
 3002                None,
 3003                OpenMode::Activate,
 3004                cx,
 3005            );
 3006            cx.spawn_in(window, async move |_vh, cx| {
 3007                let OpenResult {
 3008                    window: multi_workspace_window,
 3009                    ..
 3010                } = task.await?;
 3011                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3012                    let workspace = multi_workspace.workspace().clone();
 3013                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3014                })
 3015            })
 3016        }
 3017    }
 3018
 3019    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3020        self.project.read(cx).worktrees(cx)
 3021    }
 3022
 3023    pub fn visible_worktrees<'a>(
 3024        &self,
 3025        cx: &'a App,
 3026    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3027        self.project.read(cx).visible_worktrees(cx)
 3028    }
 3029
 3030    #[cfg(any(test, feature = "test-support"))]
 3031    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3032        let futures = self
 3033            .worktrees(cx)
 3034            .filter_map(|worktree| worktree.read(cx).as_local())
 3035            .map(|worktree| worktree.scan_complete())
 3036            .collect::<Vec<_>>();
 3037        async move {
 3038            for future in futures {
 3039                future.await;
 3040            }
 3041        }
 3042    }
 3043
 3044    pub fn close_global(cx: &mut App) {
 3045        cx.defer(|cx| {
 3046            cx.windows().iter().find(|window| {
 3047                window
 3048                    .update(cx, |_, window, _| {
 3049                        if window.is_window_active() {
 3050                            //This can only get called when the window's project connection has been lost
 3051                            //so we don't need to prompt the user for anything and instead just close the window
 3052                            window.remove_window();
 3053                            true
 3054                        } else {
 3055                            false
 3056                        }
 3057                    })
 3058                    .unwrap_or(false)
 3059            });
 3060        });
 3061    }
 3062
 3063    pub fn move_focused_panel_to_next_position(
 3064        &mut self,
 3065        _: &MoveFocusedPanelToNextPosition,
 3066        window: &mut Window,
 3067        cx: &mut Context<Self>,
 3068    ) {
 3069        let docks = self.all_docks();
 3070        let active_dock = docks
 3071            .into_iter()
 3072            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3073
 3074        if let Some(dock) = active_dock {
 3075            dock.update(cx, |dock, cx| {
 3076                let active_panel = dock
 3077                    .active_panel()
 3078                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3079
 3080                if let Some(panel) = active_panel {
 3081                    panel.move_to_next_position(window, cx);
 3082                }
 3083            })
 3084        }
 3085    }
 3086
 3087    pub fn prepare_to_close(
 3088        &mut self,
 3089        close_intent: CloseIntent,
 3090        window: &mut Window,
 3091        cx: &mut Context<Self>,
 3092    ) -> Task<Result<bool>> {
 3093        let active_call = self.active_global_call();
 3094
 3095        cx.spawn_in(window, async move |this, cx| {
 3096            this.update(cx, |this, _| {
 3097                if close_intent == CloseIntent::CloseWindow {
 3098                    this.removing = true;
 3099                }
 3100            })?;
 3101
 3102            let workspace_count = cx.update(|_window, cx| {
 3103                cx.windows()
 3104                    .iter()
 3105                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3106                    .count()
 3107            })?;
 3108
 3109            #[cfg(target_os = "macos")]
 3110            let save_last_workspace = false;
 3111
 3112            // On Linux and Windows, closing the last window should restore the last workspace.
 3113            #[cfg(not(target_os = "macos"))]
 3114            let save_last_workspace = {
 3115                let remaining_workspaces = cx.update(|_window, cx| {
 3116                    cx.windows()
 3117                        .iter()
 3118                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3119                        .filter_map(|multi_workspace| {
 3120                            multi_workspace
 3121                                .update(cx, |multi_workspace, _, cx| {
 3122                                    multi_workspace.workspace().read(cx).removing
 3123                                })
 3124                                .ok()
 3125                        })
 3126                        .filter(|removing| !removing)
 3127                        .count()
 3128                })?;
 3129
 3130                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3131            };
 3132
 3133            if let Some(active_call) = active_call
 3134                && workspace_count == 1
 3135                && cx
 3136                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3137                    .unwrap_or(false)
 3138            {
 3139                if close_intent == CloseIntent::CloseWindow {
 3140                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3141                    let answer = cx.update(|window, cx| {
 3142                        window.prompt(
 3143                            PromptLevel::Warning,
 3144                            "Do you want to leave the current call?",
 3145                            None,
 3146                            &["Close window and hang up", "Cancel"],
 3147                            cx,
 3148                        )
 3149                    })?;
 3150
 3151                    if answer.await.log_err() == Some(1) {
 3152                        return anyhow::Ok(false);
 3153                    } else {
 3154                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3155                            task.await.log_err();
 3156                        }
 3157                    }
 3158                }
 3159                if close_intent == CloseIntent::ReplaceWindow {
 3160                    _ = cx.update(|_window, cx| {
 3161                        let multi_workspace = cx
 3162                            .windows()
 3163                            .iter()
 3164                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3165                            .next()
 3166                            .unwrap();
 3167                        let project = multi_workspace
 3168                            .read(cx)?
 3169                            .workspace()
 3170                            .read(cx)
 3171                            .project
 3172                            .clone();
 3173                        if project.read(cx).is_shared() {
 3174                            active_call.0.unshare_project(project, cx)?;
 3175                        }
 3176                        Ok::<_, anyhow::Error>(())
 3177                    });
 3178                }
 3179            }
 3180
 3181            let save_result = this
 3182                .update_in(cx, |this, window, cx| {
 3183                    this.save_all_internal(SaveIntent::Close, window, cx)
 3184                })?
 3185                .await;
 3186
 3187            // If we're not quitting, but closing, we remove the workspace from
 3188            // the current session.
 3189            if close_intent != CloseIntent::Quit
 3190                && !save_last_workspace
 3191                && save_result.as_ref().is_ok_and(|&res| res)
 3192            {
 3193                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3194                    .await;
 3195            }
 3196
 3197            save_result
 3198        })
 3199    }
 3200
 3201    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3202        self.save_all_internal(
 3203            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3204            window,
 3205            cx,
 3206        )
 3207        .detach_and_log_err(cx);
 3208    }
 3209
 3210    fn send_keystrokes(
 3211        &mut self,
 3212        action: &SendKeystrokes,
 3213        window: &mut Window,
 3214        cx: &mut Context<Self>,
 3215    ) {
 3216        let keystrokes: Vec<Keystroke> = action
 3217            .0
 3218            .split(' ')
 3219            .flat_map(|k| Keystroke::parse(k).log_err())
 3220            .map(|k| {
 3221                cx.keyboard_mapper()
 3222                    .map_key_equivalent(k, false)
 3223                    .inner()
 3224                    .clone()
 3225            })
 3226            .collect();
 3227        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3228    }
 3229
 3230    pub fn send_keystrokes_impl(
 3231        &mut self,
 3232        keystrokes: Vec<Keystroke>,
 3233        window: &mut Window,
 3234        cx: &mut Context<Self>,
 3235    ) -> Shared<Task<()>> {
 3236        let mut state = self.dispatching_keystrokes.borrow_mut();
 3237        if !state.dispatched.insert(keystrokes.clone()) {
 3238            cx.propagate();
 3239            return state.task.clone().unwrap();
 3240        }
 3241
 3242        state.queue.extend(keystrokes);
 3243
 3244        let keystrokes = self.dispatching_keystrokes.clone();
 3245        if state.task.is_none() {
 3246            state.task = Some(
 3247                window
 3248                    .spawn(cx, async move |cx| {
 3249                        // limit to 100 keystrokes to avoid infinite recursion.
 3250                        for _ in 0..100 {
 3251                            let keystroke = {
 3252                                let mut state = keystrokes.borrow_mut();
 3253                                let Some(keystroke) = state.queue.pop_front() else {
 3254                                    state.dispatched.clear();
 3255                                    state.task.take();
 3256                                    return;
 3257                                };
 3258                                keystroke
 3259                            };
 3260                            cx.update(|window, cx| {
 3261                                let focused = window.focused(cx);
 3262                                window.dispatch_keystroke(keystroke.clone(), cx);
 3263                                if window.focused(cx) != focused {
 3264                                    // dispatch_keystroke may cause the focus to change.
 3265                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3266                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3267                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3268                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3269                                    // )
 3270                                    window.draw(cx).clear();
 3271                                }
 3272                            })
 3273                            .ok();
 3274
 3275                            // Yield between synthetic keystrokes so deferred focus and
 3276                            // other effects can settle before dispatching the next key.
 3277                            yield_now().await;
 3278                        }
 3279
 3280                        *keystrokes.borrow_mut() = Default::default();
 3281                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3282                    })
 3283                    .shared(),
 3284            );
 3285        }
 3286        state.task.clone().unwrap()
 3287    }
 3288
 3289    fn save_all_internal(
 3290        &mut self,
 3291        mut save_intent: SaveIntent,
 3292        window: &mut Window,
 3293        cx: &mut Context<Self>,
 3294    ) -> Task<Result<bool>> {
 3295        if self.project.read(cx).is_disconnected(cx) {
 3296            return Task::ready(Ok(true));
 3297        }
 3298        let dirty_items = self
 3299            .panes
 3300            .iter()
 3301            .flat_map(|pane| {
 3302                pane.read(cx).items().filter_map(|item| {
 3303                    if item.is_dirty(cx) {
 3304                        item.tab_content_text(0, cx);
 3305                        Some((pane.downgrade(), item.boxed_clone()))
 3306                    } else {
 3307                        None
 3308                    }
 3309                })
 3310            })
 3311            .collect::<Vec<_>>();
 3312
 3313        let project = self.project.clone();
 3314        cx.spawn_in(window, async move |workspace, cx| {
 3315            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3316                let (serialize_tasks, remaining_dirty_items) =
 3317                    workspace.update_in(cx, |workspace, window, cx| {
 3318                        let mut remaining_dirty_items = Vec::new();
 3319                        let mut serialize_tasks = Vec::new();
 3320                        for (pane, item) in dirty_items {
 3321                            if let Some(task) = item
 3322                                .to_serializable_item_handle(cx)
 3323                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3324                            {
 3325                                serialize_tasks.push(task);
 3326                            } else {
 3327                                remaining_dirty_items.push((pane, item));
 3328                            }
 3329                        }
 3330                        (serialize_tasks, remaining_dirty_items)
 3331                    })?;
 3332
 3333                futures::future::try_join_all(serialize_tasks).await?;
 3334
 3335                if !remaining_dirty_items.is_empty() {
 3336                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3337                }
 3338
 3339                if remaining_dirty_items.len() > 1 {
 3340                    let answer = workspace.update_in(cx, |_, window, cx| {
 3341                        let detail = Pane::file_names_for_prompt(
 3342                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3343                            cx,
 3344                        );
 3345                        window.prompt(
 3346                            PromptLevel::Warning,
 3347                            "Do you want to save all changes in the following files?",
 3348                            Some(&detail),
 3349                            &["Save all", "Discard all", "Cancel"],
 3350                            cx,
 3351                        )
 3352                    })?;
 3353                    match answer.await.log_err() {
 3354                        Some(0) => save_intent = SaveIntent::SaveAll,
 3355                        Some(1) => save_intent = SaveIntent::Skip,
 3356                        Some(2) => return Ok(false),
 3357                        _ => {}
 3358                    }
 3359                }
 3360
 3361                remaining_dirty_items
 3362            } else {
 3363                dirty_items
 3364            };
 3365
 3366            for (pane, item) in dirty_items {
 3367                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3368                    (
 3369                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3370                        item.project_entry_ids(cx),
 3371                    )
 3372                })?;
 3373                if (singleton || !project_entry_ids.is_empty())
 3374                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3375                {
 3376                    return Ok(false);
 3377                }
 3378            }
 3379            Ok(true)
 3380        })
 3381    }
 3382
 3383    pub fn open_workspace_for_paths(
 3384        &mut self,
 3385        // replace_current_window: bool,
 3386        mut open_mode: OpenMode,
 3387        paths: Vec<PathBuf>,
 3388        window: &mut Window,
 3389        cx: &mut Context<Self>,
 3390    ) -> Task<Result<Entity<Workspace>>> {
 3391        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3392        let is_remote = self.project.read(cx).is_via_collab();
 3393        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3394        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3395
 3396        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3397        if workspace_is_empty {
 3398            open_mode = OpenMode::Replace;
 3399        }
 3400
 3401        let app_state = self.app_state.clone();
 3402
 3403        cx.spawn(async move |_, cx| {
 3404            let OpenResult { workspace, .. } = cx
 3405                .update(|cx| {
 3406                    open_paths(
 3407                        &paths,
 3408                        app_state,
 3409                        OpenOptions {
 3410                            requesting_window,
 3411                            open_mode,
 3412                            ..Default::default()
 3413                        },
 3414                        cx,
 3415                    )
 3416                })
 3417                .await?;
 3418            Ok(workspace)
 3419        })
 3420    }
 3421
 3422    #[allow(clippy::type_complexity)]
 3423    pub fn open_paths(
 3424        &mut self,
 3425        mut abs_paths: Vec<PathBuf>,
 3426        options: OpenOptions,
 3427        pane: Option<WeakEntity<Pane>>,
 3428        window: &mut Window,
 3429        cx: &mut Context<Self>,
 3430    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3431        let fs = self.app_state.fs.clone();
 3432
 3433        let caller_ordered_abs_paths = abs_paths.clone();
 3434
 3435        // Sort the paths to ensure we add worktrees for parents before their children.
 3436        abs_paths.sort_unstable();
 3437        cx.spawn_in(window, async move |this, cx| {
 3438            let mut tasks = Vec::with_capacity(abs_paths.len());
 3439
 3440            for abs_path in &abs_paths {
 3441                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3442                    OpenVisible::All => Some(true),
 3443                    OpenVisible::None => Some(false),
 3444                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3445                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3446                        Some(None) => Some(true),
 3447                        None => None,
 3448                    },
 3449                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3450                        Some(Some(metadata)) => Some(metadata.is_dir),
 3451                        Some(None) => Some(false),
 3452                        None => None,
 3453                    },
 3454                };
 3455                let project_path = match visible {
 3456                    Some(visible) => match this
 3457                        .update(cx, |this, cx| {
 3458                            Workspace::project_path_for_path(
 3459                                this.project.clone(),
 3460                                abs_path,
 3461                                visible,
 3462                                cx,
 3463                            )
 3464                        })
 3465                        .log_err()
 3466                    {
 3467                        Some(project_path) => project_path.await.log_err(),
 3468                        None => None,
 3469                    },
 3470                    None => None,
 3471                };
 3472
 3473                let this = this.clone();
 3474                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3475                let fs = fs.clone();
 3476                let pane = pane.clone();
 3477                let task = cx.spawn(async move |cx| {
 3478                    let (_worktree, project_path) = project_path?;
 3479                    if fs.is_dir(&abs_path).await {
 3480                        // Opening a directory should not race to update the active entry.
 3481                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3482                        None
 3483                    } else {
 3484                        Some(
 3485                            this.update_in(cx, |this, window, cx| {
 3486                                this.open_path(
 3487                                    project_path,
 3488                                    pane,
 3489                                    options.focus.unwrap_or(true),
 3490                                    window,
 3491                                    cx,
 3492                                )
 3493                            })
 3494                            .ok()?
 3495                            .await,
 3496                        )
 3497                    }
 3498                });
 3499                tasks.push(task);
 3500            }
 3501
 3502            let results = futures::future::join_all(tasks).await;
 3503
 3504            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3505            let mut winner: Option<(PathBuf, bool)> = None;
 3506            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3507                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3508                    if !metadata.is_dir {
 3509                        winner = Some((abs_path, false));
 3510                        break;
 3511                    }
 3512                    if winner.is_none() {
 3513                        winner = Some((abs_path, true));
 3514                    }
 3515                } else if winner.is_none() {
 3516                    winner = Some((abs_path, false));
 3517                }
 3518            }
 3519
 3520            // Compute the winner entry id on the foreground thread and emit once, after all
 3521            // paths finish opening. This avoids races between concurrently-opening paths
 3522            // (directories in particular) and makes the resulting project panel selection
 3523            // deterministic.
 3524            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3525                'emit_winner: {
 3526                    let winner_abs_path: Arc<Path> =
 3527                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3528
 3529                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3530                        OpenVisible::All => true,
 3531                        OpenVisible::None => false,
 3532                        OpenVisible::OnlyFiles => !winner_is_dir,
 3533                        OpenVisible::OnlyDirectories => winner_is_dir,
 3534                    };
 3535
 3536                    let Some(worktree_task) = this
 3537                        .update(cx, |workspace, cx| {
 3538                            workspace.project.update(cx, |project, cx| {
 3539                                project.find_or_create_worktree(
 3540                                    winner_abs_path.as_ref(),
 3541                                    visible,
 3542                                    cx,
 3543                                )
 3544                            })
 3545                        })
 3546                        .ok()
 3547                    else {
 3548                        break 'emit_winner;
 3549                    };
 3550
 3551                    let Ok((worktree, _)) = worktree_task.await else {
 3552                        break 'emit_winner;
 3553                    };
 3554
 3555                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3556                        let worktree = worktree.read(cx);
 3557                        let worktree_abs_path = worktree.abs_path();
 3558                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3559                            worktree.root_entry()
 3560                        } else {
 3561                            winner_abs_path
 3562                                .strip_prefix(worktree_abs_path.as_ref())
 3563                                .ok()
 3564                                .and_then(|relative_path| {
 3565                                    let relative_path =
 3566                                        RelPath::new(relative_path, PathStyle::local())
 3567                                            .log_err()?;
 3568                                    worktree.entry_for_path(&relative_path)
 3569                                })
 3570                        }?;
 3571                        Some(entry.id)
 3572                    }) else {
 3573                        break 'emit_winner;
 3574                    };
 3575
 3576                    this.update(cx, |workspace, cx| {
 3577                        workspace.project.update(cx, |_, cx| {
 3578                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3579                        });
 3580                    })
 3581                    .ok();
 3582                }
 3583            }
 3584
 3585            results
 3586        })
 3587    }
 3588
 3589    pub fn open_resolved_path(
 3590        &mut self,
 3591        path: ResolvedPath,
 3592        window: &mut Window,
 3593        cx: &mut Context<Self>,
 3594    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3595        match path {
 3596            ResolvedPath::ProjectPath { project_path, .. } => {
 3597                self.open_path(project_path, None, true, window, cx)
 3598            }
 3599            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3600                PathBuf::from(path),
 3601                OpenOptions {
 3602                    visible: Some(OpenVisible::None),
 3603                    ..Default::default()
 3604                },
 3605                window,
 3606                cx,
 3607            ),
 3608        }
 3609    }
 3610
 3611    pub fn absolute_path_of_worktree(
 3612        &self,
 3613        worktree_id: WorktreeId,
 3614        cx: &mut Context<Self>,
 3615    ) -> Option<PathBuf> {
 3616        self.project
 3617            .read(cx)
 3618            .worktree_for_id(worktree_id, cx)
 3619            // TODO: use `abs_path` or `root_dir`
 3620            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3621    }
 3622
 3623    pub fn add_folder_to_project(
 3624        &mut self,
 3625        _: &AddFolderToProject,
 3626        window: &mut Window,
 3627        cx: &mut Context<Self>,
 3628    ) {
 3629        let project = self.project.read(cx);
 3630        if project.is_via_collab() {
 3631            self.show_error(
 3632                &anyhow!("You cannot add folders to someone else's project"),
 3633                cx,
 3634            );
 3635            return;
 3636        }
 3637        let paths = self.prompt_for_open_path(
 3638            PathPromptOptions {
 3639                files: false,
 3640                directories: true,
 3641                multiple: true,
 3642                prompt: None,
 3643            },
 3644            DirectoryLister::Project(self.project.clone()),
 3645            window,
 3646            cx,
 3647        );
 3648        cx.spawn_in(window, async move |this, cx| {
 3649            if let Some(paths) = paths.await.log_err().flatten() {
 3650                let results = this
 3651                    .update_in(cx, |this, window, cx| {
 3652                        this.open_paths(
 3653                            paths,
 3654                            OpenOptions {
 3655                                visible: Some(OpenVisible::All),
 3656                                ..Default::default()
 3657                            },
 3658                            None,
 3659                            window,
 3660                            cx,
 3661                        )
 3662                    })?
 3663                    .await;
 3664                for result in results.into_iter().flatten() {
 3665                    result.log_err();
 3666                }
 3667            }
 3668            anyhow::Ok(())
 3669        })
 3670        .detach_and_log_err(cx);
 3671    }
 3672
 3673    pub fn project_path_for_path(
 3674        project: Entity<Project>,
 3675        abs_path: &Path,
 3676        visible: bool,
 3677        cx: &mut App,
 3678    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3679        let entry = project.update(cx, |project, cx| {
 3680            project.find_or_create_worktree(abs_path, visible, cx)
 3681        });
 3682        cx.spawn(async move |cx| {
 3683            let (worktree, path) = entry.await?;
 3684            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3685            Ok((worktree, ProjectPath { worktree_id, path }))
 3686        })
 3687    }
 3688
 3689    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3690        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3691    }
 3692
 3693    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3694        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3695    }
 3696
 3697    pub fn items_of_type<'a, T: Item>(
 3698        &'a self,
 3699        cx: &'a App,
 3700    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3701        self.panes
 3702            .iter()
 3703            .flat_map(|pane| pane.read(cx).items_of_type())
 3704    }
 3705
 3706    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3707        self.active_pane().read(cx).active_item()
 3708    }
 3709
 3710    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3711        let item = self.active_item(cx)?;
 3712        item.to_any_view().downcast::<I>().ok()
 3713    }
 3714
 3715    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3716        self.active_item(cx).and_then(|item| item.project_path(cx))
 3717    }
 3718
 3719    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3720        self.recent_navigation_history_iter(cx)
 3721            .filter_map(|(path, abs_path)| {
 3722                let worktree = self
 3723                    .project
 3724                    .read(cx)
 3725                    .worktree_for_id(path.worktree_id, cx)?;
 3726                if worktree.read(cx).is_visible() {
 3727                    abs_path
 3728                } else {
 3729                    None
 3730                }
 3731            })
 3732            .next()
 3733    }
 3734
 3735    pub fn save_active_item(
 3736        &mut self,
 3737        save_intent: SaveIntent,
 3738        window: &mut Window,
 3739        cx: &mut App,
 3740    ) -> Task<Result<()>> {
 3741        let project = self.project.clone();
 3742        let pane = self.active_pane();
 3743        let item = pane.read(cx).active_item();
 3744        let pane = pane.downgrade();
 3745
 3746        window.spawn(cx, async move |cx| {
 3747            if let Some(item) = item {
 3748                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3749                    .await
 3750                    .map(|_| ())
 3751            } else {
 3752                Ok(())
 3753            }
 3754        })
 3755    }
 3756
 3757    pub fn close_inactive_items_and_panes(
 3758        &mut self,
 3759        action: &CloseInactiveTabsAndPanes,
 3760        window: &mut Window,
 3761        cx: &mut Context<Self>,
 3762    ) {
 3763        if let Some(task) = self.close_all_internal(
 3764            true,
 3765            action.save_intent.unwrap_or(SaveIntent::Close),
 3766            window,
 3767            cx,
 3768        ) {
 3769            task.detach_and_log_err(cx)
 3770        }
 3771    }
 3772
 3773    pub fn close_all_items_and_panes(
 3774        &mut self,
 3775        action: &CloseAllItemsAndPanes,
 3776        window: &mut Window,
 3777        cx: &mut Context<Self>,
 3778    ) {
 3779        if let Some(task) = self.close_all_internal(
 3780            false,
 3781            action.save_intent.unwrap_or(SaveIntent::Close),
 3782            window,
 3783            cx,
 3784        ) {
 3785            task.detach_and_log_err(cx)
 3786        }
 3787    }
 3788
 3789    /// Closes the active item across all panes.
 3790    pub fn close_item_in_all_panes(
 3791        &mut self,
 3792        action: &CloseItemInAllPanes,
 3793        window: &mut Window,
 3794        cx: &mut Context<Self>,
 3795    ) {
 3796        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3797            return;
 3798        };
 3799
 3800        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3801        let close_pinned = action.close_pinned;
 3802
 3803        if let Some(project_path) = active_item.project_path(cx) {
 3804            self.close_items_with_project_path(
 3805                &project_path,
 3806                save_intent,
 3807                close_pinned,
 3808                window,
 3809                cx,
 3810            );
 3811        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3812            let item_id = active_item.item_id();
 3813            self.active_pane().update(cx, |pane, cx| {
 3814                pane.close_item_by_id(item_id, save_intent, window, cx)
 3815                    .detach_and_log_err(cx);
 3816            });
 3817        }
 3818    }
 3819
 3820    /// Closes all items with the given project path across all panes.
 3821    pub fn close_items_with_project_path(
 3822        &mut self,
 3823        project_path: &ProjectPath,
 3824        save_intent: SaveIntent,
 3825        close_pinned: bool,
 3826        window: &mut Window,
 3827        cx: &mut Context<Self>,
 3828    ) {
 3829        let panes = self.panes().to_vec();
 3830        for pane in panes {
 3831            pane.update(cx, |pane, cx| {
 3832                pane.close_items_for_project_path(
 3833                    project_path,
 3834                    save_intent,
 3835                    close_pinned,
 3836                    window,
 3837                    cx,
 3838                )
 3839                .detach_and_log_err(cx);
 3840            });
 3841        }
 3842    }
 3843
 3844    fn close_all_internal(
 3845        &mut self,
 3846        retain_active_pane: bool,
 3847        save_intent: SaveIntent,
 3848        window: &mut Window,
 3849        cx: &mut Context<Self>,
 3850    ) -> Option<Task<Result<()>>> {
 3851        let current_pane = self.active_pane();
 3852
 3853        let mut tasks = Vec::new();
 3854
 3855        if retain_active_pane {
 3856            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3857                pane.close_other_items(
 3858                    &CloseOtherItems {
 3859                        save_intent: None,
 3860                        close_pinned: false,
 3861                    },
 3862                    None,
 3863                    window,
 3864                    cx,
 3865                )
 3866            });
 3867
 3868            tasks.push(current_pane_close);
 3869        }
 3870
 3871        for pane in self.panes() {
 3872            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3873                continue;
 3874            }
 3875
 3876            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3877                pane.close_all_items(
 3878                    &CloseAllItems {
 3879                        save_intent: Some(save_intent),
 3880                        close_pinned: false,
 3881                    },
 3882                    window,
 3883                    cx,
 3884                )
 3885            });
 3886
 3887            tasks.push(close_pane_items)
 3888        }
 3889
 3890        if tasks.is_empty() {
 3891            None
 3892        } else {
 3893            Some(cx.spawn_in(window, async move |_, _| {
 3894                for task in tasks {
 3895                    task.await?
 3896                }
 3897                Ok(())
 3898            }))
 3899        }
 3900    }
 3901
 3902    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3903        self.dock_at_position(position).read(cx).is_open()
 3904    }
 3905
 3906    pub fn toggle_dock(
 3907        &mut self,
 3908        dock_side: DockPosition,
 3909        window: &mut Window,
 3910        cx: &mut Context<Self>,
 3911    ) {
 3912        let mut focus_center = false;
 3913        let mut reveal_dock = false;
 3914
 3915        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3916        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3917
 3918        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3919            telemetry::event!(
 3920                "Panel Button Clicked",
 3921                name = panel.persistent_name(),
 3922                toggle_state = !was_visible
 3923            );
 3924        }
 3925        if was_visible {
 3926            self.save_open_dock_positions(cx);
 3927        }
 3928
 3929        let dock = self.dock_at_position(dock_side);
 3930        dock.update(cx, |dock, cx| {
 3931            dock.set_open(!was_visible, window, cx);
 3932
 3933            if dock.active_panel().is_none() {
 3934                let Some(panel_ix) = dock
 3935                    .first_enabled_panel_idx(cx)
 3936                    .log_with_level(log::Level::Info)
 3937                else {
 3938                    return;
 3939                };
 3940                dock.activate_panel(panel_ix, window, cx);
 3941            }
 3942
 3943            if let Some(active_panel) = dock.active_panel() {
 3944                if was_visible {
 3945                    if active_panel
 3946                        .panel_focus_handle(cx)
 3947                        .contains_focused(window, cx)
 3948                    {
 3949                        focus_center = true;
 3950                    }
 3951                } else {
 3952                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3953                    window.focus(focus_handle, cx);
 3954                    reveal_dock = true;
 3955                }
 3956            }
 3957        });
 3958
 3959        if reveal_dock {
 3960            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3961        }
 3962
 3963        if focus_center {
 3964            self.active_pane
 3965                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3966        }
 3967
 3968        cx.notify();
 3969        self.serialize_workspace(window, cx);
 3970    }
 3971
 3972    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3973        self.all_docks().into_iter().find(|&dock| {
 3974            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3975        })
 3976    }
 3977
 3978    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3979        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3980            self.save_open_dock_positions(cx);
 3981            dock.update(cx, |dock, cx| {
 3982                dock.set_open(false, window, cx);
 3983            });
 3984            return true;
 3985        }
 3986        false
 3987    }
 3988
 3989    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3990        self.save_open_dock_positions(cx);
 3991        for dock in self.all_docks() {
 3992            dock.update(cx, |dock, cx| {
 3993                dock.set_open(false, window, cx);
 3994            });
 3995        }
 3996
 3997        cx.focus_self(window);
 3998        cx.notify();
 3999        self.serialize_workspace(window, cx);
 4000    }
 4001
 4002    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4003        self.all_docks()
 4004            .into_iter()
 4005            .filter_map(|dock| {
 4006                let dock_ref = dock.read(cx);
 4007                if dock_ref.is_open() {
 4008                    Some(dock_ref.position())
 4009                } else {
 4010                    None
 4011                }
 4012            })
 4013            .collect()
 4014    }
 4015
 4016    /// Saves the positions of currently open docks.
 4017    ///
 4018    /// Updates `last_open_dock_positions` with positions of all currently open
 4019    /// docks, to later be restored by the 'Toggle All Docks' action.
 4020    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4021        let open_dock_positions = self.get_open_dock_positions(cx);
 4022        if !open_dock_positions.is_empty() {
 4023            self.last_open_dock_positions = open_dock_positions;
 4024        }
 4025    }
 4026
 4027    /// Toggles all docks between open and closed states.
 4028    ///
 4029    /// If any docks are open, closes all and remembers their positions. If all
 4030    /// docks are closed, restores the last remembered dock configuration.
 4031    fn toggle_all_docks(
 4032        &mut self,
 4033        _: &ToggleAllDocks,
 4034        window: &mut Window,
 4035        cx: &mut Context<Self>,
 4036    ) {
 4037        let open_dock_positions = self.get_open_dock_positions(cx);
 4038
 4039        if !open_dock_positions.is_empty() {
 4040            self.close_all_docks(window, cx);
 4041        } else if !self.last_open_dock_positions.is_empty() {
 4042            self.restore_last_open_docks(window, cx);
 4043        }
 4044    }
 4045
 4046    /// Reopens docks from the most recently remembered configuration.
 4047    ///
 4048    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4049    /// and clears the stored positions.
 4050    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4051        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4052
 4053        for position in positions_to_open {
 4054            let dock = self.dock_at_position(position);
 4055            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4056        }
 4057
 4058        cx.focus_self(window);
 4059        cx.notify();
 4060        self.serialize_workspace(window, cx);
 4061    }
 4062
 4063    /// Transfer focus to the panel of the given type.
 4064    pub fn focus_panel<T: Panel>(
 4065        &mut self,
 4066        window: &mut Window,
 4067        cx: &mut Context<Self>,
 4068    ) -> Option<Entity<T>> {
 4069        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4070        panel.to_any().downcast().ok()
 4071    }
 4072
 4073    /// Focus the panel of the given type if it isn't already focused. If it is
 4074    /// already focused, then transfer focus back to the workspace center.
 4075    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4076    /// panel when transferring focus back to the center.
 4077    pub fn toggle_panel_focus<T: Panel>(
 4078        &mut self,
 4079        window: &mut Window,
 4080        cx: &mut Context<Self>,
 4081    ) -> bool {
 4082        let mut did_focus_panel = false;
 4083        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4084            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4085            did_focus_panel
 4086        });
 4087
 4088        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4089            self.close_panel::<T>(window, cx);
 4090        }
 4091
 4092        telemetry::event!(
 4093            "Panel Button Clicked",
 4094            name = T::persistent_name(),
 4095            toggle_state = did_focus_panel
 4096        );
 4097
 4098        did_focus_panel
 4099    }
 4100
 4101    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4102        if let Some(item) = self.active_item(cx) {
 4103            item.item_focus_handle(cx).focus(window, cx);
 4104        } else {
 4105            log::error!("Could not find a focus target when switching focus to the center panes",);
 4106        }
 4107    }
 4108
 4109    pub fn activate_panel_for_proto_id(
 4110        &mut self,
 4111        panel_id: PanelId,
 4112        window: &mut Window,
 4113        cx: &mut Context<Self>,
 4114    ) -> Option<Arc<dyn PanelHandle>> {
 4115        let mut panel = None;
 4116        for dock in self.all_docks() {
 4117            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4118                panel = dock.update(cx, |dock, cx| {
 4119                    dock.activate_panel(panel_index, window, cx);
 4120                    dock.set_open(true, window, cx);
 4121                    dock.active_panel().cloned()
 4122                });
 4123                break;
 4124            }
 4125        }
 4126
 4127        if panel.is_some() {
 4128            cx.notify();
 4129            self.serialize_workspace(window, cx);
 4130        }
 4131
 4132        panel
 4133    }
 4134
 4135    /// Focus or unfocus the given panel type, depending on the given callback.
 4136    fn focus_or_unfocus_panel<T: Panel>(
 4137        &mut self,
 4138        window: &mut Window,
 4139        cx: &mut Context<Self>,
 4140        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4141    ) -> Option<Arc<dyn PanelHandle>> {
 4142        let mut result_panel = None;
 4143        let mut serialize = false;
 4144        for dock in self.all_docks() {
 4145            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4146                let mut focus_center = false;
 4147                let panel = dock.update(cx, |dock, cx| {
 4148                    dock.activate_panel(panel_index, window, cx);
 4149
 4150                    let panel = dock.active_panel().cloned();
 4151                    if let Some(panel) = panel.as_ref() {
 4152                        if should_focus(&**panel, window, cx) {
 4153                            dock.set_open(true, window, cx);
 4154                            panel.panel_focus_handle(cx).focus(window, cx);
 4155                        } else {
 4156                            focus_center = true;
 4157                        }
 4158                    }
 4159                    panel
 4160                });
 4161
 4162                if focus_center {
 4163                    self.active_pane
 4164                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4165                }
 4166
 4167                result_panel = panel;
 4168                serialize = true;
 4169                break;
 4170            }
 4171        }
 4172
 4173        if serialize {
 4174            self.serialize_workspace(window, cx);
 4175        }
 4176
 4177        cx.notify();
 4178        result_panel
 4179    }
 4180
 4181    /// Open the panel of the given type
 4182    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4183        for dock in self.all_docks() {
 4184            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4185                dock.update(cx, |dock, cx| {
 4186                    dock.activate_panel(panel_index, window, cx);
 4187                    dock.set_open(true, window, cx);
 4188                });
 4189            }
 4190        }
 4191    }
 4192
 4193    /// Open the panel of the given type, dismissing any zoomed items that
 4194    /// would obscure it (e.g. a zoomed terminal).
 4195    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4196        let dock_position = self.all_docks().iter().find_map(|dock| {
 4197            let dock = dock.read(cx);
 4198            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4199        });
 4200        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4201        self.open_panel::<T>(window, cx);
 4202    }
 4203
 4204    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4205        for dock in self.all_docks().iter() {
 4206            dock.update(cx, |dock, cx| {
 4207                if dock.panel::<T>().is_some() {
 4208                    dock.set_open(false, window, cx)
 4209                }
 4210            })
 4211        }
 4212    }
 4213
 4214    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4215        self.all_docks()
 4216            .iter()
 4217            .find_map(|dock| dock.read(cx).panel::<T>())
 4218    }
 4219
 4220    fn dismiss_zoomed_items_to_reveal(
 4221        &mut self,
 4222        dock_to_reveal: Option<DockPosition>,
 4223        window: &mut Window,
 4224        cx: &mut Context<Self>,
 4225    ) {
 4226        // If a center pane is zoomed, unzoom it.
 4227        for pane in &self.panes {
 4228            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4229                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4230            }
 4231        }
 4232
 4233        // If another dock is zoomed, hide it.
 4234        let mut focus_center = false;
 4235        for dock in self.all_docks() {
 4236            dock.update(cx, |dock, cx| {
 4237                if Some(dock.position()) != dock_to_reveal
 4238                    && let Some(panel) = dock.active_panel()
 4239                    && panel.is_zoomed(window, cx)
 4240                {
 4241                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4242                    dock.set_open(false, window, cx);
 4243                }
 4244            });
 4245        }
 4246
 4247        if focus_center {
 4248            self.active_pane
 4249                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4250        }
 4251
 4252        if self.zoomed_position != dock_to_reveal {
 4253            self.zoomed = None;
 4254            self.zoomed_position = None;
 4255            cx.emit(Event::ZoomChanged);
 4256        }
 4257
 4258        cx.notify();
 4259    }
 4260
 4261    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4262        let pane = cx.new(|cx| {
 4263            let mut pane = Pane::new(
 4264                self.weak_handle(),
 4265                self.project.clone(),
 4266                self.pane_history_timestamp.clone(),
 4267                None,
 4268                NewFile.boxed_clone(),
 4269                true,
 4270                window,
 4271                cx,
 4272            );
 4273            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4274            pane
 4275        });
 4276        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4277            .detach();
 4278        self.panes.push(pane.clone());
 4279
 4280        window.focus(&pane.focus_handle(cx), cx);
 4281
 4282        cx.emit(Event::PaneAdded(pane.clone()));
 4283        pane
 4284    }
 4285
 4286    pub fn add_item_to_center(
 4287        &mut self,
 4288        item: Box<dyn ItemHandle>,
 4289        window: &mut Window,
 4290        cx: &mut Context<Self>,
 4291    ) -> bool {
 4292        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4293            if let Some(center_pane) = center_pane.upgrade() {
 4294                center_pane.update(cx, |pane, cx| {
 4295                    pane.add_item(item, true, true, None, window, cx)
 4296                });
 4297                true
 4298            } else {
 4299                false
 4300            }
 4301        } else {
 4302            false
 4303        }
 4304    }
 4305
 4306    pub fn add_item_to_active_pane(
 4307        &mut self,
 4308        item: Box<dyn ItemHandle>,
 4309        destination_index: Option<usize>,
 4310        focus_item: bool,
 4311        window: &mut Window,
 4312        cx: &mut App,
 4313    ) {
 4314        self.add_item(
 4315            self.active_pane.clone(),
 4316            item,
 4317            destination_index,
 4318            false,
 4319            focus_item,
 4320            window,
 4321            cx,
 4322        )
 4323    }
 4324
 4325    pub fn add_item(
 4326        &mut self,
 4327        pane: Entity<Pane>,
 4328        item: Box<dyn ItemHandle>,
 4329        destination_index: Option<usize>,
 4330        activate_pane: bool,
 4331        focus_item: bool,
 4332        window: &mut Window,
 4333        cx: &mut App,
 4334    ) {
 4335        pane.update(cx, |pane, cx| {
 4336            pane.add_item(
 4337                item,
 4338                activate_pane,
 4339                focus_item,
 4340                destination_index,
 4341                window,
 4342                cx,
 4343            )
 4344        });
 4345    }
 4346
 4347    pub fn split_item(
 4348        &mut self,
 4349        split_direction: SplitDirection,
 4350        item: Box<dyn ItemHandle>,
 4351        window: &mut Window,
 4352        cx: &mut Context<Self>,
 4353    ) {
 4354        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4355        self.add_item(new_pane, item, None, true, true, window, cx);
 4356    }
 4357
 4358    pub fn open_abs_path(
 4359        &mut self,
 4360        abs_path: PathBuf,
 4361        options: OpenOptions,
 4362        window: &mut Window,
 4363        cx: &mut Context<Self>,
 4364    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4365        cx.spawn_in(window, async move |workspace, cx| {
 4366            let open_paths_task_result = workspace
 4367                .update_in(cx, |workspace, window, cx| {
 4368                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4369                })
 4370                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4371                .await;
 4372            anyhow::ensure!(
 4373                open_paths_task_result.len() == 1,
 4374                "open abs path {abs_path:?} task returned incorrect number of results"
 4375            );
 4376            match open_paths_task_result
 4377                .into_iter()
 4378                .next()
 4379                .expect("ensured single task result")
 4380            {
 4381                Some(open_result) => {
 4382                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4383                }
 4384                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4385            }
 4386        })
 4387    }
 4388
 4389    pub fn split_abs_path(
 4390        &mut self,
 4391        abs_path: PathBuf,
 4392        visible: bool,
 4393        window: &mut Window,
 4394        cx: &mut Context<Self>,
 4395    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4396        let project_path_task =
 4397            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4398        cx.spawn_in(window, async move |this, cx| {
 4399            let (_, path) = project_path_task.await?;
 4400            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4401                .await
 4402        })
 4403    }
 4404
 4405    pub fn open_path(
 4406        &mut self,
 4407        path: impl Into<ProjectPath>,
 4408        pane: Option<WeakEntity<Pane>>,
 4409        focus_item: bool,
 4410        window: &mut Window,
 4411        cx: &mut App,
 4412    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4413        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4414    }
 4415
 4416    pub fn open_path_preview(
 4417        &mut self,
 4418        path: impl Into<ProjectPath>,
 4419        pane: Option<WeakEntity<Pane>>,
 4420        focus_item: bool,
 4421        allow_preview: bool,
 4422        activate: bool,
 4423        window: &mut Window,
 4424        cx: &mut App,
 4425    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4426        let pane = pane.unwrap_or_else(|| {
 4427            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4428                self.panes
 4429                    .first()
 4430                    .expect("There must be an active pane")
 4431                    .downgrade()
 4432            })
 4433        });
 4434
 4435        let project_path = path.into();
 4436        let task = self.load_path(project_path.clone(), window, cx);
 4437        window.spawn(cx, async move |cx| {
 4438            let (project_entry_id, build_item) = task.await?;
 4439
 4440            pane.update_in(cx, |pane, window, cx| {
 4441                pane.open_item(
 4442                    project_entry_id,
 4443                    project_path,
 4444                    focus_item,
 4445                    allow_preview,
 4446                    activate,
 4447                    None,
 4448                    window,
 4449                    cx,
 4450                    build_item,
 4451                )
 4452            })
 4453        })
 4454    }
 4455
 4456    pub fn split_path(
 4457        &mut self,
 4458        path: impl Into<ProjectPath>,
 4459        window: &mut Window,
 4460        cx: &mut Context<Self>,
 4461    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4462        self.split_path_preview(path, false, None, window, cx)
 4463    }
 4464
 4465    pub fn split_path_preview(
 4466        &mut self,
 4467        path: impl Into<ProjectPath>,
 4468        allow_preview: bool,
 4469        split_direction: Option<SplitDirection>,
 4470        window: &mut Window,
 4471        cx: &mut Context<Self>,
 4472    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4473        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4474            self.panes
 4475                .first()
 4476                .expect("There must be an active pane")
 4477                .downgrade()
 4478        });
 4479
 4480        if let Member::Pane(center_pane) = &self.center.root
 4481            && center_pane.read(cx).items_len() == 0
 4482        {
 4483            return self.open_path(path, Some(pane), true, window, cx);
 4484        }
 4485
 4486        let project_path = path.into();
 4487        let task = self.load_path(project_path.clone(), window, cx);
 4488        cx.spawn_in(window, async move |this, cx| {
 4489            let (project_entry_id, build_item) = task.await?;
 4490            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4491                let pane = pane.upgrade()?;
 4492                let new_pane = this.split_pane(
 4493                    pane,
 4494                    split_direction.unwrap_or(SplitDirection::Right),
 4495                    window,
 4496                    cx,
 4497                );
 4498                new_pane.update(cx, |new_pane, cx| {
 4499                    Some(new_pane.open_item(
 4500                        project_entry_id,
 4501                        project_path,
 4502                        true,
 4503                        allow_preview,
 4504                        true,
 4505                        None,
 4506                        window,
 4507                        cx,
 4508                        build_item,
 4509                    ))
 4510                })
 4511            })
 4512            .map(|option| option.context("pane was dropped"))?
 4513        })
 4514    }
 4515
 4516    fn load_path(
 4517        &mut self,
 4518        path: ProjectPath,
 4519        window: &mut Window,
 4520        cx: &mut App,
 4521    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4522        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4523        registry.open_path(self.project(), &path, window, cx)
 4524    }
 4525
 4526    pub fn find_project_item<T>(
 4527        &self,
 4528        pane: &Entity<Pane>,
 4529        project_item: &Entity<T::Item>,
 4530        cx: &App,
 4531    ) -> Option<Entity<T>>
 4532    where
 4533        T: ProjectItem,
 4534    {
 4535        use project::ProjectItem as _;
 4536        let project_item = project_item.read(cx);
 4537        let entry_id = project_item.entry_id(cx);
 4538        let project_path = project_item.project_path(cx);
 4539
 4540        let mut item = None;
 4541        if let Some(entry_id) = entry_id {
 4542            item = pane.read(cx).item_for_entry(entry_id, cx);
 4543        }
 4544        if item.is_none()
 4545            && let Some(project_path) = project_path
 4546        {
 4547            item = pane.read(cx).item_for_path(project_path, cx);
 4548        }
 4549
 4550        item.and_then(|item| item.downcast::<T>())
 4551    }
 4552
 4553    pub fn is_project_item_open<T>(
 4554        &self,
 4555        pane: &Entity<Pane>,
 4556        project_item: &Entity<T::Item>,
 4557        cx: &App,
 4558    ) -> bool
 4559    where
 4560        T: ProjectItem,
 4561    {
 4562        self.find_project_item::<T>(pane, project_item, cx)
 4563            .is_some()
 4564    }
 4565
 4566    pub fn open_project_item<T>(
 4567        &mut self,
 4568        pane: Entity<Pane>,
 4569        project_item: Entity<T::Item>,
 4570        activate_pane: bool,
 4571        focus_item: bool,
 4572        keep_old_preview: bool,
 4573        allow_new_preview: bool,
 4574        window: &mut Window,
 4575        cx: &mut Context<Self>,
 4576    ) -> Entity<T>
 4577    where
 4578        T: ProjectItem,
 4579    {
 4580        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4581
 4582        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4583            if !keep_old_preview
 4584                && let Some(old_id) = old_item_id
 4585                && old_id != item.item_id()
 4586            {
 4587                // switching to a different item, so unpreview old active item
 4588                pane.update(cx, |pane, _| {
 4589                    pane.unpreview_item_if_preview(old_id);
 4590                });
 4591            }
 4592
 4593            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4594            if !allow_new_preview {
 4595                pane.update(cx, |pane, _| {
 4596                    pane.unpreview_item_if_preview(item.item_id());
 4597                });
 4598            }
 4599            return item;
 4600        }
 4601
 4602        let item = pane.update(cx, |pane, cx| {
 4603            cx.new(|cx| {
 4604                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4605            })
 4606        });
 4607        let mut destination_index = None;
 4608        pane.update(cx, |pane, cx| {
 4609            if !keep_old_preview && let Some(old_id) = old_item_id {
 4610                pane.unpreview_item_if_preview(old_id);
 4611            }
 4612            if allow_new_preview {
 4613                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4614            }
 4615        });
 4616
 4617        self.add_item(
 4618            pane,
 4619            Box::new(item.clone()),
 4620            destination_index,
 4621            activate_pane,
 4622            focus_item,
 4623            window,
 4624            cx,
 4625        );
 4626        item
 4627    }
 4628
 4629    pub fn open_shared_screen(
 4630        &mut self,
 4631        peer_id: PeerId,
 4632        window: &mut Window,
 4633        cx: &mut Context<Self>,
 4634    ) {
 4635        if let Some(shared_screen) =
 4636            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4637        {
 4638            self.active_pane.update(cx, |pane, cx| {
 4639                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4640            });
 4641        }
 4642    }
 4643
 4644    pub fn activate_item(
 4645        &mut self,
 4646        item: &dyn ItemHandle,
 4647        activate_pane: bool,
 4648        focus_item: bool,
 4649        window: &mut Window,
 4650        cx: &mut App,
 4651    ) -> bool {
 4652        let result = self.panes.iter().find_map(|pane| {
 4653            pane.read(cx)
 4654                .index_for_item(item)
 4655                .map(|ix| (pane.clone(), ix))
 4656        });
 4657        if let Some((pane, ix)) = result {
 4658            pane.update(cx, |pane, cx| {
 4659                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4660            });
 4661            true
 4662        } else {
 4663            false
 4664        }
 4665    }
 4666
 4667    fn activate_pane_at_index(
 4668        &mut self,
 4669        action: &ActivatePane,
 4670        window: &mut Window,
 4671        cx: &mut Context<Self>,
 4672    ) {
 4673        let panes = self.center.panes();
 4674        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4675            window.focus(&pane.focus_handle(cx), cx);
 4676        } else {
 4677            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4678                .detach();
 4679        }
 4680    }
 4681
 4682    fn move_item_to_pane_at_index(
 4683        &mut self,
 4684        action: &MoveItemToPane,
 4685        window: &mut Window,
 4686        cx: &mut Context<Self>,
 4687    ) {
 4688        let panes = self.center.panes();
 4689        let destination = match panes.get(action.destination) {
 4690            Some(&destination) => destination.clone(),
 4691            None => {
 4692                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4693                    return;
 4694                }
 4695                let direction = SplitDirection::Right;
 4696                let split_off_pane = self
 4697                    .find_pane_in_direction(direction, cx)
 4698                    .unwrap_or_else(|| self.active_pane.clone());
 4699                let new_pane = self.add_pane(window, cx);
 4700                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4701                new_pane
 4702            }
 4703        };
 4704
 4705        if action.clone {
 4706            if self
 4707                .active_pane
 4708                .read(cx)
 4709                .active_item()
 4710                .is_some_and(|item| item.can_split(cx))
 4711            {
 4712                clone_active_item(
 4713                    self.database_id(),
 4714                    &self.active_pane,
 4715                    &destination,
 4716                    action.focus,
 4717                    window,
 4718                    cx,
 4719                );
 4720                return;
 4721            }
 4722        }
 4723        move_active_item(
 4724            &self.active_pane,
 4725            &destination,
 4726            action.focus,
 4727            true,
 4728            window,
 4729            cx,
 4730        )
 4731    }
 4732
 4733    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4734        let panes = self.center.panes();
 4735        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4736            let next_ix = (ix + 1) % panes.len();
 4737            let next_pane = panes[next_ix].clone();
 4738            window.focus(&next_pane.focus_handle(cx), cx);
 4739        }
 4740    }
 4741
 4742    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4743        let panes = self.center.panes();
 4744        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4745            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4746            let prev_pane = panes[prev_ix].clone();
 4747            window.focus(&prev_pane.focus_handle(cx), cx);
 4748        }
 4749    }
 4750
 4751    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4752        let last_pane = self.center.last_pane();
 4753        window.focus(&last_pane.focus_handle(cx), cx);
 4754    }
 4755
 4756    pub fn activate_pane_in_direction(
 4757        &mut self,
 4758        direction: SplitDirection,
 4759        window: &mut Window,
 4760        cx: &mut App,
 4761    ) {
 4762        use ActivateInDirectionTarget as Target;
 4763        enum Origin {
 4764            Sidebar,
 4765            LeftDock,
 4766            RightDock,
 4767            BottomDock,
 4768            Center,
 4769        }
 4770
 4771        let origin: Origin = if self
 4772            .sidebar_focus_handle
 4773            .as_ref()
 4774            .is_some_and(|h| h.contains_focused(window, cx))
 4775        {
 4776            Origin::Sidebar
 4777        } else {
 4778            [
 4779                (&self.left_dock, Origin::LeftDock),
 4780                (&self.right_dock, Origin::RightDock),
 4781                (&self.bottom_dock, Origin::BottomDock),
 4782            ]
 4783            .into_iter()
 4784            .find_map(|(dock, origin)| {
 4785                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4786                    Some(origin)
 4787                } else {
 4788                    None
 4789                }
 4790            })
 4791            .unwrap_or(Origin::Center)
 4792        };
 4793
 4794        let get_last_active_pane = || {
 4795            let pane = self
 4796                .last_active_center_pane
 4797                .clone()
 4798                .unwrap_or_else(|| {
 4799                    self.panes
 4800                        .first()
 4801                        .expect("There must be an active pane")
 4802                        .downgrade()
 4803                })
 4804                .upgrade()?;
 4805            (pane.read(cx).items_len() != 0).then_some(pane)
 4806        };
 4807
 4808        let try_dock =
 4809            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4810
 4811        let sidebar_target = self
 4812            .sidebar_focus_handle
 4813            .as_ref()
 4814            .map(|h| Target::Sidebar(h.clone()));
 4815
 4816        let target = match (origin, direction) {
 4817            // From the sidebar, only Right navigates into the workspace.
 4818            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4819                .or_else(|| get_last_active_pane().map(Target::Pane))
 4820                .or_else(|| try_dock(&self.bottom_dock))
 4821                .or_else(|| try_dock(&self.right_dock)),
 4822
 4823            (Origin::Sidebar, _) => None,
 4824
 4825            // We're in the center, so we first try to go to a different pane,
 4826            // otherwise try to go to a dock.
 4827            (Origin::Center, direction) => {
 4828                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4829                    Some(Target::Pane(pane))
 4830                } else {
 4831                    match direction {
 4832                        SplitDirection::Up => None,
 4833                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4834                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4835                        SplitDirection::Right => try_dock(&self.right_dock),
 4836                    }
 4837                }
 4838            }
 4839
 4840            (Origin::LeftDock, SplitDirection::Right) => {
 4841                if let Some(last_active_pane) = get_last_active_pane() {
 4842                    Some(Target::Pane(last_active_pane))
 4843                } else {
 4844                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4845                }
 4846            }
 4847
 4848            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4849
 4850            (Origin::LeftDock, SplitDirection::Down)
 4851            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4852
 4853            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4854            (Origin::BottomDock, SplitDirection::Left) => {
 4855                try_dock(&self.left_dock).or(sidebar_target)
 4856            }
 4857            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4858
 4859            (Origin::RightDock, SplitDirection::Left) => {
 4860                if let Some(last_active_pane) = get_last_active_pane() {
 4861                    Some(Target::Pane(last_active_pane))
 4862                } else {
 4863                    try_dock(&self.bottom_dock)
 4864                        .or_else(|| try_dock(&self.left_dock))
 4865                        .or(sidebar_target)
 4866                }
 4867            }
 4868
 4869            _ => None,
 4870        };
 4871
 4872        match target {
 4873            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4874                let pane = pane.read(cx);
 4875                if let Some(item) = pane.active_item() {
 4876                    item.item_focus_handle(cx).focus(window, cx);
 4877                } else {
 4878                    log::error!(
 4879                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4880                    );
 4881                }
 4882            }
 4883            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4884                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4885                window.defer(cx, move |window, cx| {
 4886                    let dock = dock.read(cx);
 4887                    if let Some(panel) = dock.active_panel() {
 4888                        panel.panel_focus_handle(cx).focus(window, cx);
 4889                    } else {
 4890                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4891                    }
 4892                })
 4893            }
 4894            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4895                focus_handle.focus(window, cx);
 4896            }
 4897            None => {}
 4898        }
 4899    }
 4900
 4901    pub fn move_item_to_pane_in_direction(
 4902        &mut self,
 4903        action: &MoveItemToPaneInDirection,
 4904        window: &mut Window,
 4905        cx: &mut Context<Self>,
 4906    ) {
 4907        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4908            Some(destination) => destination,
 4909            None => {
 4910                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4911                    return;
 4912                }
 4913                let new_pane = self.add_pane(window, cx);
 4914                self.center
 4915                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4916                new_pane
 4917            }
 4918        };
 4919
 4920        if action.clone {
 4921            if self
 4922                .active_pane
 4923                .read(cx)
 4924                .active_item()
 4925                .is_some_and(|item| item.can_split(cx))
 4926            {
 4927                clone_active_item(
 4928                    self.database_id(),
 4929                    &self.active_pane,
 4930                    &destination,
 4931                    action.focus,
 4932                    window,
 4933                    cx,
 4934                );
 4935                return;
 4936            }
 4937        }
 4938        move_active_item(
 4939            &self.active_pane,
 4940            &destination,
 4941            action.focus,
 4942            true,
 4943            window,
 4944            cx,
 4945        );
 4946    }
 4947
 4948    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4949        self.center.bounding_box_for_pane(pane)
 4950    }
 4951
 4952    pub fn find_pane_in_direction(
 4953        &mut self,
 4954        direction: SplitDirection,
 4955        cx: &App,
 4956    ) -> Option<Entity<Pane>> {
 4957        self.center
 4958            .find_pane_in_direction(&self.active_pane, direction, cx)
 4959            .cloned()
 4960    }
 4961
 4962    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4963        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4964            self.center.swap(&self.active_pane, &to, cx);
 4965            cx.notify();
 4966        }
 4967    }
 4968
 4969    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4970        if self
 4971            .center
 4972            .move_to_border(&self.active_pane, direction, cx)
 4973            .unwrap()
 4974        {
 4975            cx.notify();
 4976        }
 4977    }
 4978
 4979    pub fn resize_pane(
 4980        &mut self,
 4981        axis: gpui::Axis,
 4982        amount: Pixels,
 4983        window: &mut Window,
 4984        cx: &mut Context<Self>,
 4985    ) {
 4986        let docks = self.all_docks();
 4987        let active_dock = docks
 4988            .into_iter()
 4989            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4990
 4991        if let Some(dock_entity) = active_dock {
 4992            let dock = dock_entity.read(cx);
 4993            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 4994                return;
 4995            };
 4996            match dock.position() {
 4997                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4998                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4999                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5000            }
 5001        } else {
 5002            self.center
 5003                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5004        }
 5005        cx.notify();
 5006    }
 5007
 5008    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5009        self.center.reset_pane_sizes(cx);
 5010        cx.notify();
 5011    }
 5012
 5013    fn handle_pane_focused(
 5014        &mut self,
 5015        pane: Entity<Pane>,
 5016        window: &mut Window,
 5017        cx: &mut Context<Self>,
 5018    ) {
 5019        // This is explicitly hoisted out of the following check for pane identity as
 5020        // terminal panel panes are not registered as a center panes.
 5021        self.status_bar.update(cx, |status_bar, cx| {
 5022            status_bar.set_active_pane(&pane, window, cx);
 5023        });
 5024        if self.active_pane != pane {
 5025            self.set_active_pane(&pane, window, cx);
 5026        }
 5027
 5028        if self.last_active_center_pane.is_none() {
 5029            self.last_active_center_pane = Some(pane.downgrade());
 5030        }
 5031
 5032        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5033        // This prevents the dock from closing when focus events fire during window activation.
 5034        // We also preserve any dock whose active panel itself has focus — this covers
 5035        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5036        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5037            let dock_read = dock.read(cx);
 5038            if let Some(panel) = dock_read.active_panel() {
 5039                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5040                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5041                {
 5042                    return Some(dock_read.position());
 5043                }
 5044            }
 5045            None
 5046        });
 5047
 5048        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5049        if pane.read(cx).is_zoomed() {
 5050            self.zoomed = Some(pane.downgrade().into());
 5051        } else {
 5052            self.zoomed = None;
 5053        }
 5054        self.zoomed_position = None;
 5055        cx.emit(Event::ZoomChanged);
 5056        self.update_active_view_for_followers(window, cx);
 5057        pane.update(cx, |pane, _| {
 5058            pane.track_alternate_file_items();
 5059        });
 5060
 5061        cx.notify();
 5062    }
 5063
 5064    fn set_active_pane(
 5065        &mut self,
 5066        pane: &Entity<Pane>,
 5067        window: &mut Window,
 5068        cx: &mut Context<Self>,
 5069    ) {
 5070        self.active_pane = pane.clone();
 5071        self.active_item_path_changed(true, window, cx);
 5072        self.last_active_center_pane = Some(pane.downgrade());
 5073    }
 5074
 5075    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5076        self.update_active_view_for_followers(window, cx);
 5077    }
 5078
 5079    fn handle_pane_event(
 5080        &mut self,
 5081        pane: &Entity<Pane>,
 5082        event: &pane::Event,
 5083        window: &mut Window,
 5084        cx: &mut Context<Self>,
 5085    ) {
 5086        let mut serialize_workspace = true;
 5087        match event {
 5088            pane::Event::AddItem { item } => {
 5089                item.added_to_pane(self, pane.clone(), window, cx);
 5090                cx.emit(Event::ItemAdded {
 5091                    item: item.boxed_clone(),
 5092                });
 5093            }
 5094            pane::Event::Split { direction, mode } => {
 5095                match mode {
 5096                    SplitMode::ClonePane => {
 5097                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5098                            .detach();
 5099                    }
 5100                    SplitMode::EmptyPane => {
 5101                        self.split_pane(pane.clone(), *direction, window, cx);
 5102                    }
 5103                    SplitMode::MovePane => {
 5104                        self.split_and_move(pane.clone(), *direction, window, cx);
 5105                    }
 5106                };
 5107            }
 5108            pane::Event::JoinIntoNext => {
 5109                self.join_pane_into_next(pane.clone(), window, cx);
 5110            }
 5111            pane::Event::JoinAll => {
 5112                self.join_all_panes(window, cx);
 5113            }
 5114            pane::Event::Remove { focus_on_pane } => {
 5115                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5116            }
 5117            pane::Event::ActivateItem {
 5118                local,
 5119                focus_changed,
 5120            } => {
 5121                window.invalidate_character_coordinates();
 5122
 5123                pane.update(cx, |pane, _| {
 5124                    pane.track_alternate_file_items();
 5125                });
 5126                if *local {
 5127                    self.unfollow_in_pane(pane, window, cx);
 5128                }
 5129                serialize_workspace = *focus_changed || pane != self.active_pane();
 5130                if pane == self.active_pane() {
 5131                    self.active_item_path_changed(*focus_changed, window, cx);
 5132                    self.update_active_view_for_followers(window, cx);
 5133                } else if *local {
 5134                    self.set_active_pane(pane, window, cx);
 5135                }
 5136            }
 5137            pane::Event::UserSavedItem { item, save_intent } => {
 5138                cx.emit(Event::UserSavedItem {
 5139                    pane: pane.downgrade(),
 5140                    item: item.boxed_clone(),
 5141                    save_intent: *save_intent,
 5142                });
 5143                serialize_workspace = false;
 5144            }
 5145            pane::Event::ChangeItemTitle => {
 5146                if *pane == self.active_pane {
 5147                    self.active_item_path_changed(false, window, cx);
 5148                }
 5149                serialize_workspace = false;
 5150            }
 5151            pane::Event::RemovedItem { item } => {
 5152                cx.emit(Event::ActiveItemChanged);
 5153                self.update_window_edited(window, cx);
 5154                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5155                    && entry.get().entity_id() == pane.entity_id()
 5156                {
 5157                    entry.remove();
 5158                }
 5159                cx.emit(Event::ItemRemoved {
 5160                    item_id: item.item_id(),
 5161                });
 5162            }
 5163            pane::Event::Focus => {
 5164                window.invalidate_character_coordinates();
 5165                self.handle_pane_focused(pane.clone(), window, cx);
 5166            }
 5167            pane::Event::ZoomIn => {
 5168                if *pane == self.active_pane {
 5169                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5170                    if pane.read(cx).has_focus(window, cx) {
 5171                        self.zoomed = Some(pane.downgrade().into());
 5172                        self.zoomed_position = None;
 5173                        cx.emit(Event::ZoomChanged);
 5174                    }
 5175                    cx.notify();
 5176                }
 5177            }
 5178            pane::Event::ZoomOut => {
 5179                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5180                if self.zoomed_position.is_none() {
 5181                    self.zoomed = None;
 5182                    cx.emit(Event::ZoomChanged);
 5183                }
 5184                cx.notify();
 5185            }
 5186            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5187        }
 5188
 5189        if serialize_workspace {
 5190            self.serialize_workspace(window, cx);
 5191        }
 5192    }
 5193
 5194    pub fn unfollow_in_pane(
 5195        &mut self,
 5196        pane: &Entity<Pane>,
 5197        window: &mut Window,
 5198        cx: &mut Context<Workspace>,
 5199    ) -> Option<CollaboratorId> {
 5200        let leader_id = self.leader_for_pane(pane)?;
 5201        self.unfollow(leader_id, window, cx);
 5202        Some(leader_id)
 5203    }
 5204
 5205    pub fn split_pane(
 5206        &mut self,
 5207        pane_to_split: Entity<Pane>,
 5208        split_direction: SplitDirection,
 5209        window: &mut Window,
 5210        cx: &mut Context<Self>,
 5211    ) -> Entity<Pane> {
 5212        let new_pane = self.add_pane(window, cx);
 5213        self.center
 5214            .split(&pane_to_split, &new_pane, split_direction, cx);
 5215        cx.notify();
 5216        new_pane
 5217    }
 5218
 5219    pub fn split_and_move(
 5220        &mut self,
 5221        pane: Entity<Pane>,
 5222        direction: SplitDirection,
 5223        window: &mut Window,
 5224        cx: &mut Context<Self>,
 5225    ) {
 5226        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5227            return;
 5228        };
 5229        let new_pane = self.add_pane(window, cx);
 5230        new_pane.update(cx, |pane, cx| {
 5231            pane.add_item(item, true, true, None, window, cx)
 5232        });
 5233        self.center.split(&pane, &new_pane, direction, cx);
 5234        cx.notify();
 5235    }
 5236
 5237    pub fn split_and_clone(
 5238        &mut self,
 5239        pane: Entity<Pane>,
 5240        direction: SplitDirection,
 5241        window: &mut Window,
 5242        cx: &mut Context<Self>,
 5243    ) -> Task<Option<Entity<Pane>>> {
 5244        let Some(item) = pane.read(cx).active_item() else {
 5245            return Task::ready(None);
 5246        };
 5247        if !item.can_split(cx) {
 5248            return Task::ready(None);
 5249        }
 5250        let task = item.clone_on_split(self.database_id(), window, cx);
 5251        cx.spawn_in(window, async move |this, cx| {
 5252            if let Some(clone) = task.await {
 5253                this.update_in(cx, |this, window, cx| {
 5254                    let new_pane = this.add_pane(window, cx);
 5255                    let nav_history = pane.read(cx).fork_nav_history();
 5256                    new_pane.update(cx, |pane, cx| {
 5257                        pane.set_nav_history(nav_history, cx);
 5258                        pane.add_item(clone, true, true, None, window, cx)
 5259                    });
 5260                    this.center.split(&pane, &new_pane, direction, cx);
 5261                    cx.notify();
 5262                    new_pane
 5263                })
 5264                .ok()
 5265            } else {
 5266                None
 5267            }
 5268        })
 5269    }
 5270
 5271    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5272        let active_item = self.active_pane.read(cx).active_item();
 5273        for pane in &self.panes {
 5274            join_pane_into_active(&self.active_pane, pane, window, cx);
 5275        }
 5276        if let Some(active_item) = active_item {
 5277            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5278        }
 5279        cx.notify();
 5280    }
 5281
 5282    pub fn join_pane_into_next(
 5283        &mut self,
 5284        pane: Entity<Pane>,
 5285        window: &mut Window,
 5286        cx: &mut Context<Self>,
 5287    ) {
 5288        let next_pane = self
 5289            .find_pane_in_direction(SplitDirection::Right, cx)
 5290            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5291            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5292            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5293        let Some(next_pane) = next_pane else {
 5294            return;
 5295        };
 5296        move_all_items(&pane, &next_pane, window, cx);
 5297        cx.notify();
 5298    }
 5299
 5300    fn remove_pane(
 5301        &mut self,
 5302        pane: Entity<Pane>,
 5303        focus_on: Option<Entity<Pane>>,
 5304        window: &mut Window,
 5305        cx: &mut Context<Self>,
 5306    ) {
 5307        if self.center.remove(&pane, cx).unwrap() {
 5308            self.force_remove_pane(&pane, &focus_on, window, cx);
 5309            self.unfollow_in_pane(&pane, window, cx);
 5310            self.last_leaders_by_pane.remove(&pane.downgrade());
 5311            for removed_item in pane.read(cx).items() {
 5312                self.panes_by_item.remove(&removed_item.item_id());
 5313            }
 5314
 5315            cx.notify();
 5316        } else {
 5317            self.active_item_path_changed(true, window, cx);
 5318        }
 5319        cx.emit(Event::PaneRemoved);
 5320    }
 5321
 5322    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5323        &mut self.panes
 5324    }
 5325
 5326    pub fn panes(&self) -> &[Entity<Pane>] {
 5327        &self.panes
 5328    }
 5329
 5330    pub fn active_pane(&self) -> &Entity<Pane> {
 5331        &self.active_pane
 5332    }
 5333
 5334    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5335        for dock in self.all_docks() {
 5336            if dock.focus_handle(cx).contains_focused(window, cx)
 5337                && let Some(pane) = dock
 5338                    .read(cx)
 5339                    .active_panel()
 5340                    .and_then(|panel| panel.pane(cx))
 5341            {
 5342                return pane;
 5343            }
 5344        }
 5345        self.active_pane().clone()
 5346    }
 5347
 5348    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5349        self.find_pane_in_direction(SplitDirection::Right, cx)
 5350            .unwrap_or_else(|| {
 5351                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5352            })
 5353    }
 5354
 5355    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5356        self.pane_for_item_id(handle.item_id())
 5357    }
 5358
 5359    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5360        let weak_pane = self.panes_by_item.get(&item_id)?;
 5361        weak_pane.upgrade()
 5362    }
 5363
 5364    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5365        self.panes
 5366            .iter()
 5367            .find(|pane| pane.entity_id() == entity_id)
 5368            .cloned()
 5369    }
 5370
 5371    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5372        self.follower_states.retain(|leader_id, state| {
 5373            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5374                for item in state.items_by_leader_view_id.values() {
 5375                    item.view.set_leader_id(None, window, cx);
 5376                }
 5377                false
 5378            } else {
 5379                true
 5380            }
 5381        });
 5382        cx.notify();
 5383    }
 5384
 5385    pub fn start_following(
 5386        &mut self,
 5387        leader_id: impl Into<CollaboratorId>,
 5388        window: &mut Window,
 5389        cx: &mut Context<Self>,
 5390    ) -> Option<Task<Result<()>>> {
 5391        let leader_id = leader_id.into();
 5392        let pane = self.active_pane().clone();
 5393
 5394        self.last_leaders_by_pane
 5395            .insert(pane.downgrade(), leader_id);
 5396        self.unfollow(leader_id, window, cx);
 5397        self.unfollow_in_pane(&pane, window, cx);
 5398        self.follower_states.insert(
 5399            leader_id,
 5400            FollowerState {
 5401                center_pane: pane.clone(),
 5402                dock_pane: None,
 5403                active_view_id: None,
 5404                items_by_leader_view_id: Default::default(),
 5405            },
 5406        );
 5407        cx.notify();
 5408
 5409        match leader_id {
 5410            CollaboratorId::PeerId(leader_peer_id) => {
 5411                let room_id = self.active_call()?.room_id(cx)?;
 5412                let project_id = self.project.read(cx).remote_id();
 5413                let request = self.app_state.client.request(proto::Follow {
 5414                    room_id,
 5415                    project_id,
 5416                    leader_id: Some(leader_peer_id),
 5417                });
 5418
 5419                Some(cx.spawn_in(window, async move |this, cx| {
 5420                    let response = request.await?;
 5421                    this.update(cx, |this, _| {
 5422                        let state = this
 5423                            .follower_states
 5424                            .get_mut(&leader_id)
 5425                            .context("following interrupted")?;
 5426                        state.active_view_id = response
 5427                            .active_view
 5428                            .as_ref()
 5429                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5430                        anyhow::Ok(())
 5431                    })??;
 5432                    if let Some(view) = response.active_view {
 5433                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5434                    }
 5435                    this.update_in(cx, |this, window, cx| {
 5436                        this.leader_updated(leader_id, window, cx)
 5437                    })?;
 5438                    Ok(())
 5439                }))
 5440            }
 5441            CollaboratorId::Agent => {
 5442                self.leader_updated(leader_id, window, cx)?;
 5443                Some(Task::ready(Ok(())))
 5444            }
 5445        }
 5446    }
 5447
 5448    pub fn follow_next_collaborator(
 5449        &mut self,
 5450        _: &FollowNextCollaborator,
 5451        window: &mut Window,
 5452        cx: &mut Context<Self>,
 5453    ) {
 5454        let collaborators = self.project.read(cx).collaborators();
 5455        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5456            let mut collaborators = collaborators.keys().copied();
 5457            for peer_id in collaborators.by_ref() {
 5458                if CollaboratorId::PeerId(peer_id) == leader_id {
 5459                    break;
 5460                }
 5461            }
 5462            collaborators.next().map(CollaboratorId::PeerId)
 5463        } else if let Some(last_leader_id) =
 5464            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5465        {
 5466            match last_leader_id {
 5467                CollaboratorId::PeerId(peer_id) => {
 5468                    if collaborators.contains_key(peer_id) {
 5469                        Some(*last_leader_id)
 5470                    } else {
 5471                        None
 5472                    }
 5473                }
 5474                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5475            }
 5476        } else {
 5477            None
 5478        };
 5479
 5480        let pane = self.active_pane.clone();
 5481        let Some(leader_id) = next_leader_id.or_else(|| {
 5482            Some(CollaboratorId::PeerId(
 5483                collaborators.keys().copied().next()?,
 5484            ))
 5485        }) else {
 5486            return;
 5487        };
 5488        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5489            return;
 5490        }
 5491        if let Some(task) = self.start_following(leader_id, window, cx) {
 5492            task.detach_and_log_err(cx)
 5493        }
 5494    }
 5495
 5496    pub fn follow(
 5497        &mut self,
 5498        leader_id: impl Into<CollaboratorId>,
 5499        window: &mut Window,
 5500        cx: &mut Context<Self>,
 5501    ) {
 5502        let leader_id = leader_id.into();
 5503
 5504        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5505            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5506                return;
 5507            };
 5508            let Some(remote_participant) =
 5509                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5510            else {
 5511                return;
 5512            };
 5513
 5514            let project = self.project.read(cx);
 5515
 5516            let other_project_id = match remote_participant.location {
 5517                ParticipantLocation::External => None,
 5518                ParticipantLocation::UnsharedProject => None,
 5519                ParticipantLocation::SharedProject { project_id } => {
 5520                    if Some(project_id) == project.remote_id() {
 5521                        None
 5522                    } else {
 5523                        Some(project_id)
 5524                    }
 5525                }
 5526            };
 5527
 5528            // if they are active in another project, follow there.
 5529            if let Some(project_id) = other_project_id {
 5530                let app_state = self.app_state.clone();
 5531                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5532                    .detach_and_log_err(cx);
 5533            }
 5534        }
 5535
 5536        // if you're already following, find the right pane and focus it.
 5537        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5538            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5539
 5540            return;
 5541        }
 5542
 5543        // Otherwise, follow.
 5544        if let Some(task) = self.start_following(leader_id, window, cx) {
 5545            task.detach_and_log_err(cx)
 5546        }
 5547    }
 5548
 5549    pub fn unfollow(
 5550        &mut self,
 5551        leader_id: impl Into<CollaboratorId>,
 5552        window: &mut Window,
 5553        cx: &mut Context<Self>,
 5554    ) -> Option<()> {
 5555        cx.notify();
 5556
 5557        let leader_id = leader_id.into();
 5558        let state = self.follower_states.remove(&leader_id)?;
 5559        for (_, item) in state.items_by_leader_view_id {
 5560            item.view.set_leader_id(None, window, cx);
 5561        }
 5562
 5563        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5564            let project_id = self.project.read(cx).remote_id();
 5565            let room_id = self.active_call()?.room_id(cx)?;
 5566            self.app_state
 5567                .client
 5568                .send(proto::Unfollow {
 5569                    room_id,
 5570                    project_id,
 5571                    leader_id: Some(leader_peer_id),
 5572                })
 5573                .log_err();
 5574        }
 5575
 5576        Some(())
 5577    }
 5578
 5579    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5580        self.follower_states.contains_key(&id.into())
 5581    }
 5582
 5583    fn active_item_path_changed(
 5584        &mut self,
 5585        focus_changed: bool,
 5586        window: &mut Window,
 5587        cx: &mut Context<Self>,
 5588    ) {
 5589        cx.emit(Event::ActiveItemChanged);
 5590        let active_entry = self.active_project_path(cx);
 5591        self.project.update(cx, |project, cx| {
 5592            project.set_active_path(active_entry.clone(), cx)
 5593        });
 5594
 5595        if focus_changed && let Some(project_path) = &active_entry {
 5596            let git_store_entity = self.project.read(cx).git_store().clone();
 5597            git_store_entity.update(cx, |git_store, cx| {
 5598                git_store.set_active_repo_for_path(project_path, cx);
 5599            });
 5600        }
 5601
 5602        self.update_window_title(window, cx);
 5603    }
 5604
 5605    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5606        let project = self.project().read(cx);
 5607        let mut title = String::new();
 5608
 5609        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5610            let name = {
 5611                let settings_location = SettingsLocation {
 5612                    worktree_id: worktree.read(cx).id(),
 5613                    path: RelPath::empty(),
 5614                };
 5615
 5616                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5617                match &settings.project_name {
 5618                    Some(name) => name.as_str(),
 5619                    None => worktree.read(cx).root_name_str(),
 5620                }
 5621            };
 5622            if i > 0 {
 5623                title.push_str(", ");
 5624            }
 5625            title.push_str(name);
 5626        }
 5627
 5628        if title.is_empty() {
 5629            title = "empty project".to_string();
 5630        }
 5631
 5632        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5633            let filename = path.path.file_name().or_else(|| {
 5634                Some(
 5635                    project
 5636                        .worktree_for_id(path.worktree_id, cx)?
 5637                        .read(cx)
 5638                        .root_name_str(),
 5639                )
 5640            });
 5641
 5642            if let Some(filename) = filename {
 5643                title.push_str("");
 5644                title.push_str(filename.as_ref());
 5645            }
 5646        }
 5647
 5648        if project.is_via_collab() {
 5649            title.push_str("");
 5650        } else if project.is_shared() {
 5651            title.push_str("");
 5652        }
 5653
 5654        if let Some(last_title) = self.last_window_title.as_ref()
 5655            && &title == last_title
 5656        {
 5657            return;
 5658        }
 5659        window.set_window_title(&title);
 5660        SystemWindowTabController::update_tab_title(
 5661            cx,
 5662            window.window_handle().window_id(),
 5663            SharedString::from(&title),
 5664        );
 5665        self.last_window_title = Some(title);
 5666    }
 5667
 5668    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5669        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5670        if is_edited != self.window_edited {
 5671            self.window_edited = is_edited;
 5672            window.set_window_edited(self.window_edited)
 5673        }
 5674    }
 5675
 5676    fn update_item_dirty_state(
 5677        &mut self,
 5678        item: &dyn ItemHandle,
 5679        window: &mut Window,
 5680        cx: &mut App,
 5681    ) {
 5682        let is_dirty = item.is_dirty(cx);
 5683        let item_id = item.item_id();
 5684        let was_dirty = self.dirty_items.contains_key(&item_id);
 5685        if is_dirty == was_dirty {
 5686            return;
 5687        }
 5688        if was_dirty {
 5689            self.dirty_items.remove(&item_id);
 5690            self.update_window_edited(window, cx);
 5691            return;
 5692        }
 5693
 5694        let workspace = self.weak_handle();
 5695        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5696            return;
 5697        };
 5698        let on_release_callback = Box::new(move |cx: &mut App| {
 5699            window_handle
 5700                .update(cx, |_, window, cx| {
 5701                    workspace
 5702                        .update(cx, |workspace, cx| {
 5703                            workspace.dirty_items.remove(&item_id);
 5704                            workspace.update_window_edited(window, cx)
 5705                        })
 5706                        .ok();
 5707                })
 5708                .ok();
 5709        });
 5710
 5711        let s = item.on_release(cx, on_release_callback);
 5712        self.dirty_items.insert(item_id, s);
 5713        self.update_window_edited(window, cx);
 5714    }
 5715
 5716    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5717        if self.notifications.is_empty() {
 5718            None
 5719        } else {
 5720            Some(
 5721                div()
 5722                    .absolute()
 5723                    .right_3()
 5724                    .bottom_3()
 5725                    .w_112()
 5726                    .h_full()
 5727                    .flex()
 5728                    .flex_col()
 5729                    .justify_end()
 5730                    .gap_2()
 5731                    .children(
 5732                        self.notifications
 5733                            .iter()
 5734                            .map(|(_, notification)| notification.clone().into_any()),
 5735                    ),
 5736            )
 5737        }
 5738    }
 5739
 5740    // RPC handlers
 5741
 5742    fn active_view_for_follower(
 5743        &self,
 5744        follower_project_id: Option<u64>,
 5745        window: &mut Window,
 5746        cx: &mut Context<Self>,
 5747    ) -> Option<proto::View> {
 5748        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5749        let item = item?;
 5750        let leader_id = self
 5751            .pane_for(&*item)
 5752            .and_then(|pane| self.leader_for_pane(&pane));
 5753        let leader_peer_id = match leader_id {
 5754            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5755            Some(CollaboratorId::Agent) | None => None,
 5756        };
 5757
 5758        let item_handle = item.to_followable_item_handle(cx)?;
 5759        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5760        let variant = item_handle.to_state_proto(window, cx)?;
 5761
 5762        if item_handle.is_project_item(window, cx)
 5763            && (follower_project_id.is_none()
 5764                || follower_project_id != self.project.read(cx).remote_id())
 5765        {
 5766            return None;
 5767        }
 5768
 5769        Some(proto::View {
 5770            id: id.to_proto(),
 5771            leader_id: leader_peer_id,
 5772            variant: Some(variant),
 5773            panel_id: panel_id.map(|id| id as i32),
 5774        })
 5775    }
 5776
 5777    fn handle_follow(
 5778        &mut self,
 5779        follower_project_id: Option<u64>,
 5780        window: &mut Window,
 5781        cx: &mut Context<Self>,
 5782    ) -> proto::FollowResponse {
 5783        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5784
 5785        cx.notify();
 5786        proto::FollowResponse {
 5787            views: active_view.iter().cloned().collect(),
 5788            active_view,
 5789        }
 5790    }
 5791
 5792    fn handle_update_followers(
 5793        &mut self,
 5794        leader_id: PeerId,
 5795        message: proto::UpdateFollowers,
 5796        _window: &mut Window,
 5797        _cx: &mut Context<Self>,
 5798    ) {
 5799        self.leader_updates_tx
 5800            .unbounded_send((leader_id, message))
 5801            .ok();
 5802    }
 5803
 5804    async fn process_leader_update(
 5805        this: &WeakEntity<Self>,
 5806        leader_id: PeerId,
 5807        update: proto::UpdateFollowers,
 5808        cx: &mut AsyncWindowContext,
 5809    ) -> Result<()> {
 5810        match update.variant.context("invalid update")? {
 5811            proto::update_followers::Variant::CreateView(view) => {
 5812                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5813                let should_add_view = this.update(cx, |this, _| {
 5814                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5815                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5816                    } else {
 5817                        anyhow::Ok(false)
 5818                    }
 5819                })??;
 5820
 5821                if should_add_view {
 5822                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5823                }
 5824            }
 5825            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5826                let should_add_view = this.update(cx, |this, _| {
 5827                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5828                        state.active_view_id = update_active_view
 5829                            .view
 5830                            .as_ref()
 5831                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5832
 5833                        if state.active_view_id.is_some_and(|view_id| {
 5834                            !state.items_by_leader_view_id.contains_key(&view_id)
 5835                        }) {
 5836                            anyhow::Ok(true)
 5837                        } else {
 5838                            anyhow::Ok(false)
 5839                        }
 5840                    } else {
 5841                        anyhow::Ok(false)
 5842                    }
 5843                })??;
 5844
 5845                if should_add_view && let Some(view) = update_active_view.view {
 5846                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5847                }
 5848            }
 5849            proto::update_followers::Variant::UpdateView(update_view) => {
 5850                let variant = update_view.variant.context("missing update view variant")?;
 5851                let id = update_view.id.context("missing update view id")?;
 5852                let mut tasks = Vec::new();
 5853                this.update_in(cx, |this, window, cx| {
 5854                    let project = this.project.clone();
 5855                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5856                        let view_id = ViewId::from_proto(id.clone())?;
 5857                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5858                            tasks.push(item.view.apply_update_proto(
 5859                                &project,
 5860                                variant.clone(),
 5861                                window,
 5862                                cx,
 5863                            ));
 5864                        }
 5865                    }
 5866                    anyhow::Ok(())
 5867                })??;
 5868                try_join_all(tasks).await.log_err();
 5869            }
 5870        }
 5871        this.update_in(cx, |this, window, cx| {
 5872            this.leader_updated(leader_id, window, cx)
 5873        })?;
 5874        Ok(())
 5875    }
 5876
 5877    async fn add_view_from_leader(
 5878        this: WeakEntity<Self>,
 5879        leader_id: PeerId,
 5880        view: &proto::View,
 5881        cx: &mut AsyncWindowContext,
 5882    ) -> Result<()> {
 5883        let this = this.upgrade().context("workspace dropped")?;
 5884
 5885        let Some(id) = view.id.clone() else {
 5886            anyhow::bail!("no id for view");
 5887        };
 5888        let id = ViewId::from_proto(id)?;
 5889        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5890
 5891        let pane = this.update(cx, |this, _cx| {
 5892            let state = this
 5893                .follower_states
 5894                .get(&leader_id.into())
 5895                .context("stopped following")?;
 5896            anyhow::Ok(state.pane().clone())
 5897        })?;
 5898        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5899            let client = this.read(cx).client().clone();
 5900            pane.items().find_map(|item| {
 5901                let item = item.to_followable_item_handle(cx)?;
 5902                if item.remote_id(&client, window, cx) == Some(id) {
 5903                    Some(item)
 5904                } else {
 5905                    None
 5906                }
 5907            })
 5908        })?;
 5909        let item = if let Some(existing_item) = existing_item {
 5910            existing_item
 5911        } else {
 5912            let variant = view.variant.clone();
 5913            anyhow::ensure!(variant.is_some(), "missing view variant");
 5914
 5915            let task = cx.update(|window, cx| {
 5916                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5917            })?;
 5918
 5919            let Some(task) = task else {
 5920                anyhow::bail!(
 5921                    "failed to construct view from leader (maybe from a different version of zed?)"
 5922                );
 5923            };
 5924
 5925            let mut new_item = task.await?;
 5926            pane.update_in(cx, |pane, window, cx| {
 5927                let mut item_to_remove = None;
 5928                for (ix, item) in pane.items().enumerate() {
 5929                    if let Some(item) = item.to_followable_item_handle(cx) {
 5930                        match new_item.dedup(item.as_ref(), window, cx) {
 5931                            Some(item::Dedup::KeepExisting) => {
 5932                                new_item =
 5933                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5934                                break;
 5935                            }
 5936                            Some(item::Dedup::ReplaceExisting) => {
 5937                                item_to_remove = Some((ix, item.item_id()));
 5938                                break;
 5939                            }
 5940                            None => {}
 5941                        }
 5942                    }
 5943                }
 5944
 5945                if let Some((ix, id)) = item_to_remove {
 5946                    pane.remove_item(id, false, false, window, cx);
 5947                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5948                }
 5949            })?;
 5950
 5951            new_item
 5952        };
 5953
 5954        this.update_in(cx, |this, window, cx| {
 5955            let state = this.follower_states.get_mut(&leader_id.into())?;
 5956            item.set_leader_id(Some(leader_id.into()), window, cx);
 5957            state.items_by_leader_view_id.insert(
 5958                id,
 5959                FollowerView {
 5960                    view: item,
 5961                    location: panel_id,
 5962                },
 5963            );
 5964
 5965            Some(())
 5966        })
 5967        .context("no follower state")?;
 5968
 5969        Ok(())
 5970    }
 5971
 5972    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5973        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5974            return;
 5975        };
 5976
 5977        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5978            let buffer_entity_id = agent_location.buffer.entity_id();
 5979            let view_id = ViewId {
 5980                creator: CollaboratorId::Agent,
 5981                id: buffer_entity_id.as_u64(),
 5982            };
 5983            follower_state.active_view_id = Some(view_id);
 5984
 5985            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5986                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5987                hash_map::Entry::Vacant(entry) => {
 5988                    let existing_view =
 5989                        follower_state
 5990                            .center_pane
 5991                            .read(cx)
 5992                            .items()
 5993                            .find_map(|item| {
 5994                                let item = item.to_followable_item_handle(cx)?;
 5995                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5996                                    && item.project_item_model_ids(cx).as_slice()
 5997                                        == [buffer_entity_id]
 5998                                {
 5999                                    Some(item)
 6000                                } else {
 6001                                    None
 6002                                }
 6003                            });
 6004                    let view = existing_view.or_else(|| {
 6005                        agent_location.buffer.upgrade().and_then(|buffer| {
 6006                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6007                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6008                            })?
 6009                            .to_followable_item_handle(cx)
 6010                        })
 6011                    });
 6012
 6013                    view.map(|view| {
 6014                        entry.insert(FollowerView {
 6015                            view,
 6016                            location: None,
 6017                        })
 6018                    })
 6019                }
 6020            };
 6021
 6022            if let Some(item) = item {
 6023                item.view
 6024                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6025                item.view
 6026                    .update_agent_location(agent_location.position, window, cx);
 6027            }
 6028        } else {
 6029            follower_state.active_view_id = None;
 6030        }
 6031
 6032        self.leader_updated(CollaboratorId::Agent, window, cx);
 6033    }
 6034
 6035    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6036        let mut is_project_item = true;
 6037        let mut update = proto::UpdateActiveView::default();
 6038        if window.is_window_active() {
 6039            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6040
 6041            if let Some(item) = active_item
 6042                && item.item_focus_handle(cx).contains_focused(window, cx)
 6043            {
 6044                let leader_id = self
 6045                    .pane_for(&*item)
 6046                    .and_then(|pane| self.leader_for_pane(&pane));
 6047                let leader_peer_id = match leader_id {
 6048                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6049                    Some(CollaboratorId::Agent) | None => None,
 6050                };
 6051
 6052                if let Some(item) = item.to_followable_item_handle(cx) {
 6053                    let id = item
 6054                        .remote_id(&self.app_state.client, window, cx)
 6055                        .map(|id| id.to_proto());
 6056
 6057                    if let Some(id) = id
 6058                        && let Some(variant) = item.to_state_proto(window, cx)
 6059                    {
 6060                        let view = Some(proto::View {
 6061                            id,
 6062                            leader_id: leader_peer_id,
 6063                            variant: Some(variant),
 6064                            panel_id: panel_id.map(|id| id as i32),
 6065                        });
 6066
 6067                        is_project_item = item.is_project_item(window, cx);
 6068                        update = proto::UpdateActiveView { view };
 6069                    };
 6070                }
 6071            }
 6072        }
 6073
 6074        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6075        if active_view_id != self.last_active_view_id.as_ref() {
 6076            self.last_active_view_id = active_view_id.cloned();
 6077            self.update_followers(
 6078                is_project_item,
 6079                proto::update_followers::Variant::UpdateActiveView(update),
 6080                window,
 6081                cx,
 6082            );
 6083        }
 6084    }
 6085
 6086    fn active_item_for_followers(
 6087        &self,
 6088        window: &mut Window,
 6089        cx: &mut App,
 6090    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6091        let mut active_item = None;
 6092        let mut panel_id = None;
 6093        for dock in self.all_docks() {
 6094            if dock.focus_handle(cx).contains_focused(window, cx)
 6095                && let Some(panel) = dock.read(cx).active_panel()
 6096                && let Some(pane) = panel.pane(cx)
 6097                && let Some(item) = pane.read(cx).active_item()
 6098            {
 6099                active_item = Some(item);
 6100                panel_id = panel.remote_id();
 6101                break;
 6102            }
 6103        }
 6104
 6105        if active_item.is_none() {
 6106            active_item = self.active_pane().read(cx).active_item();
 6107        }
 6108        (active_item, panel_id)
 6109    }
 6110
 6111    fn update_followers(
 6112        &self,
 6113        project_only: bool,
 6114        update: proto::update_followers::Variant,
 6115        _: &mut Window,
 6116        cx: &mut App,
 6117    ) -> Option<()> {
 6118        // If this update only applies to for followers in the current project,
 6119        // then skip it unless this project is shared. If it applies to all
 6120        // followers, regardless of project, then set `project_id` to none,
 6121        // indicating that it goes to all followers.
 6122        let project_id = if project_only {
 6123            Some(self.project.read(cx).remote_id()?)
 6124        } else {
 6125            None
 6126        };
 6127        self.app_state().workspace_store.update(cx, |store, cx| {
 6128            store.update_followers(project_id, update, cx)
 6129        })
 6130    }
 6131
 6132    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6133        self.follower_states.iter().find_map(|(leader_id, state)| {
 6134            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6135                Some(*leader_id)
 6136            } else {
 6137                None
 6138            }
 6139        })
 6140    }
 6141
 6142    fn leader_updated(
 6143        &mut self,
 6144        leader_id: impl Into<CollaboratorId>,
 6145        window: &mut Window,
 6146        cx: &mut Context<Self>,
 6147    ) -> Option<Box<dyn ItemHandle>> {
 6148        cx.notify();
 6149
 6150        let leader_id = leader_id.into();
 6151        let (panel_id, item) = match leader_id {
 6152            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6153            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6154        };
 6155
 6156        let state = self.follower_states.get(&leader_id)?;
 6157        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6158        let pane;
 6159        if let Some(panel_id) = panel_id {
 6160            pane = self
 6161                .activate_panel_for_proto_id(panel_id, window, cx)?
 6162                .pane(cx)?;
 6163            let state = self.follower_states.get_mut(&leader_id)?;
 6164            state.dock_pane = Some(pane.clone());
 6165        } else {
 6166            pane = state.center_pane.clone();
 6167            let state = self.follower_states.get_mut(&leader_id)?;
 6168            if let Some(dock_pane) = state.dock_pane.take() {
 6169                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6170            }
 6171        }
 6172
 6173        pane.update(cx, |pane, cx| {
 6174            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6175            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6176                pane.activate_item(index, false, false, window, cx);
 6177            } else {
 6178                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6179            }
 6180
 6181            if focus_active_item {
 6182                pane.focus_active_item(window, cx)
 6183            }
 6184        });
 6185
 6186        Some(item)
 6187    }
 6188
 6189    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6190        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6191        let active_view_id = state.active_view_id?;
 6192        Some(
 6193            state
 6194                .items_by_leader_view_id
 6195                .get(&active_view_id)?
 6196                .view
 6197                .boxed_clone(),
 6198        )
 6199    }
 6200
 6201    fn active_item_for_peer(
 6202        &self,
 6203        peer_id: PeerId,
 6204        window: &mut Window,
 6205        cx: &mut Context<Self>,
 6206    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6207        let call = self.active_call()?;
 6208        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6209        let leader_in_this_app;
 6210        let leader_in_this_project;
 6211        match participant.location {
 6212            ParticipantLocation::SharedProject { project_id } => {
 6213                leader_in_this_app = true;
 6214                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6215            }
 6216            ParticipantLocation::UnsharedProject => {
 6217                leader_in_this_app = true;
 6218                leader_in_this_project = false;
 6219            }
 6220            ParticipantLocation::External => {
 6221                leader_in_this_app = false;
 6222                leader_in_this_project = false;
 6223            }
 6224        };
 6225        let state = self.follower_states.get(&peer_id.into())?;
 6226        let mut item_to_activate = None;
 6227        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6228            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6229                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6230            {
 6231                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6232            }
 6233        } else if let Some(shared_screen) =
 6234            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6235        {
 6236            item_to_activate = Some((None, Box::new(shared_screen)));
 6237        }
 6238        item_to_activate
 6239    }
 6240
 6241    fn shared_screen_for_peer(
 6242        &self,
 6243        peer_id: PeerId,
 6244        pane: &Entity<Pane>,
 6245        window: &mut Window,
 6246        cx: &mut App,
 6247    ) -> Option<Entity<SharedScreen>> {
 6248        self.active_call()?
 6249            .create_shared_screen(peer_id, pane, window, cx)
 6250    }
 6251
 6252    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6253        if window.is_window_active() {
 6254            self.update_active_view_for_followers(window, cx);
 6255
 6256            if let Some(database_id) = self.database_id {
 6257                let db = WorkspaceDb::global(cx);
 6258                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6259                    .detach();
 6260            }
 6261        } else {
 6262            for pane in &self.panes {
 6263                pane.update(cx, |pane, cx| {
 6264                    if let Some(item) = pane.active_item() {
 6265                        item.workspace_deactivated(window, cx);
 6266                    }
 6267                    for item in pane.items() {
 6268                        if matches!(
 6269                            item.workspace_settings(cx).autosave,
 6270                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6271                        ) {
 6272                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6273                                .detach_and_log_err(cx);
 6274                        }
 6275                    }
 6276                });
 6277            }
 6278        }
 6279    }
 6280
 6281    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6282        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6283    }
 6284
 6285    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6286        self.active_call.as_ref().map(|(call, _)| call.clone())
 6287    }
 6288
 6289    fn on_active_call_event(
 6290        &mut self,
 6291        event: &ActiveCallEvent,
 6292        window: &mut Window,
 6293        cx: &mut Context<Self>,
 6294    ) {
 6295        match event {
 6296            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6297            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6298                self.leader_updated(participant_id, window, cx);
 6299            }
 6300        }
 6301    }
 6302
 6303    pub fn database_id(&self) -> Option<WorkspaceId> {
 6304        self.database_id
 6305    }
 6306
 6307    #[cfg(any(test, feature = "test-support"))]
 6308    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6309        self.database_id = Some(id);
 6310    }
 6311
 6312    pub fn session_id(&self) -> Option<String> {
 6313        self.session_id.clone()
 6314    }
 6315
 6316    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6317        let Some(display) = window.display(cx) else {
 6318            return Task::ready(());
 6319        };
 6320        let Ok(display_uuid) = display.uuid() else {
 6321            return Task::ready(());
 6322        };
 6323
 6324        let window_bounds = window.inner_window_bounds();
 6325        let database_id = self.database_id;
 6326        let has_paths = !self.root_paths(cx).is_empty();
 6327        let db = WorkspaceDb::global(cx);
 6328        let kvp = db::kvp::KeyValueStore::global(cx);
 6329
 6330        cx.background_executor().spawn(async move {
 6331            if !has_paths {
 6332                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6333                    .await
 6334                    .log_err();
 6335            }
 6336            if let Some(database_id) = database_id {
 6337                db.set_window_open_status(
 6338                    database_id,
 6339                    SerializedWindowBounds(window_bounds),
 6340                    display_uuid,
 6341                )
 6342                .await
 6343                .log_err();
 6344            } else {
 6345                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6346                    .await
 6347                    .log_err();
 6348            }
 6349        })
 6350    }
 6351
 6352    /// Bypass the 200ms serialization throttle and write workspace state to
 6353    /// the DB immediately. Returns a task the caller can await to ensure the
 6354    /// write completes. Used by the quit handler so the most recent state
 6355    /// isn't lost to a pending throttle timer when the process exits.
 6356    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6357        self._schedule_serialize_workspace.take();
 6358        self._serialize_workspace_task.take();
 6359        self.bounds_save_task_queued.take();
 6360
 6361        let bounds_task = self.save_window_bounds(window, cx);
 6362        let serialize_task = self.serialize_workspace_internal(window, cx);
 6363        cx.spawn(async move |_| {
 6364            bounds_task.await;
 6365            serialize_task.await;
 6366        })
 6367    }
 6368
 6369    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6370        let project = self.project().read(cx);
 6371        project
 6372            .visible_worktrees(cx)
 6373            .map(|worktree| worktree.read(cx).abs_path())
 6374            .collect::<Vec<_>>()
 6375    }
 6376
 6377    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 6378        let host = self.project().read(cx).remote_connection_options(cx);
 6379        let repositories = self.project().read(cx).repositories(cx);
 6380        let paths: Vec<_> = self
 6381            .root_paths(cx)
 6382            .iter()
 6383            .map(|root_path| {
 6384                repositories
 6385                    .values()
 6386                    .find(|repo| repo.read(cx).snapshot().work_directory_abs_path == *root_path)
 6387                    .map(|repo| {
 6388                        repo.read(cx)
 6389                            .snapshot()
 6390                            .original_repo_abs_path
 6391                            .to_path_buf()
 6392                    })
 6393                    .unwrap_or_else(|| root_path.to_path_buf())
 6394            })
 6395            .collect();
 6396        ProjectGroupKey::from_paths(&paths, host)
 6397    }
 6398
 6399    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6400        match member {
 6401            Member::Axis(PaneAxis { members, .. }) => {
 6402                for child in members.iter() {
 6403                    self.remove_panes(child.clone(), window, cx)
 6404                }
 6405            }
 6406            Member::Pane(pane) => {
 6407                self.force_remove_pane(&pane, &None, window, cx);
 6408            }
 6409        }
 6410    }
 6411
 6412    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6413        self.session_id.take();
 6414        self.serialize_workspace_internal(window, cx)
 6415    }
 6416
 6417    fn force_remove_pane(
 6418        &mut self,
 6419        pane: &Entity<Pane>,
 6420        focus_on: &Option<Entity<Pane>>,
 6421        window: &mut Window,
 6422        cx: &mut Context<Workspace>,
 6423    ) {
 6424        self.panes.retain(|p| p != pane);
 6425        if let Some(focus_on) = focus_on {
 6426            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6427        } else if self.active_pane() == pane {
 6428            self.panes
 6429                .last()
 6430                .unwrap()
 6431                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6432        }
 6433        if self.last_active_center_pane == Some(pane.downgrade()) {
 6434            self.last_active_center_pane = None;
 6435        }
 6436        cx.notify();
 6437    }
 6438
 6439    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6440        if self._schedule_serialize_workspace.is_none() {
 6441            self._schedule_serialize_workspace =
 6442                Some(cx.spawn_in(window, async move |this, cx| {
 6443                    cx.background_executor()
 6444                        .timer(SERIALIZATION_THROTTLE_TIME)
 6445                        .await;
 6446                    this.update_in(cx, |this, window, cx| {
 6447                        this._serialize_workspace_task =
 6448                            Some(this.serialize_workspace_internal(window, cx));
 6449                        this._schedule_serialize_workspace.take();
 6450                    })
 6451                    .log_err();
 6452                }));
 6453        }
 6454    }
 6455
 6456    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6457        let Some(database_id) = self.database_id() else {
 6458            return Task::ready(());
 6459        };
 6460
 6461        fn serialize_pane_handle(
 6462            pane_handle: &Entity<Pane>,
 6463            window: &mut Window,
 6464            cx: &mut App,
 6465        ) -> SerializedPane {
 6466            let (items, active, pinned_count) = {
 6467                let pane = pane_handle.read(cx);
 6468                let active_item_id = pane.active_item().map(|item| item.item_id());
 6469                (
 6470                    pane.items()
 6471                        .filter_map(|handle| {
 6472                            let handle = handle.to_serializable_item_handle(cx)?;
 6473
 6474                            Some(SerializedItem {
 6475                                kind: Arc::from(handle.serialized_item_kind()),
 6476                                item_id: handle.item_id().as_u64(),
 6477                                active: Some(handle.item_id()) == active_item_id,
 6478                                preview: pane.is_active_preview_item(handle.item_id()),
 6479                            })
 6480                        })
 6481                        .collect::<Vec<_>>(),
 6482                    pane.has_focus(window, cx),
 6483                    pane.pinned_count(),
 6484                )
 6485            };
 6486
 6487            SerializedPane::new(items, active, pinned_count)
 6488        }
 6489
 6490        fn build_serialized_pane_group(
 6491            pane_group: &Member,
 6492            window: &mut Window,
 6493            cx: &mut App,
 6494        ) -> SerializedPaneGroup {
 6495            match pane_group {
 6496                Member::Axis(PaneAxis {
 6497                    axis,
 6498                    members,
 6499                    flexes,
 6500                    bounding_boxes: _,
 6501                }) => SerializedPaneGroup::Group {
 6502                    axis: SerializedAxis(*axis),
 6503                    children: members
 6504                        .iter()
 6505                        .map(|member| build_serialized_pane_group(member, window, cx))
 6506                        .collect::<Vec<_>>(),
 6507                    flexes: Some(flexes.lock().clone()),
 6508                },
 6509                Member::Pane(pane_handle) => {
 6510                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6511                }
 6512            }
 6513        }
 6514
 6515        fn build_serialized_docks(
 6516            this: &Workspace,
 6517            window: &mut Window,
 6518            cx: &mut App,
 6519        ) -> DockStructure {
 6520            this.capture_dock_state(window, cx)
 6521        }
 6522
 6523        match self.workspace_location(cx) {
 6524            WorkspaceLocation::Location(location, paths) => {
 6525                let breakpoints = self.project.update(cx, |project, cx| {
 6526                    project
 6527                        .breakpoint_store()
 6528                        .read(cx)
 6529                        .all_source_breakpoints(cx)
 6530                });
 6531                let user_toolchains = self
 6532                    .project
 6533                    .read(cx)
 6534                    .user_toolchains(cx)
 6535                    .unwrap_or_default();
 6536
 6537                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6538                let docks = build_serialized_docks(self, window, cx);
 6539                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6540
 6541                let serialized_workspace = SerializedWorkspace {
 6542                    id: database_id,
 6543                    location,
 6544                    paths,
 6545                    center_group,
 6546                    window_bounds,
 6547                    display: Default::default(),
 6548                    docks,
 6549                    centered_layout: self.centered_layout,
 6550                    session_id: self.session_id.clone(),
 6551                    breakpoints,
 6552                    window_id: Some(window.window_handle().window_id().as_u64()),
 6553                    user_toolchains,
 6554                };
 6555
 6556                let db = WorkspaceDb::global(cx);
 6557                window.spawn(cx, async move |_| {
 6558                    db.save_workspace(serialized_workspace).await;
 6559                })
 6560            }
 6561            WorkspaceLocation::DetachFromSession => {
 6562                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6563                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6564                // Save dock state for empty local workspaces
 6565                let docks = build_serialized_docks(self, window, cx);
 6566                let db = WorkspaceDb::global(cx);
 6567                let kvp = db::kvp::KeyValueStore::global(cx);
 6568                window.spawn(cx, async move |_| {
 6569                    db.set_window_open_status(
 6570                        database_id,
 6571                        window_bounds,
 6572                        display.unwrap_or_default(),
 6573                    )
 6574                    .await
 6575                    .log_err();
 6576                    db.set_session_id(database_id, None).await.log_err();
 6577                    persistence::write_default_dock_state(&kvp, docks)
 6578                        .await
 6579                        .log_err();
 6580                })
 6581            }
 6582            WorkspaceLocation::None => {
 6583                // Save dock state for empty non-local workspaces
 6584                let docks = build_serialized_docks(self, window, cx);
 6585                let kvp = db::kvp::KeyValueStore::global(cx);
 6586                window.spawn(cx, async move |_| {
 6587                    persistence::write_default_dock_state(&kvp, docks)
 6588                        .await
 6589                        .log_err();
 6590                })
 6591            }
 6592        }
 6593    }
 6594
 6595    fn has_any_items_open(&self, cx: &App) -> bool {
 6596        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6597    }
 6598
 6599    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6600        let paths = PathList::new(&self.root_paths(cx));
 6601        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6602            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6603        } else if self.project.read(cx).is_local() {
 6604            if !paths.is_empty() || self.has_any_items_open(cx) {
 6605                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6606            } else {
 6607                WorkspaceLocation::DetachFromSession
 6608            }
 6609        } else {
 6610            WorkspaceLocation::None
 6611        }
 6612    }
 6613
 6614    fn update_history(&self, cx: &mut App) {
 6615        let Some(id) = self.database_id() else {
 6616            return;
 6617        };
 6618        if !self.project.read(cx).is_local() {
 6619            return;
 6620        }
 6621        if let Some(manager) = HistoryManager::global(cx) {
 6622            let paths = PathList::new(&self.root_paths(cx));
 6623            manager.update(cx, |this, cx| {
 6624                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6625            });
 6626        }
 6627    }
 6628
 6629    async fn serialize_items(
 6630        this: &WeakEntity<Self>,
 6631        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6632        cx: &mut AsyncWindowContext,
 6633    ) -> Result<()> {
 6634        const CHUNK_SIZE: usize = 200;
 6635
 6636        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6637
 6638        while let Some(items_received) = serializable_items.next().await {
 6639            let unique_items =
 6640                items_received
 6641                    .into_iter()
 6642                    .fold(HashMap::default(), |mut acc, item| {
 6643                        acc.entry(item.item_id()).or_insert(item);
 6644                        acc
 6645                    });
 6646
 6647            // We use into_iter() here so that the references to the items are moved into
 6648            // the tasks and not kept alive while we're sleeping.
 6649            for (_, item) in unique_items.into_iter() {
 6650                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6651                    item.serialize(workspace, false, window, cx)
 6652                }) {
 6653                    cx.background_spawn(async move { task.await.log_err() })
 6654                        .detach();
 6655                }
 6656            }
 6657
 6658            cx.background_executor()
 6659                .timer(SERIALIZATION_THROTTLE_TIME)
 6660                .await;
 6661        }
 6662
 6663        Ok(())
 6664    }
 6665
 6666    pub(crate) fn enqueue_item_serialization(
 6667        &mut self,
 6668        item: Box<dyn SerializableItemHandle>,
 6669    ) -> Result<()> {
 6670        self.serializable_items_tx
 6671            .unbounded_send(item)
 6672            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6673    }
 6674
 6675    pub(crate) fn load_workspace(
 6676        serialized_workspace: SerializedWorkspace,
 6677        paths_to_open: Vec<Option<ProjectPath>>,
 6678        window: &mut Window,
 6679        cx: &mut Context<Workspace>,
 6680    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6681        cx.spawn_in(window, async move |workspace, cx| {
 6682            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6683
 6684            let mut center_group = None;
 6685            let mut center_items = None;
 6686
 6687            // Traverse the splits tree and add to things
 6688            if let Some((group, active_pane, items)) = serialized_workspace
 6689                .center_group
 6690                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6691                .await
 6692            {
 6693                center_items = Some(items);
 6694                center_group = Some((group, active_pane))
 6695            }
 6696
 6697            let mut items_by_project_path = HashMap::default();
 6698            let mut item_ids_by_kind = HashMap::default();
 6699            let mut all_deserialized_items = Vec::default();
 6700            cx.update(|_, cx| {
 6701                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6702                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6703                        item_ids_by_kind
 6704                            .entry(serializable_item_handle.serialized_item_kind())
 6705                            .or_insert(Vec::new())
 6706                            .push(item.item_id().as_u64() as ItemId);
 6707                    }
 6708
 6709                    if let Some(project_path) = item.project_path(cx) {
 6710                        items_by_project_path.insert(project_path, item.clone());
 6711                    }
 6712                    all_deserialized_items.push(item);
 6713                }
 6714            })?;
 6715
 6716            let opened_items = paths_to_open
 6717                .into_iter()
 6718                .map(|path_to_open| {
 6719                    path_to_open
 6720                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6721                })
 6722                .collect::<Vec<_>>();
 6723
 6724            // Remove old panes from workspace panes list
 6725            workspace.update_in(cx, |workspace, window, cx| {
 6726                if let Some((center_group, active_pane)) = center_group {
 6727                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6728
 6729                    // Swap workspace center group
 6730                    workspace.center = PaneGroup::with_root(center_group);
 6731                    workspace.center.set_is_center(true);
 6732                    workspace.center.mark_positions(cx);
 6733
 6734                    if let Some(active_pane) = active_pane {
 6735                        workspace.set_active_pane(&active_pane, window, cx);
 6736                        cx.focus_self(window);
 6737                    } else {
 6738                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6739                    }
 6740                }
 6741
 6742                let docks = serialized_workspace.docks;
 6743
 6744                for (dock, serialized_dock) in [
 6745                    (&mut workspace.right_dock, docks.right),
 6746                    (&mut workspace.left_dock, docks.left),
 6747                    (&mut workspace.bottom_dock, docks.bottom),
 6748                ]
 6749                .iter_mut()
 6750                {
 6751                    dock.update(cx, |dock, cx| {
 6752                        dock.serialized_dock = Some(serialized_dock.clone());
 6753                        dock.restore_state(window, cx);
 6754                    });
 6755                }
 6756
 6757                cx.notify();
 6758            })?;
 6759
 6760            let _ = project
 6761                .update(cx, |project, cx| {
 6762                    project
 6763                        .breakpoint_store()
 6764                        .update(cx, |breakpoint_store, cx| {
 6765                            breakpoint_store
 6766                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6767                        })
 6768                })
 6769                .await;
 6770
 6771            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6772            // after loading the items, we might have different items and in order to avoid
 6773            // the database filling up, we delete items that haven't been loaded now.
 6774            //
 6775            // The items that have been loaded, have been saved after they've been added to the workspace.
 6776            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6777                item_ids_by_kind
 6778                    .into_iter()
 6779                    .map(|(item_kind, loaded_items)| {
 6780                        SerializableItemRegistry::cleanup(
 6781                            item_kind,
 6782                            serialized_workspace.id,
 6783                            loaded_items,
 6784                            window,
 6785                            cx,
 6786                        )
 6787                        .log_err()
 6788                    })
 6789                    .collect::<Vec<_>>()
 6790            })?;
 6791
 6792            futures::future::join_all(clean_up_tasks).await;
 6793
 6794            workspace
 6795                .update_in(cx, |workspace, window, cx| {
 6796                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6797                    workspace.serialize_workspace_internal(window, cx).detach();
 6798
 6799                    // Ensure that we mark the window as edited if we did load dirty items
 6800                    workspace.update_window_edited(window, cx);
 6801                })
 6802                .ok();
 6803
 6804            Ok(opened_items)
 6805        })
 6806    }
 6807
 6808    pub fn key_context(&self, cx: &App) -> KeyContext {
 6809        let mut context = KeyContext::new_with_defaults();
 6810        context.add("Workspace");
 6811        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6812        if let Some(status) = self
 6813            .debugger_provider
 6814            .as_ref()
 6815            .and_then(|provider| provider.active_thread_state(cx))
 6816        {
 6817            match status {
 6818                ThreadStatus::Running | ThreadStatus::Stepping => {
 6819                    context.add("debugger_running");
 6820                }
 6821                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6822                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6823            }
 6824        }
 6825
 6826        if self.left_dock.read(cx).is_open() {
 6827            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6828                context.set("left_dock", active_panel.panel_key());
 6829            }
 6830        }
 6831
 6832        if self.right_dock.read(cx).is_open() {
 6833            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6834                context.set("right_dock", active_panel.panel_key());
 6835            }
 6836        }
 6837
 6838        if self.bottom_dock.read(cx).is_open() {
 6839            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6840                context.set("bottom_dock", active_panel.panel_key());
 6841            }
 6842        }
 6843
 6844        context
 6845    }
 6846
 6847    /// Multiworkspace uses this to add workspace action handling to itself
 6848    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6849        self.add_workspace_actions_listeners(div, window, cx)
 6850            .on_action(cx.listener(
 6851                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6852                    for action in &action_sequence.0 {
 6853                        window.dispatch_action(action.boxed_clone(), cx);
 6854                    }
 6855                },
 6856            ))
 6857            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6858            .on_action(cx.listener(Self::close_all_items_and_panes))
 6859            .on_action(cx.listener(Self::close_item_in_all_panes))
 6860            .on_action(cx.listener(Self::save_all))
 6861            .on_action(cx.listener(Self::send_keystrokes))
 6862            .on_action(cx.listener(Self::add_folder_to_project))
 6863            .on_action(cx.listener(Self::follow_next_collaborator))
 6864            .on_action(cx.listener(Self::activate_pane_at_index))
 6865            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6866            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6867            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6868            .on_action(cx.listener(Self::toggle_theme_mode))
 6869            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6870                let pane = workspace.active_pane().clone();
 6871                workspace.unfollow_in_pane(&pane, window, cx);
 6872            }))
 6873            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6874                workspace
 6875                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6876                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6877            }))
 6878            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6879                workspace
 6880                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6881                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6882            }))
 6883            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6884                workspace
 6885                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6886                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6887            }))
 6888            .on_action(
 6889                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6890                    workspace.activate_previous_pane(window, cx)
 6891                }),
 6892            )
 6893            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6894                workspace.activate_next_pane(window, cx)
 6895            }))
 6896            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6897                workspace.activate_last_pane(window, cx)
 6898            }))
 6899            .on_action(
 6900                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6901                    workspace.activate_next_window(cx)
 6902                }),
 6903            )
 6904            .on_action(
 6905                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6906                    workspace.activate_previous_window(cx)
 6907                }),
 6908            )
 6909            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6910                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6911            }))
 6912            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6913                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6914            }))
 6915            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6916                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6917            }))
 6918            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6919                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6920            }))
 6921            .on_action(cx.listener(
 6922                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6923                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6924                },
 6925            ))
 6926            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6927                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6928            }))
 6929            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6930                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6931            }))
 6932            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6933                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6934            }))
 6935            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6936                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6937            }))
 6938            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6939                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6940                    SplitDirection::Down,
 6941                    SplitDirection::Up,
 6942                    SplitDirection::Right,
 6943                    SplitDirection::Left,
 6944                ];
 6945                for dir in DIRECTION_PRIORITY {
 6946                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6947                        workspace.swap_pane_in_direction(dir, cx);
 6948                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6949                        break;
 6950                    }
 6951                }
 6952            }))
 6953            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6954                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6955            }))
 6956            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6957                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6958            }))
 6959            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6960                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6961            }))
 6962            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6963                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6964            }))
 6965            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6966                this.toggle_dock(DockPosition::Left, window, cx);
 6967            }))
 6968            .on_action(cx.listener(
 6969                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6970                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6971                },
 6972            ))
 6973            .on_action(cx.listener(
 6974                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6975                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6976                },
 6977            ))
 6978            .on_action(cx.listener(
 6979                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6980                    if !workspace.close_active_dock(window, cx) {
 6981                        cx.propagate();
 6982                    }
 6983                },
 6984            ))
 6985            .on_action(
 6986                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6987                    workspace.close_all_docks(window, cx);
 6988                }),
 6989            )
 6990            .on_action(cx.listener(Self::toggle_all_docks))
 6991            .on_action(cx.listener(
 6992                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6993                    workspace.clear_all_notifications(cx);
 6994                },
 6995            ))
 6996            .on_action(cx.listener(
 6997                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6998                    workspace.clear_navigation_history(window, cx);
 6999                },
 7000            ))
 7001            .on_action(cx.listener(
 7002                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7003                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7004                        workspace.suppress_notification(&notification_id, cx);
 7005                    }
 7006                },
 7007            ))
 7008            .on_action(cx.listener(
 7009                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7010                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7011                },
 7012            ))
 7013            .on_action(
 7014                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7015                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7016                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7017                            trusted_worktrees.clear_trusted_paths()
 7018                        });
 7019                        let db = WorkspaceDb::global(cx);
 7020                        cx.spawn(async move |_, cx| {
 7021                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7022                                cx.update(|cx| reload(cx));
 7023                            }
 7024                        })
 7025                        .detach();
 7026                    }
 7027                }),
 7028            )
 7029            .on_action(cx.listener(
 7030                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7031                    workspace.reopen_closed_item(window, cx).detach();
 7032                },
 7033            ))
 7034            .on_action(cx.listener(
 7035                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7036                    for dock in workspace.all_docks() {
 7037                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7038                            let panel = dock.read(cx).active_panel().cloned();
 7039                            if let Some(panel) = panel {
 7040                                dock.update(cx, |dock, cx| {
 7041                                    dock.set_panel_size_state(
 7042                                        panel.as_ref(),
 7043                                        dock::PanelSizeState::default(),
 7044                                        cx,
 7045                                    );
 7046                                });
 7047                            }
 7048                            return;
 7049                        }
 7050                    }
 7051                },
 7052            ))
 7053            .on_action(cx.listener(
 7054                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7055                    for dock in workspace.all_docks() {
 7056                        let panel = dock.read(cx).visible_panel().cloned();
 7057                        if let Some(panel) = panel {
 7058                            dock.update(cx, |dock, cx| {
 7059                                dock.set_panel_size_state(
 7060                                    panel.as_ref(),
 7061                                    dock::PanelSizeState::default(),
 7062                                    cx,
 7063                                );
 7064                            });
 7065                        }
 7066                    }
 7067                },
 7068            ))
 7069            .on_action(cx.listener(
 7070                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7071                    adjust_active_dock_size_by_px(
 7072                        px_with_ui_font_fallback(act.px, cx),
 7073                        workspace,
 7074                        window,
 7075                        cx,
 7076                    );
 7077                },
 7078            ))
 7079            .on_action(cx.listener(
 7080                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7081                    adjust_active_dock_size_by_px(
 7082                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7083                        workspace,
 7084                        window,
 7085                        cx,
 7086                    );
 7087                },
 7088            ))
 7089            .on_action(cx.listener(
 7090                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7091                    adjust_open_docks_size_by_px(
 7092                        px_with_ui_font_fallback(act.px, cx),
 7093                        workspace,
 7094                        window,
 7095                        cx,
 7096                    );
 7097                },
 7098            ))
 7099            .on_action(cx.listener(
 7100                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7101                    adjust_open_docks_size_by_px(
 7102                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7103                        workspace,
 7104                        window,
 7105                        cx,
 7106                    );
 7107                },
 7108            ))
 7109            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7110            .on_action(cx.listener(
 7111                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7112                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7113                        let dock = active_dock.read(cx);
 7114                        if let Some(active_panel) = dock.active_panel() {
 7115                            if active_panel.pane(cx).is_none() {
 7116                                let mut recent_pane: Option<Entity<Pane>> = None;
 7117                                let mut recent_timestamp = 0;
 7118                                for pane_handle in workspace.panes() {
 7119                                    let pane = pane_handle.read(cx);
 7120                                    for entry in pane.activation_history() {
 7121                                        if entry.timestamp > recent_timestamp {
 7122                                            recent_timestamp = entry.timestamp;
 7123                                            recent_pane = Some(pane_handle.clone());
 7124                                        }
 7125                                    }
 7126                                }
 7127
 7128                                if let Some(pane) = recent_pane {
 7129                                    let wrap_around = action.wrap_around;
 7130                                    pane.update(cx, |pane, cx| {
 7131                                        let current_index = pane.active_item_index();
 7132                                        let items_len = pane.items_len();
 7133                                        if items_len > 0 {
 7134                                            let next_index = if current_index + 1 < items_len {
 7135                                                current_index + 1
 7136                                            } else if wrap_around {
 7137                                                0
 7138                                            } else {
 7139                                                return;
 7140                                            };
 7141                                            pane.activate_item(
 7142                                                next_index, false, false, window, cx,
 7143                                            );
 7144                                        }
 7145                                    });
 7146                                    return;
 7147                                }
 7148                            }
 7149                        }
 7150                    }
 7151                    cx.propagate();
 7152                },
 7153            ))
 7154            .on_action(cx.listener(
 7155                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7156                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7157                        let dock = active_dock.read(cx);
 7158                        if let Some(active_panel) = dock.active_panel() {
 7159                            if active_panel.pane(cx).is_none() {
 7160                                let mut recent_pane: Option<Entity<Pane>> = None;
 7161                                let mut recent_timestamp = 0;
 7162                                for pane_handle in workspace.panes() {
 7163                                    let pane = pane_handle.read(cx);
 7164                                    for entry in pane.activation_history() {
 7165                                        if entry.timestamp > recent_timestamp {
 7166                                            recent_timestamp = entry.timestamp;
 7167                                            recent_pane = Some(pane_handle.clone());
 7168                                        }
 7169                                    }
 7170                                }
 7171
 7172                                if let Some(pane) = recent_pane {
 7173                                    let wrap_around = action.wrap_around;
 7174                                    pane.update(cx, |pane, cx| {
 7175                                        let current_index = pane.active_item_index();
 7176                                        let items_len = pane.items_len();
 7177                                        if items_len > 0 {
 7178                                            let prev_index = if current_index > 0 {
 7179                                                current_index - 1
 7180                                            } else if wrap_around {
 7181                                                items_len.saturating_sub(1)
 7182                                            } else {
 7183                                                return;
 7184                                            };
 7185                                            pane.activate_item(
 7186                                                prev_index, false, false, window, cx,
 7187                                            );
 7188                                        }
 7189                                    });
 7190                                    return;
 7191                                }
 7192                            }
 7193                        }
 7194                    }
 7195                    cx.propagate();
 7196                },
 7197            ))
 7198            .on_action(cx.listener(
 7199                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7200                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7201                        let dock = active_dock.read(cx);
 7202                        if let Some(active_panel) = dock.active_panel() {
 7203                            if active_panel.pane(cx).is_none() {
 7204                                let active_pane = workspace.active_pane().clone();
 7205                                active_pane.update(cx, |pane, cx| {
 7206                                    pane.close_active_item(action, window, cx)
 7207                                        .detach_and_log_err(cx);
 7208                                });
 7209                                return;
 7210                            }
 7211                        }
 7212                    }
 7213                    cx.propagate();
 7214                },
 7215            ))
 7216            .on_action(
 7217                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7218                    let pane = workspace.active_pane().clone();
 7219                    if let Some(item) = pane.read(cx).active_item() {
 7220                        item.toggle_read_only(window, cx);
 7221                    }
 7222                }),
 7223            )
 7224            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7225                workspace.focus_center_pane(window, cx);
 7226            }))
 7227            .on_action(cx.listener(Workspace::cancel))
 7228    }
 7229
 7230    #[cfg(any(test, feature = "test-support"))]
 7231    pub fn set_random_database_id(&mut self) {
 7232        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7233    }
 7234
 7235    #[cfg(any(test, feature = "test-support"))]
 7236    pub(crate) fn test_new(
 7237        project: Entity<Project>,
 7238        window: &mut Window,
 7239        cx: &mut Context<Self>,
 7240    ) -> Self {
 7241        use node_runtime::NodeRuntime;
 7242        use session::Session;
 7243
 7244        let client = project.read(cx).client();
 7245        let user_store = project.read(cx).user_store();
 7246        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7247        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7248        window.activate_window();
 7249        let app_state = Arc::new(AppState {
 7250            languages: project.read(cx).languages().clone(),
 7251            workspace_store,
 7252            client,
 7253            user_store,
 7254            fs: project.read(cx).fs().clone(),
 7255            build_window_options: |_, _| Default::default(),
 7256            node_runtime: NodeRuntime::unavailable(),
 7257            session,
 7258        });
 7259        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7260        workspace
 7261            .active_pane
 7262            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7263        workspace
 7264    }
 7265
 7266    pub fn register_action<A: Action>(
 7267        &mut self,
 7268        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7269    ) -> &mut Self {
 7270        let callback = Arc::new(callback);
 7271
 7272        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7273            let callback = callback.clone();
 7274            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7275                (callback)(workspace, event, window, cx)
 7276            }))
 7277        }));
 7278        self
 7279    }
 7280    pub fn register_action_renderer(
 7281        &mut self,
 7282        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7283    ) -> &mut Self {
 7284        self.workspace_actions.push(Box::new(callback));
 7285        self
 7286    }
 7287
 7288    fn add_workspace_actions_listeners(
 7289        &self,
 7290        mut div: Div,
 7291        window: &mut Window,
 7292        cx: &mut Context<Self>,
 7293    ) -> Div {
 7294        for action in self.workspace_actions.iter() {
 7295            div = (action)(div, self, window, cx)
 7296        }
 7297        div
 7298    }
 7299
 7300    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7301        self.modal_layer.read(cx).has_active_modal()
 7302    }
 7303
 7304    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7305        self.modal_layer
 7306            .read(cx)
 7307            .is_active_modal_command_palette(cx)
 7308    }
 7309
 7310    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7311        self.modal_layer.read(cx).active_modal()
 7312    }
 7313
 7314    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7315    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7316    /// If no modal is active, the new modal will be shown.
 7317    ///
 7318    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7319    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7320    /// will not be shown.
 7321    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7322    where
 7323        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7324    {
 7325        self.modal_layer.update(cx, |modal_layer, cx| {
 7326            modal_layer.toggle_modal(window, cx, build)
 7327        })
 7328    }
 7329
 7330    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7331        self.modal_layer
 7332            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7333    }
 7334
 7335    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7336        self.toast_layer
 7337            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7338    }
 7339
 7340    pub fn toggle_centered_layout(
 7341        &mut self,
 7342        _: &ToggleCenteredLayout,
 7343        _: &mut Window,
 7344        cx: &mut Context<Self>,
 7345    ) {
 7346        self.centered_layout = !self.centered_layout;
 7347        if let Some(database_id) = self.database_id() {
 7348            let db = WorkspaceDb::global(cx);
 7349            let centered_layout = self.centered_layout;
 7350            cx.background_spawn(async move {
 7351                db.set_centered_layout(database_id, centered_layout).await
 7352            })
 7353            .detach_and_log_err(cx);
 7354        }
 7355        cx.notify();
 7356    }
 7357
 7358    fn adjust_padding(padding: Option<f32>) -> f32 {
 7359        padding
 7360            .unwrap_or(CenteredPaddingSettings::default().0)
 7361            .clamp(
 7362                CenteredPaddingSettings::MIN_PADDING,
 7363                CenteredPaddingSettings::MAX_PADDING,
 7364            )
 7365    }
 7366
 7367    fn render_dock(
 7368        &self,
 7369        position: DockPosition,
 7370        dock: &Entity<Dock>,
 7371        window: &mut Window,
 7372        cx: &mut App,
 7373    ) -> Option<Div> {
 7374        if self.zoomed_position == Some(position) {
 7375            return None;
 7376        }
 7377
 7378        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7379            let pane = panel.pane(cx)?;
 7380            let follower_states = &self.follower_states;
 7381            leader_border_for_pane(follower_states, &pane, window, cx)
 7382        });
 7383
 7384        let mut container = div()
 7385            .flex()
 7386            .overflow_hidden()
 7387            .flex_none()
 7388            .child(dock.clone())
 7389            .children(leader_border);
 7390
 7391        // Apply sizing only when the dock is open. When closed the dock is still
 7392        // included in the element tree so its focus handle remains mounted — without
 7393        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7394        let dock = dock.read(cx);
 7395        if let Some(panel) = dock.visible_panel() {
 7396            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7397            if position.axis() == Axis::Horizontal {
 7398                let use_flexible = panel.has_flexible_size(window, cx);
 7399                let flex_grow = if use_flexible {
 7400                    size_state
 7401                        .and_then(|state| state.flex)
 7402                        .or_else(|| self.default_dock_flex(position))
 7403                } else {
 7404                    None
 7405                };
 7406                if let Some(grow) = flex_grow {
 7407                    let grow = grow.max(0.001);
 7408                    let style = container.style();
 7409                    style.flex_grow = Some(grow);
 7410                    style.flex_shrink = Some(1.0);
 7411                    style.flex_basis = Some(relative(0.).into());
 7412                } else {
 7413                    let size = size_state
 7414                        .and_then(|state| state.size)
 7415                        .unwrap_or_else(|| panel.default_size(window, cx));
 7416                    container = container.w(size);
 7417                }
 7418            } else {
 7419                let size = size_state
 7420                    .and_then(|state| state.size)
 7421                    .unwrap_or_else(|| panel.default_size(window, cx));
 7422                container = container.h(size);
 7423            }
 7424        }
 7425
 7426        Some(container)
 7427    }
 7428
 7429    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7430        window
 7431            .root::<MultiWorkspace>()
 7432            .flatten()
 7433            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7434    }
 7435
 7436    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7437        self.zoomed.as_ref()
 7438    }
 7439
 7440    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7441        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7442            return;
 7443        };
 7444        let windows = cx.windows();
 7445        let next_window =
 7446            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7447                || {
 7448                    windows
 7449                        .iter()
 7450                        .cycle()
 7451                        .skip_while(|window| window.window_id() != current_window_id)
 7452                        .nth(1)
 7453                },
 7454            );
 7455
 7456        if let Some(window) = next_window {
 7457            window
 7458                .update(cx, |_, window, _| window.activate_window())
 7459                .ok();
 7460        }
 7461    }
 7462
 7463    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7464        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7465            return;
 7466        };
 7467        let windows = cx.windows();
 7468        let prev_window =
 7469            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7470                || {
 7471                    windows
 7472                        .iter()
 7473                        .rev()
 7474                        .cycle()
 7475                        .skip_while(|window| window.window_id() != current_window_id)
 7476                        .nth(1)
 7477                },
 7478            );
 7479
 7480        if let Some(window) = prev_window {
 7481            window
 7482                .update(cx, |_, window, _| window.activate_window())
 7483                .ok();
 7484        }
 7485    }
 7486
 7487    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7488        if cx.stop_active_drag(window) {
 7489        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7490            dismiss_app_notification(&notification_id, cx);
 7491        } else {
 7492            cx.propagate();
 7493        }
 7494    }
 7495
 7496    fn resize_dock(
 7497        &mut self,
 7498        dock_pos: DockPosition,
 7499        new_size: Pixels,
 7500        window: &mut Window,
 7501        cx: &mut Context<Self>,
 7502    ) {
 7503        match dock_pos {
 7504            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7505            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7506            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7507        }
 7508    }
 7509
 7510    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7511        let workspace_width = self.bounds.size.width;
 7512        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7513
 7514        self.right_dock.read_with(cx, |right_dock, cx| {
 7515            let right_dock_size = right_dock
 7516                .stored_active_panel_size(window, cx)
 7517                .unwrap_or(Pixels::ZERO);
 7518            if right_dock_size + size > workspace_width {
 7519                size = workspace_width - right_dock_size
 7520            }
 7521        });
 7522
 7523        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7524        self.left_dock.update(cx, |left_dock, cx| {
 7525            if WorkspaceSettings::get_global(cx)
 7526                .resize_all_panels_in_dock
 7527                .contains(&DockPosition::Left)
 7528            {
 7529                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7530            } else {
 7531                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7532            }
 7533        });
 7534    }
 7535
 7536    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7537        let workspace_width = self.bounds.size.width;
 7538        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7539        self.left_dock.read_with(cx, |left_dock, cx| {
 7540            let left_dock_size = left_dock
 7541                .stored_active_panel_size(window, cx)
 7542                .unwrap_or(Pixels::ZERO);
 7543            if left_dock_size + size > workspace_width {
 7544                size = workspace_width - left_dock_size
 7545            }
 7546        });
 7547        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7548        self.right_dock.update(cx, |right_dock, cx| {
 7549            if WorkspaceSettings::get_global(cx)
 7550                .resize_all_panels_in_dock
 7551                .contains(&DockPosition::Right)
 7552            {
 7553                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7554            } else {
 7555                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7556            }
 7557        });
 7558    }
 7559
 7560    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7561        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7562        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7563            if WorkspaceSettings::get_global(cx)
 7564                .resize_all_panels_in_dock
 7565                .contains(&DockPosition::Bottom)
 7566            {
 7567                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7568            } else {
 7569                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7570            }
 7571        });
 7572    }
 7573
 7574    fn toggle_edit_predictions_all_files(
 7575        &mut self,
 7576        _: &ToggleEditPrediction,
 7577        _window: &mut Window,
 7578        cx: &mut Context<Self>,
 7579    ) {
 7580        let fs = self.project().read(cx).fs().clone();
 7581        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7582        update_settings_file(fs, cx, move |file, _| {
 7583            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7584        });
 7585    }
 7586
 7587    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7588        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7589        let next_mode = match current_mode {
 7590            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7591                theme_settings::ThemeAppearanceMode::Dark
 7592            }
 7593            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7594                theme_settings::ThemeAppearanceMode::Light
 7595            }
 7596            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7597                match cx.theme().appearance() {
 7598                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7599                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7600                }
 7601            }
 7602        };
 7603
 7604        let fs = self.project().read(cx).fs().clone();
 7605        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7606            theme_settings::set_mode(settings, next_mode);
 7607        });
 7608    }
 7609
 7610    pub fn show_worktree_trust_security_modal(
 7611        &mut self,
 7612        toggle: bool,
 7613        window: &mut Window,
 7614        cx: &mut Context<Self>,
 7615    ) {
 7616        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7617            if toggle {
 7618                security_modal.update(cx, |security_modal, cx| {
 7619                    security_modal.dismiss(cx);
 7620                })
 7621            } else {
 7622                security_modal.update(cx, |security_modal, cx| {
 7623                    security_modal.refresh_restricted_paths(cx);
 7624                });
 7625            }
 7626        } else {
 7627            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7628                .map(|trusted_worktrees| {
 7629                    trusted_worktrees
 7630                        .read(cx)
 7631                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7632                })
 7633                .unwrap_or(false);
 7634            if has_restricted_worktrees {
 7635                let project = self.project().read(cx);
 7636                let remote_host = project
 7637                    .remote_connection_options(cx)
 7638                    .map(RemoteHostLocation::from);
 7639                let worktree_store = project.worktree_store().downgrade();
 7640                self.toggle_modal(window, cx, |_, cx| {
 7641                    SecurityModal::new(worktree_store, remote_host, cx)
 7642                });
 7643            }
 7644        }
 7645    }
 7646}
 7647
 7648pub trait AnyActiveCall {
 7649    fn entity(&self) -> AnyEntity;
 7650    fn is_in_room(&self, _: &App) -> bool;
 7651    fn room_id(&self, _: &App) -> Option<u64>;
 7652    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7653    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7654    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7655    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7656    fn is_sharing_project(&self, _: &App) -> bool;
 7657    fn has_remote_participants(&self, _: &App) -> bool;
 7658    fn local_participant_is_guest(&self, _: &App) -> bool;
 7659    fn client(&self, _: &App) -> Arc<Client>;
 7660    fn share_on_join(&self, _: &App) -> bool;
 7661    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7662    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7663    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7664    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7665    fn join_project(
 7666        &self,
 7667        _: u64,
 7668        _: Arc<LanguageRegistry>,
 7669        _: Arc<dyn Fs>,
 7670        _: &mut App,
 7671    ) -> Task<Result<Entity<Project>>>;
 7672    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7673    fn subscribe(
 7674        &self,
 7675        _: &mut Window,
 7676        _: &mut Context<Workspace>,
 7677        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7678    ) -> Subscription;
 7679    fn create_shared_screen(
 7680        &self,
 7681        _: PeerId,
 7682        _: &Entity<Pane>,
 7683        _: &mut Window,
 7684        _: &mut App,
 7685    ) -> Option<Entity<SharedScreen>>;
 7686}
 7687
 7688#[derive(Clone)]
 7689pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7690impl Global for GlobalAnyActiveCall {}
 7691
 7692impl GlobalAnyActiveCall {
 7693    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7694        cx.try_global()
 7695    }
 7696
 7697    pub(crate) fn global(cx: &App) -> &Self {
 7698        cx.global()
 7699    }
 7700}
 7701
 7702pub fn merge_conflict_notification_id() -> NotificationId {
 7703    struct MergeConflictNotification;
 7704    NotificationId::unique::<MergeConflictNotification>()
 7705}
 7706
 7707/// Workspace-local view of a remote participant's location.
 7708#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7709pub enum ParticipantLocation {
 7710    SharedProject { project_id: u64 },
 7711    UnsharedProject,
 7712    External,
 7713}
 7714
 7715impl ParticipantLocation {
 7716    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7717        match location
 7718            .and_then(|l| l.variant)
 7719            .context("participant location was not provided")?
 7720        {
 7721            proto::participant_location::Variant::SharedProject(project) => {
 7722                Ok(Self::SharedProject {
 7723                    project_id: project.id,
 7724                })
 7725            }
 7726            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7727            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7728        }
 7729    }
 7730}
 7731/// Workspace-local view of a remote collaborator's state.
 7732/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7733#[derive(Clone)]
 7734pub struct RemoteCollaborator {
 7735    pub user: Arc<User>,
 7736    pub peer_id: PeerId,
 7737    pub location: ParticipantLocation,
 7738    pub participant_index: ParticipantIndex,
 7739}
 7740
 7741pub enum ActiveCallEvent {
 7742    ParticipantLocationChanged { participant_id: PeerId },
 7743    RemoteVideoTracksChanged { participant_id: PeerId },
 7744}
 7745
 7746fn leader_border_for_pane(
 7747    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7748    pane: &Entity<Pane>,
 7749    _: &Window,
 7750    cx: &App,
 7751) -> Option<Div> {
 7752    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7753        if state.pane() == pane {
 7754            Some((*leader_id, state))
 7755        } else {
 7756            None
 7757        }
 7758    })?;
 7759
 7760    let mut leader_color = match leader_id {
 7761        CollaboratorId::PeerId(leader_peer_id) => {
 7762            let leader = GlobalAnyActiveCall::try_global(cx)?
 7763                .0
 7764                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7765
 7766            cx.theme()
 7767                .players()
 7768                .color_for_participant(leader.participant_index.0)
 7769                .cursor
 7770        }
 7771        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7772    };
 7773    leader_color.fade_out(0.3);
 7774    Some(
 7775        div()
 7776            .absolute()
 7777            .size_full()
 7778            .left_0()
 7779            .top_0()
 7780            .border_2()
 7781            .border_color(leader_color),
 7782    )
 7783}
 7784
 7785fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7786    ZED_WINDOW_POSITION
 7787        .zip(*ZED_WINDOW_SIZE)
 7788        .map(|(position, size)| Bounds {
 7789            origin: position,
 7790            size,
 7791        })
 7792}
 7793
 7794fn open_items(
 7795    serialized_workspace: Option<SerializedWorkspace>,
 7796    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7797    window: &mut Window,
 7798    cx: &mut Context<Workspace>,
 7799) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7800    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7801        Workspace::load_workspace(
 7802            serialized_workspace,
 7803            project_paths_to_open
 7804                .iter()
 7805                .map(|(_, project_path)| project_path)
 7806                .cloned()
 7807                .collect(),
 7808            window,
 7809            cx,
 7810        )
 7811    });
 7812
 7813    cx.spawn_in(window, async move |workspace, cx| {
 7814        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7815
 7816        if let Some(restored_items) = restored_items {
 7817            let restored_items = restored_items.await?;
 7818
 7819            let restored_project_paths = restored_items
 7820                .iter()
 7821                .filter_map(|item| {
 7822                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7823                        .ok()
 7824                        .flatten()
 7825                })
 7826                .collect::<HashSet<_>>();
 7827
 7828            for restored_item in restored_items {
 7829                opened_items.push(restored_item.map(Ok));
 7830            }
 7831
 7832            project_paths_to_open
 7833                .iter_mut()
 7834                .for_each(|(_, project_path)| {
 7835                    if let Some(project_path_to_open) = project_path
 7836                        && restored_project_paths.contains(project_path_to_open)
 7837                    {
 7838                        *project_path = None;
 7839                    }
 7840                });
 7841        } else {
 7842            for _ in 0..project_paths_to_open.len() {
 7843                opened_items.push(None);
 7844            }
 7845        }
 7846        assert!(opened_items.len() == project_paths_to_open.len());
 7847
 7848        let tasks =
 7849            project_paths_to_open
 7850                .into_iter()
 7851                .enumerate()
 7852                .map(|(ix, (abs_path, project_path))| {
 7853                    let workspace = workspace.clone();
 7854                    cx.spawn(async move |cx| {
 7855                        let file_project_path = project_path?;
 7856                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7857                            workspace.project().update(cx, |project, cx| {
 7858                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7859                            })
 7860                        });
 7861
 7862                        // We only want to open file paths here. If one of the items
 7863                        // here is a directory, it was already opened further above
 7864                        // with a `find_or_create_worktree`.
 7865                        if let Ok(task) = abs_path_task
 7866                            && task.await.is_none_or(|p| p.is_file())
 7867                        {
 7868                            return Some((
 7869                                ix,
 7870                                workspace
 7871                                    .update_in(cx, |workspace, window, cx| {
 7872                                        workspace.open_path(
 7873                                            file_project_path,
 7874                                            None,
 7875                                            true,
 7876                                            window,
 7877                                            cx,
 7878                                        )
 7879                                    })
 7880                                    .log_err()?
 7881                                    .await,
 7882                            ));
 7883                        }
 7884                        None
 7885                    })
 7886                });
 7887
 7888        let tasks = tasks.collect::<Vec<_>>();
 7889
 7890        let tasks = futures::future::join_all(tasks);
 7891        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7892            opened_items[ix] = Some(path_open_result);
 7893        }
 7894
 7895        Ok(opened_items)
 7896    })
 7897}
 7898
 7899#[derive(Clone)]
 7900enum ActivateInDirectionTarget {
 7901    Pane(Entity<Pane>),
 7902    Dock(Entity<Dock>),
 7903    Sidebar(FocusHandle),
 7904}
 7905
 7906fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7907    window
 7908        .update(cx, |multi_workspace, _, cx| {
 7909            let workspace = multi_workspace.workspace().clone();
 7910            workspace.update(cx, |workspace, cx| {
 7911                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7912                    struct DatabaseFailedNotification;
 7913
 7914                    workspace.show_notification(
 7915                        NotificationId::unique::<DatabaseFailedNotification>(),
 7916                        cx,
 7917                        |cx| {
 7918                            cx.new(|cx| {
 7919                                MessageNotification::new("Failed to load the database file.", cx)
 7920                                    .primary_message("File an Issue")
 7921                                    .primary_icon(IconName::Plus)
 7922                                    .primary_on_click(|window, cx| {
 7923                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7924                                    })
 7925                            })
 7926                        },
 7927                    );
 7928                }
 7929            });
 7930        })
 7931        .log_err();
 7932}
 7933
 7934fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7935    if val == 0 {
 7936        ThemeSettings::get_global(cx).ui_font_size(cx)
 7937    } else {
 7938        px(val as f32)
 7939    }
 7940}
 7941
 7942fn adjust_active_dock_size_by_px(
 7943    px: Pixels,
 7944    workspace: &mut Workspace,
 7945    window: &mut Window,
 7946    cx: &mut Context<Workspace>,
 7947) {
 7948    let Some(active_dock) = workspace
 7949        .all_docks()
 7950        .into_iter()
 7951        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7952    else {
 7953        return;
 7954    };
 7955    let dock = active_dock.read(cx);
 7956    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7957        return;
 7958    };
 7959    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7960}
 7961
 7962fn adjust_open_docks_size_by_px(
 7963    px: Pixels,
 7964    workspace: &mut Workspace,
 7965    window: &mut Window,
 7966    cx: &mut Context<Workspace>,
 7967) {
 7968    let docks = workspace
 7969        .all_docks()
 7970        .into_iter()
 7971        .filter_map(|dock_entity| {
 7972            let dock = dock_entity.read(cx);
 7973            if dock.is_open() {
 7974                let dock_pos = dock.position();
 7975                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7976                Some((dock_pos, panel_size + px))
 7977            } else {
 7978                None
 7979            }
 7980        })
 7981        .collect::<Vec<_>>();
 7982
 7983    for (position, new_size) in docks {
 7984        workspace.resize_dock(position, new_size, window, cx);
 7985    }
 7986}
 7987
 7988impl Focusable for Workspace {
 7989    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7990        self.active_pane.focus_handle(cx)
 7991    }
 7992}
 7993
 7994#[derive(Clone)]
 7995struct DraggedDock(DockPosition);
 7996
 7997impl Render for DraggedDock {
 7998    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7999        gpui::Empty
 8000    }
 8001}
 8002
 8003impl Render for Workspace {
 8004    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8005        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8006        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8007            log::info!("Rendered first frame");
 8008        }
 8009
 8010        let centered_layout = self.centered_layout
 8011            && self.center.panes().len() == 1
 8012            && self.active_item(cx).is_some();
 8013        let render_padding = |size| {
 8014            (size > 0.0).then(|| {
 8015                div()
 8016                    .h_full()
 8017                    .w(relative(size))
 8018                    .bg(cx.theme().colors().editor_background)
 8019                    .border_color(cx.theme().colors().pane_group_border)
 8020            })
 8021        };
 8022        let paddings = if centered_layout {
 8023            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8024            (
 8025                render_padding(Self::adjust_padding(
 8026                    settings.left_padding.map(|padding| padding.0),
 8027                )),
 8028                render_padding(Self::adjust_padding(
 8029                    settings.right_padding.map(|padding| padding.0),
 8030                )),
 8031            )
 8032        } else {
 8033            (None, None)
 8034        };
 8035        let ui_font = theme_settings::setup_ui_font(window, cx);
 8036
 8037        let theme = cx.theme().clone();
 8038        let colors = theme.colors();
 8039        let notification_entities = self
 8040            .notifications
 8041            .iter()
 8042            .map(|(_, notification)| notification.entity_id())
 8043            .collect::<Vec<_>>();
 8044        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8045
 8046        div()
 8047            .relative()
 8048            .size_full()
 8049            .flex()
 8050            .flex_col()
 8051            .font(ui_font)
 8052            .gap_0()
 8053                .justify_start()
 8054                .items_start()
 8055                .text_color(colors.text)
 8056                .overflow_hidden()
 8057                .children(self.titlebar_item.clone())
 8058                .on_modifiers_changed(move |_, _, cx| {
 8059                    for &id in &notification_entities {
 8060                        cx.notify(id);
 8061                    }
 8062                })
 8063                .child(
 8064                    div()
 8065                        .size_full()
 8066                        .relative()
 8067                        .flex_1()
 8068                        .flex()
 8069                        .flex_col()
 8070                        .child(
 8071                            div()
 8072                                .id("workspace")
 8073                                .bg(colors.background)
 8074                                .relative()
 8075                                .flex_1()
 8076                                .w_full()
 8077                                .flex()
 8078                                .flex_col()
 8079                                .overflow_hidden()
 8080                                .border_t_1()
 8081                                .border_b_1()
 8082                                .border_color(colors.border)
 8083                                .child({
 8084                                    let this = cx.entity();
 8085                                    canvas(
 8086                                        move |bounds, window, cx| {
 8087                                            this.update(cx, |this, cx| {
 8088                                                let bounds_changed = this.bounds != bounds;
 8089                                                this.bounds = bounds;
 8090
 8091                                                if bounds_changed {
 8092                                                    this.left_dock.update(cx, |dock, cx| {
 8093                                                        dock.clamp_panel_size(
 8094                                                            bounds.size.width,
 8095                                                            window,
 8096                                                            cx,
 8097                                                        )
 8098                                                    });
 8099
 8100                                                    this.right_dock.update(cx, |dock, cx| {
 8101                                                        dock.clamp_panel_size(
 8102                                                            bounds.size.width,
 8103                                                            window,
 8104                                                            cx,
 8105                                                        )
 8106                                                    });
 8107
 8108                                                    this.bottom_dock.update(cx, |dock, cx| {
 8109                                                        dock.clamp_panel_size(
 8110                                                            bounds.size.height,
 8111                                                            window,
 8112                                                            cx,
 8113                                                        )
 8114                                                    });
 8115                                                }
 8116                                            })
 8117                                        },
 8118                                        |_, _, _, _| {},
 8119                                    )
 8120                                    .absolute()
 8121                                    .size_full()
 8122                                })
 8123                                .when(self.zoomed.is_none(), |this| {
 8124                                    this.on_drag_move(cx.listener(
 8125                                        move |workspace,
 8126                                              e: &DragMoveEvent<DraggedDock>,
 8127                                              window,
 8128                                              cx| {
 8129                                            if workspace.previous_dock_drag_coordinates
 8130                                                != Some(e.event.position)
 8131                                            {
 8132                                                workspace.previous_dock_drag_coordinates =
 8133                                                    Some(e.event.position);
 8134
 8135                                                match e.drag(cx).0 {
 8136                                                    DockPosition::Left => {
 8137                                                        workspace.resize_left_dock(
 8138                                                            e.event.position.x
 8139                                                                - workspace.bounds.left(),
 8140                                                            window,
 8141                                                            cx,
 8142                                                        );
 8143                                                    }
 8144                                                    DockPosition::Right => {
 8145                                                        workspace.resize_right_dock(
 8146                                                            workspace.bounds.right()
 8147                                                                - e.event.position.x,
 8148                                                            window,
 8149                                                            cx,
 8150                                                        );
 8151                                                    }
 8152                                                    DockPosition::Bottom => {
 8153                                                        workspace.resize_bottom_dock(
 8154                                                            workspace.bounds.bottom()
 8155                                                                - e.event.position.y,
 8156                                                            window,
 8157                                                            cx,
 8158                                                        );
 8159                                                    }
 8160                                                };
 8161                                                workspace.serialize_workspace(window, cx);
 8162                                            }
 8163                                        },
 8164                                    ))
 8165
 8166                                })
 8167                                .child({
 8168                                    match bottom_dock_layout {
 8169                                        BottomDockLayout::Full => div()
 8170                                            .flex()
 8171                                            .flex_col()
 8172                                            .h_full()
 8173                                            .child(
 8174                                                div()
 8175                                                    .flex()
 8176                                                    .flex_row()
 8177                                                    .flex_1()
 8178                                                    .overflow_hidden()
 8179                                                    .children(self.render_dock(
 8180                                                        DockPosition::Left,
 8181                                                        &self.left_dock,
 8182                                                        window,
 8183                                                        cx,
 8184                                                    ))
 8185
 8186                                                    .child(
 8187                                                        div()
 8188                                                            .flex()
 8189                                                            .flex_col()
 8190                                                            .flex_1()
 8191                                                            .overflow_hidden()
 8192                                                            .child(
 8193                                                                h_flex()
 8194                                                                    .flex_1()
 8195                                                                    .when_some(
 8196                                                                        paddings.0,
 8197                                                                        |this, p| {
 8198                                                                            this.child(
 8199                                                                                p.border_r_1(),
 8200                                                                            )
 8201                                                                        },
 8202                                                                    )
 8203                                                                    .child(self.center.render(
 8204                                                                        self.zoomed.as_ref(),
 8205                                                                        &PaneRenderContext {
 8206                                                                            follower_states:
 8207                                                                                &self.follower_states,
 8208                                                                            active_call: self.active_call(),
 8209                                                                            active_pane: &self.active_pane,
 8210                                                                            app_state: &self.app_state,
 8211                                                                            project: &self.project,
 8212                                                                            workspace: &self.weak_self,
 8213                                                                        },
 8214                                                                        window,
 8215                                                                        cx,
 8216                                                                    ))
 8217                                                                    .when_some(
 8218                                                                        paddings.1,
 8219                                                                        |this, p| {
 8220                                                                            this.child(
 8221                                                                                p.border_l_1(),
 8222                                                                            )
 8223                                                                        },
 8224                                                                    ),
 8225                                                            ),
 8226                                                    )
 8227
 8228                                                    .children(self.render_dock(
 8229                                                        DockPosition::Right,
 8230                                                        &self.right_dock,
 8231                                                        window,
 8232                                                        cx,
 8233                                                    )),
 8234                                            )
 8235                                            .child(div().w_full().children(self.render_dock(
 8236                                                DockPosition::Bottom,
 8237                                                &self.bottom_dock,
 8238                                                window,
 8239                                                cx
 8240                                            ))),
 8241
 8242                                        BottomDockLayout::LeftAligned => div()
 8243                                            .flex()
 8244                                            .flex_row()
 8245                                            .h_full()
 8246                                            .child(
 8247                                                div()
 8248                                                    .flex()
 8249                                                    .flex_col()
 8250                                                    .flex_1()
 8251                                                    .h_full()
 8252                                                    .child(
 8253                                                        div()
 8254                                                            .flex()
 8255                                                            .flex_row()
 8256                                                            .flex_1()
 8257                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8258
 8259                                                            .child(
 8260                                                                div()
 8261                                                                    .flex()
 8262                                                                    .flex_col()
 8263                                                                    .flex_1()
 8264                                                                    .overflow_hidden()
 8265                                                                    .child(
 8266                                                                        h_flex()
 8267                                                                            .flex_1()
 8268                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8269                                                                            .child(self.center.render(
 8270                                                                                self.zoomed.as_ref(),
 8271                                                                                &PaneRenderContext {
 8272                                                                                    follower_states:
 8273                                                                                        &self.follower_states,
 8274                                                                                    active_call: self.active_call(),
 8275                                                                                    active_pane: &self.active_pane,
 8276                                                                                    app_state: &self.app_state,
 8277                                                                                    project: &self.project,
 8278                                                                                    workspace: &self.weak_self,
 8279                                                                                },
 8280                                                                                window,
 8281                                                                                cx,
 8282                                                                            ))
 8283                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8284                                                                    )
 8285                                                            )
 8286
 8287                                                    )
 8288                                                    .child(
 8289                                                        div()
 8290                                                            .w_full()
 8291                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8292                                                    ),
 8293                                            )
 8294                                            .children(self.render_dock(
 8295                                                DockPosition::Right,
 8296                                                &self.right_dock,
 8297                                                window,
 8298                                                cx,
 8299                                            )),
 8300                                        BottomDockLayout::RightAligned => div()
 8301                                            .flex()
 8302                                            .flex_row()
 8303                                            .h_full()
 8304                                            .children(self.render_dock(
 8305                                                DockPosition::Left,
 8306                                                &self.left_dock,
 8307                                                window,
 8308                                                cx,
 8309                                            ))
 8310
 8311                                            .child(
 8312                                                div()
 8313                                                    .flex()
 8314                                                    .flex_col()
 8315                                                    .flex_1()
 8316                                                    .h_full()
 8317                                                    .child(
 8318                                                        div()
 8319                                                            .flex()
 8320                                                            .flex_row()
 8321                                                            .flex_1()
 8322                                                            .child(
 8323                                                                div()
 8324                                                                    .flex()
 8325                                                                    .flex_col()
 8326                                                                    .flex_1()
 8327                                                                    .overflow_hidden()
 8328                                                                    .child(
 8329                                                                        h_flex()
 8330                                                                            .flex_1()
 8331                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8332                                                                            .child(self.center.render(
 8333                                                                                self.zoomed.as_ref(),
 8334                                                                                &PaneRenderContext {
 8335                                                                                    follower_states:
 8336                                                                                        &self.follower_states,
 8337                                                                                    active_call: self.active_call(),
 8338                                                                                    active_pane: &self.active_pane,
 8339                                                                                    app_state: &self.app_state,
 8340                                                                                    project: &self.project,
 8341                                                                                    workspace: &self.weak_self,
 8342                                                                                },
 8343                                                                                window,
 8344                                                                                cx,
 8345                                                                            ))
 8346                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8347                                                                    )
 8348                                                            )
 8349
 8350                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8351                                                    )
 8352                                                    .child(
 8353                                                        div()
 8354                                                            .w_full()
 8355                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8356                                                    ),
 8357                                            ),
 8358                                        BottomDockLayout::Contained => div()
 8359                                            .flex()
 8360                                            .flex_row()
 8361                                            .h_full()
 8362                                            .children(self.render_dock(
 8363                                                DockPosition::Left,
 8364                                                &self.left_dock,
 8365                                                window,
 8366                                                cx,
 8367                                            ))
 8368
 8369                                            .child(
 8370                                                div()
 8371                                                    .flex()
 8372                                                    .flex_col()
 8373                                                    .flex_1()
 8374                                                    .overflow_hidden()
 8375                                                    .child(
 8376                                                        h_flex()
 8377                                                            .flex_1()
 8378                                                            .when_some(paddings.0, |this, p| {
 8379                                                                this.child(p.border_r_1())
 8380                                                            })
 8381                                                            .child(self.center.render(
 8382                                                                self.zoomed.as_ref(),
 8383                                                                &PaneRenderContext {
 8384                                                                    follower_states:
 8385                                                                        &self.follower_states,
 8386                                                                    active_call: self.active_call(),
 8387                                                                    active_pane: &self.active_pane,
 8388                                                                    app_state: &self.app_state,
 8389                                                                    project: &self.project,
 8390                                                                    workspace: &self.weak_self,
 8391                                                                },
 8392                                                                window,
 8393                                                                cx,
 8394                                                            ))
 8395                                                            .when_some(paddings.1, |this, p| {
 8396                                                                this.child(p.border_l_1())
 8397                                                            }),
 8398                                                    )
 8399                                                    .children(self.render_dock(
 8400                                                        DockPosition::Bottom,
 8401                                                        &self.bottom_dock,
 8402                                                        window,
 8403                                                        cx,
 8404                                                    )),
 8405                                            )
 8406
 8407                                            .children(self.render_dock(
 8408                                                DockPosition::Right,
 8409                                                &self.right_dock,
 8410                                                window,
 8411                                                cx,
 8412                                            )),
 8413                                    }
 8414                                })
 8415                                .children(self.zoomed.as_ref().and_then(|view| {
 8416                                    let zoomed_view = view.upgrade()?;
 8417                                    let div = div()
 8418                                        .occlude()
 8419                                        .absolute()
 8420                                        .overflow_hidden()
 8421                                        .border_color(colors.border)
 8422                                        .bg(colors.background)
 8423                                        .child(zoomed_view)
 8424                                        .inset_0()
 8425                                        .shadow_lg();
 8426
 8427                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8428                                       return Some(div);
 8429                                    }
 8430
 8431                                    Some(match self.zoomed_position {
 8432                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8433                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8434                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8435                                        None => {
 8436                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8437                                        }
 8438                                    })
 8439                                }))
 8440                                .children(self.render_notifications(window, cx)),
 8441                        )
 8442                        .when(self.status_bar_visible(cx), |parent| {
 8443                            parent.child(self.status_bar.clone())
 8444                        })
 8445                        .child(self.toast_layer.clone()),
 8446                )
 8447    }
 8448}
 8449
 8450impl WorkspaceStore {
 8451    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8452        Self {
 8453            workspaces: Default::default(),
 8454            _subscriptions: vec![
 8455                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8456                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8457            ],
 8458            client,
 8459        }
 8460    }
 8461
 8462    pub fn update_followers(
 8463        &self,
 8464        project_id: Option<u64>,
 8465        update: proto::update_followers::Variant,
 8466        cx: &App,
 8467    ) -> Option<()> {
 8468        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8469        let room_id = active_call.0.room_id(cx)?;
 8470        self.client
 8471            .send(proto::UpdateFollowers {
 8472                room_id,
 8473                project_id,
 8474                variant: Some(update),
 8475            })
 8476            .log_err()
 8477    }
 8478
 8479    pub async fn handle_follow(
 8480        this: Entity<Self>,
 8481        envelope: TypedEnvelope<proto::Follow>,
 8482        mut cx: AsyncApp,
 8483    ) -> Result<proto::FollowResponse> {
 8484        this.update(&mut cx, |this, cx| {
 8485            let follower = Follower {
 8486                project_id: envelope.payload.project_id,
 8487                peer_id: envelope.original_sender_id()?,
 8488            };
 8489
 8490            let mut response = proto::FollowResponse::default();
 8491
 8492            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8493                let Some(workspace) = weak_workspace.upgrade() else {
 8494                    return false;
 8495                };
 8496                window_handle
 8497                    .update(cx, |_, window, cx| {
 8498                        workspace.update(cx, |workspace, cx| {
 8499                            let handler_response =
 8500                                workspace.handle_follow(follower.project_id, window, cx);
 8501                            if let Some(active_view) = handler_response.active_view
 8502                                && workspace.project.read(cx).remote_id() == follower.project_id
 8503                            {
 8504                                response.active_view = Some(active_view)
 8505                            }
 8506                        });
 8507                    })
 8508                    .is_ok()
 8509            });
 8510
 8511            Ok(response)
 8512        })
 8513    }
 8514
 8515    async fn handle_update_followers(
 8516        this: Entity<Self>,
 8517        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8518        mut cx: AsyncApp,
 8519    ) -> Result<()> {
 8520        let leader_id = envelope.original_sender_id()?;
 8521        let update = envelope.payload;
 8522
 8523        this.update(&mut cx, |this, cx| {
 8524            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8525                let Some(workspace) = weak_workspace.upgrade() else {
 8526                    return false;
 8527                };
 8528                window_handle
 8529                    .update(cx, |_, window, cx| {
 8530                        workspace.update(cx, |workspace, cx| {
 8531                            let project_id = workspace.project.read(cx).remote_id();
 8532                            if update.project_id != project_id && update.project_id.is_some() {
 8533                                return;
 8534                            }
 8535                            workspace.handle_update_followers(
 8536                                leader_id,
 8537                                update.clone(),
 8538                                window,
 8539                                cx,
 8540                            );
 8541                        });
 8542                    })
 8543                    .is_ok()
 8544            });
 8545            Ok(())
 8546        })
 8547    }
 8548
 8549    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8550        self.workspaces.iter().map(|(_, weak)| weak)
 8551    }
 8552
 8553    pub fn workspaces_with_windows(
 8554        &self,
 8555    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8556        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8557    }
 8558}
 8559
 8560impl ViewId {
 8561    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8562        Ok(Self {
 8563            creator: message
 8564                .creator
 8565                .map(CollaboratorId::PeerId)
 8566                .context("creator is missing")?,
 8567            id: message.id,
 8568        })
 8569    }
 8570
 8571    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8572        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8573            Some(proto::ViewId {
 8574                creator: Some(peer_id),
 8575                id: self.id,
 8576            })
 8577        } else {
 8578            None
 8579        }
 8580    }
 8581}
 8582
 8583impl FollowerState {
 8584    fn pane(&self) -> &Entity<Pane> {
 8585        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8586    }
 8587}
 8588
 8589pub trait WorkspaceHandle {
 8590    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8591}
 8592
 8593impl WorkspaceHandle for Entity<Workspace> {
 8594    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8595        self.read(cx)
 8596            .worktrees(cx)
 8597            .flat_map(|worktree| {
 8598                let worktree_id = worktree.read(cx).id();
 8599                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8600                    worktree_id,
 8601                    path: f.path.clone(),
 8602                })
 8603            })
 8604            .collect::<Vec<_>>()
 8605    }
 8606}
 8607
 8608pub async fn last_opened_workspace_location(
 8609    db: &WorkspaceDb,
 8610    fs: &dyn fs::Fs,
 8611) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8612    db.last_workspace(fs)
 8613        .await
 8614        .log_err()
 8615        .flatten()
 8616        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8617}
 8618
 8619pub async fn last_session_workspace_locations(
 8620    db: &WorkspaceDb,
 8621    last_session_id: &str,
 8622    last_session_window_stack: Option<Vec<WindowId>>,
 8623    fs: &dyn fs::Fs,
 8624) -> Option<Vec<SessionWorkspace>> {
 8625    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8626        .await
 8627        .log_err()
 8628}
 8629
 8630pub struct MultiWorkspaceRestoreResult {
 8631    pub window_handle: WindowHandle<MultiWorkspace>,
 8632    pub errors: Vec<anyhow::Error>,
 8633}
 8634
 8635pub async fn restore_multiworkspace(
 8636    multi_workspace: SerializedMultiWorkspace,
 8637    app_state: Arc<AppState>,
 8638    cx: &mut AsyncApp,
 8639) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8640    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8641    let mut group_iter = workspaces.into_iter();
 8642    let first = group_iter
 8643        .next()
 8644        .context("window group must not be empty")?;
 8645
 8646    let window_handle = if first.paths.is_empty() {
 8647        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8648            .await?
 8649    } else {
 8650        let OpenResult { window, .. } = cx
 8651            .update(|cx| {
 8652                Workspace::new_local(
 8653                    first.paths.paths().to_vec(),
 8654                    app_state.clone(),
 8655                    None,
 8656                    None,
 8657                    None,
 8658                    OpenMode::Activate,
 8659                    cx,
 8660                )
 8661            })
 8662            .await?;
 8663        window
 8664    };
 8665
 8666    let mut errors = Vec::new();
 8667
 8668    for session_workspace in group_iter {
 8669        let error = if session_workspace.paths.is_empty() {
 8670            cx.update(|cx| {
 8671                open_workspace_by_id(
 8672                    session_workspace.workspace_id,
 8673                    app_state.clone(),
 8674                    Some(window_handle),
 8675                    cx,
 8676                )
 8677            })
 8678            .await
 8679            .err()
 8680        } else {
 8681            cx.update(|cx| {
 8682                Workspace::new_local(
 8683                    session_workspace.paths.paths().to_vec(),
 8684                    app_state.clone(),
 8685                    Some(window_handle),
 8686                    None,
 8687                    None,
 8688                    OpenMode::Add,
 8689                    cx,
 8690                )
 8691            })
 8692            .await
 8693            .err()
 8694        };
 8695
 8696        if let Some(error) = error {
 8697            errors.push(error);
 8698        }
 8699    }
 8700
 8701    if let Some(target_id) = state.active_workspace_id {
 8702        window_handle
 8703            .update(cx, |multi_workspace, window, cx| {
 8704                let target_workspace = multi_workspace
 8705                    .workspaces()
 8706                    .find(|ws| ws.read(cx).database_id() == Some(target_id));
 8707                if let Some(workspace) = target_workspace {
 8708                    multi_workspace.activate(workspace, window, cx);
 8709                }
 8710            })
 8711            .ok();
 8712    } else {
 8713        window_handle
 8714            .update(cx, |multi_workspace, window, cx| {
 8715                let first_workspace = multi_workspace.workspaces().next();
 8716                if let Some(workspace) = first_workspace {
 8717                    multi_workspace.activate(workspace, window, cx);
 8718                }
 8719            })
 8720            .ok();
 8721    }
 8722
 8723    if state.sidebar_open {
 8724        window_handle
 8725            .update(cx, |multi_workspace, _, cx| {
 8726                multi_workspace.open_sidebar(cx);
 8727            })
 8728            .ok();
 8729    }
 8730
 8731    if let Some(sidebar_state) = &state.sidebar_state {
 8732        let sidebar_state = sidebar_state.clone();
 8733        window_handle
 8734            .update(cx, |multi_workspace, window, cx| {
 8735                if let Some(sidebar) = multi_workspace.sidebar() {
 8736                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8737                }
 8738                multi_workspace.serialize(cx);
 8739            })
 8740            .ok();
 8741    }
 8742
 8743    window_handle
 8744        .update(cx, |_, window, _cx| {
 8745            window.activate_window();
 8746        })
 8747        .ok();
 8748
 8749    Ok(MultiWorkspaceRestoreResult {
 8750        window_handle,
 8751        errors,
 8752    })
 8753}
 8754
 8755actions!(
 8756    collab,
 8757    [
 8758        /// Opens the channel notes for the current call.
 8759        ///
 8760        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8761        /// channel in the collab panel.
 8762        ///
 8763        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8764        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8765        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8766        OpenChannelNotes,
 8767        /// Mutes your microphone.
 8768        Mute,
 8769        /// Deafens yourself (mute both microphone and speakers).
 8770        Deafen,
 8771        /// Leaves the current call.
 8772        LeaveCall,
 8773        /// Shares the current project with collaborators.
 8774        ShareProject,
 8775        /// Shares your screen with collaborators.
 8776        ScreenShare,
 8777        /// Copies the current room name and session id for debugging purposes.
 8778        CopyRoomId,
 8779    ]
 8780);
 8781
 8782/// Opens the channel notes for a specific channel by its ID.
 8783#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8784#[action(namespace = collab)]
 8785#[serde(deny_unknown_fields)]
 8786pub struct OpenChannelNotesById {
 8787    pub channel_id: u64,
 8788}
 8789
 8790actions!(
 8791    zed,
 8792    [
 8793        /// Opens the Zed log file.
 8794        OpenLog,
 8795        /// Reveals the Zed log file in the system file manager.
 8796        RevealLogInFileManager
 8797    ]
 8798);
 8799
 8800async fn join_channel_internal(
 8801    channel_id: ChannelId,
 8802    app_state: &Arc<AppState>,
 8803    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8804    requesting_workspace: Option<WeakEntity<Workspace>>,
 8805    active_call: &dyn AnyActiveCall,
 8806    cx: &mut AsyncApp,
 8807) -> Result<bool> {
 8808    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8809        if !active_call.is_in_room(cx) {
 8810            return (false, false);
 8811        }
 8812
 8813        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8814        let should_prompt = active_call.is_sharing_project(cx)
 8815            && active_call.has_remote_participants(cx)
 8816            && !already_in_channel;
 8817        (should_prompt, already_in_channel)
 8818    });
 8819
 8820    if already_in_channel {
 8821        let task = cx.update(|cx| {
 8822            if let Some((project, host)) = active_call.most_active_project(cx) {
 8823                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8824            } else {
 8825                None
 8826            }
 8827        });
 8828        if let Some(task) = task {
 8829            task.await?;
 8830        }
 8831        return anyhow::Ok(true);
 8832    }
 8833
 8834    if should_prompt {
 8835        if let Some(multi_workspace) = requesting_window {
 8836            let answer = multi_workspace
 8837                .update(cx, |_, window, cx| {
 8838                    window.prompt(
 8839                        PromptLevel::Warning,
 8840                        "Do you want to switch channels?",
 8841                        Some("Leaving this call will unshare your current project."),
 8842                        &["Yes, Join Channel", "Cancel"],
 8843                        cx,
 8844                    )
 8845                })?
 8846                .await;
 8847
 8848            if answer == Ok(1) {
 8849                return Ok(false);
 8850            }
 8851        } else {
 8852            return Ok(false);
 8853        }
 8854    }
 8855
 8856    let client = cx.update(|cx| active_call.client(cx));
 8857
 8858    let mut client_status = client.status();
 8859
 8860    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8861    'outer: loop {
 8862        let Some(status) = client_status.recv().await else {
 8863            anyhow::bail!("error connecting");
 8864        };
 8865
 8866        match status {
 8867            Status::Connecting
 8868            | Status::Authenticating
 8869            | Status::Authenticated
 8870            | Status::Reconnecting
 8871            | Status::Reauthenticating
 8872            | Status::Reauthenticated => continue,
 8873            Status::Connected { .. } => break 'outer,
 8874            Status::SignedOut | Status::AuthenticationError => {
 8875                return Err(ErrorCode::SignedOut.into());
 8876            }
 8877            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8878            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8879                return Err(ErrorCode::Disconnected.into());
 8880            }
 8881        }
 8882    }
 8883
 8884    let joined = cx
 8885        .update(|cx| active_call.join_channel(channel_id, cx))
 8886        .await?;
 8887
 8888    if !joined {
 8889        return anyhow::Ok(true);
 8890    }
 8891
 8892    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8893
 8894    let task = cx.update(|cx| {
 8895        if let Some((project, host)) = active_call.most_active_project(cx) {
 8896            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8897        }
 8898
 8899        // If you are the first to join a channel, see if you should share your project.
 8900        if !active_call.has_remote_participants(cx)
 8901            && !active_call.local_participant_is_guest(cx)
 8902            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8903        {
 8904            let project = workspace.update(cx, |workspace, cx| {
 8905                let project = workspace.project.read(cx);
 8906
 8907                if !active_call.share_on_join(cx) {
 8908                    return None;
 8909                }
 8910
 8911                if (project.is_local() || project.is_via_remote_server())
 8912                    && project.visible_worktrees(cx).any(|tree| {
 8913                        tree.read(cx)
 8914                            .root_entry()
 8915                            .is_some_and(|entry| entry.is_dir())
 8916                    })
 8917                {
 8918                    Some(workspace.project.clone())
 8919                } else {
 8920                    None
 8921                }
 8922            });
 8923            if let Some(project) = project {
 8924                let share_task = active_call.share_project(project, cx);
 8925                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8926                    share_task.await?;
 8927                    Ok(())
 8928                }));
 8929            }
 8930        }
 8931
 8932        None
 8933    });
 8934    if let Some(task) = task {
 8935        task.await?;
 8936        return anyhow::Ok(true);
 8937    }
 8938    anyhow::Ok(false)
 8939}
 8940
 8941pub fn join_channel(
 8942    channel_id: ChannelId,
 8943    app_state: Arc<AppState>,
 8944    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8945    requesting_workspace: Option<WeakEntity<Workspace>>,
 8946    cx: &mut App,
 8947) -> Task<Result<()>> {
 8948    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8949    cx.spawn(async move |cx| {
 8950        let result = join_channel_internal(
 8951            channel_id,
 8952            &app_state,
 8953            requesting_window,
 8954            requesting_workspace,
 8955            &*active_call.0,
 8956            cx,
 8957        )
 8958        .await;
 8959
 8960        // join channel succeeded, and opened a window
 8961        if matches!(result, Ok(true)) {
 8962            return anyhow::Ok(());
 8963        }
 8964
 8965        // find an existing workspace to focus and show call controls
 8966        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8967        if active_window.is_none() {
 8968            // no open workspaces, make one to show the error in (blergh)
 8969            let OpenResult {
 8970                window: window_handle,
 8971                ..
 8972            } = cx
 8973                .update(|cx| {
 8974                    Workspace::new_local(
 8975                        vec![],
 8976                        app_state.clone(),
 8977                        requesting_window,
 8978                        None,
 8979                        None,
 8980                        OpenMode::Activate,
 8981                        cx,
 8982                    )
 8983                })
 8984                .await?;
 8985
 8986            window_handle
 8987                .update(cx, |_, window, _cx| {
 8988                    window.activate_window();
 8989                })
 8990                .ok();
 8991
 8992            if result.is_ok() {
 8993                cx.update(|cx| {
 8994                    cx.dispatch_action(&OpenChannelNotes);
 8995                });
 8996            }
 8997
 8998            active_window = Some(window_handle);
 8999        }
 9000
 9001        if let Err(err) = result {
 9002            log::error!("failed to join channel: {}", err);
 9003            if let Some(active_window) = active_window {
 9004                active_window
 9005                    .update(cx, |_, window, cx| {
 9006                        let detail: SharedString = match err.error_code() {
 9007                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9008                            ErrorCode::UpgradeRequired => concat!(
 9009                                "Your are running an unsupported version of Zed. ",
 9010                                "Please update to continue."
 9011                            )
 9012                            .into(),
 9013                            ErrorCode::NoSuchChannel => concat!(
 9014                                "No matching channel was found. ",
 9015                                "Please check the link and try again."
 9016                            )
 9017                            .into(),
 9018                            ErrorCode::Forbidden => concat!(
 9019                                "This channel is private, and you do not have access. ",
 9020                                "Please ask someone to add you and try again."
 9021                            )
 9022                            .into(),
 9023                            ErrorCode::Disconnected => {
 9024                                "Please check your internet connection and try again.".into()
 9025                            }
 9026                            _ => format!("{}\n\nPlease try again.", err).into(),
 9027                        };
 9028                        window.prompt(
 9029                            PromptLevel::Critical,
 9030                            "Failed to join channel",
 9031                            Some(&detail),
 9032                            &["Ok"],
 9033                            cx,
 9034                        )
 9035                    })?
 9036                    .await
 9037                    .ok();
 9038            }
 9039        }
 9040
 9041        // return ok, we showed the error to the user.
 9042        anyhow::Ok(())
 9043    })
 9044}
 9045
 9046pub async fn get_any_active_multi_workspace(
 9047    app_state: Arc<AppState>,
 9048    mut cx: AsyncApp,
 9049) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9050    // find an existing workspace to focus and show call controls
 9051    let active_window = activate_any_workspace_window(&mut cx);
 9052    if active_window.is_none() {
 9053        cx.update(|cx| {
 9054            Workspace::new_local(
 9055                vec![],
 9056                app_state.clone(),
 9057                None,
 9058                None,
 9059                None,
 9060                OpenMode::Activate,
 9061                cx,
 9062            )
 9063        })
 9064        .await?;
 9065    }
 9066    activate_any_workspace_window(&mut cx).context("could not open zed")
 9067}
 9068
 9069fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9070    cx.update(|cx| {
 9071        if let Some(workspace_window) = cx
 9072            .active_window()
 9073            .and_then(|window| window.downcast::<MultiWorkspace>())
 9074        {
 9075            return Some(workspace_window);
 9076        }
 9077
 9078        for window in cx.windows() {
 9079            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9080                workspace_window
 9081                    .update(cx, |_, window, _| window.activate_window())
 9082                    .ok();
 9083                return Some(workspace_window);
 9084            }
 9085        }
 9086        None
 9087    })
 9088}
 9089
 9090pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9091    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9092}
 9093
 9094pub fn workspace_windows_for_location(
 9095    serialized_location: &SerializedWorkspaceLocation,
 9096    cx: &App,
 9097) -> Vec<WindowHandle<MultiWorkspace>> {
 9098    cx.windows()
 9099        .into_iter()
 9100        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9101        .filter(|multi_workspace| {
 9102            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9103                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9104                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9105                }
 9106                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9107                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9108                    a.distro_name == b.distro_name
 9109                }
 9110                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9111                    a.container_id == b.container_id
 9112                }
 9113                #[cfg(any(test, feature = "test-support"))]
 9114                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9115                    a.id == b.id
 9116                }
 9117                _ => false,
 9118            };
 9119
 9120            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9121                multi_workspace.workspaces().any(|workspace| {
 9122                    match workspace.read(cx).workspace_location(cx) {
 9123                        WorkspaceLocation::Location(location, _) => {
 9124                            match (&location, serialized_location) {
 9125                                (
 9126                                    SerializedWorkspaceLocation::Local,
 9127                                    SerializedWorkspaceLocation::Local,
 9128                                ) => true,
 9129                                (
 9130                                    SerializedWorkspaceLocation::Remote(a),
 9131                                    SerializedWorkspaceLocation::Remote(b),
 9132                                ) => same_host(a, b),
 9133                                _ => false,
 9134                            }
 9135                        }
 9136                        _ => false,
 9137                    }
 9138                })
 9139            })
 9140        })
 9141        .collect()
 9142}
 9143
 9144pub async fn find_existing_workspace(
 9145    abs_paths: &[PathBuf],
 9146    open_options: &OpenOptions,
 9147    location: &SerializedWorkspaceLocation,
 9148    cx: &mut AsyncApp,
 9149) -> (
 9150    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9151    OpenVisible,
 9152) {
 9153    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9154    let mut open_visible = OpenVisible::All;
 9155    let mut best_match = None;
 9156
 9157    if open_options.open_new_workspace != Some(true) {
 9158        cx.update(|cx| {
 9159            for window in workspace_windows_for_location(location, cx) {
 9160                if let Ok(multi_workspace) = window.read(cx) {
 9161                    for workspace in multi_workspace.workspaces() {
 9162                        let project = workspace.read(cx).project.read(cx);
 9163                        let m = project.visibility_for_paths(
 9164                            abs_paths,
 9165                            open_options.open_new_workspace == None,
 9166                            cx,
 9167                        );
 9168                        if m > best_match {
 9169                            existing = Some((window, workspace.clone()));
 9170                            best_match = m;
 9171                        } else if best_match.is_none()
 9172                            && open_options.open_new_workspace == Some(false)
 9173                        {
 9174                            existing = Some((window, workspace.clone()))
 9175                        }
 9176                    }
 9177                }
 9178            }
 9179        });
 9180
 9181        let all_paths_are_files = existing
 9182            .as_ref()
 9183            .and_then(|(_, target_workspace)| {
 9184                cx.update(|cx| {
 9185                    let workspace = target_workspace.read(cx);
 9186                    let project = workspace.project.read(cx);
 9187                    let path_style = workspace.path_style(cx);
 9188                    Some(!abs_paths.iter().any(|path| {
 9189                        let path = util::paths::SanitizedPath::new(path);
 9190                        project.worktrees(cx).any(|worktree| {
 9191                            let worktree = worktree.read(cx);
 9192                            let abs_path = worktree.abs_path();
 9193                            path_style
 9194                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9195                                .and_then(|rel| worktree.entry_for_path(&rel))
 9196                                .is_some_and(|e| e.is_dir())
 9197                        })
 9198                    }))
 9199                })
 9200            })
 9201            .unwrap_or(false);
 9202
 9203        if open_options.open_new_workspace.is_none()
 9204            && existing.is_some()
 9205            && open_options.wait
 9206            && all_paths_are_files
 9207        {
 9208            cx.update(|cx| {
 9209                let windows = workspace_windows_for_location(location, cx);
 9210                let window = cx
 9211                    .active_window()
 9212                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9213                    .filter(|window| windows.contains(window))
 9214                    .or_else(|| windows.into_iter().next());
 9215                if let Some(window) = window {
 9216                    if let Ok(multi_workspace) = window.read(cx) {
 9217                        let active_workspace = multi_workspace.workspace().clone();
 9218                        existing = Some((window, active_workspace));
 9219                        open_visible = OpenVisible::None;
 9220                    }
 9221                }
 9222            });
 9223        }
 9224    }
 9225    (existing, open_visible)
 9226}
 9227
 9228#[derive(Default, Clone)]
 9229pub struct OpenOptions {
 9230    pub visible: Option<OpenVisible>,
 9231    pub focus: Option<bool>,
 9232    pub open_new_workspace: Option<bool>,
 9233    pub wait: bool,
 9234    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9235    pub open_mode: OpenMode,
 9236    pub env: Option<HashMap<String, String>>,
 9237}
 9238
 9239/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9240/// or [`Workspace::open_workspace_for_paths`].
 9241pub struct OpenResult {
 9242    pub window: WindowHandle<MultiWorkspace>,
 9243    pub workspace: Entity<Workspace>,
 9244    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9245}
 9246
 9247/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9248pub fn open_workspace_by_id(
 9249    workspace_id: WorkspaceId,
 9250    app_state: Arc<AppState>,
 9251    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9252    cx: &mut App,
 9253) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9254    let project_handle = Project::local(
 9255        app_state.client.clone(),
 9256        app_state.node_runtime.clone(),
 9257        app_state.user_store.clone(),
 9258        app_state.languages.clone(),
 9259        app_state.fs.clone(),
 9260        None,
 9261        project::LocalProjectFlags {
 9262            init_worktree_trust: true,
 9263            ..project::LocalProjectFlags::default()
 9264        },
 9265        cx,
 9266    );
 9267
 9268    let db = WorkspaceDb::global(cx);
 9269    let kvp = db::kvp::KeyValueStore::global(cx);
 9270    cx.spawn(async move |cx| {
 9271        let serialized_workspace = db
 9272            .workspace_for_id(workspace_id)
 9273            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9274
 9275        let centered_layout = serialized_workspace.centered_layout;
 9276
 9277        let (window, workspace) = if let Some(window) = requesting_window {
 9278            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9279                let workspace = cx.new(|cx| {
 9280                    let mut workspace = Workspace::new(
 9281                        Some(workspace_id),
 9282                        project_handle.clone(),
 9283                        app_state.clone(),
 9284                        window,
 9285                        cx,
 9286                    );
 9287                    workspace.centered_layout = centered_layout;
 9288                    workspace
 9289                });
 9290                multi_workspace.add(workspace.clone(), &*window, cx);
 9291                workspace
 9292            })?;
 9293            (window, workspace)
 9294        } else {
 9295            let window_bounds_override = window_bounds_env_override();
 9296
 9297            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9298                (Some(WindowBounds::Windowed(bounds)), None)
 9299            } else if let Some(display) = serialized_workspace.display
 9300                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9301            {
 9302                (Some(bounds.0), Some(display))
 9303            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9304                (Some(bounds), Some(display))
 9305            } else {
 9306                (None, None)
 9307            };
 9308
 9309            let options = cx.update(|cx| {
 9310                let mut options = (app_state.build_window_options)(display, cx);
 9311                options.window_bounds = window_bounds;
 9312                options
 9313            });
 9314
 9315            let window = cx.open_window(options, {
 9316                let app_state = app_state.clone();
 9317                let project_handle = project_handle.clone();
 9318                move |window, cx| {
 9319                    let workspace = cx.new(|cx| {
 9320                        let mut workspace = Workspace::new(
 9321                            Some(workspace_id),
 9322                            project_handle,
 9323                            app_state,
 9324                            window,
 9325                            cx,
 9326                        );
 9327                        workspace.centered_layout = centered_layout;
 9328                        workspace
 9329                    });
 9330                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9331                }
 9332            })?;
 9333
 9334            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9335                multi_workspace.workspace().clone()
 9336            })?;
 9337
 9338            (window, workspace)
 9339        };
 9340
 9341        notify_if_database_failed(window, cx);
 9342
 9343        // Restore items from the serialized workspace
 9344        window
 9345            .update(cx, |_, window, cx| {
 9346                workspace.update(cx, |_workspace, cx| {
 9347                    open_items(Some(serialized_workspace), vec![], window, cx)
 9348                })
 9349            })?
 9350            .await?;
 9351
 9352        window.update(cx, |_, window, cx| {
 9353            workspace.update(cx, |workspace, cx| {
 9354                workspace.serialize_workspace(window, cx);
 9355            });
 9356        })?;
 9357
 9358        Ok(window)
 9359    })
 9360}
 9361
 9362#[allow(clippy::type_complexity)]
 9363pub fn open_paths(
 9364    abs_paths: &[PathBuf],
 9365    app_state: Arc<AppState>,
 9366    open_options: OpenOptions,
 9367    cx: &mut App,
 9368) -> Task<anyhow::Result<OpenResult>> {
 9369    let abs_paths = abs_paths.to_vec();
 9370    #[cfg(target_os = "windows")]
 9371    let wsl_path = abs_paths
 9372        .iter()
 9373        .find_map(|p| util::paths::WslPath::from_path(p));
 9374
 9375    cx.spawn(async move |cx| {
 9376        let (mut existing, mut open_visible) = find_existing_workspace(
 9377            &abs_paths,
 9378            &open_options,
 9379            &SerializedWorkspaceLocation::Local,
 9380            cx,
 9381        )
 9382        .await;
 9383
 9384        // Fallback: if no workspace contains the paths and all paths are files,
 9385        // prefer an existing local workspace window (active window first).
 9386        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9387            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9388            let all_metadatas = futures::future::join_all(all_paths)
 9389                .await
 9390                .into_iter()
 9391                .filter_map(|result| result.ok().flatten())
 9392                .collect::<Vec<_>>();
 9393
 9394            if all_metadatas.iter().all(|file| !file.is_dir) {
 9395                cx.update(|cx| {
 9396                    let windows = workspace_windows_for_location(
 9397                        &SerializedWorkspaceLocation::Local,
 9398                        cx,
 9399                    );
 9400                    let window = cx
 9401                        .active_window()
 9402                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9403                        .filter(|window| windows.contains(window))
 9404                        .or_else(|| windows.into_iter().next());
 9405                    if let Some(window) = window {
 9406                        if let Ok(multi_workspace) = window.read(cx) {
 9407                            let active_workspace = multi_workspace.workspace().clone();
 9408                            existing = Some((window, active_workspace));
 9409                            open_visible = OpenVisible::None;
 9410                        }
 9411                    }
 9412                });
 9413            }
 9414        }
 9415
 9416        let result = if let Some((existing, target_workspace)) = existing {
 9417            let open_task = existing
 9418                .update(cx, |multi_workspace, window, cx| {
 9419                    window.activate_window();
 9420                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9421                    target_workspace.update(cx, |workspace, cx| {
 9422                        workspace.open_paths(
 9423                            abs_paths,
 9424                            OpenOptions {
 9425                                visible: Some(open_visible),
 9426                                ..Default::default()
 9427                            },
 9428                            None,
 9429                            window,
 9430                            cx,
 9431                        )
 9432                    })
 9433                })?
 9434                .await;
 9435
 9436            _ = existing.update(cx, |multi_workspace, _, cx| {
 9437                let workspace = multi_workspace.workspace().clone();
 9438                workspace.update(cx, |workspace, cx| {
 9439                    for item in open_task.iter().flatten() {
 9440                        if let Err(e) = item {
 9441                            workspace.show_error(&e, cx);
 9442                        }
 9443                    }
 9444                });
 9445            });
 9446
 9447            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9448        } else {
 9449            let result = cx
 9450                .update(move |cx| {
 9451                    Workspace::new_local(
 9452                        abs_paths,
 9453                        app_state.clone(),
 9454                        open_options.requesting_window,
 9455                        open_options.env,
 9456                        None,
 9457                        open_options.open_mode,
 9458                        cx,
 9459                    )
 9460                })
 9461                .await;
 9462
 9463            if let Ok(ref result) = result {
 9464                result.window
 9465                    .update(cx, |_, window, _cx| {
 9466                        window.activate_window();
 9467                    })
 9468                    .log_err();
 9469            }
 9470
 9471            result
 9472        };
 9473
 9474        #[cfg(target_os = "windows")]
 9475        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9476            && let Ok(ref result) = result
 9477        {
 9478            result.window
 9479                .update(cx, move |multi_workspace, _window, cx| {
 9480                    struct OpenInWsl;
 9481                    let workspace = multi_workspace.workspace().clone();
 9482                    workspace.update(cx, |workspace, cx| {
 9483                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9484                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9485                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9486                            cx.new(move |cx| {
 9487                                MessageNotification::new(msg, cx)
 9488                                    .primary_message("Open in WSL")
 9489                                    .primary_icon(IconName::FolderOpen)
 9490                                    .primary_on_click(move |window, cx| {
 9491                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9492                                                distro: remote::WslConnectionOptions {
 9493                                                        distro_name: distro.clone(),
 9494                                                    user: None,
 9495                                                },
 9496                                                paths: vec![path.clone().into()],
 9497                                            }), cx)
 9498                                    })
 9499                            })
 9500                        });
 9501                    });
 9502                })
 9503                .unwrap();
 9504        };
 9505        result
 9506    })
 9507}
 9508
 9509pub fn open_new(
 9510    open_options: OpenOptions,
 9511    app_state: Arc<AppState>,
 9512    cx: &mut App,
 9513    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9514) -> Task<anyhow::Result<()>> {
 9515    let addition = open_options.open_mode;
 9516    let task = Workspace::new_local(
 9517        Vec::new(),
 9518        app_state,
 9519        open_options.requesting_window,
 9520        open_options.env,
 9521        Some(Box::new(init)),
 9522        addition,
 9523        cx,
 9524    );
 9525    cx.spawn(async move |cx| {
 9526        let OpenResult { window, .. } = task.await?;
 9527        window
 9528            .update(cx, |_, window, _cx| {
 9529                window.activate_window();
 9530            })
 9531            .ok();
 9532        Ok(())
 9533    })
 9534}
 9535
 9536pub fn create_and_open_local_file(
 9537    path: &'static Path,
 9538    window: &mut Window,
 9539    cx: &mut Context<Workspace>,
 9540    default_content: impl 'static + Send + FnOnce() -> Rope,
 9541) -> Task<Result<Box<dyn ItemHandle>>> {
 9542    cx.spawn_in(window, async move |workspace, cx| {
 9543        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9544        if !fs.is_file(path).await {
 9545            fs.create_file(path, Default::default()).await?;
 9546            fs.save(path, &default_content(), Default::default())
 9547                .await?;
 9548        }
 9549
 9550        workspace
 9551            .update_in(cx, |workspace, window, cx| {
 9552                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9553                    let path = workspace
 9554                        .project
 9555                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9556                    cx.spawn_in(window, async move |workspace, cx| {
 9557                        let path = path.await?;
 9558
 9559                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9560
 9561                        let mut items = workspace
 9562                            .update_in(cx, |workspace, window, cx| {
 9563                                workspace.open_paths(
 9564                                    vec![path.to_path_buf()],
 9565                                    OpenOptions {
 9566                                        visible: Some(OpenVisible::None),
 9567                                        ..Default::default()
 9568                                    },
 9569                                    None,
 9570                                    window,
 9571                                    cx,
 9572                                )
 9573                            })?
 9574                            .await;
 9575                        let item = items.pop().flatten();
 9576                        item.with_context(|| format!("path {path:?} is not a file"))?
 9577                    })
 9578                })
 9579            })?
 9580            .await?
 9581            .await
 9582    })
 9583}
 9584
 9585pub fn open_remote_project_with_new_connection(
 9586    window: WindowHandle<MultiWorkspace>,
 9587    remote_connection: Arc<dyn RemoteConnection>,
 9588    cancel_rx: oneshot::Receiver<()>,
 9589    delegate: Arc<dyn RemoteClientDelegate>,
 9590    app_state: Arc<AppState>,
 9591    paths: Vec<PathBuf>,
 9592    cx: &mut App,
 9593) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9594    cx.spawn(async move |cx| {
 9595        let (workspace_id, serialized_workspace) =
 9596            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9597                .await?;
 9598
 9599        let session = match cx
 9600            .update(|cx| {
 9601                remote::RemoteClient::new(
 9602                    ConnectionIdentifier::Workspace(workspace_id.0),
 9603                    remote_connection,
 9604                    cancel_rx,
 9605                    delegate,
 9606                    cx,
 9607                )
 9608            })
 9609            .await?
 9610        {
 9611            Some(result) => result,
 9612            None => return Ok(Vec::new()),
 9613        };
 9614
 9615        let project = cx.update(|cx| {
 9616            project::Project::remote(
 9617                session,
 9618                app_state.client.clone(),
 9619                app_state.node_runtime.clone(),
 9620                app_state.user_store.clone(),
 9621                app_state.languages.clone(),
 9622                app_state.fs.clone(),
 9623                true,
 9624                cx,
 9625            )
 9626        });
 9627
 9628        open_remote_project_inner(
 9629            project,
 9630            paths,
 9631            workspace_id,
 9632            serialized_workspace,
 9633            app_state,
 9634            window,
 9635            cx,
 9636        )
 9637        .await
 9638    })
 9639}
 9640
 9641pub fn open_remote_project_with_existing_connection(
 9642    connection_options: RemoteConnectionOptions,
 9643    project: Entity<Project>,
 9644    paths: Vec<PathBuf>,
 9645    app_state: Arc<AppState>,
 9646    window: WindowHandle<MultiWorkspace>,
 9647    cx: &mut AsyncApp,
 9648) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9649    cx.spawn(async move |cx| {
 9650        let (workspace_id, serialized_workspace) =
 9651            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9652
 9653        open_remote_project_inner(
 9654            project,
 9655            paths,
 9656            workspace_id,
 9657            serialized_workspace,
 9658            app_state,
 9659            window,
 9660            cx,
 9661        )
 9662        .await
 9663    })
 9664}
 9665
 9666async fn open_remote_project_inner(
 9667    project: Entity<Project>,
 9668    paths: Vec<PathBuf>,
 9669    workspace_id: WorkspaceId,
 9670    serialized_workspace: Option<SerializedWorkspace>,
 9671    app_state: Arc<AppState>,
 9672    window: WindowHandle<MultiWorkspace>,
 9673    cx: &mut AsyncApp,
 9674) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9675    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9676    let toolchains = db.toolchains(workspace_id).await?;
 9677    for (toolchain, worktree_path, path) in toolchains {
 9678        project
 9679            .update(cx, |this, cx| {
 9680                let Some(worktree_id) =
 9681                    this.find_worktree(&worktree_path, cx)
 9682                        .and_then(|(worktree, rel_path)| {
 9683                            if rel_path.is_empty() {
 9684                                Some(worktree.read(cx).id())
 9685                            } else {
 9686                                None
 9687                            }
 9688                        })
 9689                else {
 9690                    return Task::ready(None);
 9691                };
 9692
 9693                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9694            })
 9695            .await;
 9696    }
 9697    let mut project_paths_to_open = vec![];
 9698    let mut project_path_errors = vec![];
 9699
 9700    for path in paths {
 9701        let result = cx
 9702            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9703            .await;
 9704        match result {
 9705            Ok((_, project_path)) => {
 9706                project_paths_to_open.push((path.clone(), Some(project_path)));
 9707            }
 9708            Err(error) => {
 9709                project_path_errors.push(error);
 9710            }
 9711        };
 9712    }
 9713
 9714    if project_paths_to_open.is_empty() {
 9715        return Err(project_path_errors.pop().context("no paths given")?);
 9716    }
 9717
 9718    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9719        telemetry::event!("SSH Project Opened");
 9720
 9721        let new_workspace = cx.new(|cx| {
 9722            let mut workspace =
 9723                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9724            workspace.update_history(cx);
 9725
 9726            if let Some(ref serialized) = serialized_workspace {
 9727                workspace.centered_layout = serialized.centered_layout;
 9728            }
 9729
 9730            workspace
 9731        });
 9732
 9733        multi_workspace.activate(new_workspace.clone(), window, cx);
 9734        new_workspace
 9735    })?;
 9736
 9737    let items = window
 9738        .update(cx, |_, window, cx| {
 9739            window.activate_window();
 9740            workspace.update(cx, |_workspace, cx| {
 9741                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9742            })
 9743        })?
 9744        .await?;
 9745
 9746    workspace.update(cx, |workspace, cx| {
 9747        for error in project_path_errors {
 9748            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9749                if let Some(path) = error.error_tag("path") {
 9750                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9751                }
 9752            } else {
 9753                workspace.show_error(&error, cx)
 9754            }
 9755        }
 9756    });
 9757
 9758    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9759}
 9760
 9761fn deserialize_remote_project(
 9762    connection_options: RemoteConnectionOptions,
 9763    paths: Vec<PathBuf>,
 9764    cx: &AsyncApp,
 9765) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9766    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9767    cx.background_spawn(async move {
 9768        let remote_connection_id = db
 9769            .get_or_create_remote_connection(connection_options)
 9770            .await?;
 9771
 9772        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9773
 9774        let workspace_id = if let Some(workspace_id) =
 9775            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9776        {
 9777            workspace_id
 9778        } else {
 9779            db.next_id().await?
 9780        };
 9781
 9782        Ok((workspace_id, serialized_workspace))
 9783    })
 9784}
 9785
 9786pub fn join_in_room_project(
 9787    project_id: u64,
 9788    follow_user_id: u64,
 9789    app_state: Arc<AppState>,
 9790    cx: &mut App,
 9791) -> Task<Result<()>> {
 9792    let windows = cx.windows();
 9793    cx.spawn(async move |cx| {
 9794        let existing_window_and_workspace: Option<(
 9795            WindowHandle<MultiWorkspace>,
 9796            Entity<Workspace>,
 9797        )> = windows.into_iter().find_map(|window_handle| {
 9798            window_handle
 9799                .downcast::<MultiWorkspace>()
 9800                .and_then(|window_handle| {
 9801                    window_handle
 9802                        .update(cx, |multi_workspace, _window, cx| {
 9803                            for workspace in multi_workspace.workspaces() {
 9804                                if workspace.read(cx).project().read(cx).remote_id()
 9805                                    == Some(project_id)
 9806                                {
 9807                                    return Some((window_handle, workspace.clone()));
 9808                                }
 9809                            }
 9810                            None
 9811                        })
 9812                        .unwrap_or(None)
 9813                })
 9814        });
 9815
 9816        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9817            existing_window_and_workspace
 9818        {
 9819            existing_window
 9820                .update(cx, |multi_workspace, window, cx| {
 9821                    multi_workspace.activate(target_workspace, window, cx);
 9822                })
 9823                .ok();
 9824            existing_window
 9825        } else {
 9826            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9827            let project = cx
 9828                .update(|cx| {
 9829                    active_call.0.join_project(
 9830                        project_id,
 9831                        app_state.languages.clone(),
 9832                        app_state.fs.clone(),
 9833                        cx,
 9834                    )
 9835                })
 9836                .await?;
 9837
 9838            let window_bounds_override = window_bounds_env_override();
 9839            cx.update(|cx| {
 9840                let mut options = (app_state.build_window_options)(None, cx);
 9841                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9842                cx.open_window(options, |window, cx| {
 9843                    let workspace = cx.new(|cx| {
 9844                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9845                    });
 9846                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9847                })
 9848            })?
 9849        };
 9850
 9851        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9852            cx.activate(true);
 9853            window.activate_window();
 9854
 9855            // We set the active workspace above, so this is the correct workspace.
 9856            let workspace = multi_workspace.workspace().clone();
 9857            workspace.update(cx, |workspace, cx| {
 9858                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9859                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9860                    .or_else(|| {
 9861                        // If we couldn't follow the given user, follow the host instead.
 9862                        let collaborator = workspace
 9863                            .project()
 9864                            .read(cx)
 9865                            .collaborators()
 9866                            .values()
 9867                            .find(|collaborator| collaborator.is_host)?;
 9868                        Some(collaborator.peer_id)
 9869                    });
 9870
 9871                if let Some(follow_peer_id) = follow_peer_id {
 9872                    workspace.follow(follow_peer_id, window, cx);
 9873                }
 9874            });
 9875        })?;
 9876
 9877        anyhow::Ok(())
 9878    })
 9879}
 9880
 9881pub fn reload(cx: &mut App) {
 9882    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9883    let mut workspace_windows = cx
 9884        .windows()
 9885        .into_iter()
 9886        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9887        .collect::<Vec<_>>();
 9888
 9889    // If multiple windows have unsaved changes, and need a save prompt,
 9890    // prompt in the active window before switching to a different window.
 9891    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9892
 9893    let mut prompt = None;
 9894    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9895        prompt = window
 9896            .update(cx, |_, window, cx| {
 9897                window.prompt(
 9898                    PromptLevel::Info,
 9899                    "Are you sure you want to restart?",
 9900                    None,
 9901                    &["Restart", "Cancel"],
 9902                    cx,
 9903                )
 9904            })
 9905            .ok();
 9906    }
 9907
 9908    cx.spawn(async move |cx| {
 9909        if let Some(prompt) = prompt {
 9910            let answer = prompt.await?;
 9911            if answer != 0 {
 9912                return anyhow::Ok(());
 9913            }
 9914        }
 9915
 9916        // If the user cancels any save prompt, then keep the app open.
 9917        for window in workspace_windows {
 9918            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9919                let workspace = multi_workspace.workspace().clone();
 9920                workspace.update(cx, |workspace, cx| {
 9921                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9922                })
 9923            }) && !should_close.await?
 9924            {
 9925                return anyhow::Ok(());
 9926            }
 9927        }
 9928        cx.update(|cx| cx.restart());
 9929        anyhow::Ok(())
 9930    })
 9931    .detach_and_log_err(cx);
 9932}
 9933
 9934fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9935    let mut parts = value.split(',');
 9936    let x: usize = parts.next()?.parse().ok()?;
 9937    let y: usize = parts.next()?.parse().ok()?;
 9938    Some(point(px(x as f32), px(y as f32)))
 9939}
 9940
 9941fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9942    let mut parts = value.split(',');
 9943    let width: usize = parts.next()?.parse().ok()?;
 9944    let height: usize = parts.next()?.parse().ok()?;
 9945    Some(size(px(width as f32), px(height as f32)))
 9946}
 9947
 9948/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9949/// appropriate.
 9950///
 9951/// The `border_radius_tiling` parameter allows overriding which corners get
 9952/// rounded, independently of the actual window tiling state. This is used
 9953/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9954/// we want square corners on the left (so the sidebar appears flush with the
 9955/// window edge) but we still need the shadow padding for proper visual
 9956/// appearance. Unlike actual window tiling, this only affects border radius -
 9957/// not padding or shadows.
 9958pub fn client_side_decorations(
 9959    element: impl IntoElement,
 9960    window: &mut Window,
 9961    cx: &mut App,
 9962    border_radius_tiling: Tiling,
 9963) -> Stateful<Div> {
 9964    const BORDER_SIZE: Pixels = px(1.0);
 9965    let decorations = window.window_decorations();
 9966    let tiling = match decorations {
 9967        Decorations::Server => Tiling::default(),
 9968        Decorations::Client { tiling } => tiling,
 9969    };
 9970
 9971    match decorations {
 9972        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9973        Decorations::Server => window.set_client_inset(px(0.0)),
 9974    }
 9975
 9976    struct GlobalResizeEdge(ResizeEdge);
 9977    impl Global for GlobalResizeEdge {}
 9978
 9979    div()
 9980        .id("window-backdrop")
 9981        .bg(transparent_black())
 9982        .map(|div| match decorations {
 9983            Decorations::Server => div,
 9984            Decorations::Client { .. } => div
 9985                .when(
 9986                    !(tiling.top
 9987                        || tiling.right
 9988                        || border_radius_tiling.top
 9989                        || border_radius_tiling.right),
 9990                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9991                )
 9992                .when(
 9993                    !(tiling.top
 9994                        || tiling.left
 9995                        || border_radius_tiling.top
 9996                        || border_radius_tiling.left),
 9997                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9998                )
 9999                .when(
10000                    !(tiling.bottom
10001                        || tiling.right
10002                        || border_radius_tiling.bottom
10003                        || border_radius_tiling.right),
10004                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10005                )
10006                .when(
10007                    !(tiling.bottom
10008                        || tiling.left
10009                        || border_radius_tiling.bottom
10010                        || border_radius_tiling.left),
10011                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10012                )
10013                .when(!tiling.top, |div| {
10014                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10015                })
10016                .when(!tiling.bottom, |div| {
10017                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10018                })
10019                .when(!tiling.left, |div| {
10020                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10021                })
10022                .when(!tiling.right, |div| {
10023                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10024                })
10025                .on_mouse_move(move |e, window, cx| {
10026                    let size = window.window_bounds().get_bounds().size;
10027                    let pos = e.position;
10028
10029                    let new_edge =
10030                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10031
10032                    let edge = cx.try_global::<GlobalResizeEdge>();
10033                    if new_edge != edge.map(|edge| edge.0) {
10034                        window
10035                            .window_handle()
10036                            .update(cx, |workspace, _, cx| {
10037                                cx.notify(workspace.entity_id());
10038                            })
10039                            .ok();
10040                    }
10041                })
10042                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10043                    let size = window.window_bounds().get_bounds().size;
10044                    let pos = e.position;
10045
10046                    let edge = match resize_edge(
10047                        pos,
10048                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10049                        size,
10050                        tiling,
10051                    ) {
10052                        Some(value) => value,
10053                        None => return,
10054                    };
10055
10056                    window.start_window_resize(edge);
10057                }),
10058        })
10059        .size_full()
10060        .child(
10061            div()
10062                .cursor(CursorStyle::Arrow)
10063                .map(|div| match decorations {
10064                    Decorations::Server => div,
10065                    Decorations::Client { .. } => div
10066                        .border_color(cx.theme().colors().border)
10067                        .when(
10068                            !(tiling.top
10069                                || tiling.right
10070                                || border_radius_tiling.top
10071                                || border_radius_tiling.right),
10072                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10073                        )
10074                        .when(
10075                            !(tiling.top
10076                                || tiling.left
10077                                || border_radius_tiling.top
10078                                || border_radius_tiling.left),
10079                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10080                        )
10081                        .when(
10082                            !(tiling.bottom
10083                                || tiling.right
10084                                || border_radius_tiling.bottom
10085                                || border_radius_tiling.right),
10086                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10087                        )
10088                        .when(
10089                            !(tiling.bottom
10090                                || tiling.left
10091                                || border_radius_tiling.bottom
10092                                || border_radius_tiling.left),
10093                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10094                        )
10095                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10096                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10097                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10098                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10099                        .when(!tiling.is_tiled(), |div| {
10100                            div.shadow(vec![gpui::BoxShadow {
10101                                color: Hsla {
10102                                    h: 0.,
10103                                    s: 0.,
10104                                    l: 0.,
10105                                    a: 0.4,
10106                                },
10107                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10108                                spread_radius: px(0.),
10109                                offset: point(px(0.0), px(0.0)),
10110                            }])
10111                        }),
10112                })
10113                .on_mouse_move(|_e, _, cx| {
10114                    cx.stop_propagation();
10115                })
10116                .size_full()
10117                .child(element),
10118        )
10119        .map(|div| match decorations {
10120            Decorations::Server => div,
10121            Decorations::Client { tiling, .. } => div.child(
10122                canvas(
10123                    |_bounds, window, _| {
10124                        window.insert_hitbox(
10125                            Bounds::new(
10126                                point(px(0.0), px(0.0)),
10127                                window.window_bounds().get_bounds().size,
10128                            ),
10129                            HitboxBehavior::Normal,
10130                        )
10131                    },
10132                    move |_bounds, hitbox, window, cx| {
10133                        let mouse = window.mouse_position();
10134                        let size = window.window_bounds().get_bounds().size;
10135                        let Some(edge) =
10136                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10137                        else {
10138                            return;
10139                        };
10140                        cx.set_global(GlobalResizeEdge(edge));
10141                        window.set_cursor_style(
10142                            match edge {
10143                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10144                                ResizeEdge::Left | ResizeEdge::Right => {
10145                                    CursorStyle::ResizeLeftRight
10146                                }
10147                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10148                                    CursorStyle::ResizeUpLeftDownRight
10149                                }
10150                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10151                                    CursorStyle::ResizeUpRightDownLeft
10152                                }
10153                            },
10154                            &hitbox,
10155                        );
10156                    },
10157                )
10158                .size_full()
10159                .absolute(),
10160            ),
10161        })
10162}
10163
10164fn resize_edge(
10165    pos: Point<Pixels>,
10166    shadow_size: Pixels,
10167    window_size: Size<Pixels>,
10168    tiling: Tiling,
10169) -> Option<ResizeEdge> {
10170    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10171    if bounds.contains(&pos) {
10172        return None;
10173    }
10174
10175    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10176    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10177    if !tiling.top && top_left_bounds.contains(&pos) {
10178        return Some(ResizeEdge::TopLeft);
10179    }
10180
10181    let top_right_bounds = Bounds::new(
10182        Point::new(window_size.width - corner_size.width, px(0.)),
10183        corner_size,
10184    );
10185    if !tiling.top && top_right_bounds.contains(&pos) {
10186        return Some(ResizeEdge::TopRight);
10187    }
10188
10189    let bottom_left_bounds = Bounds::new(
10190        Point::new(px(0.), window_size.height - corner_size.height),
10191        corner_size,
10192    );
10193    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10194        return Some(ResizeEdge::BottomLeft);
10195    }
10196
10197    let bottom_right_bounds = Bounds::new(
10198        Point::new(
10199            window_size.width - corner_size.width,
10200            window_size.height - corner_size.height,
10201        ),
10202        corner_size,
10203    );
10204    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10205        return Some(ResizeEdge::BottomRight);
10206    }
10207
10208    if !tiling.top && pos.y < shadow_size {
10209        Some(ResizeEdge::Top)
10210    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10211        Some(ResizeEdge::Bottom)
10212    } else if !tiling.left && pos.x < shadow_size {
10213        Some(ResizeEdge::Left)
10214    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10215        Some(ResizeEdge::Right)
10216    } else {
10217        None
10218    }
10219}
10220
10221fn join_pane_into_active(
10222    active_pane: &Entity<Pane>,
10223    pane: &Entity<Pane>,
10224    window: &mut Window,
10225    cx: &mut App,
10226) {
10227    if pane == active_pane {
10228    } else if pane.read(cx).items_len() == 0 {
10229        pane.update(cx, |_, cx| {
10230            cx.emit(pane::Event::Remove {
10231                focus_on_pane: None,
10232            });
10233        })
10234    } else {
10235        move_all_items(pane, active_pane, window, cx);
10236    }
10237}
10238
10239fn move_all_items(
10240    from_pane: &Entity<Pane>,
10241    to_pane: &Entity<Pane>,
10242    window: &mut Window,
10243    cx: &mut App,
10244) {
10245    let destination_is_different = from_pane != to_pane;
10246    let mut moved_items = 0;
10247    for (item_ix, item_handle) in from_pane
10248        .read(cx)
10249        .items()
10250        .enumerate()
10251        .map(|(ix, item)| (ix, item.clone()))
10252        .collect::<Vec<_>>()
10253    {
10254        let ix = item_ix - moved_items;
10255        if destination_is_different {
10256            // Close item from previous pane
10257            from_pane.update(cx, |source, cx| {
10258                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10259            });
10260            moved_items += 1;
10261        }
10262
10263        // This automatically removes duplicate items in the pane
10264        to_pane.update(cx, |destination, cx| {
10265            destination.add_item(item_handle, true, true, None, window, cx);
10266            window.focus(&destination.focus_handle(cx), cx)
10267        });
10268    }
10269}
10270
10271pub fn move_item(
10272    source: &Entity<Pane>,
10273    destination: &Entity<Pane>,
10274    item_id_to_move: EntityId,
10275    destination_index: usize,
10276    activate: bool,
10277    window: &mut Window,
10278    cx: &mut App,
10279) {
10280    let Some((item_ix, item_handle)) = source
10281        .read(cx)
10282        .items()
10283        .enumerate()
10284        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10285        .map(|(ix, item)| (ix, item.clone()))
10286    else {
10287        // Tab was closed during drag
10288        return;
10289    };
10290
10291    if source != destination {
10292        // Close item from previous pane
10293        source.update(cx, |source, cx| {
10294            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10295        });
10296    }
10297
10298    // This automatically removes duplicate items in the pane
10299    destination.update(cx, |destination, cx| {
10300        destination.add_item_inner(
10301            item_handle,
10302            activate,
10303            activate,
10304            activate,
10305            Some(destination_index),
10306            window,
10307            cx,
10308        );
10309        if activate {
10310            window.focus(&destination.focus_handle(cx), cx)
10311        }
10312    });
10313}
10314
10315pub fn move_active_item(
10316    source: &Entity<Pane>,
10317    destination: &Entity<Pane>,
10318    focus_destination: bool,
10319    close_if_empty: bool,
10320    window: &mut Window,
10321    cx: &mut App,
10322) {
10323    if source == destination {
10324        return;
10325    }
10326    let Some(active_item) = source.read(cx).active_item() else {
10327        return;
10328    };
10329    source.update(cx, |source_pane, cx| {
10330        let item_id = active_item.item_id();
10331        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10332        destination.update(cx, |target_pane, cx| {
10333            target_pane.add_item(
10334                active_item,
10335                focus_destination,
10336                focus_destination,
10337                Some(target_pane.items_len()),
10338                window,
10339                cx,
10340            );
10341        });
10342    });
10343}
10344
10345pub fn clone_active_item(
10346    workspace_id: Option<WorkspaceId>,
10347    source: &Entity<Pane>,
10348    destination: &Entity<Pane>,
10349    focus_destination: 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    if !active_item.can_split(cx) {
10360        return;
10361    }
10362    let destination = destination.downgrade();
10363    let task = active_item.clone_on_split(workspace_id, window, cx);
10364    window
10365        .spawn(cx, async move |cx| {
10366            let Some(clone) = task.await else {
10367                return;
10368            };
10369            destination
10370                .update_in(cx, |target_pane, window, cx| {
10371                    target_pane.add_item(
10372                        clone,
10373                        focus_destination,
10374                        focus_destination,
10375                        Some(target_pane.items_len()),
10376                        window,
10377                        cx,
10378                    );
10379                })
10380                .log_err();
10381        })
10382        .detach();
10383}
10384
10385#[derive(Debug)]
10386pub struct WorkspacePosition {
10387    pub window_bounds: Option<WindowBounds>,
10388    pub display: Option<Uuid>,
10389    pub centered_layout: bool,
10390}
10391
10392pub fn remote_workspace_position_from_db(
10393    connection_options: RemoteConnectionOptions,
10394    paths_to_open: &[PathBuf],
10395    cx: &App,
10396) -> Task<Result<WorkspacePosition>> {
10397    let paths = paths_to_open.to_vec();
10398    let db = WorkspaceDb::global(cx);
10399    let kvp = db::kvp::KeyValueStore::global(cx);
10400
10401    cx.background_spawn(async move {
10402        let remote_connection_id = db
10403            .get_or_create_remote_connection(connection_options)
10404            .await
10405            .context("fetching serialized ssh project")?;
10406        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10407
10408        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10409            (Some(WindowBounds::Windowed(bounds)), None)
10410        } else {
10411            let restorable_bounds = serialized_workspace
10412                .as_ref()
10413                .and_then(|workspace| {
10414                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10415                })
10416                .or_else(|| persistence::read_default_window_bounds(&kvp));
10417
10418            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10419                (Some(serialized_bounds), Some(serialized_display))
10420            } else {
10421                (None, None)
10422            }
10423        };
10424
10425        let centered_layout = serialized_workspace
10426            .as_ref()
10427            .map(|w| w.centered_layout)
10428            .unwrap_or(false);
10429
10430        Ok(WorkspacePosition {
10431            window_bounds,
10432            display,
10433            centered_layout,
10434        })
10435    })
10436}
10437
10438pub fn with_active_or_new_workspace(
10439    cx: &mut App,
10440    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10441) {
10442    match cx
10443        .active_window()
10444        .and_then(|w| w.downcast::<MultiWorkspace>())
10445    {
10446        Some(multi_workspace) => {
10447            cx.defer(move |cx| {
10448                multi_workspace
10449                    .update(cx, |multi_workspace, window, cx| {
10450                        let workspace = multi_workspace.workspace().clone();
10451                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10452                    })
10453                    .log_err();
10454            });
10455        }
10456        None => {
10457            let app_state = AppState::global(cx);
10458            open_new(
10459                OpenOptions::default(),
10460                app_state,
10461                cx,
10462                move |workspace, window, cx| f(workspace, window, cx),
10463            )
10464            .detach_and_log_err(cx);
10465        }
10466    }
10467}
10468
10469/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10470/// key. This migration path only runs once per panel per workspace.
10471fn load_legacy_panel_size(
10472    panel_key: &str,
10473    dock_position: DockPosition,
10474    workspace: &Workspace,
10475    cx: &mut App,
10476) -> Option<Pixels> {
10477    #[derive(Deserialize)]
10478    struct LegacyPanelState {
10479        #[serde(default)]
10480        width: Option<Pixels>,
10481        #[serde(default)]
10482        height: Option<Pixels>,
10483    }
10484
10485    let workspace_id = workspace
10486        .database_id()
10487        .map(|id| i64::from(id).to_string())
10488        .or_else(|| workspace.session_id())?;
10489
10490    let legacy_key = match panel_key {
10491        "ProjectPanel" => {
10492            format!("{}-{:?}", "ProjectPanel", workspace_id)
10493        }
10494        "OutlinePanel" => {
10495            format!("{}-{:?}", "OutlinePanel", workspace_id)
10496        }
10497        "GitPanel" => {
10498            format!("{}-{:?}", "GitPanel", workspace_id)
10499        }
10500        "TerminalPanel" => {
10501            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10502        }
10503        _ => return None,
10504    };
10505
10506    let kvp = db::kvp::KeyValueStore::global(cx);
10507    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10508    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10509    let size = match dock_position {
10510        DockPosition::Bottom => state.height,
10511        DockPosition::Left | DockPosition::Right => state.width,
10512    }?;
10513
10514    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10515        .detach_and_log_err(cx);
10516
10517    Some(size)
10518}
10519
10520#[cfg(test)]
10521mod tests {
10522    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10523
10524    use super::*;
10525    use crate::{
10526        dock::{PanelEvent, test::TestPanel},
10527        item::{
10528            ItemBufferKind, ItemEvent,
10529            test::{TestItem, TestProjectItem},
10530        },
10531    };
10532    use fs::FakeFs;
10533    use gpui::{
10534        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10535        UpdateGlobal, VisualTestContext, px,
10536    };
10537    use project::{Project, ProjectEntryId};
10538    use serde_json::json;
10539    use settings::SettingsStore;
10540    use util::path;
10541    use util::rel_path::rel_path;
10542
10543    #[gpui::test]
10544    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10545        init_test(cx);
10546
10547        let fs = FakeFs::new(cx.executor());
10548        let project = Project::test(fs, [], cx).await;
10549        let (workspace, cx) =
10550            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10551
10552        // Adding an item with no ambiguity renders the tab without detail.
10553        let item1 = cx.new(|cx| {
10554            let mut item = TestItem::new(cx);
10555            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10556            item
10557        });
10558        workspace.update_in(cx, |workspace, window, cx| {
10559            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10560        });
10561        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10562
10563        // Adding an item that creates ambiguity increases the level of detail on
10564        // both tabs.
10565        let item2 = cx.new_window_entity(|_window, cx| {
10566            let mut item = TestItem::new(cx);
10567            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10568            item
10569        });
10570        workspace.update_in(cx, |workspace, window, cx| {
10571            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10572        });
10573        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10574        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10575
10576        // Adding an item that creates ambiguity increases the level of detail only
10577        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10578        // we stop at the highest detail available.
10579        let item3 = cx.new(|cx| {
10580            let mut item = TestItem::new(cx);
10581            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10582            item
10583        });
10584        workspace.update_in(cx, |workspace, window, cx| {
10585            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10586        });
10587        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10588        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10589        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10590    }
10591
10592    #[gpui::test]
10593    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10594        init_test(cx);
10595
10596        let fs = FakeFs::new(cx.executor());
10597        fs.insert_tree(
10598            "/root1",
10599            json!({
10600                "one.txt": "",
10601                "two.txt": "",
10602            }),
10603        )
10604        .await;
10605        fs.insert_tree(
10606            "/root2",
10607            json!({
10608                "three.txt": "",
10609            }),
10610        )
10611        .await;
10612
10613        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10614        let (workspace, cx) =
10615            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10616        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10617        let worktree_id = project.update(cx, |project, cx| {
10618            project.worktrees(cx).next().unwrap().read(cx).id()
10619        });
10620
10621        let item1 = cx.new(|cx| {
10622            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10623        });
10624        let item2 = cx.new(|cx| {
10625            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10626        });
10627
10628        // Add an item to an empty pane
10629        workspace.update_in(cx, |workspace, window, cx| {
10630            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10631        });
10632        project.update(cx, |project, cx| {
10633            assert_eq!(
10634                project.active_entry(),
10635                project
10636                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10637                    .map(|e| e.id)
10638            );
10639        });
10640        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10641
10642        // Add a second item to a non-empty pane
10643        workspace.update_in(cx, |workspace, window, cx| {
10644            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10645        });
10646        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10647        project.update(cx, |project, cx| {
10648            assert_eq!(
10649                project.active_entry(),
10650                project
10651                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10652                    .map(|e| e.id)
10653            );
10654        });
10655
10656        // Close the active item
10657        pane.update_in(cx, |pane, window, cx| {
10658            pane.close_active_item(&Default::default(), window, cx)
10659        })
10660        .await
10661        .unwrap();
10662        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10663        project.update(cx, |project, cx| {
10664            assert_eq!(
10665                project.active_entry(),
10666                project
10667                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10668                    .map(|e| e.id)
10669            );
10670        });
10671
10672        // Add a project folder
10673        project
10674            .update(cx, |project, cx| {
10675                project.find_or_create_worktree("root2", true, cx)
10676            })
10677            .await
10678            .unwrap();
10679        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10680
10681        // Remove a project folder
10682        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10683        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10684    }
10685
10686    #[gpui::test]
10687    async fn test_close_window(cx: &mut TestAppContext) {
10688        init_test(cx);
10689
10690        let fs = FakeFs::new(cx.executor());
10691        fs.insert_tree("/root", json!({ "one": "" })).await;
10692
10693        let project = Project::test(fs, ["root".as_ref()], cx).await;
10694        let (workspace, cx) =
10695            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10696
10697        // When there are no dirty items, there's nothing to do.
10698        let item1 = cx.new(TestItem::new);
10699        workspace.update_in(cx, |w, window, cx| {
10700            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10701        });
10702        let task = workspace.update_in(cx, |w, window, cx| {
10703            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10704        });
10705        assert!(task.await.unwrap());
10706
10707        // When there are dirty untitled items, prompt to save each one. If the user
10708        // cancels any prompt, then abort.
10709        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10710        let item3 = cx.new(|cx| {
10711            TestItem::new(cx)
10712                .with_dirty(true)
10713                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10714        });
10715        workspace.update_in(cx, |w, window, cx| {
10716            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10717            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10718        });
10719        let task = workspace.update_in(cx, |w, window, cx| {
10720            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10721        });
10722        cx.executor().run_until_parked();
10723        cx.simulate_prompt_answer("Cancel"); // cancel save all
10724        cx.executor().run_until_parked();
10725        assert!(!cx.has_pending_prompt());
10726        assert!(!task.await.unwrap());
10727    }
10728
10729    #[gpui::test]
10730    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10731        init_test(cx);
10732
10733        let fs = FakeFs::new(cx.executor());
10734        fs.insert_tree("/root", json!({ "one": "" })).await;
10735
10736        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10737        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10738        let multi_workspace_handle =
10739            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10740        cx.run_until_parked();
10741
10742        let workspace_a = multi_workspace_handle
10743            .read_with(cx, |mw, _| mw.workspace().clone())
10744            .unwrap();
10745
10746        let workspace_b = multi_workspace_handle
10747            .update(cx, |mw, window, cx| {
10748                mw.test_add_workspace(project_b, window, cx)
10749            })
10750            .unwrap();
10751
10752        // Activate workspace A
10753        multi_workspace_handle
10754            .update(cx, |mw, window, cx| {
10755                let workspace = mw
10756                    .workspaces()
10757                    .nth(0)
10758                    .expect("no workspace at index 0")
10759                    .clone();
10760                mw.activate(workspace, window, cx);
10761            })
10762            .unwrap();
10763
10764        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10765
10766        // Workspace A has a clean item
10767        let item_a = cx.new(TestItem::new);
10768        workspace_a.update_in(cx, |w, window, cx| {
10769            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10770        });
10771
10772        // Workspace B has a dirty item
10773        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10774        workspace_b.update_in(cx, |w, window, cx| {
10775            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10776        });
10777
10778        // Verify workspace A is active
10779        multi_workspace_handle
10780            .read_with(cx, |mw, _| {
10781                assert_eq!(
10782                    mw.workspaces()
10783                        .position(|workspace| workspace == mw.active_workspace()),
10784                    Some(0)
10785                );
10786            })
10787            .unwrap();
10788
10789        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10790        multi_workspace_handle
10791            .update(cx, |mw, window, cx| {
10792                mw.close_window(&CloseWindow, window, cx);
10793            })
10794            .unwrap();
10795        cx.run_until_parked();
10796
10797        // Workspace B should now be active since it has dirty items that need attention
10798        multi_workspace_handle
10799            .read_with(cx, |mw, _| {
10800                assert_eq!(
10801                    mw.workspaces()
10802                        .position(|workspace| workspace == mw.active_workspace()),
10803                    Some(1),
10804                    "workspace B should be activated when it prompts"
10805                );
10806            })
10807            .unwrap();
10808
10809        // User cancels the save prompt from workspace B
10810        cx.simulate_prompt_answer("Cancel");
10811        cx.run_until_parked();
10812
10813        // Window should still exist because workspace B's close was cancelled
10814        assert!(
10815            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10816            "window should still exist after cancelling one workspace's close"
10817        );
10818    }
10819
10820    #[gpui::test]
10821    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10822        init_test(cx);
10823
10824        // Register TestItem as a serializable item
10825        cx.update(|cx| {
10826            register_serializable_item::<TestItem>(cx);
10827        });
10828
10829        let fs = FakeFs::new(cx.executor());
10830        fs.insert_tree("/root", json!({ "one": "" })).await;
10831
10832        let project = Project::test(fs, ["root".as_ref()], cx).await;
10833        let (workspace, cx) =
10834            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10835
10836        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10837        let item1 = cx.new(|cx| {
10838            TestItem::new(cx)
10839                .with_dirty(true)
10840                .with_serialize(|| Some(Task::ready(Ok(()))))
10841        });
10842        let item2 = cx.new(|cx| {
10843            TestItem::new(cx)
10844                .with_dirty(true)
10845                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10846                .with_serialize(|| Some(Task::ready(Ok(()))))
10847        });
10848        workspace.update_in(cx, |w, window, cx| {
10849            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10850            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10851        });
10852        let task = workspace.update_in(cx, |w, window, cx| {
10853            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10854        });
10855        assert!(task.await.unwrap());
10856    }
10857
10858    #[gpui::test]
10859    async fn test_close_pane_items(cx: &mut TestAppContext) {
10860        init_test(cx);
10861
10862        let fs = FakeFs::new(cx.executor());
10863
10864        let project = Project::test(fs, None, cx).await;
10865        let (workspace, cx) =
10866            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10867
10868        let item1 = cx.new(|cx| {
10869            TestItem::new(cx)
10870                .with_dirty(true)
10871                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10872        });
10873        let item2 = cx.new(|cx| {
10874            TestItem::new(cx)
10875                .with_dirty(true)
10876                .with_conflict(true)
10877                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10878        });
10879        let item3 = cx.new(|cx| {
10880            TestItem::new(cx)
10881                .with_dirty(true)
10882                .with_conflict(true)
10883                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10884        });
10885        let item4 = cx.new(|cx| {
10886            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10887                let project_item = TestProjectItem::new_untitled(cx);
10888                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10889                project_item
10890            }])
10891        });
10892        let pane = workspace.update_in(cx, |workspace, window, cx| {
10893            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10894            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10895            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10896            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10897            workspace.active_pane().clone()
10898        });
10899
10900        let close_items = pane.update_in(cx, |pane, window, cx| {
10901            pane.activate_item(1, true, true, window, cx);
10902            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10903            let item1_id = item1.item_id();
10904            let item3_id = item3.item_id();
10905            let item4_id = item4.item_id();
10906            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10907                [item1_id, item3_id, item4_id].contains(&id)
10908            })
10909        });
10910        cx.executor().run_until_parked();
10911
10912        assert!(cx.has_pending_prompt());
10913        cx.simulate_prompt_answer("Save all");
10914
10915        cx.executor().run_until_parked();
10916
10917        // Item 1 is saved. There's a prompt to save item 3.
10918        pane.update(cx, |pane, cx| {
10919            assert_eq!(item1.read(cx).save_count, 1);
10920            assert_eq!(item1.read(cx).save_as_count, 0);
10921            assert_eq!(item1.read(cx).reload_count, 0);
10922            assert_eq!(pane.items_len(), 3);
10923            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10924        });
10925        assert!(cx.has_pending_prompt());
10926
10927        // Cancel saving item 3.
10928        cx.simulate_prompt_answer("Discard");
10929        cx.executor().run_until_parked();
10930
10931        // Item 3 is reloaded. There's a prompt to save item 4.
10932        pane.update(cx, |pane, cx| {
10933            assert_eq!(item3.read(cx).save_count, 0);
10934            assert_eq!(item3.read(cx).save_as_count, 0);
10935            assert_eq!(item3.read(cx).reload_count, 1);
10936            assert_eq!(pane.items_len(), 2);
10937            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10938        });
10939
10940        // There's a prompt for a path for item 4.
10941        cx.simulate_new_path_selection(|_| Some(Default::default()));
10942        close_items.await.unwrap();
10943
10944        // The requested items are closed.
10945        pane.update(cx, |pane, cx| {
10946            assert_eq!(item4.read(cx).save_count, 0);
10947            assert_eq!(item4.read(cx).save_as_count, 1);
10948            assert_eq!(item4.read(cx).reload_count, 0);
10949            assert_eq!(pane.items_len(), 1);
10950            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10951        });
10952    }
10953
10954    #[gpui::test]
10955    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10956        init_test(cx);
10957
10958        let fs = FakeFs::new(cx.executor());
10959        let project = Project::test(fs, [], cx).await;
10960        let (workspace, cx) =
10961            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10962
10963        // Create several workspace items with single project entries, and two
10964        // workspace items with multiple project entries.
10965        let single_entry_items = (0..=4)
10966            .map(|project_entry_id| {
10967                cx.new(|cx| {
10968                    TestItem::new(cx)
10969                        .with_dirty(true)
10970                        .with_project_items(&[dirty_project_item(
10971                            project_entry_id,
10972                            &format!("{project_entry_id}.txt"),
10973                            cx,
10974                        )])
10975                })
10976            })
10977            .collect::<Vec<_>>();
10978        let item_2_3 = cx.new(|cx| {
10979            TestItem::new(cx)
10980                .with_dirty(true)
10981                .with_buffer_kind(ItemBufferKind::Multibuffer)
10982                .with_project_items(&[
10983                    single_entry_items[2].read(cx).project_items[0].clone(),
10984                    single_entry_items[3].read(cx).project_items[0].clone(),
10985                ])
10986        });
10987        let item_3_4 = cx.new(|cx| {
10988            TestItem::new(cx)
10989                .with_dirty(true)
10990                .with_buffer_kind(ItemBufferKind::Multibuffer)
10991                .with_project_items(&[
10992                    single_entry_items[3].read(cx).project_items[0].clone(),
10993                    single_entry_items[4].read(cx).project_items[0].clone(),
10994                ])
10995        });
10996
10997        // Create two panes that contain the following project entries:
10998        //   left pane:
10999        //     multi-entry items:   (2, 3)
11000        //     single-entry items:  0, 2, 3, 4
11001        //   right pane:
11002        //     single-entry items:  4, 1
11003        //     multi-entry items:   (3, 4)
11004        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11005            let left_pane = workspace.active_pane().clone();
11006            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11007            workspace.add_item_to_active_pane(
11008                single_entry_items[0].boxed_clone(),
11009                None,
11010                true,
11011                window,
11012                cx,
11013            );
11014            workspace.add_item_to_active_pane(
11015                single_entry_items[2].boxed_clone(),
11016                None,
11017                true,
11018                window,
11019                cx,
11020            );
11021            workspace.add_item_to_active_pane(
11022                single_entry_items[3].boxed_clone(),
11023                None,
11024                true,
11025                window,
11026                cx,
11027            );
11028            workspace.add_item_to_active_pane(
11029                single_entry_items[4].boxed_clone(),
11030                None,
11031                true,
11032                window,
11033                cx,
11034            );
11035
11036            let right_pane =
11037                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11038
11039            let boxed_clone = single_entry_items[1].boxed_clone();
11040            let right_pane = window.spawn(cx, async move |cx| {
11041                right_pane.await.inspect(|right_pane| {
11042                    right_pane
11043                        .update_in(cx, |pane, window, cx| {
11044                            pane.add_item(boxed_clone, true, true, None, window, cx);
11045                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11046                        })
11047                        .unwrap();
11048                })
11049            });
11050
11051            (left_pane, right_pane)
11052        });
11053        let right_pane = right_pane.await.unwrap();
11054        cx.focus(&right_pane);
11055
11056        let close = right_pane.update_in(cx, |pane, window, cx| {
11057            pane.close_all_items(&CloseAllItems::default(), window, cx)
11058                .unwrap()
11059        });
11060        cx.executor().run_until_parked();
11061
11062        let msg = cx.pending_prompt().unwrap().0;
11063        assert!(msg.contains("1.txt"));
11064        assert!(!msg.contains("2.txt"));
11065        assert!(!msg.contains("3.txt"));
11066        assert!(!msg.contains("4.txt"));
11067
11068        // With best-effort close, cancelling item 1 keeps it open but items 4
11069        // and (3,4) still close since their entries exist in left pane.
11070        cx.simulate_prompt_answer("Cancel");
11071        close.await;
11072
11073        right_pane.read_with(cx, |pane, _| {
11074            assert_eq!(pane.items_len(), 1);
11075        });
11076
11077        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11078        left_pane
11079            .update_in(cx, |left_pane, window, cx| {
11080                left_pane.close_item_by_id(
11081                    single_entry_items[3].entity_id(),
11082                    SaveIntent::Skip,
11083                    window,
11084                    cx,
11085                )
11086            })
11087            .await
11088            .unwrap();
11089
11090        let close = left_pane.update_in(cx, |pane, window, cx| {
11091            pane.close_all_items(&CloseAllItems::default(), window, cx)
11092                .unwrap()
11093        });
11094        cx.executor().run_until_parked();
11095
11096        let details = cx.pending_prompt().unwrap().1;
11097        assert!(details.contains("0.txt"));
11098        assert!(details.contains("3.txt"));
11099        assert!(details.contains("4.txt"));
11100        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11101        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11102        // assert!(!details.contains("2.txt"));
11103
11104        cx.simulate_prompt_answer("Save all");
11105        cx.executor().run_until_parked();
11106        close.await;
11107
11108        left_pane.read_with(cx, |pane, _| {
11109            assert_eq!(pane.items_len(), 0);
11110        });
11111    }
11112
11113    #[gpui::test]
11114    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11115        init_test(cx);
11116
11117        let fs = FakeFs::new(cx.executor());
11118        let project = Project::test(fs, [], cx).await;
11119        let (workspace, cx) =
11120            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11121        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11122
11123        let item = cx.new(|cx| {
11124            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11125        });
11126        let item_id = item.entity_id();
11127        workspace.update_in(cx, |workspace, window, cx| {
11128            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11129        });
11130
11131        // Autosave on window change.
11132        item.update(cx, |item, cx| {
11133            SettingsStore::update_global(cx, |settings, cx| {
11134                settings.update_user_settings(cx, |settings| {
11135                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11136                })
11137            });
11138            item.is_dirty = true;
11139        });
11140
11141        // Deactivating the window saves the file.
11142        cx.deactivate_window();
11143        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11144
11145        // Re-activating the window doesn't save the file.
11146        cx.update(|window, _| window.activate_window());
11147        cx.executor().run_until_parked();
11148        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11149
11150        // Autosave on focus change.
11151        item.update_in(cx, |item, window, cx| {
11152            cx.focus_self(window);
11153            SettingsStore::update_global(cx, |settings, cx| {
11154                settings.update_user_settings(cx, |settings| {
11155                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11156                })
11157            });
11158            item.is_dirty = true;
11159        });
11160        // Blurring the item saves the file.
11161        item.update_in(cx, |_, window, _| window.blur());
11162        cx.executor().run_until_parked();
11163        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11164
11165        // Deactivating the window still saves the file.
11166        item.update_in(cx, |item, window, cx| {
11167            cx.focus_self(window);
11168            item.is_dirty = true;
11169        });
11170        cx.deactivate_window();
11171        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11172
11173        // Autosave after delay.
11174        item.update(cx, |item, cx| {
11175            SettingsStore::update_global(cx, |settings, cx| {
11176                settings.update_user_settings(cx, |settings| {
11177                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11178                        milliseconds: 500.into(),
11179                    });
11180                })
11181            });
11182            item.is_dirty = true;
11183            cx.emit(ItemEvent::Edit);
11184        });
11185
11186        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11187        cx.executor().advance_clock(Duration::from_millis(250));
11188        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11189
11190        // After delay expires, the file is saved.
11191        cx.executor().advance_clock(Duration::from_millis(250));
11192        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11193
11194        // Autosave after delay, should save earlier than delay if tab is closed
11195        item.update(cx, |item, cx| {
11196            item.is_dirty = true;
11197            cx.emit(ItemEvent::Edit);
11198        });
11199        cx.executor().advance_clock(Duration::from_millis(250));
11200        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11201
11202        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11203        pane.update_in(cx, |pane, window, cx| {
11204            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11205        })
11206        .await
11207        .unwrap();
11208        assert!(!cx.has_pending_prompt());
11209        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11210
11211        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11212        workspace.update_in(cx, |workspace, window, cx| {
11213            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11214        });
11215        item.update_in(cx, |item, _window, cx| {
11216            item.is_dirty = true;
11217            for project_item in &mut item.project_items {
11218                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11219            }
11220        });
11221        cx.run_until_parked();
11222        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11223
11224        // Autosave on focus change, ensuring closing the tab counts as such.
11225        item.update(cx, |item, cx| {
11226            SettingsStore::update_global(cx, |settings, cx| {
11227                settings.update_user_settings(cx, |settings| {
11228                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11229                })
11230            });
11231            item.is_dirty = true;
11232            for project_item in &mut item.project_items {
11233                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11234            }
11235        });
11236
11237        pane.update_in(cx, |pane, window, cx| {
11238            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11239        })
11240        .await
11241        .unwrap();
11242        assert!(!cx.has_pending_prompt());
11243        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11244
11245        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11246        workspace.update_in(cx, |workspace, window, cx| {
11247            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11248        });
11249        item.update_in(cx, |item, window, cx| {
11250            item.project_items[0].update(cx, |item, _| {
11251                item.entry_id = None;
11252            });
11253            item.is_dirty = true;
11254            window.blur();
11255        });
11256        cx.run_until_parked();
11257        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11258
11259        // Ensure autosave is prevented for deleted files also when closing the buffer.
11260        let _close_items = pane.update_in(cx, |pane, window, cx| {
11261            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11262        });
11263        cx.run_until_parked();
11264        assert!(cx.has_pending_prompt());
11265        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11266    }
11267
11268    #[gpui::test]
11269    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11270        init_test(cx);
11271
11272        let fs = FakeFs::new(cx.executor());
11273        let project = Project::test(fs, [], cx).await;
11274        let (workspace, cx) =
11275            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11276
11277        // Create a multibuffer-like item with two child focus handles,
11278        // simulating individual buffer editors within a multibuffer.
11279        let item = cx.new(|cx| {
11280            TestItem::new(cx)
11281                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11282                .with_child_focus_handles(2, cx)
11283        });
11284        workspace.update_in(cx, |workspace, window, cx| {
11285            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11286        });
11287
11288        // Set autosave to OnFocusChange and focus the first child handle,
11289        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11290        item.update_in(cx, |item, window, cx| {
11291            SettingsStore::update_global(cx, |settings, cx| {
11292                settings.update_user_settings(cx, |settings| {
11293                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11294                })
11295            });
11296            item.is_dirty = true;
11297            window.focus(&item.child_focus_handles[0], cx);
11298        });
11299        cx.executor().run_until_parked();
11300        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11301
11302        // Moving focus from one child to another within the same item should
11303        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11304        item.update_in(cx, |item, window, cx| {
11305            window.focus(&item.child_focus_handles[1], cx);
11306        });
11307        cx.executor().run_until_parked();
11308        item.read_with(cx, |item, _| {
11309            assert_eq!(
11310                item.save_count, 0,
11311                "Switching focus between children within the same item should not autosave"
11312            );
11313        });
11314
11315        // Blurring the item saves the file. This is the core regression scenario:
11316        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11317        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11318        // the leaf is always a child focus handle, so `on_blur` never detected
11319        // focus leaving the item.
11320        item.update_in(cx, |_, window, _| window.blur());
11321        cx.executor().run_until_parked();
11322        item.read_with(cx, |item, _| {
11323            assert_eq!(
11324                item.save_count, 1,
11325                "Blurring should trigger autosave when focus was on a child of the item"
11326            );
11327        });
11328
11329        // Deactivating the window should also trigger autosave when a child of
11330        // the multibuffer item currently owns focus.
11331        item.update_in(cx, |item, window, cx| {
11332            item.is_dirty = true;
11333            window.focus(&item.child_focus_handles[0], cx);
11334        });
11335        cx.executor().run_until_parked();
11336        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11337
11338        cx.deactivate_window();
11339        item.read_with(cx, |item, _| {
11340            assert_eq!(
11341                item.save_count, 2,
11342                "Deactivating window should trigger autosave when focus was on a child"
11343            );
11344        });
11345    }
11346
11347    #[gpui::test]
11348    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11349        init_test(cx);
11350
11351        let fs = FakeFs::new(cx.executor());
11352
11353        let project = Project::test(fs, [], cx).await;
11354        let (workspace, cx) =
11355            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11356
11357        let item = cx.new(|cx| {
11358            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11359        });
11360        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11361        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11362        let toolbar_notify_count = Rc::new(RefCell::new(0));
11363
11364        workspace.update_in(cx, |workspace, window, cx| {
11365            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11366            let toolbar_notification_count = toolbar_notify_count.clone();
11367            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11368                *toolbar_notification_count.borrow_mut() += 1
11369            })
11370            .detach();
11371        });
11372
11373        pane.read_with(cx, |pane, _| {
11374            assert!(!pane.can_navigate_backward());
11375            assert!(!pane.can_navigate_forward());
11376        });
11377
11378        item.update_in(cx, |item, _, cx| {
11379            item.set_state("one".to_string(), cx);
11380        });
11381
11382        // Toolbar must be notified to re-render the navigation buttons
11383        assert_eq!(*toolbar_notify_count.borrow(), 1);
11384
11385        pane.read_with(cx, |pane, _| {
11386            assert!(pane.can_navigate_backward());
11387            assert!(!pane.can_navigate_forward());
11388        });
11389
11390        workspace
11391            .update_in(cx, |workspace, window, cx| {
11392                workspace.go_back(pane.downgrade(), window, cx)
11393            })
11394            .await
11395            .unwrap();
11396
11397        assert_eq!(*toolbar_notify_count.borrow(), 2);
11398        pane.read_with(cx, |pane, _| {
11399            assert!(!pane.can_navigate_backward());
11400            assert!(pane.can_navigate_forward());
11401        });
11402    }
11403
11404    /// Tests that the navigation history deduplicates entries for the same item.
11405    ///
11406    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11407    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11408    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11409    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11410    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11411    ///
11412    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11413    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11414    #[gpui::test]
11415    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11416        init_test(cx);
11417
11418        let fs = FakeFs::new(cx.executor());
11419        let project = Project::test(fs, [], cx).await;
11420        let (workspace, cx) =
11421            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11422
11423        let item_a = cx.new(|cx| {
11424            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11425        });
11426        let item_b = cx.new(|cx| {
11427            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11428        });
11429        let item_c = cx.new(|cx| {
11430            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11431        });
11432
11433        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11434
11435        workspace.update_in(cx, |workspace, window, cx| {
11436            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11437            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11438            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11439        });
11440
11441        workspace.update_in(cx, |workspace, window, cx| {
11442            workspace.activate_item(&item_a, false, false, window, cx);
11443        });
11444        cx.run_until_parked();
11445
11446        workspace.update_in(cx, |workspace, window, cx| {
11447            workspace.activate_item(&item_b, false, false, window, cx);
11448        });
11449        cx.run_until_parked();
11450
11451        workspace.update_in(cx, |workspace, window, cx| {
11452            workspace.activate_item(&item_a, false, false, window, cx);
11453        });
11454        cx.run_until_parked();
11455
11456        workspace.update_in(cx, |workspace, window, cx| {
11457            workspace.activate_item(&item_b, false, false, window, cx);
11458        });
11459        cx.run_until_parked();
11460
11461        workspace.update_in(cx, |workspace, window, cx| {
11462            workspace.activate_item(&item_a, false, false, window, cx);
11463        });
11464        cx.run_until_parked();
11465
11466        workspace.update_in(cx, |workspace, window, cx| {
11467            workspace.activate_item(&item_b, false, false, window, cx);
11468        });
11469        cx.run_until_parked();
11470
11471        workspace.update_in(cx, |workspace, window, cx| {
11472            workspace.activate_item(&item_c, false, false, window, cx);
11473        });
11474        cx.run_until_parked();
11475
11476        let backward_count = pane.read_with(cx, |pane, cx| {
11477            let mut count = 0;
11478            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11479                count += 1;
11480            });
11481            count
11482        });
11483        assert!(
11484            backward_count <= 4,
11485            "Should have at most 4 entries, got {}",
11486            backward_count
11487        );
11488
11489        workspace
11490            .update_in(cx, |workspace, window, cx| {
11491                workspace.go_back(pane.downgrade(), window, cx)
11492            })
11493            .await
11494            .unwrap();
11495
11496        let active_item = workspace.read_with(cx, |workspace, cx| {
11497            workspace.active_item(cx).unwrap().item_id()
11498        });
11499        assert_eq!(
11500            active_item,
11501            item_b.entity_id(),
11502            "After first go_back, should be at item B"
11503        );
11504
11505        workspace
11506            .update_in(cx, |workspace, window, cx| {
11507                workspace.go_back(pane.downgrade(), window, cx)
11508            })
11509            .await
11510            .unwrap();
11511
11512        let active_item = workspace.read_with(cx, |workspace, cx| {
11513            workspace.active_item(cx).unwrap().item_id()
11514        });
11515        assert_eq!(
11516            active_item,
11517            item_a.entity_id(),
11518            "After second go_back, should be at item A"
11519        );
11520
11521        pane.read_with(cx, |pane, _| {
11522            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11523        });
11524    }
11525
11526    #[gpui::test]
11527    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11528        init_test(cx);
11529        let fs = FakeFs::new(cx.executor());
11530        let project = Project::test(fs, [], cx).await;
11531        let (multi_workspace, cx) =
11532            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11533        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11534
11535        workspace.update_in(cx, |workspace, window, cx| {
11536            let first_item = cx.new(|cx| {
11537                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11538            });
11539            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11540            workspace.split_pane(
11541                workspace.active_pane().clone(),
11542                SplitDirection::Right,
11543                window,
11544                cx,
11545            );
11546            workspace.split_pane(
11547                workspace.active_pane().clone(),
11548                SplitDirection::Right,
11549                window,
11550                cx,
11551            );
11552        });
11553
11554        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11555            let panes = workspace.center.panes();
11556            assert!(panes.len() >= 2);
11557            (
11558                panes.first().expect("at least one pane").entity_id(),
11559                panes.last().expect("at least one pane").entity_id(),
11560            )
11561        });
11562
11563        workspace.update_in(cx, |workspace, window, cx| {
11564            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11565        });
11566        workspace.update(cx, |workspace, _| {
11567            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11568            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11569        });
11570
11571        cx.dispatch_action(ActivateLastPane);
11572
11573        workspace.update(cx, |workspace, _| {
11574            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11575        });
11576    }
11577
11578    #[gpui::test]
11579    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11580        init_test(cx);
11581        let fs = FakeFs::new(cx.executor());
11582
11583        let project = Project::test(fs, [], cx).await;
11584        let (workspace, cx) =
11585            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11586
11587        let panel = workspace.update_in(cx, |workspace, window, cx| {
11588            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11589            workspace.add_panel(panel.clone(), window, cx);
11590
11591            workspace
11592                .right_dock()
11593                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11594
11595            panel
11596        });
11597
11598        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11599        pane.update_in(cx, |pane, window, cx| {
11600            let item = cx.new(TestItem::new);
11601            pane.add_item(Box::new(item), true, true, None, window, cx);
11602        });
11603
11604        // Transfer focus from center to panel
11605        workspace.update_in(cx, |workspace, window, cx| {
11606            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11607        });
11608
11609        workspace.update_in(cx, |workspace, window, cx| {
11610            assert!(workspace.right_dock().read(cx).is_open());
11611            assert!(!panel.is_zoomed(window, cx));
11612            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11613        });
11614
11615        // Transfer focus from panel to center
11616        workspace.update_in(cx, |workspace, window, cx| {
11617            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11618        });
11619
11620        workspace.update_in(cx, |workspace, window, cx| {
11621            assert!(workspace.right_dock().read(cx).is_open());
11622            assert!(!panel.is_zoomed(window, cx));
11623            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11624            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11625        });
11626
11627        // Close the dock
11628        workspace.update_in(cx, |workspace, window, cx| {
11629            workspace.toggle_dock(DockPosition::Right, window, cx);
11630        });
11631
11632        workspace.update_in(cx, |workspace, window, cx| {
11633            assert!(!workspace.right_dock().read(cx).is_open());
11634            assert!(!panel.is_zoomed(window, cx));
11635            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11636            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11637        });
11638
11639        // Open the dock
11640        workspace.update_in(cx, |workspace, window, cx| {
11641            workspace.toggle_dock(DockPosition::Right, window, cx);
11642        });
11643
11644        workspace.update_in(cx, |workspace, window, cx| {
11645            assert!(workspace.right_dock().read(cx).is_open());
11646            assert!(!panel.is_zoomed(window, cx));
11647            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11648        });
11649
11650        // Focus and zoom panel
11651        panel.update_in(cx, |panel, window, cx| {
11652            cx.focus_self(window);
11653            panel.set_zoomed(true, window, cx)
11654        });
11655
11656        workspace.update_in(cx, |workspace, window, cx| {
11657            assert!(workspace.right_dock().read(cx).is_open());
11658            assert!(panel.is_zoomed(window, cx));
11659            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11660        });
11661
11662        // Transfer focus to the center closes the dock
11663        workspace.update_in(cx, |workspace, window, cx| {
11664            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11665        });
11666
11667        workspace.update_in(cx, |workspace, window, cx| {
11668            assert!(!workspace.right_dock().read(cx).is_open());
11669            assert!(panel.is_zoomed(window, cx));
11670            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11671        });
11672
11673        // Transferring focus back to the panel keeps it zoomed
11674        workspace.update_in(cx, |workspace, window, cx| {
11675            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11676        });
11677
11678        workspace.update_in(cx, |workspace, window, cx| {
11679            assert!(workspace.right_dock().read(cx).is_open());
11680            assert!(panel.is_zoomed(window, cx));
11681            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11682        });
11683
11684        // Close the dock while it is zoomed
11685        workspace.update_in(cx, |workspace, window, cx| {
11686            workspace.toggle_dock(DockPosition::Right, window, cx)
11687        });
11688
11689        workspace.update_in(cx, |workspace, window, cx| {
11690            assert!(!workspace.right_dock().read(cx).is_open());
11691            assert!(panel.is_zoomed(window, cx));
11692            assert!(workspace.zoomed.is_none());
11693            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11694        });
11695
11696        // Opening the dock, when it's zoomed, retains focus
11697        workspace.update_in(cx, |workspace, window, cx| {
11698            workspace.toggle_dock(DockPosition::Right, window, cx)
11699        });
11700
11701        workspace.update_in(cx, |workspace, window, cx| {
11702            assert!(workspace.right_dock().read(cx).is_open());
11703            assert!(panel.is_zoomed(window, cx));
11704            assert!(workspace.zoomed.is_some());
11705            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11706        });
11707
11708        // Unzoom and close the panel, zoom the active pane.
11709        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11710        workspace.update_in(cx, |workspace, window, cx| {
11711            workspace.toggle_dock(DockPosition::Right, window, cx)
11712        });
11713        pane.update_in(cx, |pane, window, cx| {
11714            pane.toggle_zoom(&Default::default(), window, cx)
11715        });
11716
11717        // Opening a dock unzooms the pane.
11718        workspace.update_in(cx, |workspace, window, cx| {
11719            workspace.toggle_dock(DockPosition::Right, window, cx)
11720        });
11721        workspace.update_in(cx, |workspace, window, cx| {
11722            let pane = pane.read(cx);
11723            assert!(!pane.is_zoomed());
11724            assert!(!pane.focus_handle(cx).is_focused(window));
11725            assert!(workspace.right_dock().read(cx).is_open());
11726            assert!(workspace.zoomed.is_none());
11727        });
11728    }
11729
11730    #[gpui::test]
11731    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11732        init_test(cx);
11733        let fs = FakeFs::new(cx.executor());
11734
11735        let project = Project::test(fs, [], cx).await;
11736        let (workspace, cx) =
11737            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11738
11739        let panel = workspace.update_in(cx, |workspace, window, cx| {
11740            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11741            workspace.add_panel(panel.clone(), window, cx);
11742            panel
11743        });
11744
11745        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11746        pane.update_in(cx, |pane, window, cx| {
11747            let item = cx.new(TestItem::new);
11748            pane.add_item(Box::new(item), true, true, None, window, cx);
11749        });
11750
11751        // Enable close_panel_on_toggle
11752        cx.update_global(|store: &mut SettingsStore, cx| {
11753            store.update_user_settings(cx, |settings| {
11754                settings.workspace.close_panel_on_toggle = Some(true);
11755            });
11756        });
11757
11758        // Panel starts closed. Toggling should open and focus it.
11759        workspace.update_in(cx, |workspace, window, cx| {
11760            assert!(!workspace.right_dock().read(cx).is_open());
11761            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11762        });
11763
11764        workspace.update_in(cx, |workspace, window, cx| {
11765            assert!(
11766                workspace.right_dock().read(cx).is_open(),
11767                "Dock should be open after toggling from center"
11768            );
11769            assert!(
11770                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11771                "Panel should be focused after toggling from center"
11772            );
11773        });
11774
11775        // Panel is open and focused. Toggling should close the panel and
11776        // return focus to the center.
11777        workspace.update_in(cx, |workspace, window, cx| {
11778            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11779        });
11780
11781        workspace.update_in(cx, |workspace, window, cx| {
11782            assert!(
11783                !workspace.right_dock().read(cx).is_open(),
11784                "Dock should be closed after toggling from focused panel"
11785            );
11786            assert!(
11787                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11788                "Panel should not be focused after toggling from focused panel"
11789            );
11790        });
11791
11792        // Open the dock and focus something else so the panel is open but not
11793        // focused. Toggling should focus the panel (not close it).
11794        workspace.update_in(cx, |workspace, window, cx| {
11795            workspace
11796                .right_dock()
11797                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11798            window.focus(&pane.read(cx).focus_handle(cx), cx);
11799        });
11800
11801        workspace.update_in(cx, |workspace, window, cx| {
11802            assert!(workspace.right_dock().read(cx).is_open());
11803            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11804            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11805        });
11806
11807        workspace.update_in(cx, |workspace, window, cx| {
11808            assert!(
11809                workspace.right_dock().read(cx).is_open(),
11810                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11811            );
11812            assert!(
11813                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11814                "Panel should be focused after toggling an open-but-unfocused panel"
11815            );
11816        });
11817
11818        // Now disable the setting and verify the original behavior: toggling
11819        // from a focused panel moves focus to center but leaves the dock open.
11820        cx.update_global(|store: &mut SettingsStore, cx| {
11821            store.update_user_settings(cx, |settings| {
11822                settings.workspace.close_panel_on_toggle = Some(false);
11823            });
11824        });
11825
11826        workspace.update_in(cx, |workspace, window, cx| {
11827            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11828        });
11829
11830        workspace.update_in(cx, |workspace, window, cx| {
11831            assert!(
11832                workspace.right_dock().read(cx).is_open(),
11833                "Dock should remain open when setting is disabled"
11834            );
11835            assert!(
11836                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11837                "Panel should not be focused after toggling with setting disabled"
11838            );
11839        });
11840    }
11841
11842    #[gpui::test]
11843    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11844        init_test(cx);
11845        let fs = FakeFs::new(cx.executor());
11846
11847        let project = Project::test(fs, [], cx).await;
11848        let (workspace, cx) =
11849            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11850
11851        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11852            workspace.active_pane().clone()
11853        });
11854
11855        // Add an item to the pane so it can be zoomed
11856        workspace.update_in(cx, |workspace, window, cx| {
11857            let item = cx.new(TestItem::new);
11858            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11859        });
11860
11861        // Initially not zoomed
11862        workspace.update_in(cx, |workspace, _window, cx| {
11863            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11864            assert!(
11865                workspace.zoomed.is_none(),
11866                "Workspace should track no zoomed pane"
11867            );
11868            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11869        });
11870
11871        // Zoom In
11872        pane.update_in(cx, |pane, window, cx| {
11873            pane.zoom_in(&crate::ZoomIn, window, cx);
11874        });
11875
11876        workspace.update_in(cx, |workspace, window, cx| {
11877            assert!(
11878                pane.read(cx).is_zoomed(),
11879                "Pane should be zoomed after ZoomIn"
11880            );
11881            assert!(
11882                workspace.zoomed.is_some(),
11883                "Workspace should track the zoomed pane"
11884            );
11885            assert!(
11886                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11887                "ZoomIn should focus the pane"
11888            );
11889        });
11890
11891        // Zoom In again is a no-op
11892        pane.update_in(cx, |pane, window, cx| {
11893            pane.zoom_in(&crate::ZoomIn, window, cx);
11894        });
11895
11896        workspace.update_in(cx, |workspace, window, cx| {
11897            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11898            assert!(
11899                workspace.zoomed.is_some(),
11900                "Workspace still tracks zoomed pane"
11901            );
11902            assert!(
11903                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11904                "Pane remains focused after repeated ZoomIn"
11905            );
11906        });
11907
11908        // Zoom Out
11909        pane.update_in(cx, |pane, window, cx| {
11910            pane.zoom_out(&crate::ZoomOut, window, cx);
11911        });
11912
11913        workspace.update_in(cx, |workspace, _window, cx| {
11914            assert!(
11915                !pane.read(cx).is_zoomed(),
11916                "Pane should unzoom after ZoomOut"
11917            );
11918            assert!(
11919                workspace.zoomed.is_none(),
11920                "Workspace clears zoom tracking after ZoomOut"
11921            );
11922        });
11923
11924        // Zoom Out again is a no-op
11925        pane.update_in(cx, |pane, window, cx| {
11926            pane.zoom_out(&crate::ZoomOut, window, cx);
11927        });
11928
11929        workspace.update_in(cx, |workspace, _window, cx| {
11930            assert!(
11931                !pane.read(cx).is_zoomed(),
11932                "Second ZoomOut keeps pane unzoomed"
11933            );
11934            assert!(
11935                workspace.zoomed.is_none(),
11936                "Workspace remains without zoomed pane"
11937            );
11938        });
11939    }
11940
11941    #[gpui::test]
11942    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11943        init_test(cx);
11944        let fs = FakeFs::new(cx.executor());
11945
11946        let project = Project::test(fs, [], cx).await;
11947        let (workspace, cx) =
11948            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11949        workspace.update_in(cx, |workspace, window, cx| {
11950            // Open two docks
11951            let left_dock = workspace.dock_at_position(DockPosition::Left);
11952            let right_dock = workspace.dock_at_position(DockPosition::Right);
11953
11954            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11955            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11956
11957            assert!(left_dock.read(cx).is_open());
11958            assert!(right_dock.read(cx).is_open());
11959        });
11960
11961        workspace.update_in(cx, |workspace, window, cx| {
11962            // Toggle all docks - should close both
11963            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11964
11965            let left_dock = workspace.dock_at_position(DockPosition::Left);
11966            let right_dock = workspace.dock_at_position(DockPosition::Right);
11967            assert!(!left_dock.read(cx).is_open());
11968            assert!(!right_dock.read(cx).is_open());
11969        });
11970
11971        workspace.update_in(cx, |workspace, window, cx| {
11972            // Toggle again - should reopen both
11973            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11974
11975            let left_dock = workspace.dock_at_position(DockPosition::Left);
11976            let right_dock = workspace.dock_at_position(DockPosition::Right);
11977            assert!(left_dock.read(cx).is_open());
11978            assert!(right_dock.read(cx).is_open());
11979        });
11980    }
11981
11982    #[gpui::test]
11983    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11984        init_test(cx);
11985        let fs = FakeFs::new(cx.executor());
11986
11987        let project = Project::test(fs, [], cx).await;
11988        let (workspace, cx) =
11989            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11990        workspace.update_in(cx, |workspace, window, cx| {
11991            // Open two docks
11992            let left_dock = workspace.dock_at_position(DockPosition::Left);
11993            let right_dock = workspace.dock_at_position(DockPosition::Right);
11994
11995            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11996            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11997
11998            assert!(left_dock.read(cx).is_open());
11999            assert!(right_dock.read(cx).is_open());
12000        });
12001
12002        workspace.update_in(cx, |workspace, window, cx| {
12003            // Close them manually
12004            workspace.toggle_dock(DockPosition::Left, window, cx);
12005            workspace.toggle_dock(DockPosition::Right, window, cx);
12006
12007            let left_dock = workspace.dock_at_position(DockPosition::Left);
12008            let right_dock = workspace.dock_at_position(DockPosition::Right);
12009            assert!(!left_dock.read(cx).is_open());
12010            assert!(!right_dock.read(cx).is_open());
12011        });
12012
12013        workspace.update_in(cx, |workspace, window, cx| {
12014            // Toggle all docks - only last closed (right dock) should reopen
12015            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12016
12017            let left_dock = workspace.dock_at_position(DockPosition::Left);
12018            let right_dock = workspace.dock_at_position(DockPosition::Right);
12019            assert!(!left_dock.read(cx).is_open());
12020            assert!(right_dock.read(cx).is_open());
12021        });
12022    }
12023
12024    #[gpui::test]
12025    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12026        init_test(cx);
12027        let fs = FakeFs::new(cx.executor());
12028        let project = Project::test(fs, [], cx).await;
12029        let (multi_workspace, cx) =
12030            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12031        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12032
12033        // Open two docks (left and right) with one panel each
12034        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12035            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12036            workspace.add_panel(left_panel.clone(), window, cx);
12037
12038            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12039            workspace.add_panel(right_panel.clone(), window, cx);
12040
12041            workspace.toggle_dock(DockPosition::Left, window, cx);
12042            workspace.toggle_dock(DockPosition::Right, window, cx);
12043
12044            // Verify initial state
12045            assert!(
12046                workspace.left_dock().read(cx).is_open(),
12047                "Left dock should be open"
12048            );
12049            assert_eq!(
12050                workspace
12051                    .left_dock()
12052                    .read(cx)
12053                    .visible_panel()
12054                    .unwrap()
12055                    .panel_id(),
12056                left_panel.panel_id(),
12057                "Left panel should be visible in left dock"
12058            );
12059            assert!(
12060                workspace.right_dock().read(cx).is_open(),
12061                "Right dock should be open"
12062            );
12063            assert_eq!(
12064                workspace
12065                    .right_dock()
12066                    .read(cx)
12067                    .visible_panel()
12068                    .unwrap()
12069                    .panel_id(),
12070                right_panel.panel_id(),
12071                "Right panel should be visible in right dock"
12072            );
12073            assert!(
12074                !workspace.bottom_dock().read(cx).is_open(),
12075                "Bottom dock should be closed"
12076            );
12077
12078            (left_panel, right_panel)
12079        });
12080
12081        // Focus the left panel and move it to the next position (bottom dock)
12082        workspace.update_in(cx, |workspace, window, cx| {
12083            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12084            assert!(
12085                left_panel.read(cx).focus_handle(cx).is_focused(window),
12086                "Left panel should be focused"
12087            );
12088        });
12089
12090        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12091
12092        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12093        workspace.update(cx, |workspace, cx| {
12094            assert!(
12095                !workspace.left_dock().read(cx).is_open(),
12096                "Left dock should be closed"
12097            );
12098            assert!(
12099                workspace.bottom_dock().read(cx).is_open(),
12100                "Bottom dock should now be open"
12101            );
12102            assert_eq!(
12103                left_panel.read(cx).position,
12104                DockPosition::Bottom,
12105                "Left panel should now be in the bottom dock"
12106            );
12107            assert_eq!(
12108                workspace
12109                    .bottom_dock()
12110                    .read(cx)
12111                    .visible_panel()
12112                    .unwrap()
12113                    .panel_id(),
12114                left_panel.panel_id(),
12115                "Left panel should be the visible panel in the bottom dock"
12116            );
12117        });
12118
12119        // Toggle all docks off
12120        workspace.update_in(cx, |workspace, window, cx| {
12121            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12122            assert!(
12123                !workspace.left_dock().read(cx).is_open(),
12124                "Left dock should be closed"
12125            );
12126            assert!(
12127                !workspace.right_dock().read(cx).is_open(),
12128                "Right dock should be closed"
12129            );
12130            assert!(
12131                !workspace.bottom_dock().read(cx).is_open(),
12132                "Bottom dock should be closed"
12133            );
12134        });
12135
12136        // Toggle all docks back on and verify positions are restored
12137        workspace.update_in(cx, |workspace, window, cx| {
12138            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12139            assert!(
12140                !workspace.left_dock().read(cx).is_open(),
12141                "Left dock should remain closed"
12142            );
12143            assert!(
12144                workspace.right_dock().read(cx).is_open(),
12145                "Right dock should remain open"
12146            );
12147            assert!(
12148                workspace.bottom_dock().read(cx).is_open(),
12149                "Bottom dock should remain open"
12150            );
12151            assert_eq!(
12152                left_panel.read(cx).position,
12153                DockPosition::Bottom,
12154                "Left panel should remain in the bottom dock"
12155            );
12156            assert_eq!(
12157                right_panel.read(cx).position,
12158                DockPosition::Right,
12159                "Right panel should remain in the right dock"
12160            );
12161            assert_eq!(
12162                workspace
12163                    .bottom_dock()
12164                    .read(cx)
12165                    .visible_panel()
12166                    .unwrap()
12167                    .panel_id(),
12168                left_panel.panel_id(),
12169                "Left panel should be the visible panel in the right dock"
12170            );
12171        });
12172    }
12173
12174    #[gpui::test]
12175    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12176        init_test(cx);
12177
12178        let fs = FakeFs::new(cx.executor());
12179
12180        let project = Project::test(fs, None, cx).await;
12181        let (workspace, cx) =
12182            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12183
12184        // Let's arrange the panes like this:
12185        //
12186        // +-----------------------+
12187        // |         top           |
12188        // +------+--------+-------+
12189        // | left | center | right |
12190        // +------+--------+-------+
12191        // |        bottom         |
12192        // +-----------------------+
12193
12194        let top_item = cx.new(|cx| {
12195            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12196        });
12197        let bottom_item = cx.new(|cx| {
12198            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12199        });
12200        let left_item = cx.new(|cx| {
12201            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12202        });
12203        let right_item = cx.new(|cx| {
12204            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12205        });
12206        let center_item = cx.new(|cx| {
12207            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12208        });
12209
12210        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12211            let top_pane_id = workspace.active_pane().entity_id();
12212            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12213            workspace.split_pane(
12214                workspace.active_pane().clone(),
12215                SplitDirection::Down,
12216                window,
12217                cx,
12218            );
12219            top_pane_id
12220        });
12221        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12222            let bottom_pane_id = workspace.active_pane().entity_id();
12223            workspace.add_item_to_active_pane(
12224                Box::new(bottom_item.clone()),
12225                None,
12226                false,
12227                window,
12228                cx,
12229            );
12230            workspace.split_pane(
12231                workspace.active_pane().clone(),
12232                SplitDirection::Up,
12233                window,
12234                cx,
12235            );
12236            bottom_pane_id
12237        });
12238        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12239            let left_pane_id = workspace.active_pane().entity_id();
12240            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12241            workspace.split_pane(
12242                workspace.active_pane().clone(),
12243                SplitDirection::Right,
12244                window,
12245                cx,
12246            );
12247            left_pane_id
12248        });
12249        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12250            let right_pane_id = workspace.active_pane().entity_id();
12251            workspace.add_item_to_active_pane(
12252                Box::new(right_item.clone()),
12253                None,
12254                false,
12255                window,
12256                cx,
12257            );
12258            workspace.split_pane(
12259                workspace.active_pane().clone(),
12260                SplitDirection::Left,
12261                window,
12262                cx,
12263            );
12264            right_pane_id
12265        });
12266        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12267            let center_pane_id = workspace.active_pane().entity_id();
12268            workspace.add_item_to_active_pane(
12269                Box::new(center_item.clone()),
12270                None,
12271                false,
12272                window,
12273                cx,
12274            );
12275            center_pane_id
12276        });
12277        cx.executor().run_until_parked();
12278
12279        workspace.update_in(cx, |workspace, window, cx| {
12280            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12281
12282            // Join into next from center pane into right
12283            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12284        });
12285
12286        workspace.update_in(cx, |workspace, window, cx| {
12287            let active_pane = workspace.active_pane();
12288            assert_eq!(right_pane_id, active_pane.entity_id());
12289            assert_eq!(2, active_pane.read(cx).items_len());
12290            let item_ids_in_pane =
12291                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12292            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12293            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12294
12295            // Join into next from right pane into bottom
12296            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12297        });
12298
12299        workspace.update_in(cx, |workspace, window, cx| {
12300            let active_pane = workspace.active_pane();
12301            assert_eq!(bottom_pane_id, active_pane.entity_id());
12302            assert_eq!(3, active_pane.read(cx).items_len());
12303            let item_ids_in_pane =
12304                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12305            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12306            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12307            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12308
12309            // Join into next from bottom pane into left
12310            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12311        });
12312
12313        workspace.update_in(cx, |workspace, window, cx| {
12314            let active_pane = workspace.active_pane();
12315            assert_eq!(left_pane_id, active_pane.entity_id());
12316            assert_eq!(4, active_pane.read(cx).items_len());
12317            let item_ids_in_pane =
12318                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12319            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12320            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12321            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12322            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12323
12324            // Join into next from left pane into top
12325            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12326        });
12327
12328        workspace.update_in(cx, |workspace, window, cx| {
12329            let active_pane = workspace.active_pane();
12330            assert_eq!(top_pane_id, active_pane.entity_id());
12331            assert_eq!(5, active_pane.read(cx).items_len());
12332            let item_ids_in_pane =
12333                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12334            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12335            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12336            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12337            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12338            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12339
12340            // Single pane left: no-op
12341            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12342        });
12343
12344        workspace.update(cx, |workspace, _cx| {
12345            let active_pane = workspace.active_pane();
12346            assert_eq!(top_pane_id, active_pane.entity_id());
12347        });
12348    }
12349
12350    fn add_an_item_to_active_pane(
12351        cx: &mut VisualTestContext,
12352        workspace: &Entity<Workspace>,
12353        item_id: u64,
12354    ) -> Entity<TestItem> {
12355        let item = cx.new(|cx| {
12356            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12357                item_id,
12358                "item{item_id}.txt",
12359                cx,
12360            )])
12361        });
12362        workspace.update_in(cx, |workspace, window, cx| {
12363            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12364        });
12365        item
12366    }
12367
12368    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12369        workspace.update_in(cx, |workspace, window, cx| {
12370            workspace.split_pane(
12371                workspace.active_pane().clone(),
12372                SplitDirection::Right,
12373                window,
12374                cx,
12375            )
12376        })
12377    }
12378
12379    #[gpui::test]
12380    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12381        init_test(cx);
12382        let fs = FakeFs::new(cx.executor());
12383        let project = Project::test(fs, None, cx).await;
12384        let (workspace, cx) =
12385            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12386
12387        add_an_item_to_active_pane(cx, &workspace, 1);
12388        split_pane(cx, &workspace);
12389        add_an_item_to_active_pane(cx, &workspace, 2);
12390        split_pane(cx, &workspace); // empty pane
12391        split_pane(cx, &workspace);
12392        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12393
12394        cx.executor().run_until_parked();
12395
12396        workspace.update(cx, |workspace, cx| {
12397            let num_panes = workspace.panes().len();
12398            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12399            let active_item = workspace
12400                .active_pane()
12401                .read(cx)
12402                .active_item()
12403                .expect("item is in focus");
12404
12405            assert_eq!(num_panes, 4);
12406            assert_eq!(num_items_in_current_pane, 1);
12407            assert_eq!(active_item.item_id(), last_item.item_id());
12408        });
12409
12410        workspace.update_in(cx, |workspace, window, cx| {
12411            workspace.join_all_panes(window, cx);
12412        });
12413
12414        workspace.update(cx, |workspace, cx| {
12415            let num_panes = workspace.panes().len();
12416            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12417            let active_item = workspace
12418                .active_pane()
12419                .read(cx)
12420                .active_item()
12421                .expect("item is in focus");
12422
12423            assert_eq!(num_panes, 1);
12424            assert_eq!(num_items_in_current_pane, 3);
12425            assert_eq!(active_item.item_id(), last_item.item_id());
12426        });
12427    }
12428
12429    #[gpui::test]
12430    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12431        init_test(cx);
12432        let fs = FakeFs::new(cx.executor());
12433
12434        let project = Project::test(fs, [], cx).await;
12435        let (multi_workspace, cx) =
12436            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12437        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12438
12439        workspace.update(cx, |workspace, _cx| {
12440            workspace.bounds.size.width = px(800.);
12441        });
12442
12443        workspace.update_in(cx, |workspace, window, cx| {
12444            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12445            workspace.add_panel(panel, window, cx);
12446            workspace.toggle_dock(DockPosition::Right, window, cx);
12447        });
12448
12449        let (panel, resized_width, ratio_basis_width) =
12450            workspace.update_in(cx, |workspace, window, cx| {
12451                let item = cx.new(|cx| {
12452                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12453                });
12454                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12455
12456                let dock = workspace.right_dock().read(cx);
12457                let workspace_width = workspace.bounds.size.width;
12458                let initial_width = workspace
12459                    .dock_size(&dock, window, cx)
12460                    .expect("flexible dock should have an initial width");
12461
12462                assert_eq!(initial_width, workspace_width / 2.);
12463
12464                workspace.resize_right_dock(px(300.), window, cx);
12465
12466                let dock = workspace.right_dock().read(cx);
12467                let resized_width = workspace
12468                    .dock_size(&dock, window, cx)
12469                    .expect("flexible dock should keep its resized width");
12470
12471                assert_eq!(resized_width, px(300.));
12472
12473                let panel = workspace
12474                    .right_dock()
12475                    .read(cx)
12476                    .visible_panel()
12477                    .expect("flexible dock should have a visible panel")
12478                    .panel_id();
12479
12480                (panel, resized_width, workspace_width)
12481            });
12482
12483        workspace.update_in(cx, |workspace, window, cx| {
12484            workspace.toggle_dock(DockPosition::Right, window, cx);
12485            workspace.toggle_dock(DockPosition::Right, window, cx);
12486
12487            let dock = workspace.right_dock().read(cx);
12488            let reopened_width = workspace
12489                .dock_size(&dock, window, cx)
12490                .expect("flexible dock should restore when reopened");
12491
12492            assert_eq!(reopened_width, resized_width);
12493
12494            let right_dock = workspace.right_dock().read(cx);
12495            let flexible_panel = right_dock
12496                .visible_panel()
12497                .expect("flexible dock should still have a visible panel");
12498            assert_eq!(flexible_panel.panel_id(), panel);
12499            assert_eq!(
12500                right_dock
12501                    .stored_panel_size_state(flexible_panel.as_ref())
12502                    .and_then(|size_state| size_state.flex),
12503                Some(
12504                    resized_width.to_f64() as f32
12505                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12506                )
12507            );
12508        });
12509
12510        workspace.update_in(cx, |workspace, window, cx| {
12511            workspace.split_pane(
12512                workspace.active_pane().clone(),
12513                SplitDirection::Right,
12514                window,
12515                cx,
12516            );
12517
12518            let dock = workspace.right_dock().read(cx);
12519            let split_width = workspace
12520                .dock_size(&dock, window, cx)
12521                .expect("flexible dock should keep its user-resized proportion");
12522
12523            assert_eq!(split_width, px(300.));
12524
12525            workspace.bounds.size.width = px(1600.);
12526
12527            let dock = workspace.right_dock().read(cx);
12528            let resized_window_width = workspace
12529                .dock_size(&dock, window, cx)
12530                .expect("flexible dock should preserve proportional size on window resize");
12531
12532            assert_eq!(
12533                resized_window_width,
12534                workspace.bounds.size.width
12535                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12536            );
12537        });
12538    }
12539
12540    #[gpui::test]
12541    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12542        init_test(cx);
12543        let fs = FakeFs::new(cx.executor());
12544
12545        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12546        {
12547            let project = Project::test(fs.clone(), [], cx).await;
12548            let (multi_workspace, cx) =
12549                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12550            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12551
12552            workspace.update(cx, |workspace, _cx| {
12553                workspace.set_random_database_id();
12554                workspace.bounds.size.width = px(800.);
12555            });
12556
12557            let panel = workspace.update_in(cx, |workspace, window, cx| {
12558                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12559                workspace.add_panel(panel.clone(), window, cx);
12560                workspace.toggle_dock(DockPosition::Left, window, cx);
12561                panel
12562            });
12563
12564            workspace.update_in(cx, |workspace, window, cx| {
12565                workspace.resize_left_dock(px(350.), window, cx);
12566            });
12567
12568            cx.run_until_parked();
12569
12570            let persisted = workspace.read_with(cx, |workspace, cx| {
12571                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12572            });
12573            assert_eq!(
12574                persisted.and_then(|s| s.size),
12575                Some(px(350.)),
12576                "fixed-width panel size should be persisted to KVP"
12577            );
12578
12579            // Remove the panel and re-add a fresh instance with the same key.
12580            // The new instance should have its size state restored from KVP.
12581            workspace.update_in(cx, |workspace, window, cx| {
12582                workspace.remove_panel(&panel, window, cx);
12583            });
12584
12585            workspace.update_in(cx, |workspace, window, cx| {
12586                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12587                workspace.add_panel(new_panel, window, cx);
12588
12589                let left_dock = workspace.left_dock().read(cx);
12590                let size_state = left_dock
12591                    .panel::<TestPanel>()
12592                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12593                assert_eq!(
12594                    size_state.and_then(|s| s.size),
12595                    Some(px(350.)),
12596                    "re-added fixed-width panel should restore persisted size from KVP"
12597                );
12598            });
12599        }
12600
12601        // Flexible panel: both pixel size and ratio are persisted and restored.
12602        {
12603            let project = Project::test(fs.clone(), [], cx).await;
12604            let (multi_workspace, cx) =
12605                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12606            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12607
12608            workspace.update(cx, |workspace, _cx| {
12609                workspace.set_random_database_id();
12610                workspace.bounds.size.width = px(800.);
12611            });
12612
12613            let panel = workspace.update_in(cx, |workspace, window, cx| {
12614                let item = cx.new(|cx| {
12615                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12616                });
12617                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12618
12619                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12620                workspace.add_panel(panel.clone(), window, cx);
12621                workspace.toggle_dock(DockPosition::Right, window, cx);
12622                panel
12623            });
12624
12625            workspace.update_in(cx, |workspace, window, cx| {
12626                workspace.resize_right_dock(px(300.), window, cx);
12627            });
12628
12629            cx.run_until_parked();
12630
12631            let persisted = workspace
12632                .read_with(cx, |workspace, cx| {
12633                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12634                })
12635                .expect("flexible panel state should be persisted to KVP");
12636            assert_eq!(
12637                persisted.size, None,
12638                "flexible panel should not persist a redundant pixel size"
12639            );
12640            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12641
12642            // Remove the panel and re-add: both size and ratio should be restored.
12643            workspace.update_in(cx, |workspace, window, cx| {
12644                workspace.remove_panel(&panel, window, cx);
12645            });
12646
12647            workspace.update_in(cx, |workspace, window, cx| {
12648                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12649                workspace.add_panel(new_panel, window, cx);
12650
12651                let right_dock = workspace.right_dock().read(cx);
12652                let size_state = right_dock
12653                    .panel::<TestPanel>()
12654                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12655                    .expect("re-added flexible panel should have restored size state from KVP");
12656                assert_eq!(
12657                    size_state.size, None,
12658                    "re-added flexible panel should not have a persisted pixel size"
12659                );
12660                assert_eq!(
12661                    size_state.flex,
12662                    Some(original_ratio),
12663                    "re-added flexible panel should restore persisted flex"
12664                );
12665            });
12666        }
12667    }
12668
12669    #[gpui::test]
12670    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12671        init_test(cx);
12672        let fs = FakeFs::new(cx.executor());
12673
12674        let project = Project::test(fs, [], cx).await;
12675        let (multi_workspace, cx) =
12676            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12677        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12678
12679        workspace.update(cx, |workspace, _cx| {
12680            workspace.bounds.size.width = px(900.);
12681        });
12682
12683        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12684        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12685        // and the center pane each take half the workspace width.
12686        workspace.update_in(cx, |workspace, window, cx| {
12687            let item = cx.new(|cx| {
12688                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12689            });
12690            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12691
12692            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12693            workspace.add_panel(panel, window, cx);
12694            workspace.toggle_dock(DockPosition::Left, window, cx);
12695
12696            let left_dock = workspace.left_dock().read(cx);
12697            let left_width = workspace
12698                .dock_size(&left_dock, window, cx)
12699                .expect("left dock should have an active panel");
12700
12701            assert_eq!(
12702                left_width,
12703                workspace.bounds.size.width / 2.,
12704                "flexible left panel should split evenly with the center pane"
12705            );
12706        });
12707
12708        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12709        // change horizontal width fractions, so the flexible panel stays at the same
12710        // width as each half of the split.
12711        workspace.update_in(cx, |workspace, window, cx| {
12712            workspace.split_pane(
12713                workspace.active_pane().clone(),
12714                SplitDirection::Down,
12715                window,
12716                cx,
12717            );
12718
12719            let left_dock = workspace.left_dock().read(cx);
12720            let left_width = workspace
12721                .dock_size(&left_dock, window, cx)
12722                .expect("left dock should still have an active panel after vertical split");
12723
12724            assert_eq!(
12725                left_width,
12726                workspace.bounds.size.width / 2.,
12727                "flexible left panel width should match each vertically-split pane"
12728            );
12729        });
12730
12731        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12732        // size reduces the available width, so the flexible left panel and the center
12733        // panes all shrink proportionally to accommodate it.
12734        workspace.update_in(cx, |workspace, window, cx| {
12735            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12736            workspace.add_panel(panel, window, cx);
12737            workspace.toggle_dock(DockPosition::Right, window, cx);
12738
12739            let right_dock = workspace.right_dock().read(cx);
12740            let right_width = workspace
12741                .dock_size(&right_dock, window, cx)
12742                .expect("right dock should have an active panel");
12743
12744            let left_dock = workspace.left_dock().read(cx);
12745            let left_width = workspace
12746                .dock_size(&left_dock, window, cx)
12747                .expect("left dock should still have an active panel");
12748
12749            let available_width = workspace.bounds.size.width - right_width;
12750            assert_eq!(
12751                left_width,
12752                available_width / 2.,
12753                "flexible left panel should shrink proportionally as the right dock takes space"
12754            );
12755        });
12756
12757        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12758        // flex sizing and the workspace width is divided among left-flex, center
12759        // (implicit flex 1.0), and right-flex.
12760        workspace.update_in(cx, |workspace, window, cx| {
12761            let right_dock = workspace.right_dock().clone();
12762            let right_panel = right_dock
12763                .read(cx)
12764                .visible_panel()
12765                .expect("right dock should have a visible panel")
12766                .clone();
12767            workspace.toggle_dock_panel_flexible_size(
12768                &right_dock,
12769                right_panel.as_ref(),
12770                window,
12771                cx,
12772            );
12773
12774            let right_dock = right_dock.read(cx);
12775            let right_panel = right_dock
12776                .visible_panel()
12777                .expect("right dock should still have a visible panel");
12778            assert!(
12779                right_panel.has_flexible_size(window, cx),
12780                "right panel should now be flexible"
12781            );
12782
12783            let right_size_state = right_dock
12784                .stored_panel_size_state(right_panel.as_ref())
12785                .expect("right panel should have a stored size state after toggling");
12786            let right_flex = right_size_state
12787                .flex
12788                .expect("right panel should have a flex value after toggling");
12789
12790            let left_dock = workspace.left_dock().read(cx);
12791            let left_width = workspace
12792                .dock_size(&left_dock, window, cx)
12793                .expect("left dock should still have an active panel");
12794            let right_width = workspace
12795                .dock_size(&right_dock, window, cx)
12796                .expect("right dock should still have an active panel");
12797
12798            let left_flex = workspace
12799                .default_dock_flex(DockPosition::Left)
12800                .expect("left dock should have a default flex");
12801
12802            let total_flex = left_flex + 1.0 + right_flex;
12803            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12804            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12805            assert_eq!(
12806                left_width, expected_left,
12807                "flexible left panel should share workspace width via flex ratios"
12808            );
12809            assert_eq!(
12810                right_width, expected_right,
12811                "flexible right panel should share workspace width via flex ratios"
12812            );
12813        });
12814    }
12815
12816    struct TestModal(FocusHandle);
12817
12818    impl TestModal {
12819        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12820            Self(cx.focus_handle())
12821        }
12822    }
12823
12824    impl EventEmitter<DismissEvent> for TestModal {}
12825
12826    impl Focusable for TestModal {
12827        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12828            self.0.clone()
12829        }
12830    }
12831
12832    impl ModalView for TestModal {}
12833
12834    impl Render for TestModal {
12835        fn render(
12836            &mut self,
12837            _window: &mut Window,
12838            _cx: &mut Context<TestModal>,
12839        ) -> impl IntoElement {
12840            div().track_focus(&self.0)
12841        }
12842    }
12843
12844    #[gpui::test]
12845    async fn test_panels(cx: &mut gpui::TestAppContext) {
12846        init_test(cx);
12847        let fs = FakeFs::new(cx.executor());
12848
12849        let project = Project::test(fs, [], cx).await;
12850        let (multi_workspace, cx) =
12851            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12852        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12853
12854        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12855            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12856            workspace.add_panel(panel_1.clone(), window, cx);
12857            workspace.toggle_dock(DockPosition::Left, window, cx);
12858            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12859            workspace.add_panel(panel_2.clone(), window, cx);
12860            workspace.toggle_dock(DockPosition::Right, window, cx);
12861
12862            let left_dock = workspace.left_dock();
12863            assert_eq!(
12864                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12865                panel_1.panel_id()
12866            );
12867            assert_eq!(
12868                workspace.dock_size(&left_dock.read(cx), window, cx),
12869                Some(px(300.))
12870            );
12871
12872            workspace.resize_left_dock(px(1337.), window, cx);
12873            assert_eq!(
12874                workspace
12875                    .right_dock()
12876                    .read(cx)
12877                    .visible_panel()
12878                    .unwrap()
12879                    .panel_id(),
12880                panel_2.panel_id(),
12881            );
12882
12883            (panel_1, panel_2)
12884        });
12885
12886        // Move panel_1 to the right
12887        panel_1.update_in(cx, |panel_1, window, cx| {
12888            panel_1.set_position(DockPosition::Right, window, cx)
12889        });
12890
12891        workspace.update_in(cx, |workspace, window, cx| {
12892            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12893            // Since it was the only panel on the left, the left dock should now be closed.
12894            assert!(!workspace.left_dock().read(cx).is_open());
12895            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12896            let right_dock = workspace.right_dock();
12897            assert_eq!(
12898                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12899                panel_1.panel_id()
12900            );
12901            assert_eq!(
12902                right_dock
12903                    .read(cx)
12904                    .active_panel_size()
12905                    .unwrap()
12906                    .size
12907                    .unwrap(),
12908                px(1337.)
12909            );
12910
12911            // Now we move panel_2 to the left
12912            panel_2.set_position(DockPosition::Left, window, cx);
12913        });
12914
12915        workspace.update(cx, |workspace, cx| {
12916            // Since panel_2 was not visible on the right, we don't open the left dock.
12917            assert!(!workspace.left_dock().read(cx).is_open());
12918            // And the right dock is unaffected in its displaying of panel_1
12919            assert!(workspace.right_dock().read(cx).is_open());
12920            assert_eq!(
12921                workspace
12922                    .right_dock()
12923                    .read(cx)
12924                    .visible_panel()
12925                    .unwrap()
12926                    .panel_id(),
12927                panel_1.panel_id(),
12928            );
12929        });
12930
12931        // Move panel_1 back to the left
12932        panel_1.update_in(cx, |panel_1, window, cx| {
12933            panel_1.set_position(DockPosition::Left, window, cx)
12934        });
12935
12936        workspace.update_in(cx, |workspace, window, cx| {
12937            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12938            let left_dock = workspace.left_dock();
12939            assert!(left_dock.read(cx).is_open());
12940            assert_eq!(
12941                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12942                panel_1.panel_id()
12943            );
12944            assert_eq!(
12945                workspace.dock_size(&left_dock.read(cx), window, cx),
12946                Some(px(1337.))
12947            );
12948            // And the right dock should be closed as it no longer has any panels.
12949            assert!(!workspace.right_dock().read(cx).is_open());
12950
12951            // Now we move panel_1 to the bottom
12952            panel_1.set_position(DockPosition::Bottom, window, cx);
12953        });
12954
12955        workspace.update_in(cx, |workspace, window, cx| {
12956            // Since panel_1 was visible on the left, we close the left dock.
12957            assert!(!workspace.left_dock().read(cx).is_open());
12958            // The bottom dock is sized based on the panel's default size,
12959            // since the panel orientation changed from vertical to horizontal.
12960            let bottom_dock = workspace.bottom_dock();
12961            assert_eq!(
12962                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12963                Some(px(300.))
12964            );
12965            // Close bottom dock and move panel_1 back to the left.
12966            bottom_dock.update(cx, |bottom_dock, cx| {
12967                bottom_dock.set_open(false, window, cx)
12968            });
12969            panel_1.set_position(DockPosition::Left, window, cx);
12970        });
12971
12972        // Emit activated event on panel 1
12973        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12974
12975        // Now the left dock is open and panel_1 is active and focused.
12976        workspace.update_in(cx, |workspace, window, cx| {
12977            let left_dock = workspace.left_dock();
12978            assert!(left_dock.read(cx).is_open());
12979            assert_eq!(
12980                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12981                panel_1.panel_id(),
12982            );
12983            assert!(panel_1.focus_handle(cx).is_focused(window));
12984        });
12985
12986        // Emit closed event on panel 2, which is not active
12987        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12988
12989        // Wo don't close the left dock, because panel_2 wasn't the active panel
12990        workspace.update(cx, |workspace, cx| {
12991            let left_dock = workspace.left_dock();
12992            assert!(left_dock.read(cx).is_open());
12993            assert_eq!(
12994                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12995                panel_1.panel_id(),
12996            );
12997        });
12998
12999        // Emitting a ZoomIn event shows the panel as zoomed.
13000        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13001        workspace.read_with(cx, |workspace, _| {
13002            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13003            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13004        });
13005
13006        // Move panel to another dock while it is zoomed
13007        panel_1.update_in(cx, |panel, window, cx| {
13008            panel.set_position(DockPosition::Right, window, cx)
13009        });
13010        workspace.read_with(cx, |workspace, _| {
13011            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13012
13013            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13014        });
13015
13016        // This is a helper for getting a:
13017        // - valid focus on an element,
13018        // - that isn't a part of the panes and panels system of the Workspace,
13019        // - and doesn't trigger the 'on_focus_lost' API.
13020        let focus_other_view = {
13021            let workspace = workspace.clone();
13022            move |cx: &mut VisualTestContext| {
13023                workspace.update_in(cx, |workspace, window, cx| {
13024                    if workspace.active_modal::<TestModal>(cx).is_some() {
13025                        workspace.toggle_modal(window, cx, TestModal::new);
13026                        workspace.toggle_modal(window, cx, TestModal::new);
13027                    } else {
13028                        workspace.toggle_modal(window, cx, TestModal::new);
13029                    }
13030                })
13031            }
13032        };
13033
13034        // If focus is transferred to another view that's not a panel or another pane, we still show
13035        // the panel as zoomed.
13036        focus_other_view(cx);
13037        workspace.read_with(cx, |workspace, _| {
13038            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13039            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13040        });
13041
13042        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13043        workspace.update_in(cx, |_workspace, window, cx| {
13044            cx.focus_self(window);
13045        });
13046        workspace.read_with(cx, |workspace, _| {
13047            assert_eq!(workspace.zoomed, None);
13048            assert_eq!(workspace.zoomed_position, None);
13049        });
13050
13051        // If focus is transferred again to another view that's not a panel or a pane, we won't
13052        // show the panel as zoomed because it wasn't zoomed before.
13053        focus_other_view(cx);
13054        workspace.read_with(cx, |workspace, _| {
13055            assert_eq!(workspace.zoomed, None);
13056            assert_eq!(workspace.zoomed_position, None);
13057        });
13058
13059        // When the panel is activated, it is zoomed again.
13060        cx.dispatch_action(ToggleRightDock);
13061        workspace.read_with(cx, |workspace, _| {
13062            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13063            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13064        });
13065
13066        // Emitting a ZoomOut event unzooms the panel.
13067        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13068        workspace.read_with(cx, |workspace, _| {
13069            assert_eq!(workspace.zoomed, None);
13070            assert_eq!(workspace.zoomed_position, None);
13071        });
13072
13073        // Emit closed event on panel 1, which is active
13074        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13075
13076        // Now the left dock is closed, because panel_1 was the active panel
13077        workspace.update(cx, |workspace, cx| {
13078            let right_dock = workspace.right_dock();
13079            assert!(!right_dock.read(cx).is_open());
13080        });
13081    }
13082
13083    #[gpui::test]
13084    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13085        init_test(cx);
13086
13087        let fs = FakeFs::new(cx.background_executor.clone());
13088        let project = Project::test(fs, [], cx).await;
13089        let (workspace, cx) =
13090            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13091        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13092
13093        let dirty_regular_buffer = cx.new(|cx| {
13094            TestItem::new(cx)
13095                .with_dirty(true)
13096                .with_label("1.txt")
13097                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13098        });
13099        let dirty_regular_buffer_2 = cx.new(|cx| {
13100            TestItem::new(cx)
13101                .with_dirty(true)
13102                .with_label("2.txt")
13103                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13104        });
13105        let dirty_multi_buffer_with_both = cx.new(|cx| {
13106            TestItem::new(cx)
13107                .with_dirty(true)
13108                .with_buffer_kind(ItemBufferKind::Multibuffer)
13109                .with_label("Fake Project Search")
13110                .with_project_items(&[
13111                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13112                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13113                ])
13114        });
13115        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13116        workspace.update_in(cx, |workspace, window, cx| {
13117            workspace.add_item(
13118                pane.clone(),
13119                Box::new(dirty_regular_buffer.clone()),
13120                None,
13121                false,
13122                false,
13123                window,
13124                cx,
13125            );
13126            workspace.add_item(
13127                pane.clone(),
13128                Box::new(dirty_regular_buffer_2.clone()),
13129                None,
13130                false,
13131                false,
13132                window,
13133                cx,
13134            );
13135            workspace.add_item(
13136                pane.clone(),
13137                Box::new(dirty_multi_buffer_with_both.clone()),
13138                None,
13139                false,
13140                false,
13141                window,
13142                cx,
13143            );
13144        });
13145
13146        pane.update_in(cx, |pane, window, cx| {
13147            pane.activate_item(2, true, true, window, cx);
13148            assert_eq!(
13149                pane.active_item().unwrap().item_id(),
13150                multi_buffer_with_both_files_id,
13151                "Should select the multi buffer in the pane"
13152            );
13153        });
13154        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13155            pane.close_other_items(
13156                &CloseOtherItems {
13157                    save_intent: Some(SaveIntent::Save),
13158                    close_pinned: true,
13159                },
13160                None,
13161                window,
13162                cx,
13163            )
13164        });
13165        cx.background_executor.run_until_parked();
13166        assert!(!cx.has_pending_prompt());
13167        close_all_but_multi_buffer_task
13168            .await
13169            .expect("Closing all buffers but the multi buffer failed");
13170        pane.update(cx, |pane, cx| {
13171            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13172            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13173            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13174            assert_eq!(pane.items_len(), 1);
13175            assert_eq!(
13176                pane.active_item().unwrap().item_id(),
13177                multi_buffer_with_both_files_id,
13178                "Should have only the multi buffer left in the pane"
13179            );
13180            assert!(
13181                dirty_multi_buffer_with_both.read(cx).is_dirty,
13182                "The multi buffer containing the unsaved buffer should still be dirty"
13183            );
13184        });
13185
13186        dirty_regular_buffer.update(cx, |buffer, cx| {
13187            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13188        });
13189
13190        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13191            pane.close_active_item(
13192                &CloseActiveItem {
13193                    save_intent: Some(SaveIntent::Close),
13194                    close_pinned: false,
13195                },
13196                window,
13197                cx,
13198            )
13199        });
13200        cx.background_executor.run_until_parked();
13201        assert!(
13202            cx.has_pending_prompt(),
13203            "Dirty multi buffer should prompt a save dialog"
13204        );
13205        cx.simulate_prompt_answer("Save");
13206        cx.background_executor.run_until_parked();
13207        close_multi_buffer_task
13208            .await
13209            .expect("Closing the multi buffer failed");
13210        pane.update(cx, |pane, cx| {
13211            assert_eq!(
13212                dirty_multi_buffer_with_both.read(cx).save_count,
13213                1,
13214                "Multi buffer item should get be saved"
13215            );
13216            // Test impl does not save inner items, so we do not assert them
13217            assert_eq!(
13218                pane.items_len(),
13219                0,
13220                "No more items should be left in the pane"
13221            );
13222            assert!(pane.active_item().is_none());
13223        });
13224    }
13225
13226    #[gpui::test]
13227    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13228        cx: &mut TestAppContext,
13229    ) {
13230        init_test(cx);
13231
13232        let fs = FakeFs::new(cx.background_executor.clone());
13233        let project = Project::test(fs, [], cx).await;
13234        let (workspace, cx) =
13235            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13236        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13237
13238        let dirty_regular_buffer = cx.new(|cx| {
13239            TestItem::new(cx)
13240                .with_dirty(true)
13241                .with_label("1.txt")
13242                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13243        });
13244        let dirty_regular_buffer_2 = cx.new(|cx| {
13245            TestItem::new(cx)
13246                .with_dirty(true)
13247                .with_label("2.txt")
13248                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13249        });
13250        let clear_regular_buffer = cx.new(|cx| {
13251            TestItem::new(cx)
13252                .with_label("3.txt")
13253                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13254        });
13255
13256        let dirty_multi_buffer_with_both = cx.new(|cx| {
13257            TestItem::new(cx)
13258                .with_dirty(true)
13259                .with_buffer_kind(ItemBufferKind::Multibuffer)
13260                .with_label("Fake Project Search")
13261                .with_project_items(&[
13262                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13263                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13264                    clear_regular_buffer.read(cx).project_items[0].clone(),
13265                ])
13266        });
13267        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13268        workspace.update_in(cx, |workspace, window, cx| {
13269            workspace.add_item(
13270                pane.clone(),
13271                Box::new(dirty_regular_buffer.clone()),
13272                None,
13273                false,
13274                false,
13275                window,
13276                cx,
13277            );
13278            workspace.add_item(
13279                pane.clone(),
13280                Box::new(dirty_multi_buffer_with_both.clone()),
13281                None,
13282                false,
13283                false,
13284                window,
13285                cx,
13286            );
13287        });
13288
13289        pane.update_in(cx, |pane, window, cx| {
13290            pane.activate_item(1, true, true, window, cx);
13291            assert_eq!(
13292                pane.active_item().unwrap().item_id(),
13293                multi_buffer_with_both_files_id,
13294                "Should select the multi buffer in the pane"
13295            );
13296        });
13297        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13298            pane.close_active_item(
13299                &CloseActiveItem {
13300                    save_intent: None,
13301                    close_pinned: false,
13302                },
13303                window,
13304                cx,
13305            )
13306        });
13307        cx.background_executor.run_until_parked();
13308        assert!(
13309            cx.has_pending_prompt(),
13310            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13311        );
13312    }
13313
13314    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13315    /// closed when they are deleted from disk.
13316    #[gpui::test]
13317    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13318        init_test(cx);
13319
13320        // Enable the close_on_disk_deletion setting
13321        cx.update_global(|store: &mut SettingsStore, cx| {
13322            store.update_user_settings(cx, |settings| {
13323                settings.workspace.close_on_file_delete = Some(true);
13324            });
13325        });
13326
13327        let fs = FakeFs::new(cx.background_executor.clone());
13328        let project = Project::test(fs, [], cx).await;
13329        let (workspace, cx) =
13330            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13331        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13332
13333        // Create a test item that simulates a file
13334        let item = cx.new(|cx| {
13335            TestItem::new(cx)
13336                .with_label("test.txt")
13337                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13338        });
13339
13340        // Add item to workspace
13341        workspace.update_in(cx, |workspace, window, cx| {
13342            workspace.add_item(
13343                pane.clone(),
13344                Box::new(item.clone()),
13345                None,
13346                false,
13347                false,
13348                window,
13349                cx,
13350            );
13351        });
13352
13353        // Verify the item is in the pane
13354        pane.read_with(cx, |pane, _| {
13355            assert_eq!(pane.items().count(), 1);
13356        });
13357
13358        // Simulate file deletion by setting the item's deleted state
13359        item.update(cx, |item, _| {
13360            item.set_has_deleted_file(true);
13361        });
13362
13363        // Emit UpdateTab event to trigger the close behavior
13364        cx.run_until_parked();
13365        item.update(cx, |_, cx| {
13366            cx.emit(ItemEvent::UpdateTab);
13367        });
13368
13369        // Allow the close operation to complete
13370        cx.run_until_parked();
13371
13372        // Verify the item was automatically closed
13373        pane.read_with(cx, |pane, _| {
13374            assert_eq!(
13375                pane.items().count(),
13376                0,
13377                "Item should be automatically closed when file is deleted"
13378            );
13379        });
13380    }
13381
13382    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13383    /// open with a strikethrough when they are deleted from disk.
13384    #[gpui::test]
13385    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13386        init_test(cx);
13387
13388        // Ensure close_on_disk_deletion is disabled (default)
13389        cx.update_global(|store: &mut SettingsStore, cx| {
13390            store.update_user_settings(cx, |settings| {
13391                settings.workspace.close_on_file_delete = Some(false);
13392            });
13393        });
13394
13395        let fs = FakeFs::new(cx.background_executor.clone());
13396        let project = Project::test(fs, [], cx).await;
13397        let (workspace, cx) =
13398            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13399        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13400
13401        // Create a test item that simulates a file
13402        let item = cx.new(|cx| {
13403            TestItem::new(cx)
13404                .with_label("test.txt")
13405                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13406        });
13407
13408        // Add item to workspace
13409        workspace.update_in(cx, |workspace, window, cx| {
13410            workspace.add_item(
13411                pane.clone(),
13412                Box::new(item.clone()),
13413                None,
13414                false,
13415                false,
13416                window,
13417                cx,
13418            );
13419        });
13420
13421        // Verify the item is in the pane
13422        pane.read_with(cx, |pane, _| {
13423            assert_eq!(pane.items().count(), 1);
13424        });
13425
13426        // Simulate file deletion
13427        item.update(cx, |item, _| {
13428            item.set_has_deleted_file(true);
13429        });
13430
13431        // Emit UpdateTab event
13432        cx.run_until_parked();
13433        item.update(cx, |_, cx| {
13434            cx.emit(ItemEvent::UpdateTab);
13435        });
13436
13437        // Allow any potential close operation to complete
13438        cx.run_until_parked();
13439
13440        // Verify the item remains open (with strikethrough)
13441        pane.read_with(cx, |pane, _| {
13442            assert_eq!(
13443                pane.items().count(),
13444                1,
13445                "Item should remain open when close_on_disk_deletion is disabled"
13446            );
13447        });
13448
13449        // Verify the item shows as deleted
13450        item.read_with(cx, |item, _| {
13451            assert!(
13452                item.has_deleted_file,
13453                "Item should be marked as having deleted file"
13454            );
13455        });
13456    }
13457
13458    /// Tests that dirty files are not automatically closed when deleted from disk,
13459    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13460    /// unsaved changes without being prompted.
13461    #[gpui::test]
13462    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13463        init_test(cx);
13464
13465        // Enable the close_on_file_delete setting
13466        cx.update_global(|store: &mut SettingsStore, cx| {
13467            store.update_user_settings(cx, |settings| {
13468                settings.workspace.close_on_file_delete = Some(true);
13469            });
13470        });
13471
13472        let fs = FakeFs::new(cx.background_executor.clone());
13473        let project = Project::test(fs, [], cx).await;
13474        let (workspace, cx) =
13475            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13476        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13477
13478        // Create a dirty test item
13479        let item = cx.new(|cx| {
13480            TestItem::new(cx)
13481                .with_dirty(true)
13482                .with_label("test.txt")
13483                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13484        });
13485
13486        // Add item to workspace
13487        workspace.update_in(cx, |workspace, window, cx| {
13488            workspace.add_item(
13489                pane.clone(),
13490                Box::new(item.clone()),
13491                None,
13492                false,
13493                false,
13494                window,
13495                cx,
13496            );
13497        });
13498
13499        // Simulate file deletion
13500        item.update(cx, |item, _| {
13501            item.set_has_deleted_file(true);
13502        });
13503
13504        // Emit UpdateTab event to trigger the close behavior
13505        cx.run_until_parked();
13506        item.update(cx, |_, cx| {
13507            cx.emit(ItemEvent::UpdateTab);
13508        });
13509
13510        // Allow any potential close operation to complete
13511        cx.run_until_parked();
13512
13513        // Verify the item remains open (dirty files are not auto-closed)
13514        pane.read_with(cx, |pane, _| {
13515            assert_eq!(
13516                pane.items().count(),
13517                1,
13518                "Dirty items should not be automatically closed even when file is deleted"
13519            );
13520        });
13521
13522        // Verify the item is marked as deleted and still dirty
13523        item.read_with(cx, |item, _| {
13524            assert!(
13525                item.has_deleted_file,
13526                "Item should be marked as having deleted file"
13527            );
13528            assert!(item.is_dirty, "Item should still be dirty");
13529        });
13530    }
13531
13532    /// Tests that navigation history is cleaned up when files are auto-closed
13533    /// due to deletion from disk.
13534    #[gpui::test]
13535    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13536        init_test(cx);
13537
13538        // Enable the close_on_file_delete setting
13539        cx.update_global(|store: &mut SettingsStore, cx| {
13540            store.update_user_settings(cx, |settings| {
13541                settings.workspace.close_on_file_delete = Some(true);
13542            });
13543        });
13544
13545        let fs = FakeFs::new(cx.background_executor.clone());
13546        let project = Project::test(fs, [], cx).await;
13547        let (workspace, cx) =
13548            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13549        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13550
13551        // Create test items
13552        let item1 = cx.new(|cx| {
13553            TestItem::new(cx)
13554                .with_label("test1.txt")
13555                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13556        });
13557        let item1_id = item1.item_id();
13558
13559        let item2 = cx.new(|cx| {
13560            TestItem::new(cx)
13561                .with_label("test2.txt")
13562                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13563        });
13564
13565        // Add items to workspace
13566        workspace.update_in(cx, |workspace, window, cx| {
13567            workspace.add_item(
13568                pane.clone(),
13569                Box::new(item1.clone()),
13570                None,
13571                false,
13572                false,
13573                window,
13574                cx,
13575            );
13576            workspace.add_item(
13577                pane.clone(),
13578                Box::new(item2.clone()),
13579                None,
13580                false,
13581                false,
13582                window,
13583                cx,
13584            );
13585        });
13586
13587        // Activate item1 to ensure it gets navigation entries
13588        pane.update_in(cx, |pane, window, cx| {
13589            pane.activate_item(0, true, true, window, cx);
13590        });
13591
13592        // Switch to item2 and back to create navigation history
13593        pane.update_in(cx, |pane, window, cx| {
13594            pane.activate_item(1, true, true, window, cx);
13595        });
13596        cx.run_until_parked();
13597
13598        pane.update_in(cx, |pane, window, cx| {
13599            pane.activate_item(0, true, true, window, cx);
13600        });
13601        cx.run_until_parked();
13602
13603        // Simulate file deletion for item1
13604        item1.update(cx, |item, _| {
13605            item.set_has_deleted_file(true);
13606        });
13607
13608        // Emit UpdateTab event to trigger the close behavior
13609        item1.update(cx, |_, cx| {
13610            cx.emit(ItemEvent::UpdateTab);
13611        });
13612        cx.run_until_parked();
13613
13614        // Verify item1 was closed
13615        pane.read_with(cx, |pane, _| {
13616            assert_eq!(
13617                pane.items().count(),
13618                1,
13619                "Should have 1 item remaining after auto-close"
13620            );
13621        });
13622
13623        // Check navigation history after close
13624        let has_item = pane.read_with(cx, |pane, cx| {
13625            let mut has_item = false;
13626            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13627                if entry.item.id() == item1_id {
13628                    has_item = true;
13629                }
13630            });
13631            has_item
13632        });
13633
13634        assert!(
13635            !has_item,
13636            "Navigation history should not contain closed item entries"
13637        );
13638    }
13639
13640    #[gpui::test]
13641    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13642        cx: &mut TestAppContext,
13643    ) {
13644        init_test(cx);
13645
13646        let fs = FakeFs::new(cx.background_executor.clone());
13647        let project = Project::test(fs, [], cx).await;
13648        let (workspace, cx) =
13649            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13650        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13651
13652        let dirty_regular_buffer = cx.new(|cx| {
13653            TestItem::new(cx)
13654                .with_dirty(true)
13655                .with_label("1.txt")
13656                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13657        });
13658        let dirty_regular_buffer_2 = cx.new(|cx| {
13659            TestItem::new(cx)
13660                .with_dirty(true)
13661                .with_label("2.txt")
13662                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13663        });
13664        let clear_regular_buffer = cx.new(|cx| {
13665            TestItem::new(cx)
13666                .with_label("3.txt")
13667                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13668        });
13669
13670        let dirty_multi_buffer = cx.new(|cx| {
13671            TestItem::new(cx)
13672                .with_dirty(true)
13673                .with_buffer_kind(ItemBufferKind::Multibuffer)
13674                .with_label("Fake Project Search")
13675                .with_project_items(&[
13676                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13677                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13678                    clear_regular_buffer.read(cx).project_items[0].clone(),
13679                ])
13680        });
13681        workspace.update_in(cx, |workspace, window, cx| {
13682            workspace.add_item(
13683                pane.clone(),
13684                Box::new(dirty_regular_buffer.clone()),
13685                None,
13686                false,
13687                false,
13688                window,
13689                cx,
13690            );
13691            workspace.add_item(
13692                pane.clone(),
13693                Box::new(dirty_regular_buffer_2.clone()),
13694                None,
13695                false,
13696                false,
13697                window,
13698                cx,
13699            );
13700            workspace.add_item(
13701                pane.clone(),
13702                Box::new(dirty_multi_buffer.clone()),
13703                None,
13704                false,
13705                false,
13706                window,
13707                cx,
13708            );
13709        });
13710
13711        pane.update_in(cx, |pane, window, cx| {
13712            pane.activate_item(2, true, true, window, cx);
13713            assert_eq!(
13714                pane.active_item().unwrap().item_id(),
13715                dirty_multi_buffer.item_id(),
13716                "Should select the multi buffer in the pane"
13717            );
13718        });
13719        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13720            pane.close_active_item(
13721                &CloseActiveItem {
13722                    save_intent: None,
13723                    close_pinned: false,
13724                },
13725                window,
13726                cx,
13727            )
13728        });
13729        cx.background_executor.run_until_parked();
13730        assert!(
13731            !cx.has_pending_prompt(),
13732            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13733        );
13734        close_multi_buffer_task
13735            .await
13736            .expect("Closing multi buffer failed");
13737        pane.update(cx, |pane, cx| {
13738            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13739            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13740            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13741            assert_eq!(
13742                pane.items()
13743                    .map(|item| item.item_id())
13744                    .sorted()
13745                    .collect::<Vec<_>>(),
13746                vec![
13747                    dirty_regular_buffer.item_id(),
13748                    dirty_regular_buffer_2.item_id(),
13749                ],
13750                "Should have no multi buffer left in the pane"
13751            );
13752            assert!(dirty_regular_buffer.read(cx).is_dirty);
13753            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13754        });
13755    }
13756
13757    #[gpui::test]
13758    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13759        init_test(cx);
13760        let fs = FakeFs::new(cx.executor());
13761        let project = Project::test(fs, [], cx).await;
13762        let (multi_workspace, cx) =
13763            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13764        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13765
13766        // Add a new panel to the right dock, opening the dock and setting the
13767        // focus to the new panel.
13768        let panel = workspace.update_in(cx, |workspace, window, cx| {
13769            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13770            workspace.add_panel(panel.clone(), window, cx);
13771
13772            workspace
13773                .right_dock()
13774                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13775
13776            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13777
13778            panel
13779        });
13780
13781        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13782        // panel to the next valid position which, in this case, is the left
13783        // dock.
13784        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13785        workspace.update(cx, |workspace, cx| {
13786            assert!(workspace.left_dock().read(cx).is_open());
13787            assert_eq!(panel.read(cx).position, DockPosition::Left);
13788        });
13789
13790        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13791        // panel to the next valid position which, in this case, is the bottom
13792        // dock.
13793        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13794        workspace.update(cx, |workspace, cx| {
13795            assert!(workspace.bottom_dock().read(cx).is_open());
13796            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13797        });
13798
13799        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13800        // around moving the panel to its initial position, the right dock.
13801        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13802        workspace.update(cx, |workspace, cx| {
13803            assert!(workspace.right_dock().read(cx).is_open());
13804            assert_eq!(panel.read(cx).position, DockPosition::Right);
13805        });
13806
13807        // Remove focus from the panel, ensuring that, if the panel is not
13808        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13809        // the panel's position, so the panel is still in the right dock.
13810        workspace.update_in(cx, |workspace, window, cx| {
13811            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13812        });
13813
13814        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13815        workspace.update(cx, |workspace, cx| {
13816            assert!(workspace.right_dock().read(cx).is_open());
13817            assert_eq!(panel.read(cx).position, DockPosition::Right);
13818        });
13819    }
13820
13821    #[gpui::test]
13822    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13823        init_test(cx);
13824
13825        let fs = FakeFs::new(cx.executor());
13826        let project = Project::test(fs, [], cx).await;
13827        let (workspace, cx) =
13828            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13829
13830        let item_1 = cx.new(|cx| {
13831            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13832        });
13833        workspace.update_in(cx, |workspace, window, cx| {
13834            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13835            workspace.move_item_to_pane_in_direction(
13836                &MoveItemToPaneInDirection {
13837                    direction: SplitDirection::Right,
13838                    focus: true,
13839                    clone: false,
13840                },
13841                window,
13842                cx,
13843            );
13844            workspace.move_item_to_pane_at_index(
13845                &MoveItemToPane {
13846                    destination: 3,
13847                    focus: true,
13848                    clone: false,
13849                },
13850                window,
13851                cx,
13852            );
13853
13854            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13855            assert_eq!(
13856                pane_items_paths(&workspace.active_pane, cx),
13857                vec!["first.txt".to_string()],
13858                "Single item was not moved anywhere"
13859            );
13860        });
13861
13862        let item_2 = cx.new(|cx| {
13863            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13864        });
13865        workspace.update_in(cx, |workspace, window, cx| {
13866            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13867            assert_eq!(
13868                pane_items_paths(&workspace.panes[0], cx),
13869                vec!["first.txt".to_string(), "second.txt".to_string()],
13870            );
13871            workspace.move_item_to_pane_in_direction(
13872                &MoveItemToPaneInDirection {
13873                    direction: SplitDirection::Right,
13874                    focus: true,
13875                    clone: false,
13876                },
13877                window,
13878                cx,
13879            );
13880
13881            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13882            assert_eq!(
13883                pane_items_paths(&workspace.panes[0], cx),
13884                vec!["first.txt".to_string()],
13885                "After moving, one item should be left in the original pane"
13886            );
13887            assert_eq!(
13888                pane_items_paths(&workspace.panes[1], cx),
13889                vec!["second.txt".to_string()],
13890                "New item should have been moved to the new pane"
13891            );
13892        });
13893
13894        let item_3 = cx.new(|cx| {
13895            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13896        });
13897        workspace.update_in(cx, |workspace, window, cx| {
13898            let original_pane = workspace.panes[0].clone();
13899            workspace.set_active_pane(&original_pane, window, cx);
13900            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13901            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13902            assert_eq!(
13903                pane_items_paths(&workspace.active_pane, cx),
13904                vec!["first.txt".to_string(), "third.txt".to_string()],
13905                "New pane should be ready to move one item out"
13906            );
13907
13908            workspace.move_item_to_pane_at_index(
13909                &MoveItemToPane {
13910                    destination: 3,
13911                    focus: true,
13912                    clone: false,
13913                },
13914                window,
13915                cx,
13916            );
13917            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13918            assert_eq!(
13919                pane_items_paths(&workspace.active_pane, cx),
13920                vec!["first.txt".to_string()],
13921                "After moving, one item should be left in the original pane"
13922            );
13923            assert_eq!(
13924                pane_items_paths(&workspace.panes[1], cx),
13925                vec!["second.txt".to_string()],
13926                "Previously created pane should be unchanged"
13927            );
13928            assert_eq!(
13929                pane_items_paths(&workspace.panes[2], cx),
13930                vec!["third.txt".to_string()],
13931                "New item should have been moved to the new pane"
13932            );
13933        });
13934    }
13935
13936    #[gpui::test]
13937    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13938        init_test(cx);
13939
13940        let fs = FakeFs::new(cx.executor());
13941        let project = Project::test(fs, [], cx).await;
13942        let (workspace, cx) =
13943            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13944
13945        let item_1 = cx.new(|cx| {
13946            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13947        });
13948        workspace.update_in(cx, |workspace, window, cx| {
13949            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13950            workspace.move_item_to_pane_in_direction(
13951                &MoveItemToPaneInDirection {
13952                    direction: SplitDirection::Right,
13953                    focus: true,
13954                    clone: true,
13955                },
13956                window,
13957                cx,
13958            );
13959        });
13960        cx.run_until_parked();
13961        workspace.update_in(cx, |workspace, window, cx| {
13962            workspace.move_item_to_pane_at_index(
13963                &MoveItemToPane {
13964                    destination: 3,
13965                    focus: true,
13966                    clone: true,
13967                },
13968                window,
13969                cx,
13970            );
13971        });
13972        cx.run_until_parked();
13973
13974        workspace.update(cx, |workspace, cx| {
13975            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13976            for pane in workspace.panes() {
13977                assert_eq!(
13978                    pane_items_paths(pane, cx),
13979                    vec!["first.txt".to_string()],
13980                    "Single item exists in all panes"
13981                );
13982            }
13983        });
13984
13985        // verify that the active pane has been updated after waiting for the
13986        // pane focus event to fire and resolve
13987        workspace.read_with(cx, |workspace, _app| {
13988            assert_eq!(
13989                workspace.active_pane(),
13990                &workspace.panes[2],
13991                "The third pane should be the active one: {:?}",
13992                workspace.panes
13993            );
13994        })
13995    }
13996
13997    #[gpui::test]
13998    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13999        init_test(cx);
14000
14001        let fs = FakeFs::new(cx.executor());
14002        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14003
14004        let project = Project::test(fs, ["root".as_ref()], cx).await;
14005        let (workspace, cx) =
14006            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14007
14008        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14009        // Add item to pane A with project path
14010        let item_a = cx.new(|cx| {
14011            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14012        });
14013        workspace.update_in(cx, |workspace, window, cx| {
14014            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14015        });
14016
14017        // Split to create pane B
14018        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14019            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14020        });
14021
14022        // Add item with SAME project path to pane B, and pin it
14023        let item_b = cx.new(|cx| {
14024            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14025        });
14026        pane_b.update_in(cx, |pane, window, cx| {
14027            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14028            pane.set_pinned_count(1);
14029        });
14030
14031        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14032        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14033
14034        // close_pinned: false should only close the unpinned copy
14035        workspace.update_in(cx, |workspace, window, cx| {
14036            workspace.close_item_in_all_panes(
14037                &CloseItemInAllPanes {
14038                    save_intent: Some(SaveIntent::Close),
14039                    close_pinned: false,
14040                },
14041                window,
14042                cx,
14043            )
14044        });
14045        cx.executor().run_until_parked();
14046
14047        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14048        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14049        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14050        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14051
14052        // Split again, seeing as closing the previous item also closed its
14053        // pane, so only pane remains, which does not allow us to properly test
14054        // that both items close when `close_pinned: true`.
14055        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14056            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14057        });
14058
14059        // Add an item with the same project path to pane C so that
14060        // close_item_in_all_panes can determine what to close across all panes
14061        // (it reads the active item from the active pane, and split_pane
14062        // creates an empty pane).
14063        let item_c = cx.new(|cx| {
14064            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14065        });
14066        pane_c.update_in(cx, |pane, window, cx| {
14067            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14068        });
14069
14070        // close_pinned: true should close the pinned copy too
14071        workspace.update_in(cx, |workspace, window, cx| {
14072            let panes_count = workspace.panes().len();
14073            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14074
14075            workspace.close_item_in_all_panes(
14076                &CloseItemInAllPanes {
14077                    save_intent: Some(SaveIntent::Close),
14078                    close_pinned: true,
14079                },
14080                window,
14081                cx,
14082            )
14083        });
14084        cx.executor().run_until_parked();
14085
14086        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14087        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14088        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14089        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14090    }
14091
14092    mod register_project_item_tests {
14093
14094        use super::*;
14095
14096        // View
14097        struct TestPngItemView {
14098            focus_handle: FocusHandle,
14099        }
14100        // Model
14101        struct TestPngItem {}
14102
14103        impl project::ProjectItem for TestPngItem {
14104            fn try_open(
14105                _project: &Entity<Project>,
14106                path: &ProjectPath,
14107                cx: &mut App,
14108            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14109                if path.path.extension().unwrap() == "png" {
14110                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14111                } else {
14112                    None
14113                }
14114            }
14115
14116            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14117                None
14118            }
14119
14120            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14121                None
14122            }
14123
14124            fn is_dirty(&self) -> bool {
14125                false
14126            }
14127        }
14128
14129        impl Item for TestPngItemView {
14130            type Event = ();
14131            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14132                "".into()
14133            }
14134        }
14135        impl EventEmitter<()> for TestPngItemView {}
14136        impl Focusable for TestPngItemView {
14137            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14138                self.focus_handle.clone()
14139            }
14140        }
14141
14142        impl Render for TestPngItemView {
14143            fn render(
14144                &mut self,
14145                _window: &mut Window,
14146                _cx: &mut Context<Self>,
14147            ) -> impl IntoElement {
14148                Empty
14149            }
14150        }
14151
14152        impl ProjectItem for TestPngItemView {
14153            type Item = TestPngItem;
14154
14155            fn for_project_item(
14156                _project: Entity<Project>,
14157                _pane: Option<&Pane>,
14158                _item: Entity<Self::Item>,
14159                _: &mut Window,
14160                cx: &mut Context<Self>,
14161            ) -> Self
14162            where
14163                Self: Sized,
14164            {
14165                Self {
14166                    focus_handle: cx.focus_handle(),
14167                }
14168            }
14169        }
14170
14171        // View
14172        struct TestIpynbItemView {
14173            focus_handle: FocusHandle,
14174        }
14175        // Model
14176        struct TestIpynbItem {}
14177
14178        impl project::ProjectItem for TestIpynbItem {
14179            fn try_open(
14180                _project: &Entity<Project>,
14181                path: &ProjectPath,
14182                cx: &mut App,
14183            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14184                if path.path.extension().unwrap() == "ipynb" {
14185                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14186                } else {
14187                    None
14188                }
14189            }
14190
14191            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14192                None
14193            }
14194
14195            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14196                None
14197            }
14198
14199            fn is_dirty(&self) -> bool {
14200                false
14201            }
14202        }
14203
14204        impl Item for TestIpynbItemView {
14205            type Event = ();
14206            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14207                "".into()
14208            }
14209        }
14210        impl EventEmitter<()> for TestIpynbItemView {}
14211        impl Focusable for TestIpynbItemView {
14212            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14213                self.focus_handle.clone()
14214            }
14215        }
14216
14217        impl Render for TestIpynbItemView {
14218            fn render(
14219                &mut self,
14220                _window: &mut Window,
14221                _cx: &mut Context<Self>,
14222            ) -> impl IntoElement {
14223                Empty
14224            }
14225        }
14226
14227        impl ProjectItem for TestIpynbItemView {
14228            type Item = TestIpynbItem;
14229
14230            fn for_project_item(
14231                _project: Entity<Project>,
14232                _pane: Option<&Pane>,
14233                _item: Entity<Self::Item>,
14234                _: &mut Window,
14235                cx: &mut Context<Self>,
14236            ) -> Self
14237            where
14238                Self: Sized,
14239            {
14240                Self {
14241                    focus_handle: cx.focus_handle(),
14242                }
14243            }
14244        }
14245
14246        struct TestAlternatePngItemView {
14247            focus_handle: FocusHandle,
14248        }
14249
14250        impl Item for TestAlternatePngItemView {
14251            type Event = ();
14252            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14253                "".into()
14254            }
14255        }
14256
14257        impl EventEmitter<()> for TestAlternatePngItemView {}
14258        impl Focusable for TestAlternatePngItemView {
14259            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14260                self.focus_handle.clone()
14261            }
14262        }
14263
14264        impl Render for TestAlternatePngItemView {
14265            fn render(
14266                &mut self,
14267                _window: &mut Window,
14268                _cx: &mut Context<Self>,
14269            ) -> impl IntoElement {
14270                Empty
14271            }
14272        }
14273
14274        impl ProjectItem for TestAlternatePngItemView {
14275            type Item = TestPngItem;
14276
14277            fn for_project_item(
14278                _project: Entity<Project>,
14279                _pane: Option<&Pane>,
14280                _item: Entity<Self::Item>,
14281                _: &mut Window,
14282                cx: &mut Context<Self>,
14283            ) -> Self
14284            where
14285                Self: Sized,
14286            {
14287                Self {
14288                    focus_handle: cx.focus_handle(),
14289                }
14290            }
14291        }
14292
14293        #[gpui::test]
14294        async fn test_register_project_item(cx: &mut TestAppContext) {
14295            init_test(cx);
14296
14297            cx.update(|cx| {
14298                register_project_item::<TestPngItemView>(cx);
14299                register_project_item::<TestIpynbItemView>(cx);
14300            });
14301
14302            let fs = FakeFs::new(cx.executor());
14303            fs.insert_tree(
14304                "/root1",
14305                json!({
14306                    "one.png": "BINARYDATAHERE",
14307                    "two.ipynb": "{ totally a notebook }",
14308                    "three.txt": "editing text, sure why not?"
14309                }),
14310            )
14311            .await;
14312
14313            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14314            let (workspace, cx) =
14315                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14316
14317            let worktree_id = project.update(cx, |project, cx| {
14318                project.worktrees(cx).next().unwrap().read(cx).id()
14319            });
14320
14321            let handle = workspace
14322                .update_in(cx, |workspace, window, cx| {
14323                    let project_path = (worktree_id, rel_path("one.png"));
14324                    workspace.open_path(project_path, None, true, window, cx)
14325                })
14326                .await
14327                .unwrap();
14328
14329            // Now we can check if the handle we got back errored or not
14330            assert_eq!(
14331                handle.to_any_view().entity_type(),
14332                TypeId::of::<TestPngItemView>()
14333            );
14334
14335            let handle = workspace
14336                .update_in(cx, |workspace, window, cx| {
14337                    let project_path = (worktree_id, rel_path("two.ipynb"));
14338                    workspace.open_path(project_path, None, true, window, cx)
14339                })
14340                .await
14341                .unwrap();
14342
14343            assert_eq!(
14344                handle.to_any_view().entity_type(),
14345                TypeId::of::<TestIpynbItemView>()
14346            );
14347
14348            let handle = workspace
14349                .update_in(cx, |workspace, window, cx| {
14350                    let project_path = (worktree_id, rel_path("three.txt"));
14351                    workspace.open_path(project_path, None, true, window, cx)
14352                })
14353                .await;
14354            assert!(handle.is_err());
14355        }
14356
14357        #[gpui::test]
14358        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14359            init_test(cx);
14360
14361            cx.update(|cx| {
14362                register_project_item::<TestPngItemView>(cx);
14363                register_project_item::<TestAlternatePngItemView>(cx);
14364            });
14365
14366            let fs = FakeFs::new(cx.executor());
14367            fs.insert_tree(
14368                "/root1",
14369                json!({
14370                    "one.png": "BINARYDATAHERE",
14371                    "two.ipynb": "{ totally a notebook }",
14372                    "three.txt": "editing text, sure why not?"
14373                }),
14374            )
14375            .await;
14376            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14377            let (workspace, cx) =
14378                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14379            let worktree_id = project.update(cx, |project, cx| {
14380                project.worktrees(cx).next().unwrap().read(cx).id()
14381            });
14382
14383            let handle = workspace
14384                .update_in(cx, |workspace, window, cx| {
14385                    let project_path = (worktree_id, rel_path("one.png"));
14386                    workspace.open_path(project_path, None, true, window, cx)
14387                })
14388                .await
14389                .unwrap();
14390
14391            // This _must_ be the second item registered
14392            assert_eq!(
14393                handle.to_any_view().entity_type(),
14394                TypeId::of::<TestAlternatePngItemView>()
14395            );
14396
14397            let handle = workspace
14398                .update_in(cx, |workspace, window, cx| {
14399                    let project_path = (worktree_id, rel_path("three.txt"));
14400                    workspace.open_path(project_path, None, true, window, cx)
14401                })
14402                .await;
14403            assert!(handle.is_err());
14404        }
14405    }
14406
14407    #[gpui::test]
14408    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14409        init_test(cx);
14410
14411        let fs = FakeFs::new(cx.executor());
14412        let project = Project::test(fs, [], cx).await;
14413        let (workspace, _cx) =
14414            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14415
14416        // Test with status bar shown (default)
14417        workspace.read_with(cx, |workspace, cx| {
14418            let visible = workspace.status_bar_visible(cx);
14419            assert!(visible, "Status bar should be visible by default");
14420        });
14421
14422        // Test with status bar hidden
14423        cx.update_global(|store: &mut SettingsStore, cx| {
14424            store.update_user_settings(cx, |settings| {
14425                settings.status_bar.get_or_insert_default().show = Some(false);
14426            });
14427        });
14428
14429        workspace.read_with(cx, |workspace, cx| {
14430            let visible = workspace.status_bar_visible(cx);
14431            assert!(!visible, "Status bar should be hidden when show is false");
14432        });
14433
14434        // Test with status bar shown explicitly
14435        cx.update_global(|store: &mut SettingsStore, cx| {
14436            store.update_user_settings(cx, |settings| {
14437                settings.status_bar.get_or_insert_default().show = Some(true);
14438            });
14439        });
14440
14441        workspace.read_with(cx, |workspace, cx| {
14442            let visible = workspace.status_bar_visible(cx);
14443            assert!(visible, "Status bar should be visible when show is true");
14444        });
14445    }
14446
14447    #[gpui::test]
14448    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14449        init_test(cx);
14450
14451        let fs = FakeFs::new(cx.executor());
14452        let project = Project::test(fs, [], cx).await;
14453        let (multi_workspace, cx) =
14454            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14455        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14456        let panel = workspace.update_in(cx, |workspace, window, cx| {
14457            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14458            workspace.add_panel(panel.clone(), window, cx);
14459
14460            workspace
14461                .right_dock()
14462                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14463
14464            panel
14465        });
14466
14467        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14468        let item_a = cx.new(TestItem::new);
14469        let item_b = cx.new(TestItem::new);
14470        let item_a_id = item_a.entity_id();
14471        let item_b_id = item_b.entity_id();
14472
14473        pane.update_in(cx, |pane, window, cx| {
14474            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14475            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14476        });
14477
14478        pane.read_with(cx, |pane, _| {
14479            assert_eq!(pane.items_len(), 2);
14480            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14481        });
14482
14483        workspace.update_in(cx, |workspace, window, cx| {
14484            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14485        });
14486
14487        workspace.update_in(cx, |_, window, cx| {
14488            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14489        });
14490
14491        // Assert that the `pane::CloseActiveItem` action is handled at the
14492        // workspace level when one of the dock panels is focused and, in that
14493        // case, the center pane's active item is closed but the focus is not
14494        // moved.
14495        cx.dispatch_action(pane::CloseActiveItem::default());
14496        cx.run_until_parked();
14497
14498        pane.read_with(cx, |pane, _| {
14499            assert_eq!(pane.items_len(), 1);
14500            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14501        });
14502
14503        workspace.update_in(cx, |workspace, window, cx| {
14504            assert!(workspace.right_dock().read(cx).is_open());
14505            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14506        });
14507    }
14508
14509    #[gpui::test]
14510    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14511        init_test(cx);
14512        let fs = FakeFs::new(cx.executor());
14513
14514        let project_a = Project::test(fs.clone(), [], cx).await;
14515        let project_b = Project::test(fs, [], cx).await;
14516
14517        let multi_workspace_handle =
14518            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14519        cx.run_until_parked();
14520
14521        let workspace_a = multi_workspace_handle
14522            .read_with(cx, |mw, _| mw.workspace().clone())
14523            .unwrap();
14524
14525        let _workspace_b = multi_workspace_handle
14526            .update(cx, |mw, window, cx| {
14527                mw.test_add_workspace(project_b, window, cx)
14528            })
14529            .unwrap();
14530
14531        // Switch to workspace A
14532        multi_workspace_handle
14533            .update(cx, |mw, window, cx| {
14534                let workspace = mw.workspaces().next().expect("no workspace").clone();
14535                mw.activate(workspace, window, cx);
14536            })
14537            .unwrap();
14538
14539        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14540
14541        // Add a panel to workspace A's right dock and open the dock
14542        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14543            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14544            workspace.add_panel(panel.clone(), window, cx);
14545            workspace
14546                .right_dock()
14547                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14548            panel
14549        });
14550
14551        // Focus the panel through the workspace (matching existing test pattern)
14552        workspace_a.update_in(cx, |workspace, window, cx| {
14553            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14554        });
14555
14556        // Zoom the panel
14557        panel.update_in(cx, |panel, window, cx| {
14558            panel.set_zoomed(true, window, cx);
14559        });
14560
14561        // Verify the panel is zoomed and the dock is open
14562        workspace_a.update_in(cx, |workspace, window, cx| {
14563            assert!(
14564                workspace.right_dock().read(cx).is_open(),
14565                "dock should be open before switch"
14566            );
14567            assert!(
14568                panel.is_zoomed(window, cx),
14569                "panel should be zoomed before switch"
14570            );
14571            assert!(
14572                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14573                "panel should be focused before switch"
14574            );
14575        });
14576
14577        // Switch to workspace B
14578        multi_workspace_handle
14579            .update(cx, |mw, window, cx| {
14580                let workspace = mw
14581                    .workspaces()
14582                    .nth(1)
14583                    .expect("no workspace at index 1")
14584                    .clone();
14585                mw.activate(workspace, window, cx);
14586            })
14587            .unwrap();
14588        cx.run_until_parked();
14589
14590        // Switch back to workspace A
14591        multi_workspace_handle
14592            .update(cx, |mw, window, cx| {
14593                let workspace = mw
14594                    .workspaces()
14595                    .nth(0)
14596                    .expect("no workspace at index 0")
14597                    .clone();
14598                mw.activate(workspace, window, cx);
14599            })
14600            .unwrap();
14601        cx.run_until_parked();
14602
14603        // Verify the panel is still zoomed and the dock is still open
14604        workspace_a.update_in(cx, |workspace, window, cx| {
14605            assert!(
14606                workspace.right_dock().read(cx).is_open(),
14607                "dock should still be open after switching back"
14608            );
14609            assert!(
14610                panel.is_zoomed(window, cx),
14611                "panel should still be zoomed after switching back"
14612            );
14613        });
14614    }
14615
14616    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14617        pane.read(cx)
14618            .items()
14619            .flat_map(|item| {
14620                item.project_paths(cx)
14621                    .into_iter()
14622                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14623            })
14624            .collect()
14625    }
14626
14627    pub fn init_test(cx: &mut TestAppContext) {
14628        cx.update(|cx| {
14629            let settings_store = SettingsStore::test(cx);
14630            cx.set_global(settings_store);
14631            cx.set_global(db::AppDatabase::test_new());
14632            theme_settings::init(theme::LoadThemes::JustBase, cx);
14633        });
14634    }
14635
14636    #[gpui::test]
14637    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14638        use settings::{ThemeName, ThemeSelection};
14639        use theme::SystemAppearance;
14640        use zed_actions::theme::ToggleMode;
14641
14642        init_test(cx);
14643
14644        let fs = FakeFs::new(cx.executor());
14645        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14646
14647        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14648            .await;
14649
14650        // Build a test project and workspace view so the test can invoke
14651        // the workspace action handler the same way the UI would.
14652        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14653        let (workspace, cx) =
14654            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14655
14656        // Seed the settings file with a plain static light theme so the
14657        // first toggle always starts from a known persisted state.
14658        workspace.update_in(cx, |_workspace, _window, cx| {
14659            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14660            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14661                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14662            });
14663        });
14664        cx.executor().advance_clock(Duration::from_millis(200));
14665        cx.run_until_parked();
14666
14667        // Confirm the initial persisted settings contain the static theme
14668        // we just wrote before any toggling happens.
14669        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14670        assert!(settings_text.contains(r#""theme": "One Light""#));
14671
14672        // Toggle once. This should migrate the persisted theme settings
14673        // into light/dark slots and enable system mode.
14674        workspace.update_in(cx, |workspace, window, cx| {
14675            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14676        });
14677        cx.executor().advance_clock(Duration::from_millis(200));
14678        cx.run_until_parked();
14679
14680        // 1. Static -> Dynamic
14681        // this assertion checks theme changed from static to dynamic.
14682        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14683        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14684        assert_eq!(
14685            parsed["theme"],
14686            serde_json::json!({
14687                "mode": "system",
14688                "light": "One Light",
14689                "dark": "One Dark"
14690            })
14691        );
14692
14693        // 2. Toggle again, suppose it will change the mode to light
14694        workspace.update_in(cx, |workspace, window, cx| {
14695            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14696        });
14697        cx.executor().advance_clock(Duration::from_millis(200));
14698        cx.run_until_parked();
14699
14700        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14701        assert!(settings_text.contains(r#""mode": "light""#));
14702    }
14703
14704    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14705        let item = TestProjectItem::new(id, path, cx);
14706        item.update(cx, |item, _| {
14707            item.is_dirty = true;
14708        });
14709        item
14710    }
14711
14712    #[gpui::test]
14713    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14714        cx: &mut gpui::TestAppContext,
14715    ) {
14716        init_test(cx);
14717        let fs = FakeFs::new(cx.executor());
14718
14719        let project = Project::test(fs, [], cx).await;
14720        let (workspace, cx) =
14721            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14722
14723        let panel = workspace.update_in(cx, |workspace, window, cx| {
14724            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14725            workspace.add_panel(panel.clone(), window, cx);
14726            workspace
14727                .right_dock()
14728                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14729            panel
14730        });
14731
14732        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14733        pane.update_in(cx, |pane, window, cx| {
14734            let item = cx.new(TestItem::new);
14735            pane.add_item(Box::new(item), true, true, None, window, cx);
14736        });
14737
14738        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14739        // mirrors the real-world flow and avoids side effects from directly
14740        // focusing the panel while the center pane is active.
14741        workspace.update_in(cx, |workspace, window, cx| {
14742            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14743        });
14744
14745        panel.update_in(cx, |panel, window, cx| {
14746            panel.set_zoomed(true, window, cx);
14747        });
14748
14749        workspace.update_in(cx, |workspace, window, cx| {
14750            assert!(workspace.right_dock().read(cx).is_open());
14751            assert!(panel.is_zoomed(window, cx));
14752            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14753        });
14754
14755        // Simulate a spurious pane::Event::Focus on the center pane while the
14756        // panel still has focus. This mirrors what happens during macOS window
14757        // activation: the center pane fires a focus event even though actual
14758        // focus remains on the dock panel.
14759        pane.update_in(cx, |_, _, cx| {
14760            cx.emit(pane::Event::Focus);
14761        });
14762
14763        // The dock must remain open because the panel had focus at the time the
14764        // event was processed. Before the fix, dock_to_preserve was None for
14765        // panels that don't implement pane(), causing the dock to close.
14766        workspace.update_in(cx, |workspace, window, cx| {
14767            assert!(
14768                workspace.right_dock().read(cx).is_open(),
14769                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14770            );
14771            assert!(panel.is_zoomed(window, cx));
14772        });
14773    }
14774
14775    #[gpui::test]
14776    async fn test_panels_stay_open_after_position_change_and_settings_update(
14777        cx: &mut gpui::TestAppContext,
14778    ) {
14779        init_test(cx);
14780        let fs = FakeFs::new(cx.executor());
14781        let project = Project::test(fs, [], cx).await;
14782        let (workspace, cx) =
14783            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14784
14785        // Add two panels to the left dock and open it.
14786        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14787            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14788            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14789            workspace.add_panel(panel_a.clone(), window, cx);
14790            workspace.add_panel(panel_b.clone(), window, cx);
14791            workspace.left_dock().update(cx, |dock, cx| {
14792                dock.set_open(true, window, cx);
14793                dock.activate_panel(0, window, cx);
14794            });
14795            (panel_a, panel_b)
14796        });
14797
14798        workspace.update_in(cx, |workspace, _, cx| {
14799            assert!(workspace.left_dock().read(cx).is_open());
14800        });
14801
14802        // Simulate a feature flag changing default dock positions: both panels
14803        // move from Left to Right.
14804        workspace.update_in(cx, |_workspace, _window, cx| {
14805            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14806            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14807            cx.update_global::<SettingsStore, _>(|_, _| {});
14808        });
14809
14810        // Both panels should now be in the right dock.
14811        workspace.update_in(cx, |workspace, _, cx| {
14812            let right_dock = workspace.right_dock().read(cx);
14813            assert_eq!(right_dock.panels_len(), 2);
14814        });
14815
14816        // Open the right dock and activate panel_b (simulating the user
14817        // opening the panel after it moved).
14818        workspace.update_in(cx, |workspace, window, cx| {
14819            workspace.right_dock().update(cx, |dock, cx| {
14820                dock.set_open(true, window, cx);
14821                dock.activate_panel(1, window, cx);
14822            });
14823        });
14824
14825        // Now trigger another SettingsStore change
14826        workspace.update_in(cx, |_workspace, _window, cx| {
14827            cx.update_global::<SettingsStore, _>(|_, _| {});
14828        });
14829
14830        workspace.update_in(cx, |workspace, _, cx| {
14831            assert!(
14832                workspace.right_dock().read(cx).is_open(),
14833                "Right dock should still be open after a settings change"
14834            );
14835            assert_eq!(
14836                workspace.right_dock().read(cx).panels_len(),
14837                2,
14838                "Both panels should still be in the right dock"
14839            );
14840        });
14841    }
14842}