workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22pub mod focus_follows_mouse;
   23mod status_bar;
   24pub mod tasks;
   25mod theme_preview;
   26mod toast_layer;
   27mod toolbar;
   28pub mod welcome;
   29mod workspace_settings;
   30
   31pub use crate::notifications::NotificationFrame;
   32pub use dock::Panel;
   33pub use multi_workspace::{
   34    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   35    MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject, PreviousThread,
   36    ShowFewerThreads, ShowMoreThreads, Sidebar, SidebarEvent, SidebarHandle, SidebarRenderState,
   37    SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
   38};
   39pub use path_list::{PathList, SerializedPathList};
   40pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   41
   42use anyhow::{Context as _, Result, anyhow};
   43use client::{
   44    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   45    proto::{self, ErrorCode, PanelId, PeerId},
   46};
   47use collections::{HashMap, HashSet, hash_map};
   48use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   49use fs::Fs;
   50use futures::{
   51    Future, FutureExt, StreamExt,
   52    channel::{
   53        mpsc::{self, UnboundedReceiver, UnboundedSender},
   54        oneshot,
   55    },
   56    future::{Shared, try_join_all},
   57};
   58use gpui::{
   59    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   60    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   61    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   62    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   63    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   64    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   65};
   66pub use history_manager::*;
   67pub use item::{
   68    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   69    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   70};
   71use itertools::Itertools;
   72use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   73pub use modal_layer::*;
   74use node_runtime::NodeRuntime;
   75use notifications::{
   76    DetachAndPromptErr, Notifications, dismiss_app_notification,
   77    simple_message_notification::MessageNotification,
   78};
   79pub use pane::*;
   80pub use pane_group::{
   81    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   82    SplitDirection,
   83};
   84use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   85pub use persistence::{
   86    WorkspaceDb, delete_unloaded_items,
   87    model::{
   88        DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
   89        SerializedWorkspaceLocation, SessionWorkspace,
   90    },
   91    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   92};
   93use postage::stream::Stream;
   94use project::{
   95    DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
   96    WorktreeId, WorktreeSettings,
   97    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   98    project_settings::ProjectSettings,
   99    toolchain_store::ToolchainStoreEvent,
  100    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  101};
  102use remote::{
  103    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  104    remote_client::ConnectionIdentifier,
  105};
  106use schemars::JsonSchema;
  107use serde::Deserialize;
  108use session::AppSession;
  109use settings::{
  110    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  111};
  112
  113use sqlez::{
  114    bindable::{Bind, Column, StaticColumnCount},
  115    statement::Statement,
  116};
  117use status_bar::StatusBar;
  118pub use status_bar::StatusItemView;
  119use std::{
  120    any::TypeId,
  121    borrow::Cow,
  122    cell::RefCell,
  123    cmp,
  124    collections::VecDeque,
  125    env,
  126    hash::Hash,
  127    path::{Path, PathBuf},
  128    process::ExitStatus,
  129    rc::Rc,
  130    sync::{
  131        Arc, LazyLock,
  132        atomic::{AtomicBool, AtomicUsize},
  133    },
  134    time::Duration,
  135};
  136use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  137use theme::{ActiveTheme, SystemAppearance};
  138use theme_settings::ThemeSettings;
  139pub use toolbar::{
  140    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  141};
  142pub use ui;
  143use ui::{Window, prelude::*};
  144use util::{
  145    ResultExt, TryFutureExt,
  146    paths::{PathStyle, SanitizedPath},
  147    rel_path::RelPath,
  148    serde::default_true,
  149};
  150use uuid::Uuid;
  151pub use workspace_settings::{
  152    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  153    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  154};
  155use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  156
  157use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  158use crate::{
  159    persistence::{
  160        SerializedAxis,
  161        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  162    },
  163    security_modal::SecurityModal,
  164};
  165
  166pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  167
  168static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  169    env::var("ZED_WINDOW_SIZE")
  170        .ok()
  171        .as_deref()
  172        .and_then(parse_pixel_size_env_var)
  173});
  174
  175static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  176    env::var("ZED_WINDOW_POSITION")
  177        .ok()
  178        .as_deref()
  179        .and_then(parse_pixel_position_env_var)
  180});
  181
  182pub trait TerminalProvider {
  183    fn spawn(
  184        &self,
  185        task: SpawnInTerminal,
  186        window: &mut Window,
  187        cx: &mut App,
  188    ) -> Task<Option<Result<ExitStatus>>>;
  189}
  190
  191pub trait DebuggerProvider {
  192    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  193    fn start_session(
  194        &self,
  195        definition: DebugScenario,
  196        task_context: SharedTaskContext,
  197        active_buffer: Option<Entity<Buffer>>,
  198        worktree_id: Option<WorktreeId>,
  199        window: &mut Window,
  200        cx: &mut App,
  201    );
  202
  203    fn spawn_task_or_modal(
  204        &self,
  205        workspace: &mut Workspace,
  206        action: &Spawn,
  207        window: &mut Window,
  208        cx: &mut Context<Workspace>,
  209    );
  210
  211    fn task_scheduled(&self, cx: &mut App);
  212    fn debug_scenario_scheduled(&self, cx: &mut App);
  213    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  214
  215    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  216}
  217
  218/// Opens a file or directory.
  219#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  220#[action(namespace = workspace)]
  221pub struct Open {
  222    /// When true, opens in a new window. When false, adds to the current
  223    /// window as a new workspace (multi-workspace).
  224    #[serde(default = "Open::default_create_new_window")]
  225    pub create_new_window: bool,
  226}
  227
  228impl Open {
  229    pub const DEFAULT: Self = Self {
  230        create_new_window: true,
  231    };
  232
  233    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  234    /// the serde default and `Open::DEFAULT` stay in sync.
  235    fn default_create_new_window() -> bool {
  236        Self::DEFAULT.create_new_window
  237    }
  238}
  239
  240impl Default for Open {
  241    fn default() -> Self {
  242        Self::DEFAULT
  243    }
  244}
  245
  246actions!(
  247    workspace,
  248    [
  249        /// Activates the next pane in the workspace.
  250        ActivateNextPane,
  251        /// Activates the previous pane in the workspace.
  252        ActivatePreviousPane,
  253        /// Activates the last pane in the workspace.
  254        ActivateLastPane,
  255        /// Switches to the next window.
  256        ActivateNextWindow,
  257        /// Switches to the previous window.
  258        ActivatePreviousWindow,
  259        /// Adds a folder to the current project.
  260        AddFolderToProject,
  261        /// Clears all notifications.
  262        ClearAllNotifications,
  263        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  264        ClearNavigationHistory,
  265        /// Closes the active dock.
  266        CloseActiveDock,
  267        /// Closes all docks.
  268        CloseAllDocks,
  269        /// Toggles all docks.
  270        ToggleAllDocks,
  271        /// Closes the current window.
  272        CloseWindow,
  273        /// Closes the current project.
  274        CloseProject,
  275        /// Opens the feedback dialog.
  276        Feedback,
  277        /// Follows the next collaborator in the session.
  278        FollowNextCollaborator,
  279        /// Moves the focused panel to the next position.
  280        MoveFocusedPanelToNextPosition,
  281        /// Creates a new file.
  282        NewFile,
  283        /// Creates a new file in a vertical split.
  284        NewFileSplitVertical,
  285        /// Creates a new file in a horizontal split.
  286        NewFileSplitHorizontal,
  287        /// Opens a new search.
  288        NewSearch,
  289        /// Opens a new window.
  290        NewWindow,
  291        /// Opens multiple files.
  292        OpenFiles,
  293        /// Opens the current location in terminal.
  294        OpenInTerminal,
  295        /// Opens the component preview.
  296        OpenComponentPreview,
  297        /// Reloads the active item.
  298        ReloadActiveItem,
  299        /// Resets the active dock to its default size.
  300        ResetActiveDockSize,
  301        /// Resets all open docks to their default sizes.
  302        ResetOpenDocksSize,
  303        /// Reloads the application
  304        Reload,
  305        /// Saves the current file with a new name.
  306        SaveAs,
  307        /// Saves without formatting.
  308        SaveWithoutFormat,
  309        /// Shuts down all debug adapters.
  310        ShutdownDebugAdapters,
  311        /// Suppresses the current notification.
  312        SuppressNotification,
  313        /// Toggles the bottom dock.
  314        ToggleBottomDock,
  315        /// Toggles centered layout mode.
  316        ToggleCenteredLayout,
  317        /// Toggles edit prediction feature globally for all files.
  318        ToggleEditPrediction,
  319        /// Toggles the left dock.
  320        ToggleLeftDock,
  321        /// Toggles the right dock.
  322        ToggleRightDock,
  323        /// Toggles zoom on the active pane.
  324        ToggleZoom,
  325        /// Toggles read-only mode for the active item (if supported by that item).
  326        ToggleReadOnlyFile,
  327        /// Zooms in on the active pane.
  328        ZoomIn,
  329        /// Zooms out of the active pane.
  330        ZoomOut,
  331        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  332        /// If the modal is shown already, closes it without trusting any worktree.
  333        ToggleWorktreeSecurity,
  334        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  335        /// Requires restart to take effect on already opened projects.
  336        ClearTrustedWorktrees,
  337        /// Stops following a collaborator.
  338        Unfollow,
  339        /// Restores the banner.
  340        RestoreBanner,
  341        /// Toggles expansion of the selected item.
  342        ToggleExpandItem,
  343    ]
  344);
  345
  346/// Activates a specific pane by its index.
  347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  348#[action(namespace = workspace)]
  349pub struct ActivatePane(pub usize);
  350
  351/// Moves an item to a specific pane by index.
  352#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  353#[action(namespace = workspace)]
  354#[serde(deny_unknown_fields)]
  355pub struct MoveItemToPane {
  356    #[serde(default = "default_1")]
  357    pub destination: usize,
  358    #[serde(default = "default_true")]
  359    pub focus: bool,
  360    #[serde(default)]
  361    pub clone: bool,
  362}
  363
  364fn default_1() -> usize {
  365    1
  366}
  367
  368/// Moves an item to a pane in the specified direction.
  369#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  370#[action(namespace = workspace)]
  371#[serde(deny_unknown_fields)]
  372pub struct MoveItemToPaneInDirection {
  373    #[serde(default = "default_right")]
  374    pub direction: SplitDirection,
  375    #[serde(default = "default_true")]
  376    pub focus: bool,
  377    #[serde(default)]
  378    pub clone: bool,
  379}
  380
  381/// Creates a new file in a split of the desired direction.
  382#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  383#[action(namespace = workspace)]
  384#[serde(deny_unknown_fields)]
  385pub struct NewFileSplit(pub SplitDirection);
  386
  387fn default_right() -> SplitDirection {
  388    SplitDirection::Right
  389}
  390
  391/// Saves all open files in the workspace.
  392#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  393#[action(namespace = workspace)]
  394#[serde(deny_unknown_fields)]
  395pub struct SaveAll {
  396    #[serde(default)]
  397    pub save_intent: Option<SaveIntent>,
  398}
  399
  400/// Saves the current file with the specified options.
  401#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  402#[action(namespace = workspace)]
  403#[serde(deny_unknown_fields)]
  404pub struct Save {
  405    #[serde(default)]
  406    pub save_intent: Option<SaveIntent>,
  407}
  408
  409/// Moves Focus to the central panes in the workspace.
  410#[derive(Clone, Debug, PartialEq, Eq, Action)]
  411#[action(namespace = workspace)]
  412pub struct FocusCenterPane;
  413
  414///  Closes all items and panes in the workspace.
  415#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  416#[action(namespace = workspace)]
  417#[serde(deny_unknown_fields)]
  418pub struct CloseAllItemsAndPanes {
  419    #[serde(default)]
  420    pub save_intent: Option<SaveIntent>,
  421}
  422
  423/// Closes all inactive tabs and panes in the workspace.
  424#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  425#[action(namespace = workspace)]
  426#[serde(deny_unknown_fields)]
  427pub struct CloseInactiveTabsAndPanes {
  428    #[serde(default)]
  429    pub save_intent: Option<SaveIntent>,
  430}
  431
  432/// Closes the active item across all panes.
  433#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  434#[action(namespace = workspace)]
  435#[serde(deny_unknown_fields)]
  436pub struct CloseItemInAllPanes {
  437    #[serde(default)]
  438    pub save_intent: Option<SaveIntent>,
  439    #[serde(default)]
  440    pub close_pinned: bool,
  441}
  442
  443/// Sends a sequence of keystrokes to the active element.
  444#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  445#[action(namespace = workspace)]
  446pub struct SendKeystrokes(pub String);
  447
  448actions!(
  449    project_symbols,
  450    [
  451        /// Toggles the project symbols search.
  452        #[action(name = "Toggle")]
  453        ToggleProjectSymbols
  454    ]
  455);
  456
  457/// Toggles the file finder interface.
  458#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  459#[action(namespace = file_finder, name = "Toggle")]
  460#[serde(deny_unknown_fields)]
  461pub struct ToggleFileFinder {
  462    #[serde(default)]
  463    pub separate_history: bool,
  464}
  465
  466/// Opens a new terminal in the center.
  467#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  468#[action(namespace = workspace)]
  469#[serde(deny_unknown_fields)]
  470pub struct NewCenterTerminal {
  471    /// If true, creates a local terminal even in remote projects.
  472    #[serde(default)]
  473    pub local: bool,
  474}
  475
  476/// Opens a new terminal.
  477#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  478#[action(namespace = workspace)]
  479#[serde(deny_unknown_fields)]
  480pub struct NewTerminal {
  481    /// If true, creates a local terminal even in remote projects.
  482    #[serde(default)]
  483    pub local: bool,
  484}
  485
  486/// Increases size of a currently focused dock by a given amount of pixels.
  487#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  488#[action(namespace = workspace)]
  489#[serde(deny_unknown_fields)]
  490pub struct IncreaseActiveDockSize {
  491    /// For 0px parameter, uses UI font size value.
  492    #[serde(default)]
  493    pub px: u32,
  494}
  495
  496/// Decreases size of a currently focused dock by a given amount of pixels.
  497#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  498#[action(namespace = workspace)]
  499#[serde(deny_unknown_fields)]
  500pub struct DecreaseActiveDockSize {
  501    /// For 0px parameter, uses UI font size value.
  502    #[serde(default)]
  503    pub px: u32,
  504}
  505
  506/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  507#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  508#[action(namespace = workspace)]
  509#[serde(deny_unknown_fields)]
  510pub struct IncreaseOpenDocksSize {
  511    /// For 0px parameter, uses UI font size value.
  512    #[serde(default)]
  513    pub px: u32,
  514}
  515
  516/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  517#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  518#[action(namespace = workspace)]
  519#[serde(deny_unknown_fields)]
  520pub struct DecreaseOpenDocksSize {
  521    /// For 0px parameter, uses UI font size value.
  522    #[serde(default)]
  523    pub px: u32,
  524}
  525
  526actions!(
  527    workspace,
  528    [
  529        /// Activates the pane to the left.
  530        ActivatePaneLeft,
  531        /// Activates the pane to the right.
  532        ActivatePaneRight,
  533        /// Activates the pane above.
  534        ActivatePaneUp,
  535        /// Activates the pane below.
  536        ActivatePaneDown,
  537        /// Swaps the current pane with the one to the left.
  538        SwapPaneLeft,
  539        /// Swaps the current pane with the one to the right.
  540        SwapPaneRight,
  541        /// Swaps the current pane with the one above.
  542        SwapPaneUp,
  543        /// Swaps the current pane with the one below.
  544        SwapPaneDown,
  545        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  546        SwapPaneAdjacent,
  547        /// Move the current pane to be at the far left.
  548        MovePaneLeft,
  549        /// Move the current pane to be at the far right.
  550        MovePaneRight,
  551        /// Move the current pane to be at the very top.
  552        MovePaneUp,
  553        /// Move the current pane to be at the very bottom.
  554        MovePaneDown,
  555    ]
  556);
  557
  558#[derive(PartialEq, Eq, Debug)]
  559pub enum CloseIntent {
  560    /// Quit the program entirely.
  561    Quit,
  562    /// Close a window.
  563    CloseWindow,
  564    /// Replace the workspace in an existing window.
  565    ReplaceWindow,
  566}
  567
  568#[derive(Clone)]
  569pub struct Toast {
  570    id: NotificationId,
  571    msg: Cow<'static, str>,
  572    autohide: bool,
  573    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  574}
  575
  576impl Toast {
  577    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  578        Toast {
  579            id,
  580            msg: msg.into(),
  581            on_click: None,
  582            autohide: false,
  583        }
  584    }
  585
  586    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  587    where
  588        M: Into<Cow<'static, str>>,
  589        F: Fn(&mut Window, &mut App) + 'static,
  590    {
  591        self.on_click = Some((message.into(), Arc::new(on_click)));
  592        self
  593    }
  594
  595    pub fn autohide(mut self) -> Self {
  596        self.autohide = true;
  597        self
  598    }
  599}
  600
  601impl PartialEq for Toast {
  602    fn eq(&self, other: &Self) -> bool {
  603        self.id == other.id
  604            && self.msg == other.msg
  605            && self.on_click.is_some() == other.on_click.is_some()
  606    }
  607}
  608
  609/// Opens a new terminal with the specified working directory.
  610#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  611#[action(namespace = workspace)]
  612#[serde(deny_unknown_fields)]
  613pub struct OpenTerminal {
  614    pub working_directory: PathBuf,
  615    /// If true, creates a local terminal even in remote projects.
  616    #[serde(default)]
  617    pub local: bool,
  618}
  619
  620#[derive(
  621    Clone,
  622    Copy,
  623    Debug,
  624    Default,
  625    Hash,
  626    PartialEq,
  627    Eq,
  628    PartialOrd,
  629    Ord,
  630    serde::Serialize,
  631    serde::Deserialize,
  632)]
  633pub struct WorkspaceId(i64);
  634
  635impl WorkspaceId {
  636    pub fn from_i64(value: i64) -> Self {
  637        Self(value)
  638    }
  639}
  640
  641impl StaticColumnCount for WorkspaceId {}
  642impl Bind for WorkspaceId {
  643    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  644        self.0.bind(statement, start_index)
  645    }
  646}
  647impl Column for WorkspaceId {
  648    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  649        i64::column(statement, start_index)
  650            .map(|(i, next_index)| (Self(i), next_index))
  651            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  652    }
  653}
  654impl From<WorkspaceId> for i64 {
  655    fn from(val: WorkspaceId) -> Self {
  656        val.0
  657    }
  658}
  659
  660fn prompt_and_open_paths(
  661    app_state: Arc<AppState>,
  662    options: PathPromptOptions,
  663    create_new_window: bool,
  664    cx: &mut App,
  665) {
  666    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  667        workspace_window
  668            .update(cx, |multi_workspace, window, cx| {
  669                let workspace = multi_workspace.workspace().clone();
  670                workspace.update(cx, |workspace, cx| {
  671                    prompt_for_open_path_and_open(
  672                        workspace,
  673                        app_state,
  674                        options,
  675                        create_new_window,
  676                        window,
  677                        cx,
  678                    );
  679                });
  680            })
  681            .ok();
  682    } else {
  683        let task = Workspace::new_local(
  684            Vec::new(),
  685            app_state.clone(),
  686            None,
  687            None,
  688            None,
  689            OpenMode::Activate,
  690            cx,
  691        );
  692        cx.spawn(async move |cx| {
  693            let OpenResult { window, .. } = task.await?;
  694            window.update(cx, |multi_workspace, window, cx| {
  695                window.activate_window();
  696                let workspace = multi_workspace.workspace().clone();
  697                workspace.update(cx, |workspace, cx| {
  698                    prompt_for_open_path_and_open(
  699                        workspace,
  700                        app_state,
  701                        options,
  702                        create_new_window,
  703                        window,
  704                        cx,
  705                    );
  706                });
  707            })?;
  708            anyhow::Ok(())
  709        })
  710        .detach_and_log_err(cx);
  711    }
  712}
  713
  714pub fn prompt_for_open_path_and_open(
  715    workspace: &mut Workspace,
  716    app_state: Arc<AppState>,
  717    options: PathPromptOptions,
  718    create_new_window: bool,
  719    window: &mut Window,
  720    cx: &mut Context<Workspace>,
  721) {
  722    let paths = workspace.prompt_for_open_path(
  723        options,
  724        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  725        window,
  726        cx,
  727    );
  728    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  729    cx.spawn_in(window, async move |this, cx| {
  730        let Some(paths) = paths.await.log_err().flatten() else {
  731            return;
  732        };
  733        if !create_new_window {
  734            if let Some(handle) = multi_workspace_handle {
  735                if let Some(task) = handle
  736                    .update(cx, |multi_workspace, window, cx| {
  737                        multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
  738                    })
  739                    .log_err()
  740                {
  741                    task.await.log_err();
  742                }
  743                return;
  744            }
  745        }
  746        if let Some(task) = this
  747            .update_in(cx, |this, window, cx| {
  748                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  749            })
  750            .log_err()
  751        {
  752            task.await.log_err();
  753        }
  754    })
  755    .detach();
  756}
  757
  758pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  759    component::init();
  760    theme_preview::init(cx);
  761    toast_layer::init(cx);
  762    history_manager::init(app_state.fs.clone(), cx);
  763
  764    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  765        .on_action(|_: &Reload, cx| reload(cx))
  766        .on_action(|action: &Open, cx: &mut App| {
  767            let app_state = AppState::global(cx);
  768            prompt_and_open_paths(
  769                app_state,
  770                PathPromptOptions {
  771                    files: true,
  772                    directories: true,
  773                    multiple: true,
  774                    prompt: None,
  775                },
  776                action.create_new_window,
  777                cx,
  778            );
  779        })
  780        .on_action(|_: &OpenFiles, cx: &mut App| {
  781            let directories = cx.can_select_mixed_files_and_dirs();
  782            let app_state = AppState::global(cx);
  783            prompt_and_open_paths(
  784                app_state,
  785                PathPromptOptions {
  786                    files: true,
  787                    directories,
  788                    multiple: true,
  789                    prompt: None,
  790                },
  791                true,
  792                cx,
  793            );
  794        });
  795}
  796
  797type BuildProjectItemFn =
  798    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  799
  800type BuildProjectItemForPathFn =
  801    fn(
  802        &Entity<Project>,
  803        &ProjectPath,
  804        &mut Window,
  805        &mut App,
  806    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  807
  808#[derive(Clone, Default)]
  809struct ProjectItemRegistry {
  810    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  811    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  812}
  813
  814impl ProjectItemRegistry {
  815    fn register<T: ProjectItem>(&mut self) {
  816        self.build_project_item_fns_by_type.insert(
  817            TypeId::of::<T::Item>(),
  818            |item, project, pane, window, cx| {
  819                let item = item.downcast().unwrap();
  820                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  821                    as Box<dyn ItemHandle>
  822            },
  823        );
  824        self.build_project_item_for_path_fns
  825            .push(|project, project_path, window, cx| {
  826                let project_path = project_path.clone();
  827                let is_file = project
  828                    .read(cx)
  829                    .entry_for_path(&project_path, cx)
  830                    .is_some_and(|entry| entry.is_file());
  831                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  832                let is_local = project.read(cx).is_local();
  833                let project_item =
  834                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  835                let project = project.clone();
  836                Some(window.spawn(cx, async move |cx| {
  837                    match project_item.await.with_context(|| {
  838                        format!(
  839                            "opening project path {:?}",
  840                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  841                        )
  842                    }) {
  843                        Ok(project_item) => {
  844                            let project_item = project_item;
  845                            let project_entry_id: Option<ProjectEntryId> =
  846                                project_item.read_with(cx, project::ProjectItem::entry_id);
  847                            let build_workspace_item = Box::new(
  848                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  849                                    Box::new(cx.new(|cx| {
  850                                        T::for_project_item(
  851                                            project,
  852                                            Some(pane),
  853                                            project_item,
  854                                            window,
  855                                            cx,
  856                                        )
  857                                    })) as Box<dyn ItemHandle>
  858                                },
  859                            ) as Box<_>;
  860                            Ok((project_entry_id, build_workspace_item))
  861                        }
  862                        Err(e) => {
  863                            log::warn!("Failed to open a project item: {e:#}");
  864                            if e.error_code() == ErrorCode::Internal {
  865                                if let Some(abs_path) =
  866                                    entry_abs_path.as_deref().filter(|_| is_file)
  867                                {
  868                                    if let Some(broken_project_item_view) =
  869                                        cx.update(|window, cx| {
  870                                            T::for_broken_project_item(
  871                                                abs_path, is_local, &e, window, cx,
  872                                            )
  873                                        })?
  874                                    {
  875                                        let build_workspace_item = Box::new(
  876                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  877                                                cx.new(|_| broken_project_item_view).boxed_clone()
  878                                            },
  879                                        )
  880                                        as Box<_>;
  881                                        return Ok((None, build_workspace_item));
  882                                    }
  883                                }
  884                            }
  885                            Err(e)
  886                        }
  887                    }
  888                }))
  889            });
  890    }
  891
  892    fn open_path(
  893        &self,
  894        project: &Entity<Project>,
  895        path: &ProjectPath,
  896        window: &mut Window,
  897        cx: &mut App,
  898    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  899        let Some(open_project_item) = self
  900            .build_project_item_for_path_fns
  901            .iter()
  902            .rev()
  903            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  904        else {
  905            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  906        };
  907        open_project_item
  908    }
  909
  910    fn build_item<T: project::ProjectItem>(
  911        &self,
  912        item: Entity<T>,
  913        project: Entity<Project>,
  914        pane: Option<&Pane>,
  915        window: &mut Window,
  916        cx: &mut App,
  917    ) -> Option<Box<dyn ItemHandle>> {
  918        let build = self
  919            .build_project_item_fns_by_type
  920            .get(&TypeId::of::<T>())?;
  921        Some(build(item.into_any(), project, pane, window, cx))
  922    }
  923}
  924
  925type WorkspaceItemBuilder =
  926    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  927
  928impl Global for ProjectItemRegistry {}
  929
  930/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  931/// items will get a chance to open the file, starting from the project item that
  932/// was added last.
  933pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  934    cx.default_global::<ProjectItemRegistry>().register::<I>();
  935}
  936
  937#[derive(Default)]
  938pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  939
  940struct FollowableViewDescriptor {
  941    from_state_proto: fn(
  942        Entity<Workspace>,
  943        ViewId,
  944        &mut Option<proto::view::Variant>,
  945        &mut Window,
  946        &mut App,
  947    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  948    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  949}
  950
  951impl Global for FollowableViewRegistry {}
  952
  953impl FollowableViewRegistry {
  954    pub fn register<I: FollowableItem>(cx: &mut App) {
  955        cx.default_global::<Self>().0.insert(
  956            TypeId::of::<I>(),
  957            FollowableViewDescriptor {
  958                from_state_proto: |workspace, id, state, window, cx| {
  959                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  960                        cx.foreground_executor()
  961                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  962                    })
  963                },
  964                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  965            },
  966        );
  967    }
  968
  969    pub fn from_state_proto(
  970        workspace: Entity<Workspace>,
  971        view_id: ViewId,
  972        mut state: Option<proto::view::Variant>,
  973        window: &mut Window,
  974        cx: &mut App,
  975    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  976        cx.update_default_global(|this: &mut Self, cx| {
  977            this.0.values().find_map(|descriptor| {
  978                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  979            })
  980        })
  981    }
  982
  983    pub fn to_followable_view(
  984        view: impl Into<AnyView>,
  985        cx: &App,
  986    ) -> Option<Box<dyn FollowableItemHandle>> {
  987        let this = cx.try_global::<Self>()?;
  988        let view = view.into();
  989        let descriptor = this.0.get(&view.entity_type())?;
  990        Some((descriptor.to_followable_view)(&view))
  991    }
  992}
  993
  994#[derive(Copy, Clone)]
  995struct SerializableItemDescriptor {
  996    deserialize: fn(
  997        Entity<Project>,
  998        WeakEntity<Workspace>,
  999        WorkspaceId,
 1000        ItemId,
 1001        &mut Window,
 1002        &mut Context<Pane>,
 1003    ) -> Task<Result<Box<dyn ItemHandle>>>,
 1004    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
 1005    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
 1006}
 1007
 1008#[derive(Default)]
 1009struct SerializableItemRegistry {
 1010    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
 1011    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
 1012}
 1013
 1014impl Global for SerializableItemRegistry {}
 1015
 1016impl SerializableItemRegistry {
 1017    fn deserialize(
 1018        item_kind: &str,
 1019        project: Entity<Project>,
 1020        workspace: WeakEntity<Workspace>,
 1021        workspace_id: WorkspaceId,
 1022        item_item: ItemId,
 1023        window: &mut Window,
 1024        cx: &mut Context<Pane>,
 1025    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1026        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1027            return Task::ready(Err(anyhow!(
 1028                "cannot deserialize {}, descriptor not found",
 1029                item_kind
 1030            )));
 1031        };
 1032
 1033        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1034    }
 1035
 1036    fn cleanup(
 1037        item_kind: &str,
 1038        workspace_id: WorkspaceId,
 1039        loaded_items: Vec<ItemId>,
 1040        window: &mut Window,
 1041        cx: &mut App,
 1042    ) -> Task<Result<()>> {
 1043        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1044            return Task::ready(Err(anyhow!(
 1045                "cannot cleanup {}, descriptor not found",
 1046                item_kind
 1047            )));
 1048        };
 1049
 1050        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1051    }
 1052
 1053    fn view_to_serializable_item_handle(
 1054        view: AnyView,
 1055        cx: &App,
 1056    ) -> Option<Box<dyn SerializableItemHandle>> {
 1057        let this = cx.try_global::<Self>()?;
 1058        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1059        Some((descriptor.view_to_serializable_item)(view))
 1060    }
 1061
 1062    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1063        let this = cx.try_global::<Self>()?;
 1064        this.descriptors_by_kind.get(item_kind).copied()
 1065    }
 1066}
 1067
 1068pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1069    let serialized_item_kind = I::serialized_item_kind();
 1070
 1071    let registry = cx.default_global::<SerializableItemRegistry>();
 1072    let descriptor = SerializableItemDescriptor {
 1073        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1074            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1075            cx.foreground_executor()
 1076                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1077        },
 1078        cleanup: |workspace_id, loaded_items, window, cx| {
 1079            I::cleanup(workspace_id, loaded_items, window, cx)
 1080        },
 1081        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1082    };
 1083    registry
 1084        .descriptors_by_kind
 1085        .insert(Arc::from(serialized_item_kind), descriptor);
 1086    registry
 1087        .descriptors_by_type
 1088        .insert(TypeId::of::<I>(), descriptor);
 1089}
 1090
 1091pub struct AppState {
 1092    pub languages: Arc<LanguageRegistry>,
 1093    pub client: Arc<Client>,
 1094    pub user_store: Entity<UserStore>,
 1095    pub workspace_store: Entity<WorkspaceStore>,
 1096    pub fs: Arc<dyn fs::Fs>,
 1097    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1098    pub node_runtime: NodeRuntime,
 1099    pub session: Entity<AppSession>,
 1100}
 1101
 1102struct GlobalAppState(Arc<AppState>);
 1103
 1104impl Global for GlobalAppState {}
 1105
 1106pub struct WorkspaceStore {
 1107    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1108    client: Arc<Client>,
 1109    _subscriptions: Vec<client::Subscription>,
 1110}
 1111
 1112#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1113pub enum CollaboratorId {
 1114    PeerId(PeerId),
 1115    Agent,
 1116}
 1117
 1118impl From<PeerId> for CollaboratorId {
 1119    fn from(peer_id: PeerId) -> Self {
 1120        CollaboratorId::PeerId(peer_id)
 1121    }
 1122}
 1123
 1124impl From<&PeerId> for CollaboratorId {
 1125    fn from(peer_id: &PeerId) -> Self {
 1126        CollaboratorId::PeerId(*peer_id)
 1127    }
 1128}
 1129
 1130#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1131struct Follower {
 1132    project_id: Option<u64>,
 1133    peer_id: PeerId,
 1134}
 1135
 1136impl AppState {
 1137    #[track_caller]
 1138    pub fn global(cx: &App) -> Arc<Self> {
 1139        cx.global::<GlobalAppState>().0.clone()
 1140    }
 1141    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1142        cx.try_global::<GlobalAppState>()
 1143            .map(|state| state.0.clone())
 1144    }
 1145    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1146        cx.set_global(GlobalAppState(state));
 1147    }
 1148
 1149    #[cfg(any(test, feature = "test-support"))]
 1150    pub fn test(cx: &mut App) -> Arc<Self> {
 1151        use fs::Fs;
 1152        use node_runtime::NodeRuntime;
 1153        use session::Session;
 1154        use settings::SettingsStore;
 1155
 1156        if !cx.has_global::<SettingsStore>() {
 1157            let settings_store = SettingsStore::test(cx);
 1158            cx.set_global(settings_store);
 1159        }
 1160
 1161        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1162        <dyn Fs>::set_global(fs.clone(), cx);
 1163        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1164        let clock = Arc::new(clock::FakeSystemClock::new());
 1165        let http_client = http_client::FakeHttpClient::with_404_response();
 1166        let client = Client::new(clock, http_client, cx);
 1167        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1168        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1169        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1170
 1171        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1172        client::init(&client, cx);
 1173
 1174        Arc::new(Self {
 1175            client,
 1176            fs,
 1177            languages,
 1178            user_store,
 1179            workspace_store,
 1180            node_runtime: NodeRuntime::unavailable(),
 1181            build_window_options: |_, _| Default::default(),
 1182            session,
 1183        })
 1184    }
 1185}
 1186
 1187struct DelayedDebouncedEditAction {
 1188    task: Option<Task<()>>,
 1189    cancel_channel: Option<oneshot::Sender<()>>,
 1190}
 1191
 1192impl DelayedDebouncedEditAction {
 1193    fn new() -> DelayedDebouncedEditAction {
 1194        DelayedDebouncedEditAction {
 1195            task: None,
 1196            cancel_channel: None,
 1197        }
 1198    }
 1199
 1200    fn fire_new<F>(
 1201        &mut self,
 1202        delay: Duration,
 1203        window: &mut Window,
 1204        cx: &mut Context<Workspace>,
 1205        func: F,
 1206    ) where
 1207        F: 'static
 1208            + Send
 1209            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1210    {
 1211        if let Some(channel) = self.cancel_channel.take() {
 1212            _ = channel.send(());
 1213        }
 1214
 1215        let (sender, mut receiver) = oneshot::channel::<()>();
 1216        self.cancel_channel = Some(sender);
 1217
 1218        let previous_task = self.task.take();
 1219        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1220            let mut timer = cx.background_executor().timer(delay).fuse();
 1221            if let Some(previous_task) = previous_task {
 1222                previous_task.await;
 1223            }
 1224
 1225            futures::select_biased! {
 1226                _ = receiver => return,
 1227                    _ = timer => {}
 1228            }
 1229
 1230            if let Some(result) = workspace
 1231                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1232                .log_err()
 1233            {
 1234                result.await.log_err();
 1235            }
 1236        }));
 1237    }
 1238}
 1239
 1240pub enum Event {
 1241    PaneAdded(Entity<Pane>),
 1242    PaneRemoved,
 1243    ItemAdded {
 1244        item: Box<dyn ItemHandle>,
 1245    },
 1246    ActiveItemChanged,
 1247    ItemRemoved {
 1248        item_id: EntityId,
 1249    },
 1250    UserSavedItem {
 1251        pane: WeakEntity<Pane>,
 1252        item: Box<dyn WeakItemHandle>,
 1253        save_intent: SaveIntent,
 1254    },
 1255    ContactRequestedJoin(u64),
 1256    WorkspaceCreated(WeakEntity<Workspace>),
 1257    OpenBundledFile {
 1258        text: Cow<'static, str>,
 1259        title: &'static str,
 1260        language: &'static str,
 1261    },
 1262    ZoomChanged,
 1263    ModalOpened,
 1264    Activate,
 1265    PanelAdded(AnyView),
 1266}
 1267
 1268#[derive(Debug, Clone)]
 1269pub enum OpenVisible {
 1270    All,
 1271    None,
 1272    OnlyFiles,
 1273    OnlyDirectories,
 1274}
 1275
 1276enum WorkspaceLocation {
 1277    // Valid local paths or SSH project to serialize
 1278    Location(SerializedWorkspaceLocation, PathList),
 1279    // No valid location found hence clear session id
 1280    DetachFromSession,
 1281    // No valid location found to serialize
 1282    None,
 1283}
 1284
 1285type PromptForNewPath = Box<
 1286    dyn Fn(
 1287        &mut Workspace,
 1288        DirectoryLister,
 1289        Option<String>,
 1290        &mut Window,
 1291        &mut Context<Workspace>,
 1292    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1293>;
 1294
 1295type PromptForOpenPath = Box<
 1296    dyn Fn(
 1297        &mut Workspace,
 1298        DirectoryLister,
 1299        &mut Window,
 1300        &mut Context<Workspace>,
 1301    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1302>;
 1303
 1304#[derive(Default)]
 1305struct DispatchingKeystrokes {
 1306    dispatched: HashSet<Vec<Keystroke>>,
 1307    queue: VecDeque<Keystroke>,
 1308    task: Option<Shared<Task<()>>>,
 1309}
 1310
 1311/// Collects everything project-related for a certain window opened.
 1312/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1313///
 1314/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1315/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1316/// that can be used to register a global action to be triggered from any place in the window.
 1317pub struct Workspace {
 1318    weak_self: WeakEntity<Self>,
 1319    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1320    zoomed: Option<AnyWeakView>,
 1321    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1322    zoomed_position: Option<DockPosition>,
 1323    center: PaneGroup,
 1324    left_dock: Entity<Dock>,
 1325    bottom_dock: Entity<Dock>,
 1326    right_dock: Entity<Dock>,
 1327    panes: Vec<Entity<Pane>>,
 1328    active_worktree_override: Option<WorktreeId>,
 1329    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1330    active_pane: Entity<Pane>,
 1331    last_active_center_pane: Option<WeakEntity<Pane>>,
 1332    last_active_view_id: Option<proto::ViewId>,
 1333    status_bar: Entity<StatusBar>,
 1334    pub(crate) modal_layer: Entity<ModalLayer>,
 1335    toast_layer: Entity<ToastLayer>,
 1336    titlebar_item: Option<AnyView>,
 1337    notifications: Notifications,
 1338    suppressed_notifications: HashSet<NotificationId>,
 1339    project: Entity<Project>,
 1340    follower_states: HashMap<CollaboratorId, FollowerState>,
 1341    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1342    window_edited: bool,
 1343    last_window_title: Option<String>,
 1344    dirty_items: HashMap<EntityId, Subscription>,
 1345    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1346    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1347    database_id: Option<WorkspaceId>,
 1348    app_state: Arc<AppState>,
 1349    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1350    _subscriptions: Vec<Subscription>,
 1351    _apply_leader_updates: Task<Result<()>>,
 1352    _observe_current_user: Task<Result<()>>,
 1353    _schedule_serialize_workspace: Option<Task<()>>,
 1354    _serialize_workspace_task: Option<Task<()>>,
 1355    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1356    pane_history_timestamp: Arc<AtomicUsize>,
 1357    bounds: Bounds<Pixels>,
 1358    pub centered_layout: bool,
 1359    bounds_save_task_queued: Option<Task<()>>,
 1360    on_prompt_for_new_path: Option<PromptForNewPath>,
 1361    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1362    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1363    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1364    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1365    _items_serializer: Task<Result<()>>,
 1366    session_id: Option<String>,
 1367    scheduled_tasks: Vec<Task<()>>,
 1368    last_open_dock_positions: Vec<DockPosition>,
 1369    removing: bool,
 1370    open_in_dev_container: bool,
 1371    _dev_container_task: Option<Task<Result<()>>>,
 1372    _panels_task: Option<Task<Result<()>>>,
 1373    sidebar_focus_handle: Option<FocusHandle>,
 1374    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1375}
 1376
 1377impl EventEmitter<Event> for Workspace {}
 1378
 1379#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1380pub struct ViewId {
 1381    pub creator: CollaboratorId,
 1382    pub id: u64,
 1383}
 1384
 1385pub struct FollowerState {
 1386    center_pane: Entity<Pane>,
 1387    dock_pane: Option<Entity<Pane>>,
 1388    active_view_id: Option<ViewId>,
 1389    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1390}
 1391
 1392struct FollowerView {
 1393    view: Box<dyn FollowableItemHandle>,
 1394    location: Option<proto::PanelId>,
 1395}
 1396
 1397#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1398pub enum OpenMode {
 1399    /// Open the workspace in a new window.
 1400    NewWindow,
 1401    /// Add to the window's multi workspace without activating it (used during deserialization).
 1402    Add,
 1403    /// Add to the window's multi workspace and activate it.
 1404    #[default]
 1405    Activate,
 1406}
 1407
 1408impl Workspace {
 1409    pub fn new(
 1410        workspace_id: Option<WorkspaceId>,
 1411        project: Entity<Project>,
 1412        app_state: Arc<AppState>,
 1413        window: &mut Window,
 1414        cx: &mut Context<Self>,
 1415    ) -> Self {
 1416        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1417            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1418                if let TrustedWorktreesEvent::Trusted(..) = e {
 1419                    // Do not persist auto trusted worktrees
 1420                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1421                        worktrees_store.update(cx, |worktrees_store, cx| {
 1422                            worktrees_store.schedule_serialization(
 1423                                cx,
 1424                                |new_trusted_worktrees, cx| {
 1425                                    let timeout =
 1426                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1427                                    let db = WorkspaceDb::global(cx);
 1428                                    cx.background_spawn(async move {
 1429                                        timeout.await;
 1430                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1431                                            .await
 1432                                            .log_err();
 1433                                    })
 1434                                },
 1435                            )
 1436                        });
 1437                    }
 1438                }
 1439            })
 1440            .detach();
 1441
 1442            cx.observe_global::<SettingsStore>(|_, cx| {
 1443                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1444                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1445                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1446                            trusted_worktrees.auto_trust_all(cx);
 1447                        })
 1448                    }
 1449                }
 1450            })
 1451            .detach();
 1452        }
 1453
 1454        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1455            match event {
 1456                project::Event::RemoteIdChanged(_) => {
 1457                    this.update_window_title(window, cx);
 1458                }
 1459
 1460                project::Event::CollaboratorLeft(peer_id) => {
 1461                    this.collaborator_left(*peer_id, window, cx);
 1462                }
 1463
 1464                &project::Event::WorktreeRemoved(_) => {
 1465                    this.update_window_title(window, cx);
 1466                    this.serialize_workspace(window, cx);
 1467                    this.update_history(cx);
 1468                }
 1469
 1470                &project::Event::WorktreeAdded(id) => {
 1471                    this.update_window_title(window, cx);
 1472                    if this
 1473                        .project()
 1474                        .read(cx)
 1475                        .worktree_for_id(id, cx)
 1476                        .is_some_and(|wt| wt.read(cx).is_visible())
 1477                    {
 1478                        this.serialize_workspace(window, cx);
 1479                        this.update_history(cx);
 1480                    }
 1481                }
 1482                project::Event::WorktreeUpdatedEntries(..) => {
 1483                    this.update_window_title(window, cx);
 1484                    this.serialize_workspace(window, cx);
 1485                }
 1486
 1487                project::Event::DisconnectedFromHost => {
 1488                    this.update_window_edited(window, cx);
 1489                    let leaders_to_unfollow =
 1490                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1491                    for leader_id in leaders_to_unfollow {
 1492                        this.unfollow(leader_id, window, cx);
 1493                    }
 1494                }
 1495
 1496                project::Event::DisconnectedFromRemote {
 1497                    server_not_running: _,
 1498                } => {
 1499                    this.update_window_edited(window, cx);
 1500                }
 1501
 1502                project::Event::Closed => {
 1503                    window.remove_window();
 1504                }
 1505
 1506                project::Event::DeletedEntry(_, entry_id) => {
 1507                    for pane in this.panes.iter() {
 1508                        pane.update(cx, |pane, cx| {
 1509                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1510                        });
 1511                    }
 1512                }
 1513
 1514                project::Event::Toast {
 1515                    notification_id,
 1516                    message,
 1517                    link,
 1518                } => this.show_notification(
 1519                    NotificationId::named(notification_id.clone()),
 1520                    cx,
 1521                    |cx| {
 1522                        let mut notification = MessageNotification::new(message.clone(), cx);
 1523                        if let Some(link) = link {
 1524                            notification = notification
 1525                                .more_info_message(link.label)
 1526                                .more_info_url(link.url);
 1527                        }
 1528
 1529                        cx.new(|_| notification)
 1530                    },
 1531                ),
 1532
 1533                project::Event::HideToast { notification_id } => {
 1534                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1535                }
 1536
 1537                project::Event::LanguageServerPrompt(request) => {
 1538                    struct LanguageServerPrompt;
 1539
 1540                    this.show_notification(
 1541                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1542                        cx,
 1543                        |cx| {
 1544                            cx.new(|cx| {
 1545                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1546                            })
 1547                        },
 1548                    );
 1549                }
 1550
 1551                project::Event::AgentLocationChanged => {
 1552                    this.handle_agent_location_changed(window, cx)
 1553                }
 1554
 1555                _ => {}
 1556            }
 1557            cx.notify()
 1558        })
 1559        .detach();
 1560
 1561        cx.subscribe_in(
 1562            &project.read(cx).breakpoint_store(),
 1563            window,
 1564            |workspace, _, event, window, cx| match event {
 1565                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1566                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1567                    workspace.serialize_workspace(window, cx);
 1568                }
 1569                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1570            },
 1571        )
 1572        .detach();
 1573        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1574            cx.subscribe_in(
 1575                &toolchain_store,
 1576                window,
 1577                |workspace, _, event, window, cx| match event {
 1578                    ToolchainStoreEvent::CustomToolchainsModified => {
 1579                        workspace.serialize_workspace(window, cx);
 1580                    }
 1581                    _ => {}
 1582                },
 1583            )
 1584            .detach();
 1585        }
 1586
 1587        cx.on_focus_lost(window, |this, window, cx| {
 1588            let focus_handle = this.focus_handle(cx);
 1589            window.focus(&focus_handle, cx);
 1590        })
 1591        .detach();
 1592
 1593        let weak_handle = cx.entity().downgrade();
 1594        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1595
 1596        let center_pane = cx.new(|cx| {
 1597            let mut center_pane = Pane::new(
 1598                weak_handle.clone(),
 1599                project.clone(),
 1600                pane_history_timestamp.clone(),
 1601                None,
 1602                NewFile.boxed_clone(),
 1603                true,
 1604                window,
 1605                cx,
 1606            );
 1607            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1608            center_pane.set_should_display_welcome_page(true);
 1609            center_pane
 1610        });
 1611        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1612            .detach();
 1613
 1614        window.focus(&center_pane.focus_handle(cx), cx);
 1615
 1616        cx.emit(Event::PaneAdded(center_pane.clone()));
 1617
 1618        let any_window_handle = window.window_handle();
 1619        app_state.workspace_store.update(cx, |store, _| {
 1620            store
 1621                .workspaces
 1622                .insert((any_window_handle, weak_handle.clone()));
 1623        });
 1624
 1625        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1626        let mut connection_status = app_state.client.status();
 1627        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1628            current_user.next().await;
 1629            connection_status.next().await;
 1630            let mut stream =
 1631                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1632
 1633            while stream.recv().await.is_some() {
 1634                this.update(cx, |_, cx| cx.notify())?;
 1635            }
 1636            anyhow::Ok(())
 1637        });
 1638
 1639        // All leader updates are enqueued and then processed in a single task, so
 1640        // that each asynchronous operation can be run in order.
 1641        let (leader_updates_tx, mut leader_updates_rx) =
 1642            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1643        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1644            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1645                Self::process_leader_update(&this, leader_id, update, cx)
 1646                    .await
 1647                    .log_err();
 1648            }
 1649
 1650            Ok(())
 1651        });
 1652
 1653        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1654        let modal_layer = cx.new(|_| ModalLayer::new());
 1655        let toast_layer = cx.new(|_| ToastLayer::new());
 1656        cx.subscribe(
 1657            &modal_layer,
 1658            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1659                cx.emit(Event::ModalOpened);
 1660            },
 1661        )
 1662        .detach();
 1663
 1664        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1665        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1666        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1667        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1668        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1669        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1670        let multi_workspace = window
 1671            .root::<MultiWorkspace>()
 1672            .flatten()
 1673            .map(|mw| mw.downgrade());
 1674        let status_bar = cx.new(|cx| {
 1675            let mut status_bar =
 1676                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1677            status_bar.add_left_item(left_dock_buttons, window, cx);
 1678            status_bar.add_right_item(right_dock_buttons, window, cx);
 1679            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1680            status_bar
 1681        });
 1682
 1683        let session_id = app_state.session.read(cx).id().to_owned();
 1684
 1685        let mut active_call = None;
 1686        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1687            let subscriptions =
 1688                vec![
 1689                    call.0
 1690                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1691                ];
 1692            active_call = Some((call, subscriptions));
 1693        }
 1694
 1695        let (serializable_items_tx, serializable_items_rx) =
 1696            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1697        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1698            Self::serialize_items(&this, serializable_items_rx, cx).await
 1699        });
 1700
 1701        let subscriptions = vec![
 1702            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1703            cx.observe_window_bounds(window, move |this, window, cx| {
 1704                if this.bounds_save_task_queued.is_some() {
 1705                    return;
 1706                }
 1707                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1708                    cx.background_executor()
 1709                        .timer(Duration::from_millis(100))
 1710                        .await;
 1711                    this.update_in(cx, |this, window, cx| {
 1712                        this.save_window_bounds(window, cx).detach();
 1713                        this.bounds_save_task_queued.take();
 1714                    })
 1715                    .ok();
 1716                }));
 1717                cx.notify();
 1718            }),
 1719            cx.observe_window_appearance(window, |_, window, cx| {
 1720                let window_appearance = window.appearance();
 1721
 1722                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1723
 1724                theme_settings::reload_theme(cx);
 1725                theme_settings::reload_icon_theme(cx);
 1726            }),
 1727            cx.on_release({
 1728                let weak_handle = weak_handle.clone();
 1729                move |this, cx| {
 1730                    this.app_state.workspace_store.update(cx, move |store, _| {
 1731                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1732                    })
 1733                }
 1734            }),
 1735        ];
 1736
 1737        cx.defer_in(window, move |this, window, cx| {
 1738            this.update_window_title(window, cx);
 1739            this.show_initial_notifications(cx);
 1740        });
 1741
 1742        let mut center = PaneGroup::new(center_pane.clone());
 1743        center.set_is_center(true);
 1744        center.mark_positions(cx);
 1745
 1746        Workspace {
 1747            weak_self: weak_handle.clone(),
 1748            zoomed: None,
 1749            zoomed_position: None,
 1750            previous_dock_drag_coordinates: None,
 1751            center,
 1752            panes: vec![center_pane.clone()],
 1753            panes_by_item: Default::default(),
 1754            active_pane: center_pane.clone(),
 1755            last_active_center_pane: Some(center_pane.downgrade()),
 1756            last_active_view_id: None,
 1757            status_bar,
 1758            modal_layer,
 1759            toast_layer,
 1760            titlebar_item: None,
 1761            active_worktree_override: None,
 1762            notifications: Notifications::default(),
 1763            suppressed_notifications: HashSet::default(),
 1764            left_dock,
 1765            bottom_dock,
 1766            right_dock,
 1767            _panels_task: None,
 1768            project: project.clone(),
 1769            follower_states: Default::default(),
 1770            last_leaders_by_pane: Default::default(),
 1771            dispatching_keystrokes: Default::default(),
 1772            window_edited: false,
 1773            last_window_title: None,
 1774            dirty_items: Default::default(),
 1775            active_call,
 1776            database_id: workspace_id,
 1777            app_state,
 1778            _observe_current_user,
 1779            _apply_leader_updates,
 1780            _schedule_serialize_workspace: None,
 1781            _serialize_workspace_task: None,
 1782            _schedule_serialize_ssh_paths: None,
 1783            leader_updates_tx,
 1784            _subscriptions: subscriptions,
 1785            pane_history_timestamp,
 1786            workspace_actions: Default::default(),
 1787            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1788            bounds: Default::default(),
 1789            centered_layout: false,
 1790            bounds_save_task_queued: None,
 1791            on_prompt_for_new_path: None,
 1792            on_prompt_for_open_path: None,
 1793            terminal_provider: None,
 1794            debugger_provider: None,
 1795            serializable_items_tx,
 1796            _items_serializer,
 1797            session_id: Some(session_id),
 1798
 1799            scheduled_tasks: Vec::new(),
 1800            last_open_dock_positions: Vec::new(),
 1801            removing: false,
 1802            sidebar_focus_handle: None,
 1803            multi_workspace,
 1804            open_in_dev_container: false,
 1805            _dev_container_task: None,
 1806        }
 1807    }
 1808
 1809    pub fn new_local(
 1810        abs_paths: Vec<PathBuf>,
 1811        app_state: Arc<AppState>,
 1812        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1813        env: Option<HashMap<String, String>>,
 1814        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1815        open_mode: OpenMode,
 1816        cx: &mut App,
 1817    ) -> Task<anyhow::Result<OpenResult>> {
 1818        let project_handle = Project::local(
 1819            app_state.client.clone(),
 1820            app_state.node_runtime.clone(),
 1821            app_state.user_store.clone(),
 1822            app_state.languages.clone(),
 1823            app_state.fs.clone(),
 1824            env,
 1825            Default::default(),
 1826            cx,
 1827        );
 1828
 1829        let db = WorkspaceDb::global(cx);
 1830        let kvp = db::kvp::KeyValueStore::global(cx);
 1831        cx.spawn(async move |cx| {
 1832            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1833            for path in abs_paths.into_iter() {
 1834                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1835                    paths_to_open.push(canonical)
 1836                } else {
 1837                    paths_to_open.push(path)
 1838                }
 1839            }
 1840
 1841            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1842
 1843            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1844                paths_to_open = paths.ordered_paths().cloned().collect();
 1845                if !paths.is_lexicographically_ordered() {
 1846                    project_handle.update(cx, |project, cx| {
 1847                        project.set_worktrees_reordered(true, cx);
 1848                    });
 1849                }
 1850            }
 1851
 1852            // Get project paths for all of the abs_paths
 1853            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1854                Vec::with_capacity(paths_to_open.len());
 1855
 1856            for path in paths_to_open.into_iter() {
 1857                if let Some((_, project_entry)) = cx
 1858                    .update(|cx| {
 1859                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1860                    })
 1861                    .await
 1862                    .log_err()
 1863                {
 1864                    project_paths.push((path, Some(project_entry)));
 1865                } else {
 1866                    project_paths.push((path, None));
 1867                }
 1868            }
 1869
 1870            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1871                serialized_workspace.id
 1872            } else {
 1873                db.next_id().await.unwrap_or_else(|_| Default::default())
 1874            };
 1875
 1876            let toolchains = db.toolchains(workspace_id).await?;
 1877
 1878            for (toolchain, worktree_path, path) in toolchains {
 1879                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1880                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1881                    this.find_worktree(&worktree_path, cx)
 1882                        .and_then(|(worktree, rel_path)| {
 1883                            if rel_path.is_empty() {
 1884                                Some(worktree.read(cx).id())
 1885                            } else {
 1886                                None
 1887                            }
 1888                        })
 1889                }) else {
 1890                    // We did not find a worktree with a given path, but that's whatever.
 1891                    continue;
 1892                };
 1893                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1894                    continue;
 1895                }
 1896
 1897                project_handle
 1898                    .update(cx, |this, cx| {
 1899                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1900                    })
 1901                    .await;
 1902            }
 1903            if let Some(workspace) = serialized_workspace.as_ref() {
 1904                project_handle.update(cx, |this, cx| {
 1905                    for (scope, toolchains) in &workspace.user_toolchains {
 1906                        for toolchain in toolchains {
 1907                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1908                        }
 1909                    }
 1910                });
 1911            }
 1912
 1913            let window_to_replace = match open_mode {
 1914                OpenMode::NewWindow => None,
 1915                _ => requesting_window,
 1916            };
 1917
 1918            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1919                if let Some(window) = window_to_replace {
 1920                    let centered_layout = serialized_workspace
 1921                        .as_ref()
 1922                        .map(|w| w.centered_layout)
 1923                        .unwrap_or(false);
 1924
 1925                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1926                        let workspace = cx.new(|cx| {
 1927                            let mut workspace = Workspace::new(
 1928                                Some(workspace_id),
 1929                                project_handle.clone(),
 1930                                app_state.clone(),
 1931                                window,
 1932                                cx,
 1933                            );
 1934
 1935                            workspace.centered_layout = centered_layout;
 1936
 1937                            // Call init callback to add items before window renders
 1938                            if let Some(init) = init {
 1939                                init(&mut workspace, window, cx);
 1940                            }
 1941
 1942                            workspace
 1943                        });
 1944                        match open_mode {
 1945                            OpenMode::Activate => {
 1946                                multi_workspace.activate(workspace.clone(), window, cx);
 1947                            }
 1948                            OpenMode::Add => {
 1949                                multi_workspace.add(workspace.clone(), &*window, cx);
 1950                            }
 1951                            OpenMode::NewWindow => {
 1952                                unreachable!()
 1953                            }
 1954                        }
 1955                        workspace
 1956                    })?;
 1957                    (window, workspace)
 1958                } else {
 1959                    let window_bounds_override = window_bounds_env_override();
 1960
 1961                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1962                        (Some(WindowBounds::Windowed(bounds)), None)
 1963                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1964                        && let Some(display) = workspace.display
 1965                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1966                    {
 1967                        // Reopening an existing workspace - restore its saved bounds
 1968                        (Some(bounds.0), Some(display))
 1969                    } else if let Some((display, bounds)) =
 1970                        persistence::read_default_window_bounds(&kvp)
 1971                    {
 1972                        // New or empty workspace - use the last known window bounds
 1973                        (Some(bounds), Some(display))
 1974                    } else {
 1975                        // New window - let GPUI's default_bounds() handle cascading
 1976                        (None, None)
 1977                    };
 1978
 1979                    // Use the serialized workspace to construct the new window
 1980                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1981                    options.window_bounds = window_bounds;
 1982                    let centered_layout = serialized_workspace
 1983                        .as_ref()
 1984                        .map(|w| w.centered_layout)
 1985                        .unwrap_or(false);
 1986                    let window = cx.open_window(options, {
 1987                        let app_state = app_state.clone();
 1988                        let project_handle = project_handle.clone();
 1989                        move |window, cx| {
 1990                            let workspace = cx.new(|cx| {
 1991                                let mut workspace = Workspace::new(
 1992                                    Some(workspace_id),
 1993                                    project_handle,
 1994                                    app_state,
 1995                                    window,
 1996                                    cx,
 1997                                );
 1998                                workspace.centered_layout = centered_layout;
 1999
 2000                                // Call init callback to add items before window renders
 2001                                if let Some(init) = init {
 2002                                    init(&mut workspace, window, cx);
 2003                                }
 2004
 2005                                workspace
 2006                            });
 2007                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 2008                        }
 2009                    })?;
 2010                    let workspace =
 2011                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 2012                            multi_workspace.workspace().clone()
 2013                        })?;
 2014                    (window, workspace)
 2015                };
 2016
 2017            notify_if_database_failed(window, cx);
 2018            // Check if this is an empty workspace (no paths to open)
 2019            // An empty workspace is one where project_paths is empty
 2020            let is_empty_workspace = project_paths.is_empty();
 2021            // Check if serialized workspace has paths before it's moved
 2022            let serialized_workspace_has_paths = serialized_workspace
 2023                .as_ref()
 2024                .map(|ws| !ws.paths.is_empty())
 2025                .unwrap_or(false);
 2026
 2027            let opened_items = window
 2028                .update(cx, |_, window, cx| {
 2029                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2030                        open_items(serialized_workspace, project_paths, window, cx)
 2031                    })
 2032                })?
 2033                .await
 2034                .unwrap_or_default();
 2035
 2036            // Restore default dock state for empty workspaces
 2037            // Only restore if:
 2038            // 1. This is an empty workspace (no paths), AND
 2039            // 2. The serialized workspace either doesn't exist or has no paths
 2040            if is_empty_workspace && !serialized_workspace_has_paths {
 2041                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2042                    window
 2043                        .update(cx, |_, window, cx| {
 2044                            workspace.update(cx, |workspace, cx| {
 2045                                for (dock, serialized_dock) in [
 2046                                    (&workspace.right_dock, &default_docks.right),
 2047                                    (&workspace.left_dock, &default_docks.left),
 2048                                    (&workspace.bottom_dock, &default_docks.bottom),
 2049                                ] {
 2050                                    dock.update(cx, |dock, cx| {
 2051                                        dock.serialized_dock = Some(serialized_dock.clone());
 2052                                        dock.restore_state(window, cx);
 2053                                    });
 2054                                }
 2055                                cx.notify();
 2056                            });
 2057                        })
 2058                        .log_err();
 2059                }
 2060            }
 2061
 2062            window
 2063                .update(cx, |_, _window, cx| {
 2064                    workspace.update(cx, |this: &mut Workspace, cx| {
 2065                        this.update_history(cx);
 2066                    });
 2067                })
 2068                .log_err();
 2069            Ok(OpenResult {
 2070                window,
 2071                workspace,
 2072                opened_items,
 2073            })
 2074        })
 2075    }
 2076
 2077    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2078        self.project.read(cx).project_group_key(cx)
 2079    }
 2080
 2081    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2082        self.weak_self.clone()
 2083    }
 2084
 2085    pub fn left_dock(&self) -> &Entity<Dock> {
 2086        &self.left_dock
 2087    }
 2088
 2089    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2090        &self.bottom_dock
 2091    }
 2092
 2093    pub fn set_bottom_dock_layout(
 2094        &mut self,
 2095        layout: BottomDockLayout,
 2096        window: &mut Window,
 2097        cx: &mut Context<Self>,
 2098    ) {
 2099        let fs = self.project().read(cx).fs();
 2100        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2101            content.workspace.bottom_dock_layout = Some(layout);
 2102        });
 2103
 2104        cx.notify();
 2105        self.serialize_workspace(window, cx);
 2106    }
 2107
 2108    pub fn right_dock(&self) -> &Entity<Dock> {
 2109        &self.right_dock
 2110    }
 2111
 2112    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2113        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2114    }
 2115
 2116    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2117        let left_dock = self.left_dock.read(cx);
 2118        let left_visible = left_dock.is_open();
 2119        let left_active_panel = left_dock
 2120            .active_panel()
 2121            .map(|panel| panel.persistent_name().to_string());
 2122        // `zoomed_position` is kept in sync with individual panel zoom state
 2123        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2124        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2125
 2126        let right_dock = self.right_dock.read(cx);
 2127        let right_visible = right_dock.is_open();
 2128        let right_active_panel = right_dock
 2129            .active_panel()
 2130            .map(|panel| panel.persistent_name().to_string());
 2131        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2132
 2133        let bottom_dock = self.bottom_dock.read(cx);
 2134        let bottom_visible = bottom_dock.is_open();
 2135        let bottom_active_panel = bottom_dock
 2136            .active_panel()
 2137            .map(|panel| panel.persistent_name().to_string());
 2138        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2139
 2140        DockStructure {
 2141            left: DockData {
 2142                visible: left_visible,
 2143                active_panel: left_active_panel,
 2144                zoom: left_dock_zoom,
 2145            },
 2146            right: DockData {
 2147                visible: right_visible,
 2148                active_panel: right_active_panel,
 2149                zoom: right_dock_zoom,
 2150            },
 2151            bottom: DockData {
 2152                visible: bottom_visible,
 2153                active_panel: bottom_active_panel,
 2154                zoom: bottom_dock_zoom,
 2155            },
 2156        }
 2157    }
 2158
 2159    pub fn set_dock_structure(
 2160        &self,
 2161        docks: DockStructure,
 2162        window: &mut Window,
 2163        cx: &mut Context<Self>,
 2164    ) {
 2165        for (dock, data) in [
 2166            (&self.left_dock, docks.left),
 2167            (&self.bottom_dock, docks.bottom),
 2168            (&self.right_dock, docks.right),
 2169        ] {
 2170            dock.update(cx, |dock, cx| {
 2171                dock.serialized_dock = Some(data);
 2172                dock.restore_state(window, cx);
 2173            });
 2174        }
 2175    }
 2176
 2177    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2178        self.items(cx)
 2179            .filter_map(|item| {
 2180                let project_path = item.project_path(cx)?;
 2181                self.project.read(cx).absolute_path(&project_path, cx)
 2182            })
 2183            .collect()
 2184    }
 2185
 2186    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2187        match position {
 2188            DockPosition::Left => &self.left_dock,
 2189            DockPosition::Bottom => &self.bottom_dock,
 2190            DockPosition::Right => &self.right_dock,
 2191        }
 2192    }
 2193
 2194    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2195        self.all_docks().into_iter().find_map(|dock| {
 2196            let dock = dock.read(cx);
 2197            dock.has_agent_panel(cx).then_some(dock.position())
 2198        })
 2199    }
 2200
 2201    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2202        self.all_docks().into_iter().find_map(|dock| {
 2203            let dock = dock.read(cx);
 2204            let panel = dock.panel::<T>()?;
 2205            dock.stored_panel_size_state(&panel)
 2206        })
 2207    }
 2208
 2209    pub fn persisted_panel_size_state(
 2210        &self,
 2211        panel_key: &'static str,
 2212        cx: &App,
 2213    ) -> Option<dock::PanelSizeState> {
 2214        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2215    }
 2216
 2217    pub fn persist_panel_size_state(
 2218        &self,
 2219        panel_key: &str,
 2220        size_state: dock::PanelSizeState,
 2221        cx: &mut App,
 2222    ) {
 2223        let Some(workspace_id) = self
 2224            .database_id()
 2225            .map(|id| i64::from(id).to_string())
 2226            .or(self.session_id())
 2227        else {
 2228            return;
 2229        };
 2230
 2231        let kvp = db::kvp::KeyValueStore::global(cx);
 2232        let panel_key = panel_key.to_string();
 2233        cx.background_spawn(async move {
 2234            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2235            scope
 2236                .write(
 2237                    format!("{workspace_id}:{panel_key}"),
 2238                    serde_json::to_string(&size_state)?,
 2239                )
 2240                .await
 2241        })
 2242        .detach_and_log_err(cx);
 2243    }
 2244
 2245    pub fn set_panel_size_state<T: Panel>(
 2246        &mut self,
 2247        size_state: dock::PanelSizeState,
 2248        window: &mut Window,
 2249        cx: &mut Context<Self>,
 2250    ) -> bool {
 2251        let Some(panel) = self.panel::<T>(cx) else {
 2252            return false;
 2253        };
 2254
 2255        let dock = self.dock_at_position(panel.position(window, cx));
 2256        let did_set = dock.update(cx, |dock, cx| {
 2257            dock.set_panel_size_state(&panel, size_state, cx)
 2258        });
 2259
 2260        if did_set {
 2261            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2262        }
 2263
 2264        did_set
 2265    }
 2266
 2267    pub fn toggle_dock_panel_flexible_size(
 2268        &self,
 2269        dock: &Entity<Dock>,
 2270        panel: &dyn PanelHandle,
 2271        window: &mut Window,
 2272        cx: &mut App,
 2273    ) {
 2274        let position = dock.read(cx).position();
 2275        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2276        let current_flex =
 2277            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2278        dock.update(cx, |dock, cx| {
 2279            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2280        });
 2281    }
 2282
 2283    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2284        let panel = dock.active_panel()?;
 2285        let size_state = dock
 2286            .stored_panel_size_state(panel.as_ref())
 2287            .unwrap_or_default();
 2288        let position = dock.position();
 2289
 2290        let use_flex = panel.has_flexible_size(window, cx);
 2291
 2292        if position.axis() == Axis::Horizontal
 2293            && use_flex
 2294            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2295        {
 2296            let workspace_width = self.bounds.size.width;
 2297            if workspace_width <= Pixels::ZERO {
 2298                return None;
 2299            }
 2300            let flex = flex.max(0.001);
 2301            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2302            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2303                // Both docks are flex items sharing the full workspace width.
 2304                let total_flex = flex + 1.0 + opposite_flex;
 2305                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2306            } else {
 2307                // Opposite dock is fixed-width; flex items share (W - fixed).
 2308                let opposite_fixed = opposite
 2309                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2310                    .unwrap_or_default();
 2311                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2312                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2313            }
 2314        }
 2315
 2316        Some(
 2317            size_state
 2318                .size
 2319                .unwrap_or_else(|| panel.default_size(window, cx)),
 2320        )
 2321    }
 2322
 2323    pub fn dock_flex_for_size(
 2324        &self,
 2325        position: DockPosition,
 2326        size: Pixels,
 2327        window: &Window,
 2328        cx: &App,
 2329    ) -> Option<f32> {
 2330        if position.axis() != Axis::Horizontal {
 2331            return None;
 2332        }
 2333
 2334        let workspace_width = self.bounds.size.width;
 2335        if workspace_width <= Pixels::ZERO {
 2336            return None;
 2337        }
 2338
 2339        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2340        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2341            let size = size.clamp(px(0.), workspace_width - px(1.));
 2342            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2343        } else {
 2344            let opposite_width = opposite
 2345                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2346                .unwrap_or_default();
 2347            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2348            let remaining = (available - size).max(px(1.));
 2349            Some((size / remaining).max(0.0))
 2350        }
 2351    }
 2352
 2353    fn opposite_dock_panel_and_size_state(
 2354        &self,
 2355        position: DockPosition,
 2356        window: &Window,
 2357        cx: &App,
 2358    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2359        let opposite_position = match position {
 2360            DockPosition::Left => DockPosition::Right,
 2361            DockPosition::Right => DockPosition::Left,
 2362            DockPosition::Bottom => return None,
 2363        };
 2364
 2365        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2366        let panel = opposite_dock.visible_panel()?;
 2367        let mut size_state = opposite_dock
 2368            .stored_panel_size_state(panel.as_ref())
 2369            .unwrap_or_default();
 2370        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2371            size_state.flex = self.default_dock_flex(opposite_position);
 2372        }
 2373        Some((panel.clone(), size_state))
 2374    }
 2375
 2376    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2377        if position.axis() != Axis::Horizontal {
 2378            return None;
 2379        }
 2380
 2381        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2382        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2383    }
 2384
 2385    pub fn is_edited(&self) -> bool {
 2386        self.window_edited
 2387    }
 2388
 2389    pub fn add_panel<T: Panel>(
 2390        &mut self,
 2391        panel: Entity<T>,
 2392        window: &mut Window,
 2393        cx: &mut Context<Self>,
 2394    ) {
 2395        let focus_handle = panel.panel_focus_handle(cx);
 2396        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2397            .detach();
 2398
 2399        let dock_position = panel.position(window, cx);
 2400        let dock = self.dock_at_position(dock_position);
 2401        let any_panel = panel.to_any();
 2402        let persisted_size_state =
 2403            self.persisted_panel_size_state(T::panel_key(), cx)
 2404                .or_else(|| {
 2405                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2406                        let state = dock::PanelSizeState {
 2407                            size: Some(size),
 2408                            flex: None,
 2409                        };
 2410                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2411                        state
 2412                    })
 2413                });
 2414
 2415        dock.update(cx, |dock, cx| {
 2416            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2417            if let Some(size_state) = persisted_size_state {
 2418                dock.set_panel_size_state(&panel, size_state, cx);
 2419            }
 2420            index
 2421        });
 2422
 2423        cx.emit(Event::PanelAdded(any_panel));
 2424    }
 2425
 2426    pub fn remove_panel<T: Panel>(
 2427        &mut self,
 2428        panel: &Entity<T>,
 2429        window: &mut Window,
 2430        cx: &mut Context<Self>,
 2431    ) {
 2432        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2433            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2434        }
 2435    }
 2436
 2437    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2438        &self.status_bar
 2439    }
 2440
 2441    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2442        self.sidebar_focus_handle = handle;
 2443    }
 2444
 2445    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2446        StatusBarSettings::get_global(cx).show
 2447    }
 2448
 2449    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2450        self.multi_workspace.as_ref()
 2451    }
 2452
 2453    pub fn set_multi_workspace(
 2454        &mut self,
 2455        multi_workspace: WeakEntity<MultiWorkspace>,
 2456        cx: &mut App,
 2457    ) {
 2458        self.status_bar.update(cx, |status_bar, cx| {
 2459            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2460        });
 2461        self.multi_workspace = Some(multi_workspace);
 2462    }
 2463
 2464    pub fn app_state(&self) -> &Arc<AppState> {
 2465        &self.app_state
 2466    }
 2467
 2468    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2469        self._panels_task = Some(task);
 2470    }
 2471
 2472    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2473        self._panels_task.take()
 2474    }
 2475
 2476    pub fn user_store(&self) -> &Entity<UserStore> {
 2477        &self.app_state.user_store
 2478    }
 2479
 2480    pub fn project(&self) -> &Entity<Project> {
 2481        &self.project
 2482    }
 2483
 2484    pub fn path_style(&self, cx: &App) -> PathStyle {
 2485        self.project.read(cx).path_style(cx)
 2486    }
 2487
 2488    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2489        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2490
 2491        for pane_handle in &self.panes {
 2492            let pane = pane_handle.read(cx);
 2493
 2494            for entry in pane.activation_history() {
 2495                history.insert(
 2496                    entry.entity_id,
 2497                    history
 2498                        .get(&entry.entity_id)
 2499                        .cloned()
 2500                        .unwrap_or(0)
 2501                        .max(entry.timestamp),
 2502                );
 2503            }
 2504        }
 2505
 2506        history
 2507    }
 2508
 2509    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2510        let mut recent_item: Option<Entity<T>> = None;
 2511        let mut recent_timestamp = 0;
 2512        for pane_handle in &self.panes {
 2513            let pane = pane_handle.read(cx);
 2514            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2515                pane.items().map(|item| (item.item_id(), item)).collect();
 2516            for entry in pane.activation_history() {
 2517                if entry.timestamp > recent_timestamp
 2518                    && let Some(&item) = item_map.get(&entry.entity_id)
 2519                    && let Some(typed_item) = item.act_as::<T>(cx)
 2520                {
 2521                    recent_timestamp = entry.timestamp;
 2522                    recent_item = Some(typed_item);
 2523                }
 2524            }
 2525        }
 2526        recent_item
 2527    }
 2528
 2529    pub fn recent_navigation_history_iter(
 2530        &self,
 2531        cx: &App,
 2532    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2533        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2534        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2535
 2536        for pane in &self.panes {
 2537            let pane = pane.read(cx);
 2538
 2539            pane.nav_history()
 2540                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 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                    let timestamp = entry.timestamp;
 2548                    match history.entry(project_path) {
 2549                        hash_map::Entry::Occupied(mut entry) => {
 2550                            let (_, old_timestamp) = entry.get();
 2551                            if &timestamp > old_timestamp {
 2552                                entry.insert((fs_path, timestamp));
 2553                            }
 2554                        }
 2555                        hash_map::Entry::Vacant(entry) => {
 2556                            entry.insert((fs_path, timestamp));
 2557                        }
 2558                    }
 2559                });
 2560
 2561            if let Some(item) = pane.active_item()
 2562                && let Some(project_path) = item.project_path(cx)
 2563            {
 2564                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2565
 2566                if let Some(fs_path) = &fs_path {
 2567                    abs_paths_opened
 2568                        .entry(fs_path.clone())
 2569                        .or_default()
 2570                        .insert(project_path.clone());
 2571                }
 2572
 2573                history.insert(project_path, (fs_path, std::usize::MAX));
 2574            }
 2575        }
 2576
 2577        history
 2578            .into_iter()
 2579            .sorted_by_key(|(_, (_, order))| *order)
 2580            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2581            .rev()
 2582            .filter(move |(history_path, abs_path)| {
 2583                let latest_project_path_opened = abs_path
 2584                    .as_ref()
 2585                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2586                    .and_then(|project_paths| {
 2587                        project_paths
 2588                            .iter()
 2589                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2590                    });
 2591
 2592                latest_project_path_opened.is_none_or(|path| path == history_path)
 2593            })
 2594    }
 2595
 2596    pub fn recent_navigation_history(
 2597        &self,
 2598        limit: Option<usize>,
 2599        cx: &App,
 2600    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2601        self.recent_navigation_history_iter(cx)
 2602            .take(limit.unwrap_or(usize::MAX))
 2603            .collect()
 2604    }
 2605
 2606    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2607        for pane in &self.panes {
 2608            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2609        }
 2610    }
 2611
 2612    fn navigate_history(
 2613        &mut self,
 2614        pane: WeakEntity<Pane>,
 2615        mode: NavigationMode,
 2616        window: &mut Window,
 2617        cx: &mut Context<Workspace>,
 2618    ) -> Task<Result<()>> {
 2619        self.navigate_history_impl(
 2620            pane,
 2621            mode,
 2622            window,
 2623            &mut |history, cx| history.pop(mode, cx),
 2624            cx,
 2625        )
 2626    }
 2627
 2628    fn navigate_tag_history(
 2629        &mut self,
 2630        pane: WeakEntity<Pane>,
 2631        mode: TagNavigationMode,
 2632        window: &mut Window,
 2633        cx: &mut Context<Workspace>,
 2634    ) -> Task<Result<()>> {
 2635        self.navigate_history_impl(
 2636            pane,
 2637            NavigationMode::Normal,
 2638            window,
 2639            &mut |history, _cx| history.pop_tag(mode),
 2640            cx,
 2641        )
 2642    }
 2643
 2644    fn navigate_history_impl(
 2645        &mut self,
 2646        pane: WeakEntity<Pane>,
 2647        mode: NavigationMode,
 2648        window: &mut Window,
 2649        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2650        cx: &mut Context<Workspace>,
 2651    ) -> Task<Result<()>> {
 2652        let to_load = if let Some(pane) = pane.upgrade() {
 2653            pane.update(cx, |pane, cx| {
 2654                window.focus(&pane.focus_handle(cx), cx);
 2655                loop {
 2656                    // Retrieve the weak item handle from the history.
 2657                    let entry = cb(pane.nav_history_mut(), cx)?;
 2658
 2659                    // If the item is still present in this pane, then activate it.
 2660                    if let Some(index) = entry
 2661                        .item
 2662                        .upgrade()
 2663                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2664                    {
 2665                        let prev_active_item_index = pane.active_item_index();
 2666                        pane.nav_history_mut().set_mode(mode);
 2667                        pane.activate_item(index, true, true, window, cx);
 2668                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2669
 2670                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2671                        if let Some(data) = entry.data {
 2672                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2673                        }
 2674
 2675                        if navigated {
 2676                            break None;
 2677                        }
 2678                    } else {
 2679                        // If the item is no longer present in this pane, then retrieve its
 2680                        // path info in order to reopen it.
 2681                        break pane
 2682                            .nav_history()
 2683                            .path_for_item(entry.item.id())
 2684                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2685                    }
 2686                }
 2687            })
 2688        } else {
 2689            None
 2690        };
 2691
 2692        if let Some((project_path, abs_path, entry)) = to_load {
 2693            // If the item was no longer present, then load it again from its previous path, first try the local path
 2694            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2695
 2696            cx.spawn_in(window, async move  |workspace, cx| {
 2697                let open_by_project_path = open_by_project_path.await;
 2698                let mut navigated = false;
 2699                match open_by_project_path
 2700                    .with_context(|| format!("Navigating to {project_path:?}"))
 2701                {
 2702                    Ok((project_entry_id, build_item)) => {
 2703                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2704                            pane.nav_history_mut().set_mode(mode);
 2705                            pane.active_item().map(|p| p.item_id())
 2706                        })?;
 2707
 2708                        pane.update_in(cx, |pane, window, cx| {
 2709                            let item = pane.open_item(
 2710                                project_entry_id,
 2711                                project_path,
 2712                                true,
 2713                                entry.is_preview,
 2714                                true,
 2715                                None,
 2716                                window, cx,
 2717                                build_item,
 2718                            );
 2719                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2720                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2721                            if let Some(data) = entry.data {
 2722                                navigated |= item.navigate(data, window, cx);
 2723                            }
 2724                        })?;
 2725                    }
 2726                    Err(open_by_project_path_e) => {
 2727                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2728                        // and its worktree is now dropped
 2729                        if let Some(abs_path) = abs_path {
 2730                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2731                                pane.nav_history_mut().set_mode(mode);
 2732                                pane.active_item().map(|p| p.item_id())
 2733                            })?;
 2734                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2735                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2736                            })?;
 2737                            match open_by_abs_path
 2738                                .await
 2739                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2740                            {
 2741                                Ok(item) => {
 2742                                    pane.update_in(cx, |pane, window, cx| {
 2743                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2744                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2745                                        if let Some(data) = entry.data {
 2746                                            navigated |= item.navigate(data, window, cx);
 2747                                        }
 2748                                    })?;
 2749                                }
 2750                                Err(open_by_abs_path_e) => {
 2751                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2752                                }
 2753                            }
 2754                        }
 2755                    }
 2756                }
 2757
 2758                if !navigated {
 2759                    workspace
 2760                        .update_in(cx, |workspace, window, cx| {
 2761                            Self::navigate_history(workspace, pane, mode, window, cx)
 2762                        })?
 2763                        .await?;
 2764                }
 2765
 2766                Ok(())
 2767            })
 2768        } else {
 2769            Task::ready(Ok(()))
 2770        }
 2771    }
 2772
 2773    pub fn go_back(
 2774        &mut self,
 2775        pane: WeakEntity<Pane>,
 2776        window: &mut Window,
 2777        cx: &mut Context<Workspace>,
 2778    ) -> Task<Result<()>> {
 2779        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2780    }
 2781
 2782    pub fn go_forward(
 2783        &mut self,
 2784        pane: WeakEntity<Pane>,
 2785        window: &mut Window,
 2786        cx: &mut Context<Workspace>,
 2787    ) -> Task<Result<()>> {
 2788        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2789    }
 2790
 2791    pub fn reopen_closed_item(
 2792        &mut self,
 2793        window: &mut Window,
 2794        cx: &mut Context<Workspace>,
 2795    ) -> Task<Result<()>> {
 2796        self.navigate_history(
 2797            self.active_pane().downgrade(),
 2798            NavigationMode::ReopeningClosedItem,
 2799            window,
 2800            cx,
 2801        )
 2802    }
 2803
 2804    pub fn client(&self) -> &Arc<Client> {
 2805        &self.app_state.client
 2806    }
 2807
 2808    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2809        self.titlebar_item = Some(item);
 2810        cx.notify();
 2811    }
 2812
 2813    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2814        self.on_prompt_for_new_path = Some(prompt)
 2815    }
 2816
 2817    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2818        self.on_prompt_for_open_path = Some(prompt)
 2819    }
 2820
 2821    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2822        self.terminal_provider = Some(Box::new(provider));
 2823    }
 2824
 2825    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2826        self.debugger_provider = Some(Arc::new(provider));
 2827    }
 2828
 2829    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2830        self.open_in_dev_container = value;
 2831    }
 2832
 2833    pub fn open_in_dev_container(&self) -> bool {
 2834        self.open_in_dev_container
 2835    }
 2836
 2837    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2838        self._dev_container_task = Some(task);
 2839    }
 2840
 2841    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2842        self.debugger_provider.clone()
 2843    }
 2844
 2845    pub fn prompt_for_open_path(
 2846        &mut self,
 2847        path_prompt_options: PathPromptOptions,
 2848        lister: DirectoryLister,
 2849        window: &mut Window,
 2850        cx: &mut Context<Self>,
 2851    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2852        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2853            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2854            let rx = prompt(self, lister, window, cx);
 2855            self.on_prompt_for_open_path = Some(prompt);
 2856            rx
 2857        } else {
 2858            let (tx, rx) = oneshot::channel();
 2859            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2860
 2861            cx.spawn_in(window, async move |workspace, cx| {
 2862                let Ok(result) = abs_path.await else {
 2863                    return Ok(());
 2864                };
 2865
 2866                match result {
 2867                    Ok(result) => {
 2868                        tx.send(result).ok();
 2869                    }
 2870                    Err(err) => {
 2871                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2872                            workspace.show_portal_error(err.to_string(), cx);
 2873                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2874                            let rx = prompt(workspace, lister, window, cx);
 2875                            workspace.on_prompt_for_open_path = Some(prompt);
 2876                            rx
 2877                        })?;
 2878                        if let Ok(path) = rx.await {
 2879                            tx.send(path).ok();
 2880                        }
 2881                    }
 2882                };
 2883                anyhow::Ok(())
 2884            })
 2885            .detach();
 2886
 2887            rx
 2888        }
 2889    }
 2890
 2891    pub fn prompt_for_new_path(
 2892        &mut self,
 2893        lister: DirectoryLister,
 2894        suggested_name: Option<String>,
 2895        window: &mut Window,
 2896        cx: &mut Context<Self>,
 2897    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2898        if self.project.read(cx).is_via_collab()
 2899            || self.project.read(cx).is_via_remote_server()
 2900            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2901        {
 2902            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2903            let rx = prompt(self, lister, suggested_name, window, cx);
 2904            self.on_prompt_for_new_path = Some(prompt);
 2905            return rx;
 2906        }
 2907
 2908        let (tx, rx) = oneshot::channel();
 2909        cx.spawn_in(window, async move |workspace, cx| {
 2910            let abs_path = workspace.update(cx, |workspace, cx| {
 2911                let relative_to = workspace
 2912                    .most_recent_active_path(cx)
 2913                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2914                    .or_else(|| {
 2915                        let project = workspace.project.read(cx);
 2916                        project.visible_worktrees(cx).find_map(|worktree| {
 2917                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2918                        })
 2919                    })
 2920                    .or_else(std::env::home_dir)
 2921                    .unwrap_or_else(|| PathBuf::from(""));
 2922                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2923            })?;
 2924            let abs_path = match abs_path.await? {
 2925                Ok(path) => path,
 2926                Err(err) => {
 2927                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2928                        workspace.show_portal_error(err.to_string(), cx);
 2929
 2930                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2931                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2932                        workspace.on_prompt_for_new_path = Some(prompt);
 2933                        rx
 2934                    })?;
 2935                    if let Ok(path) = rx.await {
 2936                        tx.send(path).ok();
 2937                    }
 2938                    return anyhow::Ok(());
 2939                }
 2940            };
 2941
 2942            tx.send(abs_path.map(|path| vec![path])).ok();
 2943            anyhow::Ok(())
 2944        })
 2945        .detach();
 2946
 2947        rx
 2948    }
 2949
 2950    pub fn titlebar_item(&self) -> Option<AnyView> {
 2951        self.titlebar_item.clone()
 2952    }
 2953
 2954    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2955    /// When set, git-related operations should use this worktree instead of deriving
 2956    /// the active worktree from the focused file.
 2957    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2958        self.active_worktree_override
 2959    }
 2960
 2961    pub fn set_active_worktree_override(
 2962        &mut self,
 2963        worktree_id: Option<WorktreeId>,
 2964        cx: &mut Context<Self>,
 2965    ) {
 2966        self.active_worktree_override = worktree_id;
 2967        cx.notify();
 2968    }
 2969
 2970    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2971        self.active_worktree_override = None;
 2972        cx.notify();
 2973    }
 2974
 2975    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2976    ///
 2977    /// If the given workspace has a local project, then it will be passed
 2978    /// to the callback. Otherwise, a new empty window will be created.
 2979    pub fn with_local_workspace<T, F>(
 2980        &mut self,
 2981        window: &mut Window,
 2982        cx: &mut Context<Self>,
 2983        callback: F,
 2984    ) -> Task<Result<T>>
 2985    where
 2986        T: 'static,
 2987        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2988    {
 2989        if self.project.read(cx).is_local() {
 2990            Task::ready(Ok(callback(self, window, cx)))
 2991        } else {
 2992            let env = self.project.read(cx).cli_environment(cx);
 2993            let task = Self::new_local(
 2994                Vec::new(),
 2995                self.app_state.clone(),
 2996                None,
 2997                env,
 2998                None,
 2999                OpenMode::Activate,
 3000                cx,
 3001            );
 3002            cx.spawn_in(window, async move |_vh, cx| {
 3003                let OpenResult {
 3004                    window: multi_workspace_window,
 3005                    ..
 3006                } = task.await?;
 3007                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3008                    let workspace = multi_workspace.workspace().clone();
 3009                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3010                })
 3011            })
 3012        }
 3013    }
 3014
 3015    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3016    ///
 3017    /// If the given workspace has a local project, then it will be passed
 3018    /// to the callback. Otherwise, a new empty window will be created.
 3019    pub fn with_local_or_wsl_workspace<T, F>(
 3020        &mut self,
 3021        window: &mut Window,
 3022        cx: &mut Context<Self>,
 3023        callback: F,
 3024    ) -> Task<Result<T>>
 3025    where
 3026        T: 'static,
 3027        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3028    {
 3029        let project = self.project.read(cx);
 3030        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3031            Task::ready(Ok(callback(self, window, cx)))
 3032        } else {
 3033            let env = self.project.read(cx).cli_environment(cx);
 3034            let task = Self::new_local(
 3035                Vec::new(),
 3036                self.app_state.clone(),
 3037                None,
 3038                env,
 3039                None,
 3040                OpenMode::Activate,
 3041                cx,
 3042            );
 3043            cx.spawn_in(window, async move |_vh, cx| {
 3044                let OpenResult {
 3045                    window: multi_workspace_window,
 3046                    ..
 3047                } = task.await?;
 3048                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3049                    let workspace = multi_workspace.workspace().clone();
 3050                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3051                })
 3052            })
 3053        }
 3054    }
 3055
 3056    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3057        self.project.read(cx).worktrees(cx)
 3058    }
 3059
 3060    pub fn visible_worktrees<'a>(
 3061        &self,
 3062        cx: &'a App,
 3063    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3064        self.project.read(cx).visible_worktrees(cx)
 3065    }
 3066
 3067    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3068        let futures = self
 3069            .worktrees(cx)
 3070            .filter_map(|worktree| worktree.read(cx).as_local())
 3071            .map(|worktree| worktree.scan_complete())
 3072            .collect::<Vec<_>>();
 3073        async move {
 3074            for future in futures {
 3075                future.await;
 3076            }
 3077        }
 3078    }
 3079
 3080    pub fn close_global(cx: &mut App) {
 3081        cx.defer(|cx| {
 3082            cx.windows().iter().find(|window| {
 3083                window
 3084                    .update(cx, |_, window, _| {
 3085                        if window.is_window_active() {
 3086                            //This can only get called when the window's project connection has been lost
 3087                            //so we don't need to prompt the user for anything and instead just close the window
 3088                            window.remove_window();
 3089                            true
 3090                        } else {
 3091                            false
 3092                        }
 3093                    })
 3094                    .unwrap_or(false)
 3095            });
 3096        });
 3097    }
 3098
 3099    pub fn move_focused_panel_to_next_position(
 3100        &mut self,
 3101        _: &MoveFocusedPanelToNextPosition,
 3102        window: &mut Window,
 3103        cx: &mut Context<Self>,
 3104    ) {
 3105        let docks = self.all_docks();
 3106        let active_dock = docks
 3107            .into_iter()
 3108            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3109
 3110        if let Some(dock) = active_dock {
 3111            dock.update(cx, |dock, cx| {
 3112                let active_panel = dock
 3113                    .active_panel()
 3114                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3115
 3116                if let Some(panel) = active_panel {
 3117                    panel.move_to_next_position(window, cx);
 3118                }
 3119            })
 3120        }
 3121    }
 3122
 3123    pub fn prepare_to_close(
 3124        &mut self,
 3125        close_intent: CloseIntent,
 3126        window: &mut Window,
 3127        cx: &mut Context<Self>,
 3128    ) -> Task<Result<bool>> {
 3129        let active_call = self.active_global_call();
 3130
 3131        cx.spawn_in(window, async move |this, cx| {
 3132            this.update(cx, |this, _| {
 3133                if close_intent == CloseIntent::CloseWindow {
 3134                    this.removing = true;
 3135                }
 3136            })?;
 3137
 3138            let workspace_count = cx.update(|_window, cx| {
 3139                cx.windows()
 3140                    .iter()
 3141                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3142                    .count()
 3143            })?;
 3144
 3145            #[cfg(target_os = "macos")]
 3146            let save_last_workspace = false;
 3147
 3148            // On Linux and Windows, closing the last window should restore the last workspace.
 3149            #[cfg(not(target_os = "macos"))]
 3150            let save_last_workspace = {
 3151                let remaining_workspaces = cx.update(|_window, cx| {
 3152                    cx.windows()
 3153                        .iter()
 3154                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3155                        .filter_map(|multi_workspace| {
 3156                            multi_workspace
 3157                                .update(cx, |multi_workspace, _, cx| {
 3158                                    multi_workspace.workspace().read(cx).removing
 3159                                })
 3160                                .ok()
 3161                        })
 3162                        .filter(|removing| !removing)
 3163                        .count()
 3164                })?;
 3165
 3166                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3167            };
 3168
 3169            if let Some(active_call) = active_call
 3170                && workspace_count == 1
 3171                && cx
 3172                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3173                    .unwrap_or(false)
 3174            {
 3175                if close_intent == CloseIntent::CloseWindow {
 3176                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3177                    let answer = cx.update(|window, cx| {
 3178                        window.prompt(
 3179                            PromptLevel::Warning,
 3180                            "Do you want to leave the current call?",
 3181                            None,
 3182                            &["Close window and hang up", "Cancel"],
 3183                            cx,
 3184                        )
 3185                    })?;
 3186
 3187                    if answer.await.log_err() == Some(1) {
 3188                        return anyhow::Ok(false);
 3189                    } else {
 3190                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3191                            task.await.log_err();
 3192                        }
 3193                    }
 3194                }
 3195                if close_intent == CloseIntent::ReplaceWindow {
 3196                    _ = cx.update(|_window, cx| {
 3197                        let multi_workspace = cx
 3198                            .windows()
 3199                            .iter()
 3200                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3201                            .next()
 3202                            .unwrap();
 3203                        let project = multi_workspace
 3204                            .read(cx)?
 3205                            .workspace()
 3206                            .read(cx)
 3207                            .project
 3208                            .clone();
 3209                        if project.read(cx).is_shared() {
 3210                            active_call.0.unshare_project(project, cx)?;
 3211                        }
 3212                        Ok::<_, anyhow::Error>(())
 3213                    });
 3214                }
 3215            }
 3216
 3217            let save_result = this
 3218                .update_in(cx, |this, window, cx| {
 3219                    this.save_all_internal(SaveIntent::Close, window, cx)
 3220                })?
 3221                .await;
 3222
 3223            // If we're not quitting, but closing, we remove the workspace from
 3224            // the current session.
 3225            if close_intent != CloseIntent::Quit
 3226                && !save_last_workspace
 3227                && save_result.as_ref().is_ok_and(|&res| res)
 3228            {
 3229                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3230                    .await;
 3231            }
 3232
 3233            save_result
 3234        })
 3235    }
 3236
 3237    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3238        self.save_all_internal(
 3239            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3240            window,
 3241            cx,
 3242        )
 3243        .detach_and_log_err(cx);
 3244    }
 3245
 3246    fn send_keystrokes(
 3247        &mut self,
 3248        action: &SendKeystrokes,
 3249        window: &mut Window,
 3250        cx: &mut Context<Self>,
 3251    ) {
 3252        let keystrokes: Vec<Keystroke> = action
 3253            .0
 3254            .split(' ')
 3255            .flat_map(|k| Keystroke::parse(k).log_err())
 3256            .map(|k| {
 3257                cx.keyboard_mapper()
 3258                    .map_key_equivalent(k, false)
 3259                    .inner()
 3260                    .clone()
 3261            })
 3262            .collect();
 3263        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3264    }
 3265
 3266    pub fn send_keystrokes_impl(
 3267        &mut self,
 3268        keystrokes: Vec<Keystroke>,
 3269        window: &mut Window,
 3270        cx: &mut Context<Self>,
 3271    ) -> Shared<Task<()>> {
 3272        let mut state = self.dispatching_keystrokes.borrow_mut();
 3273        if !state.dispatched.insert(keystrokes.clone()) {
 3274            cx.propagate();
 3275            return state.task.clone().unwrap();
 3276        }
 3277
 3278        state.queue.extend(keystrokes);
 3279
 3280        let keystrokes = self.dispatching_keystrokes.clone();
 3281        if state.task.is_none() {
 3282            state.task = Some(
 3283                window
 3284                    .spawn(cx, async move |cx| {
 3285                        // limit to 100 keystrokes to avoid infinite recursion.
 3286                        for _ in 0..100 {
 3287                            let keystroke = {
 3288                                let mut state = keystrokes.borrow_mut();
 3289                                let Some(keystroke) = state.queue.pop_front() else {
 3290                                    state.dispatched.clear();
 3291                                    state.task.take();
 3292                                    return;
 3293                                };
 3294                                keystroke
 3295                            };
 3296                            cx.update(|window, cx| {
 3297                                let focused = window.focused(cx);
 3298                                window.dispatch_keystroke(keystroke.clone(), cx);
 3299                                if window.focused(cx) != focused {
 3300                                    // dispatch_keystroke may cause the focus to change.
 3301                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3302                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3303                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3304                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3305                                    // )
 3306                                    window.draw(cx).clear();
 3307                                }
 3308                            })
 3309                            .ok();
 3310
 3311                            // Yield between synthetic keystrokes so deferred focus and
 3312                            // other effects can settle before dispatching the next key.
 3313                            yield_now().await;
 3314                        }
 3315
 3316                        *keystrokes.borrow_mut() = Default::default();
 3317                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3318                    })
 3319                    .shared(),
 3320            );
 3321        }
 3322        state.task.clone().unwrap()
 3323    }
 3324
 3325    fn save_all_internal(
 3326        &mut self,
 3327        mut save_intent: SaveIntent,
 3328        window: &mut Window,
 3329        cx: &mut Context<Self>,
 3330    ) -> Task<Result<bool>> {
 3331        if self.project.read(cx).is_disconnected(cx) {
 3332            return Task::ready(Ok(true));
 3333        }
 3334        let dirty_items = self
 3335            .panes
 3336            .iter()
 3337            .flat_map(|pane| {
 3338                pane.read(cx).items().filter_map(|item| {
 3339                    if item.is_dirty(cx) {
 3340                        item.tab_content_text(0, cx);
 3341                        Some((pane.downgrade(), item.boxed_clone()))
 3342                    } else {
 3343                        None
 3344                    }
 3345                })
 3346            })
 3347            .collect::<Vec<_>>();
 3348
 3349        let project = self.project.clone();
 3350        cx.spawn_in(window, async move |workspace, cx| {
 3351            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3352                let (serialize_tasks, remaining_dirty_items) =
 3353                    workspace.update_in(cx, |workspace, window, cx| {
 3354                        let mut remaining_dirty_items = Vec::new();
 3355                        let mut serialize_tasks = Vec::new();
 3356                        for (pane, item) in dirty_items {
 3357                            if let Some(task) = item
 3358                                .to_serializable_item_handle(cx)
 3359                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3360                            {
 3361                                serialize_tasks.push(task);
 3362                            } else {
 3363                                remaining_dirty_items.push((pane, item));
 3364                            }
 3365                        }
 3366                        (serialize_tasks, remaining_dirty_items)
 3367                    })?;
 3368
 3369                futures::future::try_join_all(serialize_tasks).await?;
 3370
 3371                if !remaining_dirty_items.is_empty() {
 3372                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3373                }
 3374
 3375                if remaining_dirty_items.len() > 1 {
 3376                    let answer = workspace.update_in(cx, |_, window, cx| {
 3377                        cx.emit(Event::Activate);
 3378                        let detail = Pane::file_names_for_prompt(
 3379                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3380                            cx,
 3381                        );
 3382                        window.prompt(
 3383                            PromptLevel::Warning,
 3384                            "Do you want to save all changes in the following files?",
 3385                            Some(&detail),
 3386                            &["Save all", "Discard all", "Cancel"],
 3387                            cx,
 3388                        )
 3389                    })?;
 3390                    match answer.await.log_err() {
 3391                        Some(0) => save_intent = SaveIntent::SaveAll,
 3392                        Some(1) => save_intent = SaveIntent::Skip,
 3393                        Some(2) => return Ok(false),
 3394                        _ => {}
 3395                    }
 3396                }
 3397
 3398                remaining_dirty_items
 3399            } else {
 3400                dirty_items
 3401            };
 3402
 3403            for (pane, item) in dirty_items {
 3404                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3405                    (
 3406                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3407                        item.project_entry_ids(cx),
 3408                    )
 3409                })?;
 3410                if (singleton || !project_entry_ids.is_empty())
 3411                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3412                {
 3413                    return Ok(false);
 3414                }
 3415            }
 3416            Ok(true)
 3417        })
 3418    }
 3419
 3420    pub fn open_workspace_for_paths(
 3421        &mut self,
 3422        // replace_current_window: bool,
 3423        mut open_mode: OpenMode,
 3424        paths: Vec<PathBuf>,
 3425        window: &mut Window,
 3426        cx: &mut Context<Self>,
 3427    ) -> Task<Result<Entity<Workspace>>> {
 3428        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3429        let is_remote = self.project.read(cx).is_via_collab();
 3430        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3431        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3432
 3433        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3434        if workspace_is_empty {
 3435            open_mode = OpenMode::Activate;
 3436        }
 3437
 3438        let app_state = self.app_state.clone();
 3439
 3440        cx.spawn(async move |_, cx| {
 3441            let OpenResult { workspace, .. } = cx
 3442                .update(|cx| {
 3443                    open_paths(
 3444                        &paths,
 3445                        app_state,
 3446                        OpenOptions {
 3447                            requesting_window,
 3448                            open_mode,
 3449                            ..Default::default()
 3450                        },
 3451                        cx,
 3452                    )
 3453                })
 3454                .await?;
 3455            Ok(workspace)
 3456        })
 3457    }
 3458
 3459    #[allow(clippy::type_complexity)]
 3460    pub fn open_paths(
 3461        &mut self,
 3462        mut abs_paths: Vec<PathBuf>,
 3463        options: OpenOptions,
 3464        pane: Option<WeakEntity<Pane>>,
 3465        window: &mut Window,
 3466        cx: &mut Context<Self>,
 3467    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3468        let fs = self.app_state.fs.clone();
 3469
 3470        let caller_ordered_abs_paths = abs_paths.clone();
 3471
 3472        // Sort the paths to ensure we add worktrees for parents before their children.
 3473        abs_paths.sort_unstable();
 3474        cx.spawn_in(window, async move |this, cx| {
 3475            let mut tasks = Vec::with_capacity(abs_paths.len());
 3476
 3477            for abs_path in &abs_paths {
 3478                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3479                    OpenVisible::All => Some(true),
 3480                    OpenVisible::None => Some(false),
 3481                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3482                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3483                        Some(None) => Some(true),
 3484                        None => None,
 3485                    },
 3486                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3487                        Some(Some(metadata)) => Some(metadata.is_dir),
 3488                        Some(None) => Some(false),
 3489                        None => None,
 3490                    },
 3491                };
 3492                let project_path = match visible {
 3493                    Some(visible) => match this
 3494                        .update(cx, |this, cx| {
 3495                            Workspace::project_path_for_path(
 3496                                this.project.clone(),
 3497                                abs_path,
 3498                                visible,
 3499                                cx,
 3500                            )
 3501                        })
 3502                        .log_err()
 3503                    {
 3504                        Some(project_path) => project_path.await.log_err(),
 3505                        None => None,
 3506                    },
 3507                    None => None,
 3508                };
 3509
 3510                let this = this.clone();
 3511                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3512                let fs = fs.clone();
 3513                let pane = pane.clone();
 3514                let task = cx.spawn(async move |cx| {
 3515                    let (_worktree, project_path) = project_path?;
 3516                    if fs.is_dir(&abs_path).await {
 3517                        // Opening a directory should not race to update the active entry.
 3518                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3519                        None
 3520                    } else {
 3521                        Some(
 3522                            this.update_in(cx, |this, window, cx| {
 3523                                this.open_path(
 3524                                    project_path,
 3525                                    pane,
 3526                                    options.focus.unwrap_or(true),
 3527                                    window,
 3528                                    cx,
 3529                                )
 3530                            })
 3531                            .ok()?
 3532                            .await,
 3533                        )
 3534                    }
 3535                });
 3536                tasks.push(task);
 3537            }
 3538
 3539            let results = futures::future::join_all(tasks).await;
 3540
 3541            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3542            let mut winner: Option<(PathBuf, bool)> = None;
 3543            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3544                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3545                    if !metadata.is_dir {
 3546                        winner = Some((abs_path, false));
 3547                        break;
 3548                    }
 3549                    if winner.is_none() {
 3550                        winner = Some((abs_path, true));
 3551                    }
 3552                } else if winner.is_none() {
 3553                    winner = Some((abs_path, false));
 3554                }
 3555            }
 3556
 3557            // Compute the winner entry id on the foreground thread and emit once, after all
 3558            // paths finish opening. This avoids races between concurrently-opening paths
 3559            // (directories in particular) and makes the resulting project panel selection
 3560            // deterministic.
 3561            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3562                'emit_winner: {
 3563                    let winner_abs_path: Arc<Path> =
 3564                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3565
 3566                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3567                        OpenVisible::All => true,
 3568                        OpenVisible::None => false,
 3569                        OpenVisible::OnlyFiles => !winner_is_dir,
 3570                        OpenVisible::OnlyDirectories => winner_is_dir,
 3571                    };
 3572
 3573                    let Some(worktree_task) = this
 3574                        .update(cx, |workspace, cx| {
 3575                            workspace.project.update(cx, |project, cx| {
 3576                                project.find_or_create_worktree(
 3577                                    winner_abs_path.as_ref(),
 3578                                    visible,
 3579                                    cx,
 3580                                )
 3581                            })
 3582                        })
 3583                        .ok()
 3584                    else {
 3585                        break 'emit_winner;
 3586                    };
 3587
 3588                    let Ok((worktree, _)) = worktree_task.await else {
 3589                        break 'emit_winner;
 3590                    };
 3591
 3592                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3593                        let worktree = worktree.read(cx);
 3594                        let worktree_abs_path = worktree.abs_path();
 3595                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3596                            worktree.root_entry()
 3597                        } else {
 3598                            winner_abs_path
 3599                                .strip_prefix(worktree_abs_path.as_ref())
 3600                                .ok()
 3601                                .and_then(|relative_path| {
 3602                                    let relative_path =
 3603                                        RelPath::new(relative_path, PathStyle::local())
 3604                                            .log_err()?;
 3605                                    worktree.entry_for_path(&relative_path)
 3606                                })
 3607                        }?;
 3608                        Some(entry.id)
 3609                    }) else {
 3610                        break 'emit_winner;
 3611                    };
 3612
 3613                    this.update(cx, |workspace, cx| {
 3614                        workspace.project.update(cx, |_, cx| {
 3615                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3616                        });
 3617                    })
 3618                    .ok();
 3619                }
 3620            }
 3621
 3622            results
 3623        })
 3624    }
 3625
 3626    pub fn open_resolved_path(
 3627        &mut self,
 3628        path: ResolvedPath,
 3629        window: &mut Window,
 3630        cx: &mut Context<Self>,
 3631    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3632        match path {
 3633            ResolvedPath::ProjectPath { project_path, .. } => {
 3634                self.open_path(project_path, None, true, window, cx)
 3635            }
 3636            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3637                PathBuf::from(path),
 3638                OpenOptions {
 3639                    visible: Some(OpenVisible::None),
 3640                    ..Default::default()
 3641                },
 3642                window,
 3643                cx,
 3644            ),
 3645        }
 3646    }
 3647
 3648    pub fn absolute_path_of_worktree(
 3649        &self,
 3650        worktree_id: WorktreeId,
 3651        cx: &mut Context<Self>,
 3652    ) -> Option<PathBuf> {
 3653        self.project
 3654            .read(cx)
 3655            .worktree_for_id(worktree_id, cx)
 3656            // TODO: use `abs_path` or `root_dir`
 3657            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3658    }
 3659
 3660    pub fn add_folder_to_project(
 3661        &mut self,
 3662        _: &AddFolderToProject,
 3663        window: &mut Window,
 3664        cx: &mut Context<Self>,
 3665    ) {
 3666        let project = self.project.read(cx);
 3667        if project.is_via_collab() {
 3668            self.show_error(
 3669                &anyhow!("You cannot add folders to someone else's project"),
 3670                cx,
 3671            );
 3672            return;
 3673        }
 3674        let paths = self.prompt_for_open_path(
 3675            PathPromptOptions {
 3676                files: false,
 3677                directories: true,
 3678                multiple: true,
 3679                prompt: None,
 3680            },
 3681            DirectoryLister::Project(self.project.clone()),
 3682            window,
 3683            cx,
 3684        );
 3685        cx.spawn_in(window, async move |this, cx| {
 3686            if let Some(paths) = paths.await.log_err().flatten() {
 3687                let results = this
 3688                    .update_in(cx, |this, window, cx| {
 3689                        this.open_paths(
 3690                            paths,
 3691                            OpenOptions {
 3692                                visible: Some(OpenVisible::All),
 3693                                ..Default::default()
 3694                            },
 3695                            None,
 3696                            window,
 3697                            cx,
 3698                        )
 3699                    })?
 3700                    .await;
 3701                for result in results.into_iter().flatten() {
 3702                    result.log_err();
 3703                }
 3704            }
 3705            anyhow::Ok(())
 3706        })
 3707        .detach_and_log_err(cx);
 3708    }
 3709
 3710    pub fn project_path_for_path(
 3711        project: Entity<Project>,
 3712        abs_path: &Path,
 3713        visible: bool,
 3714        cx: &mut App,
 3715    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3716        let entry = project.update(cx, |project, cx| {
 3717            project.find_or_create_worktree(abs_path, visible, cx)
 3718        });
 3719        cx.spawn(async move |cx| {
 3720            let (worktree, path) = entry.await?;
 3721            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3722            Ok((worktree, ProjectPath { worktree_id, path }))
 3723        })
 3724    }
 3725
 3726    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3727        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3728    }
 3729
 3730    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3731        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3732    }
 3733
 3734    pub fn items_of_type<'a, T: Item>(
 3735        &'a self,
 3736        cx: &'a App,
 3737    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3738        self.panes
 3739            .iter()
 3740            .flat_map(|pane| pane.read(cx).items_of_type())
 3741    }
 3742
 3743    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3744        self.active_pane().read(cx).active_item()
 3745    }
 3746
 3747    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3748        let item = self.active_item(cx)?;
 3749        item.to_any_view().downcast::<I>().ok()
 3750    }
 3751
 3752    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3753        self.active_item(cx).and_then(|item| item.project_path(cx))
 3754    }
 3755
 3756    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3757        self.recent_navigation_history_iter(cx)
 3758            .filter_map(|(path, abs_path)| {
 3759                let worktree = self
 3760                    .project
 3761                    .read(cx)
 3762                    .worktree_for_id(path.worktree_id, cx)?;
 3763                if worktree.read(cx).is_visible() {
 3764                    abs_path
 3765                } else {
 3766                    None
 3767                }
 3768            })
 3769            .next()
 3770    }
 3771
 3772    pub fn save_active_item(
 3773        &mut self,
 3774        save_intent: SaveIntent,
 3775        window: &mut Window,
 3776        cx: &mut App,
 3777    ) -> Task<Result<()>> {
 3778        let project = self.project.clone();
 3779        let pane = self.active_pane();
 3780        let item = pane.read(cx).active_item();
 3781        let pane = pane.downgrade();
 3782
 3783        window.spawn(cx, async move |cx| {
 3784            if let Some(item) = item {
 3785                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3786                    .await
 3787                    .map(|_| ())
 3788            } else {
 3789                Ok(())
 3790            }
 3791        })
 3792    }
 3793
 3794    pub fn close_inactive_items_and_panes(
 3795        &mut self,
 3796        action: &CloseInactiveTabsAndPanes,
 3797        window: &mut Window,
 3798        cx: &mut Context<Self>,
 3799    ) {
 3800        if let Some(task) = self.close_all_internal(
 3801            true,
 3802            action.save_intent.unwrap_or(SaveIntent::Close),
 3803            window,
 3804            cx,
 3805        ) {
 3806            task.detach_and_log_err(cx)
 3807        }
 3808    }
 3809
 3810    pub fn close_all_items_and_panes(
 3811        &mut self,
 3812        action: &CloseAllItemsAndPanes,
 3813        window: &mut Window,
 3814        cx: &mut Context<Self>,
 3815    ) {
 3816        if let Some(task) = self.close_all_internal(
 3817            false,
 3818            action.save_intent.unwrap_or(SaveIntent::Close),
 3819            window,
 3820            cx,
 3821        ) {
 3822            task.detach_and_log_err(cx)
 3823        }
 3824    }
 3825
 3826    /// Closes the active item across all panes.
 3827    pub fn close_item_in_all_panes(
 3828        &mut self,
 3829        action: &CloseItemInAllPanes,
 3830        window: &mut Window,
 3831        cx: &mut Context<Self>,
 3832    ) {
 3833        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3834            return;
 3835        };
 3836
 3837        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3838        let close_pinned = action.close_pinned;
 3839
 3840        if let Some(project_path) = active_item.project_path(cx) {
 3841            self.close_items_with_project_path(
 3842                &project_path,
 3843                save_intent,
 3844                close_pinned,
 3845                window,
 3846                cx,
 3847            );
 3848        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3849            let item_id = active_item.item_id();
 3850            self.active_pane().update(cx, |pane, cx| {
 3851                pane.close_item_by_id(item_id, save_intent, window, cx)
 3852                    .detach_and_log_err(cx);
 3853            });
 3854        }
 3855    }
 3856
 3857    /// Closes all items with the given project path across all panes.
 3858    pub fn close_items_with_project_path(
 3859        &mut self,
 3860        project_path: &ProjectPath,
 3861        save_intent: SaveIntent,
 3862        close_pinned: bool,
 3863        window: &mut Window,
 3864        cx: &mut Context<Self>,
 3865    ) {
 3866        let panes = self.panes().to_vec();
 3867        for pane in panes {
 3868            pane.update(cx, |pane, cx| {
 3869                pane.close_items_for_project_path(
 3870                    project_path,
 3871                    save_intent,
 3872                    close_pinned,
 3873                    window,
 3874                    cx,
 3875                )
 3876                .detach_and_log_err(cx);
 3877            });
 3878        }
 3879    }
 3880
 3881    fn close_all_internal(
 3882        &mut self,
 3883        retain_active_pane: bool,
 3884        save_intent: SaveIntent,
 3885        window: &mut Window,
 3886        cx: &mut Context<Self>,
 3887    ) -> Option<Task<Result<()>>> {
 3888        let current_pane = self.active_pane();
 3889
 3890        let mut tasks = Vec::new();
 3891
 3892        if retain_active_pane {
 3893            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3894                pane.close_other_items(
 3895                    &CloseOtherItems {
 3896                        save_intent: None,
 3897                        close_pinned: false,
 3898                    },
 3899                    None,
 3900                    window,
 3901                    cx,
 3902                )
 3903            });
 3904
 3905            tasks.push(current_pane_close);
 3906        }
 3907
 3908        for pane in self.panes() {
 3909            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3910                continue;
 3911            }
 3912
 3913            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3914                pane.close_all_items(
 3915                    &CloseAllItems {
 3916                        save_intent: Some(save_intent),
 3917                        close_pinned: false,
 3918                    },
 3919                    window,
 3920                    cx,
 3921                )
 3922            });
 3923
 3924            tasks.push(close_pane_items)
 3925        }
 3926
 3927        if tasks.is_empty() {
 3928            None
 3929        } else {
 3930            Some(cx.spawn_in(window, async move |_, _| {
 3931                for task in tasks {
 3932                    task.await?
 3933                }
 3934                Ok(())
 3935            }))
 3936        }
 3937    }
 3938
 3939    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3940        self.dock_at_position(position).read(cx).is_open()
 3941    }
 3942
 3943    pub fn toggle_dock(
 3944        &mut self,
 3945        dock_side: DockPosition,
 3946        window: &mut Window,
 3947        cx: &mut Context<Self>,
 3948    ) {
 3949        let mut focus_center = false;
 3950        let mut reveal_dock = false;
 3951
 3952        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3953        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3954
 3955        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3956            telemetry::event!(
 3957                "Panel Button Clicked",
 3958                name = panel.persistent_name(),
 3959                toggle_state = !was_visible
 3960            );
 3961        }
 3962        if was_visible {
 3963            self.save_open_dock_positions(cx);
 3964        }
 3965
 3966        let dock = self.dock_at_position(dock_side);
 3967        dock.update(cx, |dock, cx| {
 3968            dock.set_open(!was_visible, window, cx);
 3969
 3970            if dock.active_panel().is_none() {
 3971                let Some(panel_ix) = dock
 3972                    .first_enabled_panel_idx(cx)
 3973                    .log_with_level(log::Level::Info)
 3974                else {
 3975                    return;
 3976                };
 3977                dock.activate_panel(panel_ix, window, cx);
 3978            }
 3979
 3980            if let Some(active_panel) = dock.active_panel() {
 3981                if was_visible {
 3982                    if active_panel
 3983                        .panel_focus_handle(cx)
 3984                        .contains_focused(window, cx)
 3985                    {
 3986                        focus_center = true;
 3987                    }
 3988                } else {
 3989                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3990                    window.focus(focus_handle, cx);
 3991                    reveal_dock = true;
 3992                }
 3993            }
 3994        });
 3995
 3996        if reveal_dock {
 3997            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3998        }
 3999
 4000        if focus_center {
 4001            self.active_pane
 4002                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4003        }
 4004
 4005        cx.notify();
 4006        self.serialize_workspace(window, cx);
 4007    }
 4008
 4009    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 4010        self.all_docks().into_iter().find(|&dock| {
 4011            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4012        })
 4013    }
 4014
 4015    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4016        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4017            self.save_open_dock_positions(cx);
 4018            dock.update(cx, |dock, cx| {
 4019                dock.set_open(false, window, cx);
 4020            });
 4021            return true;
 4022        }
 4023        false
 4024    }
 4025
 4026    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4027        self.save_open_dock_positions(cx);
 4028        for dock in self.all_docks() {
 4029            dock.update(cx, |dock, cx| {
 4030                dock.set_open(false, window, cx);
 4031            });
 4032        }
 4033
 4034        cx.focus_self(window);
 4035        cx.notify();
 4036        self.serialize_workspace(window, cx);
 4037    }
 4038
 4039    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4040        self.all_docks()
 4041            .into_iter()
 4042            .filter_map(|dock| {
 4043                let dock_ref = dock.read(cx);
 4044                if dock_ref.is_open() {
 4045                    Some(dock_ref.position())
 4046                } else {
 4047                    None
 4048                }
 4049            })
 4050            .collect()
 4051    }
 4052
 4053    /// Saves the positions of currently open docks.
 4054    ///
 4055    /// Updates `last_open_dock_positions` with positions of all currently open
 4056    /// docks, to later be restored by the 'Toggle All Docks' action.
 4057    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4058        let open_dock_positions = self.get_open_dock_positions(cx);
 4059        if !open_dock_positions.is_empty() {
 4060            self.last_open_dock_positions = open_dock_positions;
 4061        }
 4062    }
 4063
 4064    /// Toggles all docks between open and closed states.
 4065    ///
 4066    /// If any docks are open, closes all and remembers their positions. If all
 4067    /// docks are closed, restores the last remembered dock configuration.
 4068    fn toggle_all_docks(
 4069        &mut self,
 4070        _: &ToggleAllDocks,
 4071        window: &mut Window,
 4072        cx: &mut Context<Self>,
 4073    ) {
 4074        let open_dock_positions = self.get_open_dock_positions(cx);
 4075
 4076        if !open_dock_positions.is_empty() {
 4077            self.close_all_docks(window, cx);
 4078        } else if !self.last_open_dock_positions.is_empty() {
 4079            self.restore_last_open_docks(window, cx);
 4080        }
 4081    }
 4082
 4083    /// Reopens docks from the most recently remembered configuration.
 4084    ///
 4085    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4086    /// and clears the stored positions.
 4087    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4088        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4089
 4090        for position in positions_to_open {
 4091            let dock = self.dock_at_position(position);
 4092            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4093        }
 4094
 4095        cx.focus_self(window);
 4096        cx.notify();
 4097        self.serialize_workspace(window, cx);
 4098    }
 4099
 4100    /// Transfer focus to the panel of the given type.
 4101    pub fn focus_panel<T: Panel>(
 4102        &mut self,
 4103        window: &mut Window,
 4104        cx: &mut Context<Self>,
 4105    ) -> Option<Entity<T>> {
 4106        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4107        panel.to_any().downcast().ok()
 4108    }
 4109
 4110    /// Focus the panel of the given type if it isn't already focused. If it is
 4111    /// already focused, then transfer focus back to the workspace center.
 4112    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4113    /// panel when transferring focus back to the center.
 4114    pub fn toggle_panel_focus<T: Panel>(
 4115        &mut self,
 4116        window: &mut Window,
 4117        cx: &mut Context<Self>,
 4118    ) -> bool {
 4119        let mut did_focus_panel = false;
 4120        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4121            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4122            did_focus_panel
 4123        });
 4124
 4125        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4126            self.close_panel::<T>(window, cx);
 4127        }
 4128
 4129        telemetry::event!(
 4130            "Panel Button Clicked",
 4131            name = T::persistent_name(),
 4132            toggle_state = did_focus_panel
 4133        );
 4134
 4135        did_focus_panel
 4136    }
 4137
 4138    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4139        if let Some(item) = self.active_item(cx) {
 4140            item.item_focus_handle(cx).focus(window, cx);
 4141        } else {
 4142            log::error!("Could not find a focus target when switching focus to the center panes",);
 4143        }
 4144    }
 4145
 4146    pub fn activate_panel_for_proto_id(
 4147        &mut self,
 4148        panel_id: PanelId,
 4149        window: &mut Window,
 4150        cx: &mut Context<Self>,
 4151    ) -> Option<Arc<dyn PanelHandle>> {
 4152        let mut panel = None;
 4153        for dock in self.all_docks() {
 4154            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4155                panel = dock.update(cx, |dock, cx| {
 4156                    dock.activate_panel(panel_index, window, cx);
 4157                    dock.set_open(true, window, cx);
 4158                    dock.active_panel().cloned()
 4159                });
 4160                break;
 4161            }
 4162        }
 4163
 4164        if panel.is_some() {
 4165            cx.notify();
 4166            self.serialize_workspace(window, cx);
 4167        }
 4168
 4169        panel
 4170    }
 4171
 4172    /// Focus or unfocus the given panel type, depending on the given callback.
 4173    fn focus_or_unfocus_panel<T: Panel>(
 4174        &mut self,
 4175        window: &mut Window,
 4176        cx: &mut Context<Self>,
 4177        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4178    ) -> Option<Arc<dyn PanelHandle>> {
 4179        let mut result_panel = None;
 4180        let mut serialize = false;
 4181        for dock in self.all_docks() {
 4182            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4183                let mut focus_center = false;
 4184                let panel = dock.update(cx, |dock, cx| {
 4185                    dock.activate_panel(panel_index, window, cx);
 4186
 4187                    let panel = dock.active_panel().cloned();
 4188                    if let Some(panel) = panel.as_ref() {
 4189                        if should_focus(&**panel, window, cx) {
 4190                            dock.set_open(true, window, cx);
 4191                            panel.panel_focus_handle(cx).focus(window, cx);
 4192                        } else {
 4193                            focus_center = true;
 4194                        }
 4195                    }
 4196                    panel
 4197                });
 4198
 4199                if focus_center {
 4200                    self.active_pane
 4201                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4202                }
 4203
 4204                result_panel = panel;
 4205                serialize = true;
 4206                break;
 4207            }
 4208        }
 4209
 4210        if serialize {
 4211            self.serialize_workspace(window, cx);
 4212        }
 4213
 4214        cx.notify();
 4215        result_panel
 4216    }
 4217
 4218    /// Open the panel of the given type
 4219    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4220        for dock in self.all_docks() {
 4221            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4222                dock.update(cx, |dock, cx| {
 4223                    dock.activate_panel(panel_index, window, cx);
 4224                    dock.set_open(true, window, cx);
 4225                });
 4226            }
 4227        }
 4228    }
 4229
 4230    /// Open the panel of the given type, dismissing any zoomed items that
 4231    /// would obscure it (e.g. a zoomed terminal).
 4232    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4233        let dock_position = self.all_docks().iter().find_map(|dock| {
 4234            let dock = dock.read(cx);
 4235            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4236        });
 4237        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4238        self.open_panel::<T>(window, cx);
 4239    }
 4240
 4241    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4242        for dock in self.all_docks().iter() {
 4243            dock.update(cx, |dock, cx| {
 4244                if dock.panel::<T>().is_some() {
 4245                    dock.set_open(false, window, cx)
 4246                }
 4247            })
 4248        }
 4249    }
 4250
 4251    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4252        self.all_docks()
 4253            .iter()
 4254            .find_map(|dock| dock.read(cx).panel::<T>())
 4255    }
 4256
 4257    fn dismiss_zoomed_items_to_reveal(
 4258        &mut self,
 4259        dock_to_reveal: Option<DockPosition>,
 4260        window: &mut Window,
 4261        cx: &mut Context<Self>,
 4262    ) {
 4263        // If a center pane is zoomed, unzoom it.
 4264        for pane in &self.panes {
 4265            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4266                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4267            }
 4268        }
 4269
 4270        // If another dock is zoomed, hide it.
 4271        let mut focus_center = false;
 4272        for dock in self.all_docks() {
 4273            dock.update(cx, |dock, cx| {
 4274                if Some(dock.position()) != dock_to_reveal
 4275                    && let Some(panel) = dock.active_panel()
 4276                    && panel.is_zoomed(window, cx)
 4277                {
 4278                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4279                    dock.set_open(false, window, cx);
 4280                }
 4281            });
 4282        }
 4283
 4284        if focus_center {
 4285            self.active_pane
 4286                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4287        }
 4288
 4289        if self.zoomed_position != dock_to_reveal {
 4290            self.zoomed = None;
 4291            self.zoomed_position = None;
 4292            cx.emit(Event::ZoomChanged);
 4293        }
 4294
 4295        cx.notify();
 4296    }
 4297
 4298    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4299        let pane = cx.new(|cx| {
 4300            let mut pane = Pane::new(
 4301                self.weak_handle(),
 4302                self.project.clone(),
 4303                self.pane_history_timestamp.clone(),
 4304                None,
 4305                NewFile.boxed_clone(),
 4306                true,
 4307                window,
 4308                cx,
 4309            );
 4310            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4311            pane
 4312        });
 4313        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4314            .detach();
 4315        self.panes.push(pane.clone());
 4316
 4317        window.focus(&pane.focus_handle(cx), cx);
 4318
 4319        cx.emit(Event::PaneAdded(pane.clone()));
 4320        pane
 4321    }
 4322
 4323    pub fn add_item_to_center(
 4324        &mut self,
 4325        item: Box<dyn ItemHandle>,
 4326        window: &mut Window,
 4327        cx: &mut Context<Self>,
 4328    ) -> bool {
 4329        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4330            if let Some(center_pane) = center_pane.upgrade() {
 4331                center_pane.update(cx, |pane, cx| {
 4332                    pane.add_item(item, true, true, None, window, cx)
 4333                });
 4334                true
 4335            } else {
 4336                false
 4337            }
 4338        } else {
 4339            false
 4340        }
 4341    }
 4342
 4343    pub fn add_item_to_active_pane(
 4344        &mut self,
 4345        item: Box<dyn ItemHandle>,
 4346        destination_index: Option<usize>,
 4347        focus_item: bool,
 4348        window: &mut Window,
 4349        cx: &mut App,
 4350    ) {
 4351        self.add_item(
 4352            self.active_pane.clone(),
 4353            item,
 4354            destination_index,
 4355            false,
 4356            focus_item,
 4357            window,
 4358            cx,
 4359        )
 4360    }
 4361
 4362    pub fn add_item(
 4363        &mut self,
 4364        pane: Entity<Pane>,
 4365        item: Box<dyn ItemHandle>,
 4366        destination_index: Option<usize>,
 4367        activate_pane: bool,
 4368        focus_item: bool,
 4369        window: &mut Window,
 4370        cx: &mut App,
 4371    ) {
 4372        pane.update(cx, |pane, cx| {
 4373            pane.add_item(
 4374                item,
 4375                activate_pane,
 4376                focus_item,
 4377                destination_index,
 4378                window,
 4379                cx,
 4380            )
 4381        });
 4382    }
 4383
 4384    pub fn split_item(
 4385        &mut self,
 4386        split_direction: SplitDirection,
 4387        item: Box<dyn ItemHandle>,
 4388        window: &mut Window,
 4389        cx: &mut Context<Self>,
 4390    ) {
 4391        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4392        self.add_item(new_pane, item, None, true, true, window, cx);
 4393    }
 4394
 4395    pub fn open_abs_path(
 4396        &mut self,
 4397        abs_path: PathBuf,
 4398        options: OpenOptions,
 4399        window: &mut Window,
 4400        cx: &mut Context<Self>,
 4401    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4402        cx.spawn_in(window, async move |workspace, cx| {
 4403            let open_paths_task_result = workspace
 4404                .update_in(cx, |workspace, window, cx| {
 4405                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4406                })
 4407                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4408                .await;
 4409            anyhow::ensure!(
 4410                open_paths_task_result.len() == 1,
 4411                "open abs path {abs_path:?} task returned incorrect number of results"
 4412            );
 4413            match open_paths_task_result
 4414                .into_iter()
 4415                .next()
 4416                .expect("ensured single task result")
 4417            {
 4418                Some(open_result) => {
 4419                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4420                }
 4421                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4422            }
 4423        })
 4424    }
 4425
 4426    pub fn split_abs_path(
 4427        &mut self,
 4428        abs_path: PathBuf,
 4429        visible: bool,
 4430        window: &mut Window,
 4431        cx: &mut Context<Self>,
 4432    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4433        let project_path_task =
 4434            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4435        cx.spawn_in(window, async move |this, cx| {
 4436            let (_, path) = project_path_task.await?;
 4437            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4438                .await
 4439        })
 4440    }
 4441
 4442    pub fn open_path(
 4443        &mut self,
 4444        path: impl Into<ProjectPath>,
 4445        pane: Option<WeakEntity<Pane>>,
 4446        focus_item: bool,
 4447        window: &mut Window,
 4448        cx: &mut App,
 4449    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4450        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4451    }
 4452
 4453    pub fn open_path_preview(
 4454        &mut self,
 4455        path: impl Into<ProjectPath>,
 4456        pane: Option<WeakEntity<Pane>>,
 4457        focus_item: bool,
 4458        allow_preview: bool,
 4459        activate: bool,
 4460        window: &mut Window,
 4461        cx: &mut App,
 4462    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4463        let pane = pane.unwrap_or_else(|| {
 4464            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4465                self.panes
 4466                    .first()
 4467                    .expect("There must be an active pane")
 4468                    .downgrade()
 4469            })
 4470        });
 4471
 4472        let project_path = path.into();
 4473        let task = self.load_path(project_path.clone(), window, cx);
 4474        window.spawn(cx, async move |cx| {
 4475            let (project_entry_id, build_item) = task.await?;
 4476
 4477            pane.update_in(cx, |pane, window, cx| {
 4478                pane.open_item(
 4479                    project_entry_id,
 4480                    project_path,
 4481                    focus_item,
 4482                    allow_preview,
 4483                    activate,
 4484                    None,
 4485                    window,
 4486                    cx,
 4487                    build_item,
 4488                )
 4489            })
 4490        })
 4491    }
 4492
 4493    pub fn split_path(
 4494        &mut self,
 4495        path: impl Into<ProjectPath>,
 4496        window: &mut Window,
 4497        cx: &mut Context<Self>,
 4498    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4499        self.split_path_preview(path, false, None, window, cx)
 4500    }
 4501
 4502    pub fn split_path_preview(
 4503        &mut self,
 4504        path: impl Into<ProjectPath>,
 4505        allow_preview: bool,
 4506        split_direction: Option<SplitDirection>,
 4507        window: &mut Window,
 4508        cx: &mut Context<Self>,
 4509    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4510        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4511            self.panes
 4512                .first()
 4513                .expect("There must be an active pane")
 4514                .downgrade()
 4515        });
 4516
 4517        if let Member::Pane(center_pane) = &self.center.root
 4518            && center_pane.read(cx).items_len() == 0
 4519        {
 4520            return self.open_path(path, Some(pane), true, window, cx);
 4521        }
 4522
 4523        let project_path = path.into();
 4524        let task = self.load_path(project_path.clone(), window, cx);
 4525        cx.spawn_in(window, async move |this, cx| {
 4526            let (project_entry_id, build_item) = task.await?;
 4527            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4528                let pane = pane.upgrade()?;
 4529                let new_pane = this.split_pane(
 4530                    pane,
 4531                    split_direction.unwrap_or(SplitDirection::Right),
 4532                    window,
 4533                    cx,
 4534                );
 4535                new_pane.update(cx, |new_pane, cx| {
 4536                    Some(new_pane.open_item(
 4537                        project_entry_id,
 4538                        project_path,
 4539                        true,
 4540                        allow_preview,
 4541                        true,
 4542                        None,
 4543                        window,
 4544                        cx,
 4545                        build_item,
 4546                    ))
 4547                })
 4548            })
 4549            .map(|option| option.context("pane was dropped"))?
 4550        })
 4551    }
 4552
 4553    fn load_path(
 4554        &mut self,
 4555        path: ProjectPath,
 4556        window: &mut Window,
 4557        cx: &mut App,
 4558    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4559        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4560        registry.open_path(self.project(), &path, window, cx)
 4561    }
 4562
 4563    pub fn find_project_item<T>(
 4564        &self,
 4565        pane: &Entity<Pane>,
 4566        project_item: &Entity<T::Item>,
 4567        cx: &App,
 4568    ) -> Option<Entity<T>>
 4569    where
 4570        T: ProjectItem,
 4571    {
 4572        use project::ProjectItem as _;
 4573        let project_item = project_item.read(cx);
 4574        let entry_id = project_item.entry_id(cx);
 4575        let project_path = project_item.project_path(cx);
 4576
 4577        let mut item = None;
 4578        if let Some(entry_id) = entry_id {
 4579            item = pane.read(cx).item_for_entry(entry_id, cx);
 4580        }
 4581        if item.is_none()
 4582            && let Some(project_path) = project_path
 4583        {
 4584            item = pane.read(cx).item_for_path(project_path, cx);
 4585        }
 4586
 4587        item.and_then(|item| item.downcast::<T>())
 4588    }
 4589
 4590    pub fn is_project_item_open<T>(
 4591        &self,
 4592        pane: &Entity<Pane>,
 4593        project_item: &Entity<T::Item>,
 4594        cx: &App,
 4595    ) -> bool
 4596    where
 4597        T: ProjectItem,
 4598    {
 4599        self.find_project_item::<T>(pane, project_item, cx)
 4600            .is_some()
 4601    }
 4602
 4603    pub fn open_project_item<T>(
 4604        &mut self,
 4605        pane: Entity<Pane>,
 4606        project_item: Entity<T::Item>,
 4607        activate_pane: bool,
 4608        focus_item: bool,
 4609        keep_old_preview: bool,
 4610        allow_new_preview: bool,
 4611        window: &mut Window,
 4612        cx: &mut Context<Self>,
 4613    ) -> Entity<T>
 4614    where
 4615        T: ProjectItem,
 4616    {
 4617        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4618
 4619        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4620            if !keep_old_preview
 4621                && let Some(old_id) = old_item_id
 4622                && old_id != item.item_id()
 4623            {
 4624                // switching to a different item, so unpreview old active item
 4625                pane.update(cx, |pane, _| {
 4626                    pane.unpreview_item_if_preview(old_id);
 4627                });
 4628            }
 4629
 4630            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4631            if !allow_new_preview {
 4632                pane.update(cx, |pane, _| {
 4633                    pane.unpreview_item_if_preview(item.item_id());
 4634                });
 4635            }
 4636            return item;
 4637        }
 4638
 4639        let item = pane.update(cx, |pane, cx| {
 4640            cx.new(|cx| {
 4641                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4642            })
 4643        });
 4644        let mut destination_index = None;
 4645        pane.update(cx, |pane, cx| {
 4646            if !keep_old_preview && let Some(old_id) = old_item_id {
 4647                pane.unpreview_item_if_preview(old_id);
 4648            }
 4649            if allow_new_preview {
 4650                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4651            }
 4652        });
 4653
 4654        self.add_item(
 4655            pane,
 4656            Box::new(item.clone()),
 4657            destination_index,
 4658            activate_pane,
 4659            focus_item,
 4660            window,
 4661            cx,
 4662        );
 4663        item
 4664    }
 4665
 4666    pub fn open_shared_screen(
 4667        &mut self,
 4668        peer_id: PeerId,
 4669        window: &mut Window,
 4670        cx: &mut Context<Self>,
 4671    ) {
 4672        if let Some(shared_screen) =
 4673            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4674        {
 4675            self.active_pane.update(cx, |pane, cx| {
 4676                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4677            });
 4678        }
 4679    }
 4680
 4681    pub fn activate_item(
 4682        &mut self,
 4683        item: &dyn ItemHandle,
 4684        activate_pane: bool,
 4685        focus_item: bool,
 4686        window: &mut Window,
 4687        cx: &mut App,
 4688    ) -> bool {
 4689        let result = self.panes.iter().find_map(|pane| {
 4690            pane.read(cx)
 4691                .index_for_item(item)
 4692                .map(|ix| (pane.clone(), ix))
 4693        });
 4694        if let Some((pane, ix)) = result {
 4695            pane.update(cx, |pane, cx| {
 4696                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4697            });
 4698            true
 4699        } else {
 4700            false
 4701        }
 4702    }
 4703
 4704    fn activate_pane_at_index(
 4705        &mut self,
 4706        action: &ActivatePane,
 4707        window: &mut Window,
 4708        cx: &mut Context<Self>,
 4709    ) {
 4710        let panes = self.center.panes();
 4711        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4712            window.focus(&pane.focus_handle(cx), cx);
 4713        } else {
 4714            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4715                .detach();
 4716        }
 4717    }
 4718
 4719    fn move_item_to_pane_at_index(
 4720        &mut self,
 4721        action: &MoveItemToPane,
 4722        window: &mut Window,
 4723        cx: &mut Context<Self>,
 4724    ) {
 4725        let panes = self.center.panes();
 4726        let destination = match panes.get(action.destination) {
 4727            Some(&destination) => destination.clone(),
 4728            None => {
 4729                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4730                    return;
 4731                }
 4732                let direction = SplitDirection::Right;
 4733                let split_off_pane = self
 4734                    .find_pane_in_direction(direction, cx)
 4735                    .unwrap_or_else(|| self.active_pane.clone());
 4736                let new_pane = self.add_pane(window, cx);
 4737                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4738                new_pane
 4739            }
 4740        };
 4741
 4742        if action.clone {
 4743            if self
 4744                .active_pane
 4745                .read(cx)
 4746                .active_item()
 4747                .is_some_and(|item| item.can_split(cx))
 4748            {
 4749                clone_active_item(
 4750                    self.database_id(),
 4751                    &self.active_pane,
 4752                    &destination,
 4753                    action.focus,
 4754                    window,
 4755                    cx,
 4756                );
 4757                return;
 4758            }
 4759        }
 4760        move_active_item(
 4761            &self.active_pane,
 4762            &destination,
 4763            action.focus,
 4764            true,
 4765            window,
 4766            cx,
 4767        )
 4768    }
 4769
 4770    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4771        let panes = self.center.panes();
 4772        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4773            let next_ix = (ix + 1) % panes.len();
 4774            let next_pane = panes[next_ix].clone();
 4775            window.focus(&next_pane.focus_handle(cx), cx);
 4776        }
 4777    }
 4778
 4779    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4780        let panes = self.center.panes();
 4781        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4782            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4783            let prev_pane = panes[prev_ix].clone();
 4784            window.focus(&prev_pane.focus_handle(cx), cx);
 4785        }
 4786    }
 4787
 4788    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4789        let last_pane = self.center.last_pane();
 4790        window.focus(&last_pane.focus_handle(cx), cx);
 4791    }
 4792
 4793    pub fn activate_pane_in_direction(
 4794        &mut self,
 4795        direction: SplitDirection,
 4796        window: &mut Window,
 4797        cx: &mut App,
 4798    ) {
 4799        use ActivateInDirectionTarget as Target;
 4800        enum Origin {
 4801            Sidebar,
 4802            LeftDock,
 4803            RightDock,
 4804            BottomDock,
 4805            Center,
 4806        }
 4807
 4808        let origin: Origin = if self
 4809            .sidebar_focus_handle
 4810            .as_ref()
 4811            .is_some_and(|h| h.contains_focused(window, cx))
 4812        {
 4813            Origin::Sidebar
 4814        } else {
 4815            [
 4816                (&self.left_dock, Origin::LeftDock),
 4817                (&self.right_dock, Origin::RightDock),
 4818                (&self.bottom_dock, Origin::BottomDock),
 4819            ]
 4820            .into_iter()
 4821            .find_map(|(dock, origin)| {
 4822                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4823                    Some(origin)
 4824                } else {
 4825                    None
 4826                }
 4827            })
 4828            .unwrap_or(Origin::Center)
 4829        };
 4830
 4831        let get_last_active_pane = || {
 4832            let pane = self
 4833                .last_active_center_pane
 4834                .clone()
 4835                .unwrap_or_else(|| {
 4836                    self.panes
 4837                        .first()
 4838                        .expect("There must be an active pane")
 4839                        .downgrade()
 4840                })
 4841                .upgrade()?;
 4842            (pane.read(cx).items_len() != 0).then_some(pane)
 4843        };
 4844
 4845        let try_dock =
 4846            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4847
 4848        let sidebar_target = self
 4849            .sidebar_focus_handle
 4850            .as_ref()
 4851            .map(|h| Target::Sidebar(h.clone()));
 4852
 4853        let sidebar_on_right = self
 4854            .multi_workspace
 4855            .as_ref()
 4856            .and_then(|mw| mw.upgrade())
 4857            .map_or(false, |mw| {
 4858                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4859            });
 4860
 4861        let away_from_sidebar = if sidebar_on_right {
 4862            SplitDirection::Left
 4863        } else {
 4864            SplitDirection::Right
 4865        };
 4866
 4867        let (near_dock, far_dock) = if sidebar_on_right {
 4868            (&self.right_dock, &self.left_dock)
 4869        } else {
 4870            (&self.left_dock, &self.right_dock)
 4871        };
 4872
 4873        let target = match (origin, direction) {
 4874            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4875                .or_else(|| get_last_active_pane().map(Target::Pane))
 4876                .or_else(|| try_dock(&self.bottom_dock))
 4877                .or_else(|| try_dock(far_dock)),
 4878
 4879            (Origin::Sidebar, _) => None,
 4880
 4881            // We're in the center, so we first try to go to a different pane,
 4882            // otherwise try to go to a dock.
 4883            (Origin::Center, direction) => {
 4884                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4885                    Some(Target::Pane(pane))
 4886                } else {
 4887                    match direction {
 4888                        SplitDirection::Up => None,
 4889                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4890                        SplitDirection::Left => {
 4891                            let dock_target = try_dock(&self.left_dock);
 4892                            if sidebar_on_right {
 4893                                dock_target
 4894                            } else {
 4895                                dock_target.or(sidebar_target)
 4896                            }
 4897                        }
 4898                        SplitDirection::Right => {
 4899                            let dock_target = try_dock(&self.right_dock);
 4900                            if sidebar_on_right {
 4901                                dock_target.or(sidebar_target)
 4902                            } else {
 4903                                dock_target
 4904                            }
 4905                        }
 4906                    }
 4907                }
 4908            }
 4909
 4910            (Origin::LeftDock, SplitDirection::Right) => {
 4911                if let Some(last_active_pane) = get_last_active_pane() {
 4912                    Some(Target::Pane(last_active_pane))
 4913                } else {
 4914                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4915                }
 4916            }
 4917
 4918            (Origin::LeftDock, SplitDirection::Left) => {
 4919                if sidebar_on_right {
 4920                    None
 4921                } else {
 4922                    sidebar_target
 4923                }
 4924            }
 4925
 4926            (Origin::LeftDock, SplitDirection::Down)
 4927            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4928
 4929            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4930            (Origin::BottomDock, SplitDirection::Left) => {
 4931                let dock_target = try_dock(&self.left_dock);
 4932                if sidebar_on_right {
 4933                    dock_target
 4934                } else {
 4935                    dock_target.or(sidebar_target)
 4936                }
 4937            }
 4938            (Origin::BottomDock, SplitDirection::Right) => {
 4939                let dock_target = try_dock(&self.right_dock);
 4940                if sidebar_on_right {
 4941                    dock_target.or(sidebar_target)
 4942                } else {
 4943                    dock_target
 4944                }
 4945            }
 4946
 4947            (Origin::RightDock, SplitDirection::Left) => {
 4948                if let Some(last_active_pane) = get_last_active_pane() {
 4949                    Some(Target::Pane(last_active_pane))
 4950                } else {
 4951                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4952                }
 4953            }
 4954
 4955            (Origin::RightDock, SplitDirection::Right) => {
 4956                if sidebar_on_right {
 4957                    sidebar_target
 4958                } else {
 4959                    None
 4960                }
 4961            }
 4962
 4963            _ => None,
 4964        };
 4965
 4966        match target {
 4967            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4968                let pane = pane.read(cx);
 4969                if let Some(item) = pane.active_item() {
 4970                    item.item_focus_handle(cx).focus(window, cx);
 4971                } else {
 4972                    log::error!(
 4973                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4974                    );
 4975                }
 4976            }
 4977            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4978                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4979                window.defer(cx, move |window, cx| {
 4980                    let dock = dock.read(cx);
 4981                    if let Some(panel) = dock.active_panel() {
 4982                        panel.panel_focus_handle(cx).focus(window, cx);
 4983                    } else {
 4984                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4985                    }
 4986                })
 4987            }
 4988            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4989                focus_handle.focus(window, cx);
 4990            }
 4991            None => {}
 4992        }
 4993    }
 4994
 4995    pub fn move_item_to_pane_in_direction(
 4996        &mut self,
 4997        action: &MoveItemToPaneInDirection,
 4998        window: &mut Window,
 4999        cx: &mut Context<Self>,
 5000    ) {
 5001        let destination = match self.find_pane_in_direction(action.direction, cx) {
 5002            Some(destination) => destination,
 5003            None => {
 5004                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 5005                    return;
 5006                }
 5007                let new_pane = self.add_pane(window, cx);
 5008                self.center
 5009                    .split(&self.active_pane, &new_pane, action.direction, cx);
 5010                new_pane
 5011            }
 5012        };
 5013
 5014        if action.clone {
 5015            if self
 5016                .active_pane
 5017                .read(cx)
 5018                .active_item()
 5019                .is_some_and(|item| item.can_split(cx))
 5020            {
 5021                clone_active_item(
 5022                    self.database_id(),
 5023                    &self.active_pane,
 5024                    &destination,
 5025                    action.focus,
 5026                    window,
 5027                    cx,
 5028                );
 5029                return;
 5030            }
 5031        }
 5032        move_active_item(
 5033            &self.active_pane,
 5034            &destination,
 5035            action.focus,
 5036            true,
 5037            window,
 5038            cx,
 5039        );
 5040    }
 5041
 5042    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5043        self.center.bounding_box_for_pane(pane)
 5044    }
 5045
 5046    pub fn find_pane_in_direction(
 5047        &mut self,
 5048        direction: SplitDirection,
 5049        cx: &App,
 5050    ) -> Option<Entity<Pane>> {
 5051        self.center
 5052            .find_pane_in_direction(&self.active_pane, direction, cx)
 5053            .cloned()
 5054    }
 5055
 5056    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5057        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5058            self.center.swap(&self.active_pane, &to, cx);
 5059            cx.notify();
 5060        }
 5061    }
 5062
 5063    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5064        if self
 5065            .center
 5066            .move_to_border(&self.active_pane, direction, cx)
 5067            .unwrap()
 5068        {
 5069            cx.notify();
 5070        }
 5071    }
 5072
 5073    pub fn resize_pane(
 5074        &mut self,
 5075        axis: gpui::Axis,
 5076        amount: Pixels,
 5077        window: &mut Window,
 5078        cx: &mut Context<Self>,
 5079    ) {
 5080        let docks = self.all_docks();
 5081        let active_dock = docks
 5082            .into_iter()
 5083            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5084
 5085        if let Some(dock_entity) = active_dock {
 5086            let dock = dock_entity.read(cx);
 5087            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5088                return;
 5089            };
 5090            match dock.position() {
 5091                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5092                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5093                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5094            }
 5095        } else {
 5096            self.center
 5097                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5098        }
 5099        cx.notify();
 5100    }
 5101
 5102    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5103        self.center.reset_pane_sizes(cx);
 5104        cx.notify();
 5105    }
 5106
 5107    fn handle_pane_focused(
 5108        &mut self,
 5109        pane: Entity<Pane>,
 5110        window: &mut Window,
 5111        cx: &mut Context<Self>,
 5112    ) {
 5113        // This is explicitly hoisted out of the following check for pane identity as
 5114        // terminal panel panes are not registered as a center panes.
 5115        self.status_bar.update(cx, |status_bar, cx| {
 5116            status_bar.set_active_pane(&pane, window, cx);
 5117        });
 5118        if self.active_pane != pane {
 5119            self.set_active_pane(&pane, window, cx);
 5120        }
 5121
 5122        if self.last_active_center_pane.is_none() {
 5123            self.last_active_center_pane = Some(pane.downgrade());
 5124        }
 5125
 5126        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5127        // This prevents the dock from closing when focus events fire during window activation.
 5128        // We also preserve any dock whose active panel itself has focus — this covers
 5129        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5130        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5131            let dock_read = dock.read(cx);
 5132            if let Some(panel) = dock_read.active_panel() {
 5133                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5134                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5135                {
 5136                    return Some(dock_read.position());
 5137                }
 5138            }
 5139            None
 5140        });
 5141
 5142        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5143        if pane.read(cx).is_zoomed() {
 5144            self.zoomed = Some(pane.downgrade().into());
 5145        } else {
 5146            self.zoomed = None;
 5147        }
 5148        self.zoomed_position = None;
 5149        cx.emit(Event::ZoomChanged);
 5150        self.update_active_view_for_followers(window, cx);
 5151        pane.update(cx, |pane, _| {
 5152            pane.track_alternate_file_items();
 5153        });
 5154
 5155        cx.notify();
 5156    }
 5157
 5158    fn set_active_pane(
 5159        &mut self,
 5160        pane: &Entity<Pane>,
 5161        window: &mut Window,
 5162        cx: &mut Context<Self>,
 5163    ) {
 5164        self.active_pane = pane.clone();
 5165        self.active_item_path_changed(true, window, cx);
 5166        self.last_active_center_pane = Some(pane.downgrade());
 5167    }
 5168
 5169    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5170        self.update_active_view_for_followers(window, cx);
 5171    }
 5172
 5173    fn handle_pane_event(
 5174        &mut self,
 5175        pane: &Entity<Pane>,
 5176        event: &pane::Event,
 5177        window: &mut Window,
 5178        cx: &mut Context<Self>,
 5179    ) {
 5180        let mut serialize_workspace = true;
 5181        match event {
 5182            pane::Event::AddItem { item } => {
 5183                item.added_to_pane(self, pane.clone(), window, cx);
 5184                cx.emit(Event::ItemAdded {
 5185                    item: item.boxed_clone(),
 5186                });
 5187            }
 5188            pane::Event::Split { direction, mode } => {
 5189                match mode {
 5190                    SplitMode::ClonePane => {
 5191                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5192                            .detach();
 5193                    }
 5194                    SplitMode::EmptyPane => {
 5195                        self.split_pane(pane.clone(), *direction, window, cx);
 5196                    }
 5197                    SplitMode::MovePane => {
 5198                        self.split_and_move(pane.clone(), *direction, window, cx);
 5199                    }
 5200                };
 5201            }
 5202            pane::Event::JoinIntoNext => {
 5203                self.join_pane_into_next(pane.clone(), window, cx);
 5204            }
 5205            pane::Event::JoinAll => {
 5206                self.join_all_panes(window, cx);
 5207            }
 5208            pane::Event::Remove { focus_on_pane } => {
 5209                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5210            }
 5211            pane::Event::ActivateItem {
 5212                local,
 5213                focus_changed,
 5214            } => {
 5215                window.invalidate_character_coordinates();
 5216
 5217                pane.update(cx, |pane, _| {
 5218                    pane.track_alternate_file_items();
 5219                });
 5220                if *local {
 5221                    self.unfollow_in_pane(pane, window, cx);
 5222                }
 5223                serialize_workspace = *focus_changed || pane != self.active_pane();
 5224                if pane == self.active_pane() {
 5225                    self.active_item_path_changed(*focus_changed, window, cx);
 5226                    self.update_active_view_for_followers(window, cx);
 5227                } else if *local {
 5228                    self.set_active_pane(pane, window, cx);
 5229                }
 5230            }
 5231            pane::Event::UserSavedItem { item, save_intent } => {
 5232                cx.emit(Event::UserSavedItem {
 5233                    pane: pane.downgrade(),
 5234                    item: item.boxed_clone(),
 5235                    save_intent: *save_intent,
 5236                });
 5237                serialize_workspace = false;
 5238            }
 5239            pane::Event::ChangeItemTitle => {
 5240                if *pane == self.active_pane {
 5241                    self.active_item_path_changed(false, window, cx);
 5242                }
 5243                serialize_workspace = false;
 5244            }
 5245            pane::Event::RemovedItem { item } => {
 5246                cx.emit(Event::ActiveItemChanged);
 5247                self.update_window_edited(window, cx);
 5248                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5249                    && entry.get().entity_id() == pane.entity_id()
 5250                {
 5251                    entry.remove();
 5252                }
 5253                cx.emit(Event::ItemRemoved {
 5254                    item_id: item.item_id(),
 5255                });
 5256            }
 5257            pane::Event::Focus => {
 5258                window.invalidate_character_coordinates();
 5259                self.handle_pane_focused(pane.clone(), window, cx);
 5260            }
 5261            pane::Event::ZoomIn => {
 5262                if *pane == self.active_pane {
 5263                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5264                    if pane.read(cx).has_focus(window, cx) {
 5265                        self.zoomed = Some(pane.downgrade().into());
 5266                        self.zoomed_position = None;
 5267                        cx.emit(Event::ZoomChanged);
 5268                    }
 5269                    cx.notify();
 5270                }
 5271            }
 5272            pane::Event::ZoomOut => {
 5273                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5274                if self.zoomed_position.is_none() {
 5275                    self.zoomed = None;
 5276                    cx.emit(Event::ZoomChanged);
 5277                }
 5278                cx.notify();
 5279            }
 5280            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5281        }
 5282
 5283        if serialize_workspace {
 5284            self.serialize_workspace(window, cx);
 5285        }
 5286    }
 5287
 5288    pub fn unfollow_in_pane(
 5289        &mut self,
 5290        pane: &Entity<Pane>,
 5291        window: &mut Window,
 5292        cx: &mut Context<Workspace>,
 5293    ) -> Option<CollaboratorId> {
 5294        let leader_id = self.leader_for_pane(pane)?;
 5295        self.unfollow(leader_id, window, cx);
 5296        Some(leader_id)
 5297    }
 5298
 5299    pub fn split_pane(
 5300        &mut self,
 5301        pane_to_split: Entity<Pane>,
 5302        split_direction: SplitDirection,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) -> Entity<Pane> {
 5306        let new_pane = self.add_pane(window, cx);
 5307        self.center
 5308            .split(&pane_to_split, &new_pane, split_direction, cx);
 5309        cx.notify();
 5310        new_pane
 5311    }
 5312
 5313    pub fn split_and_move(
 5314        &mut self,
 5315        pane: Entity<Pane>,
 5316        direction: SplitDirection,
 5317        window: &mut Window,
 5318        cx: &mut Context<Self>,
 5319    ) {
 5320        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5321            return;
 5322        };
 5323        let new_pane = self.add_pane(window, cx);
 5324        new_pane.update(cx, |pane, cx| {
 5325            pane.add_item(item, true, true, None, window, cx)
 5326        });
 5327        self.center.split(&pane, &new_pane, direction, cx);
 5328        cx.notify();
 5329    }
 5330
 5331    pub fn split_and_clone(
 5332        &mut self,
 5333        pane: Entity<Pane>,
 5334        direction: SplitDirection,
 5335        window: &mut Window,
 5336        cx: &mut Context<Self>,
 5337    ) -> Task<Option<Entity<Pane>>> {
 5338        let Some(item) = pane.read(cx).active_item() else {
 5339            return Task::ready(None);
 5340        };
 5341        if !item.can_split(cx) {
 5342            return Task::ready(None);
 5343        }
 5344        let task = item.clone_on_split(self.database_id(), window, cx);
 5345        cx.spawn_in(window, async move |this, cx| {
 5346            if let Some(clone) = task.await {
 5347                this.update_in(cx, |this, window, cx| {
 5348                    let new_pane = this.add_pane(window, cx);
 5349                    let nav_history = pane.read(cx).fork_nav_history();
 5350                    new_pane.update(cx, |pane, cx| {
 5351                        pane.set_nav_history(nav_history, cx);
 5352                        pane.add_item(clone, true, true, None, window, cx)
 5353                    });
 5354                    this.center.split(&pane, &new_pane, direction, cx);
 5355                    cx.notify();
 5356                    new_pane
 5357                })
 5358                .ok()
 5359            } else {
 5360                None
 5361            }
 5362        })
 5363    }
 5364
 5365    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5366        let active_item = self.active_pane.read(cx).active_item();
 5367        for pane in &self.panes {
 5368            join_pane_into_active(&self.active_pane, pane, window, cx);
 5369        }
 5370        if let Some(active_item) = active_item {
 5371            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5372        }
 5373        cx.notify();
 5374    }
 5375
 5376    pub fn join_pane_into_next(
 5377        &mut self,
 5378        pane: Entity<Pane>,
 5379        window: &mut Window,
 5380        cx: &mut Context<Self>,
 5381    ) {
 5382        let next_pane = self
 5383            .find_pane_in_direction(SplitDirection::Right, cx)
 5384            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5385            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5386            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5387        let Some(next_pane) = next_pane else {
 5388            return;
 5389        };
 5390        move_all_items(&pane, &next_pane, window, cx);
 5391        cx.notify();
 5392    }
 5393
 5394    fn remove_pane(
 5395        &mut self,
 5396        pane: Entity<Pane>,
 5397        focus_on: Option<Entity<Pane>>,
 5398        window: &mut Window,
 5399        cx: &mut Context<Self>,
 5400    ) {
 5401        if self.center.remove(&pane, cx).unwrap() {
 5402            self.force_remove_pane(&pane, &focus_on, window, cx);
 5403            self.unfollow_in_pane(&pane, window, cx);
 5404            self.last_leaders_by_pane.remove(&pane.downgrade());
 5405            for removed_item in pane.read(cx).items() {
 5406                self.panes_by_item.remove(&removed_item.item_id());
 5407            }
 5408
 5409            cx.notify();
 5410        } else {
 5411            self.active_item_path_changed(true, window, cx);
 5412        }
 5413        cx.emit(Event::PaneRemoved);
 5414    }
 5415
 5416    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5417        &mut self.panes
 5418    }
 5419
 5420    pub fn panes(&self) -> &[Entity<Pane>] {
 5421        &self.panes
 5422    }
 5423
 5424    pub fn active_pane(&self) -> &Entity<Pane> {
 5425        &self.active_pane
 5426    }
 5427
 5428    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5429        for dock in self.all_docks() {
 5430            if dock.focus_handle(cx).contains_focused(window, cx)
 5431                && let Some(pane) = dock
 5432                    .read(cx)
 5433                    .active_panel()
 5434                    .and_then(|panel| panel.pane(cx))
 5435            {
 5436                return pane;
 5437            }
 5438        }
 5439        self.active_pane().clone()
 5440    }
 5441
 5442    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5443        self.find_pane_in_direction(SplitDirection::Right, cx)
 5444            .unwrap_or_else(|| {
 5445                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5446            })
 5447    }
 5448
 5449    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5450        self.pane_for_item_id(handle.item_id())
 5451    }
 5452
 5453    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5454        let weak_pane = self.panes_by_item.get(&item_id)?;
 5455        weak_pane.upgrade()
 5456    }
 5457
 5458    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5459        self.panes
 5460            .iter()
 5461            .find(|pane| pane.entity_id() == entity_id)
 5462            .cloned()
 5463    }
 5464
 5465    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5466        self.follower_states.retain(|leader_id, state| {
 5467            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5468                for item in state.items_by_leader_view_id.values() {
 5469                    item.view.set_leader_id(None, window, cx);
 5470                }
 5471                false
 5472            } else {
 5473                true
 5474            }
 5475        });
 5476        cx.notify();
 5477    }
 5478
 5479    pub fn start_following(
 5480        &mut self,
 5481        leader_id: impl Into<CollaboratorId>,
 5482        window: &mut Window,
 5483        cx: &mut Context<Self>,
 5484    ) -> Option<Task<Result<()>>> {
 5485        let leader_id = leader_id.into();
 5486        let pane = self.active_pane().clone();
 5487
 5488        self.last_leaders_by_pane
 5489            .insert(pane.downgrade(), leader_id);
 5490        self.unfollow(leader_id, window, cx);
 5491        self.unfollow_in_pane(&pane, window, cx);
 5492        self.follower_states.insert(
 5493            leader_id,
 5494            FollowerState {
 5495                center_pane: pane.clone(),
 5496                dock_pane: None,
 5497                active_view_id: None,
 5498                items_by_leader_view_id: Default::default(),
 5499            },
 5500        );
 5501        cx.notify();
 5502
 5503        match leader_id {
 5504            CollaboratorId::PeerId(leader_peer_id) => {
 5505                let room_id = self.active_call()?.room_id(cx)?;
 5506                let project_id = self.project.read(cx).remote_id();
 5507                let request = self.app_state.client.request(proto::Follow {
 5508                    room_id,
 5509                    project_id,
 5510                    leader_id: Some(leader_peer_id),
 5511                });
 5512
 5513                Some(cx.spawn_in(window, async move |this, cx| {
 5514                    let response = request.await?;
 5515                    this.update(cx, |this, _| {
 5516                        let state = this
 5517                            .follower_states
 5518                            .get_mut(&leader_id)
 5519                            .context("following interrupted")?;
 5520                        state.active_view_id = response
 5521                            .active_view
 5522                            .as_ref()
 5523                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5524                        anyhow::Ok(())
 5525                    })??;
 5526                    if let Some(view) = response.active_view {
 5527                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5528                    }
 5529                    this.update_in(cx, |this, window, cx| {
 5530                        this.leader_updated(leader_id, window, cx)
 5531                    })?;
 5532                    Ok(())
 5533                }))
 5534            }
 5535            CollaboratorId::Agent => {
 5536                self.leader_updated(leader_id, window, cx)?;
 5537                Some(Task::ready(Ok(())))
 5538            }
 5539        }
 5540    }
 5541
 5542    pub fn follow_next_collaborator(
 5543        &mut self,
 5544        _: &FollowNextCollaborator,
 5545        window: &mut Window,
 5546        cx: &mut Context<Self>,
 5547    ) {
 5548        let collaborators = self.project.read(cx).collaborators();
 5549        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5550            let mut collaborators = collaborators.keys().copied();
 5551            for peer_id in collaborators.by_ref() {
 5552                if CollaboratorId::PeerId(peer_id) == leader_id {
 5553                    break;
 5554                }
 5555            }
 5556            collaborators.next().map(CollaboratorId::PeerId)
 5557        } else if let Some(last_leader_id) =
 5558            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5559        {
 5560            match last_leader_id {
 5561                CollaboratorId::PeerId(peer_id) => {
 5562                    if collaborators.contains_key(peer_id) {
 5563                        Some(*last_leader_id)
 5564                    } else {
 5565                        None
 5566                    }
 5567                }
 5568                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5569            }
 5570        } else {
 5571            None
 5572        };
 5573
 5574        let pane = self.active_pane.clone();
 5575        let Some(leader_id) = next_leader_id.or_else(|| {
 5576            Some(CollaboratorId::PeerId(
 5577                collaborators.keys().copied().next()?,
 5578            ))
 5579        }) else {
 5580            return;
 5581        };
 5582        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5583            return;
 5584        }
 5585        if let Some(task) = self.start_following(leader_id, window, cx) {
 5586            task.detach_and_log_err(cx)
 5587        }
 5588    }
 5589
 5590    pub fn follow(
 5591        &mut self,
 5592        leader_id: impl Into<CollaboratorId>,
 5593        window: &mut Window,
 5594        cx: &mut Context<Self>,
 5595    ) {
 5596        let leader_id = leader_id.into();
 5597
 5598        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5599            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5600                return;
 5601            };
 5602            let Some(remote_participant) =
 5603                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5604            else {
 5605                return;
 5606            };
 5607
 5608            let project = self.project.read(cx);
 5609
 5610            let other_project_id = match remote_participant.location {
 5611                ParticipantLocation::External => None,
 5612                ParticipantLocation::UnsharedProject => None,
 5613                ParticipantLocation::SharedProject { project_id } => {
 5614                    if Some(project_id) == project.remote_id() {
 5615                        None
 5616                    } else {
 5617                        Some(project_id)
 5618                    }
 5619                }
 5620            };
 5621
 5622            // if they are active in another project, follow there.
 5623            if let Some(project_id) = other_project_id {
 5624                let app_state = self.app_state.clone();
 5625                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5626                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5627                        Some(format!("{error:#}"))
 5628                    });
 5629            }
 5630        }
 5631
 5632        // if you're already following, find the right pane and focus it.
 5633        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5634            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5635
 5636            return;
 5637        }
 5638
 5639        // Otherwise, follow.
 5640        if let Some(task) = self.start_following(leader_id, window, cx) {
 5641            task.detach_and_log_err(cx)
 5642        }
 5643    }
 5644
 5645    pub fn unfollow(
 5646        &mut self,
 5647        leader_id: impl Into<CollaboratorId>,
 5648        window: &mut Window,
 5649        cx: &mut Context<Self>,
 5650    ) -> Option<()> {
 5651        cx.notify();
 5652
 5653        let leader_id = leader_id.into();
 5654        let state = self.follower_states.remove(&leader_id)?;
 5655        for (_, item) in state.items_by_leader_view_id {
 5656            item.view.set_leader_id(None, window, cx);
 5657        }
 5658
 5659        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5660            let project_id = self.project.read(cx).remote_id();
 5661            let room_id = self.active_call()?.room_id(cx)?;
 5662            self.app_state
 5663                .client
 5664                .send(proto::Unfollow {
 5665                    room_id,
 5666                    project_id,
 5667                    leader_id: Some(leader_peer_id),
 5668                })
 5669                .log_err();
 5670        }
 5671
 5672        Some(())
 5673    }
 5674
 5675    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5676        self.follower_states.contains_key(&id.into())
 5677    }
 5678
 5679    fn active_item_path_changed(
 5680        &mut self,
 5681        focus_changed: bool,
 5682        window: &mut Window,
 5683        cx: &mut Context<Self>,
 5684    ) {
 5685        cx.emit(Event::ActiveItemChanged);
 5686        let active_entry = self.active_project_path(cx);
 5687        self.project.update(cx, |project, cx| {
 5688            project.set_active_path(active_entry.clone(), cx)
 5689        });
 5690
 5691        if focus_changed && let Some(project_path) = &active_entry {
 5692            let git_store_entity = self.project.read(cx).git_store().clone();
 5693            git_store_entity.update(cx, |git_store, cx| {
 5694                git_store.set_active_repo_for_path(project_path, cx);
 5695            });
 5696        }
 5697
 5698        self.update_window_title(window, cx);
 5699    }
 5700
 5701    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5702        let project = self.project().read(cx);
 5703        let mut title = String::new();
 5704
 5705        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5706            let name = {
 5707                let settings_location = SettingsLocation {
 5708                    worktree_id: worktree.read(cx).id(),
 5709                    path: RelPath::empty(),
 5710                };
 5711
 5712                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5713                match &settings.project_name {
 5714                    Some(name) => name.as_str(),
 5715                    None => worktree.read(cx).root_name_str(),
 5716                }
 5717            };
 5718            if i > 0 {
 5719                title.push_str(", ");
 5720            }
 5721            title.push_str(name);
 5722        }
 5723
 5724        if title.is_empty() {
 5725            title = "empty project".to_string();
 5726        }
 5727
 5728        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5729            let filename = path.path.file_name().or_else(|| {
 5730                Some(
 5731                    project
 5732                        .worktree_for_id(path.worktree_id, cx)?
 5733                        .read(cx)
 5734                        .root_name_str(),
 5735                )
 5736            });
 5737
 5738            if let Some(filename) = filename {
 5739                title.push_str("");
 5740                title.push_str(filename.as_ref());
 5741            }
 5742        }
 5743
 5744        if project.is_via_collab() {
 5745            title.push_str("");
 5746        } else if project.is_shared() {
 5747            title.push_str("");
 5748        }
 5749
 5750        if let Some(last_title) = self.last_window_title.as_ref()
 5751            && &title == last_title
 5752        {
 5753            return;
 5754        }
 5755        window.set_window_title(&title);
 5756        SystemWindowTabController::update_tab_title(
 5757            cx,
 5758            window.window_handle().window_id(),
 5759            SharedString::from(&title),
 5760        );
 5761        self.last_window_title = Some(title);
 5762    }
 5763
 5764    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5765        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5766        if is_edited != self.window_edited {
 5767            self.window_edited = is_edited;
 5768            window.set_window_edited(self.window_edited)
 5769        }
 5770    }
 5771
 5772    fn update_item_dirty_state(
 5773        &mut self,
 5774        item: &dyn ItemHandle,
 5775        window: &mut Window,
 5776        cx: &mut App,
 5777    ) {
 5778        let is_dirty = item.is_dirty(cx);
 5779        let item_id = item.item_id();
 5780        let was_dirty = self.dirty_items.contains_key(&item_id);
 5781        if is_dirty == was_dirty {
 5782            return;
 5783        }
 5784        if was_dirty {
 5785            self.dirty_items.remove(&item_id);
 5786            self.update_window_edited(window, cx);
 5787            return;
 5788        }
 5789
 5790        let workspace = self.weak_handle();
 5791        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5792            return;
 5793        };
 5794        let on_release_callback = Box::new(move |cx: &mut App| {
 5795            window_handle
 5796                .update(cx, |_, window, cx| {
 5797                    workspace
 5798                        .update(cx, |workspace, cx| {
 5799                            workspace.dirty_items.remove(&item_id);
 5800                            workspace.update_window_edited(window, cx)
 5801                        })
 5802                        .ok();
 5803                })
 5804                .ok();
 5805        });
 5806
 5807        let s = item.on_release(cx, on_release_callback);
 5808        self.dirty_items.insert(item_id, s);
 5809        self.update_window_edited(window, cx);
 5810    }
 5811
 5812    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5813        if self.notifications.is_empty() {
 5814            None
 5815        } else {
 5816            Some(
 5817                div()
 5818                    .absolute()
 5819                    .right_3()
 5820                    .bottom_3()
 5821                    .w_112()
 5822                    .h_full()
 5823                    .flex()
 5824                    .flex_col()
 5825                    .justify_end()
 5826                    .gap_2()
 5827                    .children(
 5828                        self.notifications
 5829                            .iter()
 5830                            .map(|(_, notification)| notification.clone().into_any()),
 5831                    ),
 5832            )
 5833        }
 5834    }
 5835
 5836    // RPC handlers
 5837
 5838    fn active_view_for_follower(
 5839        &self,
 5840        follower_project_id: Option<u64>,
 5841        window: &mut Window,
 5842        cx: &mut Context<Self>,
 5843    ) -> Option<proto::View> {
 5844        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5845        let item = item?;
 5846        let leader_id = self
 5847            .pane_for(&*item)
 5848            .and_then(|pane| self.leader_for_pane(&pane));
 5849        let leader_peer_id = match leader_id {
 5850            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5851            Some(CollaboratorId::Agent) | None => None,
 5852        };
 5853
 5854        let item_handle = item.to_followable_item_handle(cx)?;
 5855        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5856        let variant = item_handle.to_state_proto(window, cx)?;
 5857
 5858        if item_handle.is_project_item(window, cx)
 5859            && (follower_project_id.is_none()
 5860                || follower_project_id != self.project.read(cx).remote_id())
 5861        {
 5862            return None;
 5863        }
 5864
 5865        Some(proto::View {
 5866            id: id.to_proto(),
 5867            leader_id: leader_peer_id,
 5868            variant: Some(variant),
 5869            panel_id: panel_id.map(|id| id as i32),
 5870        })
 5871    }
 5872
 5873    fn handle_follow(
 5874        &mut self,
 5875        follower_project_id: Option<u64>,
 5876        window: &mut Window,
 5877        cx: &mut Context<Self>,
 5878    ) -> proto::FollowResponse {
 5879        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5880
 5881        cx.notify();
 5882        proto::FollowResponse {
 5883            views: active_view.iter().cloned().collect(),
 5884            active_view,
 5885        }
 5886    }
 5887
 5888    fn handle_update_followers(
 5889        &mut self,
 5890        leader_id: PeerId,
 5891        message: proto::UpdateFollowers,
 5892        _window: &mut Window,
 5893        _cx: &mut Context<Self>,
 5894    ) {
 5895        self.leader_updates_tx
 5896            .unbounded_send((leader_id, message))
 5897            .ok();
 5898    }
 5899
 5900    async fn process_leader_update(
 5901        this: &WeakEntity<Self>,
 5902        leader_id: PeerId,
 5903        update: proto::UpdateFollowers,
 5904        cx: &mut AsyncWindowContext,
 5905    ) -> Result<()> {
 5906        match update.variant.context("invalid update")? {
 5907            proto::update_followers::Variant::CreateView(view) => {
 5908                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5909                let should_add_view = this.update(cx, |this, _| {
 5910                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5911                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5912                    } else {
 5913                        anyhow::Ok(false)
 5914                    }
 5915                })??;
 5916
 5917                if should_add_view {
 5918                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5919                }
 5920            }
 5921            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5922                let should_add_view = this.update(cx, |this, _| {
 5923                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5924                        state.active_view_id = update_active_view
 5925                            .view
 5926                            .as_ref()
 5927                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5928
 5929                        if state.active_view_id.is_some_and(|view_id| {
 5930                            !state.items_by_leader_view_id.contains_key(&view_id)
 5931                        }) {
 5932                            anyhow::Ok(true)
 5933                        } else {
 5934                            anyhow::Ok(false)
 5935                        }
 5936                    } else {
 5937                        anyhow::Ok(false)
 5938                    }
 5939                })??;
 5940
 5941                if should_add_view && let Some(view) = update_active_view.view {
 5942                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5943                }
 5944            }
 5945            proto::update_followers::Variant::UpdateView(update_view) => {
 5946                let variant = update_view.variant.context("missing update view variant")?;
 5947                let id = update_view.id.context("missing update view id")?;
 5948                let mut tasks = Vec::new();
 5949                this.update_in(cx, |this, window, cx| {
 5950                    let project = this.project.clone();
 5951                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5952                        let view_id = ViewId::from_proto(id.clone())?;
 5953                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5954                            tasks.push(item.view.apply_update_proto(
 5955                                &project,
 5956                                variant.clone(),
 5957                                window,
 5958                                cx,
 5959                            ));
 5960                        }
 5961                    }
 5962                    anyhow::Ok(())
 5963                })??;
 5964                try_join_all(tasks).await.log_err();
 5965            }
 5966        }
 5967        this.update_in(cx, |this, window, cx| {
 5968            this.leader_updated(leader_id, window, cx)
 5969        })?;
 5970        Ok(())
 5971    }
 5972
 5973    async fn add_view_from_leader(
 5974        this: WeakEntity<Self>,
 5975        leader_id: PeerId,
 5976        view: &proto::View,
 5977        cx: &mut AsyncWindowContext,
 5978    ) -> Result<()> {
 5979        let this = this.upgrade().context("workspace dropped")?;
 5980
 5981        let Some(id) = view.id.clone() else {
 5982            anyhow::bail!("no id for view");
 5983        };
 5984        let id = ViewId::from_proto(id)?;
 5985        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5986
 5987        let pane = this.update(cx, |this, _cx| {
 5988            let state = this
 5989                .follower_states
 5990                .get(&leader_id.into())
 5991                .context("stopped following")?;
 5992            anyhow::Ok(state.pane().clone())
 5993        })?;
 5994        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5995            let client = this.read(cx).client().clone();
 5996            pane.items().find_map(|item| {
 5997                let item = item.to_followable_item_handle(cx)?;
 5998                if item.remote_id(&client, window, cx) == Some(id) {
 5999                    Some(item)
 6000                } else {
 6001                    None
 6002                }
 6003            })
 6004        })?;
 6005        let item = if let Some(existing_item) = existing_item {
 6006            existing_item
 6007        } else {
 6008            let variant = view.variant.clone();
 6009            anyhow::ensure!(variant.is_some(), "missing view variant");
 6010
 6011            let task = cx.update(|window, cx| {
 6012                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6013            })?;
 6014
 6015            let Some(task) = task else {
 6016                anyhow::bail!(
 6017                    "failed to construct view from leader (maybe from a different version of zed?)"
 6018                );
 6019            };
 6020
 6021            let mut new_item = task.await?;
 6022            pane.update_in(cx, |pane, window, cx| {
 6023                let mut item_to_remove = None;
 6024                for (ix, item) in pane.items().enumerate() {
 6025                    if let Some(item) = item.to_followable_item_handle(cx) {
 6026                        match new_item.dedup(item.as_ref(), window, cx) {
 6027                            Some(item::Dedup::KeepExisting) => {
 6028                                new_item =
 6029                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6030                                break;
 6031                            }
 6032                            Some(item::Dedup::ReplaceExisting) => {
 6033                                item_to_remove = Some((ix, item.item_id()));
 6034                                break;
 6035                            }
 6036                            None => {}
 6037                        }
 6038                    }
 6039                }
 6040
 6041                if let Some((ix, id)) = item_to_remove {
 6042                    pane.remove_item(id, false, false, window, cx);
 6043                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6044                }
 6045            })?;
 6046
 6047            new_item
 6048        };
 6049
 6050        this.update_in(cx, |this, window, cx| {
 6051            let state = this.follower_states.get_mut(&leader_id.into())?;
 6052            item.set_leader_id(Some(leader_id.into()), window, cx);
 6053            state.items_by_leader_view_id.insert(
 6054                id,
 6055                FollowerView {
 6056                    view: item,
 6057                    location: panel_id,
 6058                },
 6059            );
 6060
 6061            Some(())
 6062        })
 6063        .context("no follower state")?;
 6064
 6065        Ok(())
 6066    }
 6067
 6068    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6069        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6070            return;
 6071        };
 6072
 6073        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6074            let buffer_entity_id = agent_location.buffer.entity_id();
 6075            let view_id = ViewId {
 6076                creator: CollaboratorId::Agent,
 6077                id: buffer_entity_id.as_u64(),
 6078            };
 6079            follower_state.active_view_id = Some(view_id);
 6080
 6081            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6082                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6083                hash_map::Entry::Vacant(entry) => {
 6084                    let existing_view =
 6085                        follower_state
 6086                            .center_pane
 6087                            .read(cx)
 6088                            .items()
 6089                            .find_map(|item| {
 6090                                let item = item.to_followable_item_handle(cx)?;
 6091                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6092                                    && item.project_item_model_ids(cx).as_slice()
 6093                                        == [buffer_entity_id]
 6094                                {
 6095                                    Some(item)
 6096                                } else {
 6097                                    None
 6098                                }
 6099                            });
 6100                    let view = existing_view.or_else(|| {
 6101                        agent_location.buffer.upgrade().and_then(|buffer| {
 6102                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6103                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6104                            })?
 6105                            .to_followable_item_handle(cx)
 6106                        })
 6107                    });
 6108
 6109                    view.map(|view| {
 6110                        entry.insert(FollowerView {
 6111                            view,
 6112                            location: None,
 6113                        })
 6114                    })
 6115                }
 6116            };
 6117
 6118            if let Some(item) = item {
 6119                item.view
 6120                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6121                item.view
 6122                    .update_agent_location(agent_location.position, window, cx);
 6123            }
 6124        } else {
 6125            follower_state.active_view_id = None;
 6126        }
 6127
 6128        self.leader_updated(CollaboratorId::Agent, window, cx);
 6129    }
 6130
 6131    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6132        let mut is_project_item = true;
 6133        let mut update = proto::UpdateActiveView::default();
 6134        if window.is_window_active() {
 6135            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6136
 6137            if let Some(item) = active_item
 6138                && item.item_focus_handle(cx).contains_focused(window, cx)
 6139            {
 6140                let leader_id = self
 6141                    .pane_for(&*item)
 6142                    .and_then(|pane| self.leader_for_pane(&pane));
 6143                let leader_peer_id = match leader_id {
 6144                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6145                    Some(CollaboratorId::Agent) | None => None,
 6146                };
 6147
 6148                if let Some(item) = item.to_followable_item_handle(cx) {
 6149                    let id = item
 6150                        .remote_id(&self.app_state.client, window, cx)
 6151                        .map(|id| id.to_proto());
 6152
 6153                    if let Some(id) = id
 6154                        && let Some(variant) = item.to_state_proto(window, cx)
 6155                    {
 6156                        let view = Some(proto::View {
 6157                            id,
 6158                            leader_id: leader_peer_id,
 6159                            variant: Some(variant),
 6160                            panel_id: panel_id.map(|id| id as i32),
 6161                        });
 6162
 6163                        is_project_item = item.is_project_item(window, cx);
 6164                        update = proto::UpdateActiveView { view };
 6165                    };
 6166                }
 6167            }
 6168        }
 6169
 6170        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6171        if active_view_id != self.last_active_view_id.as_ref() {
 6172            self.last_active_view_id = active_view_id.cloned();
 6173            self.update_followers(
 6174                is_project_item,
 6175                proto::update_followers::Variant::UpdateActiveView(update),
 6176                window,
 6177                cx,
 6178            );
 6179        }
 6180    }
 6181
 6182    fn active_item_for_followers(
 6183        &self,
 6184        window: &mut Window,
 6185        cx: &mut App,
 6186    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6187        let mut active_item = None;
 6188        let mut panel_id = None;
 6189        for dock in self.all_docks() {
 6190            if dock.focus_handle(cx).contains_focused(window, cx)
 6191                && let Some(panel) = dock.read(cx).active_panel()
 6192                && let Some(pane) = panel.pane(cx)
 6193                && let Some(item) = pane.read(cx).active_item()
 6194            {
 6195                active_item = Some(item);
 6196                panel_id = panel.remote_id();
 6197                break;
 6198            }
 6199        }
 6200
 6201        if active_item.is_none() {
 6202            active_item = self.active_pane().read(cx).active_item();
 6203        }
 6204        (active_item, panel_id)
 6205    }
 6206
 6207    fn update_followers(
 6208        &self,
 6209        project_only: bool,
 6210        update: proto::update_followers::Variant,
 6211        _: &mut Window,
 6212        cx: &mut App,
 6213    ) -> Option<()> {
 6214        // If this update only applies to for followers in the current project,
 6215        // then skip it unless this project is shared. If it applies to all
 6216        // followers, regardless of project, then set `project_id` to none,
 6217        // indicating that it goes to all followers.
 6218        let project_id = if project_only {
 6219            Some(self.project.read(cx).remote_id()?)
 6220        } else {
 6221            None
 6222        };
 6223        self.app_state().workspace_store.update(cx, |store, cx| {
 6224            store.update_followers(project_id, update, cx)
 6225        })
 6226    }
 6227
 6228    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6229        self.follower_states.iter().find_map(|(leader_id, state)| {
 6230            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6231                Some(*leader_id)
 6232            } else {
 6233                None
 6234            }
 6235        })
 6236    }
 6237
 6238    fn leader_updated(
 6239        &mut self,
 6240        leader_id: impl Into<CollaboratorId>,
 6241        window: &mut Window,
 6242        cx: &mut Context<Self>,
 6243    ) -> Option<Box<dyn ItemHandle>> {
 6244        cx.notify();
 6245
 6246        let leader_id = leader_id.into();
 6247        let (panel_id, item) = match leader_id {
 6248            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6249            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6250        };
 6251
 6252        let state = self.follower_states.get(&leader_id)?;
 6253        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6254        let pane;
 6255        if let Some(panel_id) = panel_id {
 6256            pane = self
 6257                .activate_panel_for_proto_id(panel_id, window, cx)?
 6258                .pane(cx)?;
 6259            let state = self.follower_states.get_mut(&leader_id)?;
 6260            state.dock_pane = Some(pane.clone());
 6261        } else {
 6262            pane = state.center_pane.clone();
 6263            let state = self.follower_states.get_mut(&leader_id)?;
 6264            if let Some(dock_pane) = state.dock_pane.take() {
 6265                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6266            }
 6267        }
 6268
 6269        pane.update(cx, |pane, cx| {
 6270            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6271            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6272                pane.activate_item(index, false, false, window, cx);
 6273            } else {
 6274                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6275            }
 6276
 6277            if focus_active_item {
 6278                pane.focus_active_item(window, cx)
 6279            }
 6280        });
 6281
 6282        Some(item)
 6283    }
 6284
 6285    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6286        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6287        let active_view_id = state.active_view_id?;
 6288        Some(
 6289            state
 6290                .items_by_leader_view_id
 6291                .get(&active_view_id)?
 6292                .view
 6293                .boxed_clone(),
 6294        )
 6295    }
 6296
 6297    fn active_item_for_peer(
 6298        &self,
 6299        peer_id: PeerId,
 6300        window: &mut Window,
 6301        cx: &mut Context<Self>,
 6302    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6303        let call = self.active_call()?;
 6304        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6305        let leader_in_this_app;
 6306        let leader_in_this_project;
 6307        match participant.location {
 6308            ParticipantLocation::SharedProject { project_id } => {
 6309                leader_in_this_app = true;
 6310                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6311            }
 6312            ParticipantLocation::UnsharedProject => {
 6313                leader_in_this_app = true;
 6314                leader_in_this_project = false;
 6315            }
 6316            ParticipantLocation::External => {
 6317                leader_in_this_app = false;
 6318                leader_in_this_project = false;
 6319            }
 6320        };
 6321        let state = self.follower_states.get(&peer_id.into())?;
 6322        let mut item_to_activate = None;
 6323        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6324            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6325                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6326            {
 6327                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6328            }
 6329        } else if let Some(shared_screen) =
 6330            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6331        {
 6332            item_to_activate = Some((None, Box::new(shared_screen)));
 6333        }
 6334        item_to_activate
 6335    }
 6336
 6337    fn shared_screen_for_peer(
 6338        &self,
 6339        peer_id: PeerId,
 6340        pane: &Entity<Pane>,
 6341        window: &mut Window,
 6342        cx: &mut App,
 6343    ) -> Option<Entity<SharedScreen>> {
 6344        self.active_call()?
 6345            .create_shared_screen(peer_id, pane, window, cx)
 6346    }
 6347
 6348    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6349        if window.is_window_active() {
 6350            self.update_active_view_for_followers(window, cx);
 6351
 6352            if let Some(database_id) = self.database_id {
 6353                let db = WorkspaceDb::global(cx);
 6354                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6355                    .detach();
 6356            }
 6357        } else {
 6358            for pane in &self.panes {
 6359                pane.update(cx, |pane, cx| {
 6360                    if let Some(item) = pane.active_item() {
 6361                        item.workspace_deactivated(window, cx);
 6362                    }
 6363                    for item in pane.items() {
 6364                        if matches!(
 6365                            item.workspace_settings(cx).autosave,
 6366                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6367                        ) {
 6368                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6369                                .detach_and_log_err(cx);
 6370                        }
 6371                    }
 6372                });
 6373            }
 6374        }
 6375    }
 6376
 6377    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6378        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6379    }
 6380
 6381    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6382        self.active_call.as_ref().map(|(call, _)| call.clone())
 6383    }
 6384
 6385    fn on_active_call_event(
 6386        &mut self,
 6387        event: &ActiveCallEvent,
 6388        window: &mut Window,
 6389        cx: &mut Context<Self>,
 6390    ) {
 6391        match event {
 6392            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6393            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6394                self.leader_updated(participant_id, window, cx);
 6395            }
 6396        }
 6397    }
 6398
 6399    pub fn database_id(&self) -> Option<WorkspaceId> {
 6400        self.database_id
 6401    }
 6402
 6403    #[cfg(any(test, feature = "test-support"))]
 6404    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6405        self.database_id = Some(id);
 6406    }
 6407
 6408    pub fn session_id(&self) -> Option<String> {
 6409        self.session_id.clone()
 6410    }
 6411
 6412    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6413        let Some(display) = window.display(cx) else {
 6414            return Task::ready(());
 6415        };
 6416        let Ok(display_uuid) = display.uuid() else {
 6417            return Task::ready(());
 6418        };
 6419
 6420        let window_bounds = window.inner_window_bounds();
 6421        let database_id = self.database_id;
 6422        let has_paths = !self.root_paths(cx).is_empty();
 6423        let db = WorkspaceDb::global(cx);
 6424        let kvp = db::kvp::KeyValueStore::global(cx);
 6425
 6426        cx.background_executor().spawn(async move {
 6427            if !has_paths {
 6428                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6429                    .await
 6430                    .log_err();
 6431            }
 6432            if let Some(database_id) = database_id {
 6433                db.set_window_open_status(
 6434                    database_id,
 6435                    SerializedWindowBounds(window_bounds),
 6436                    display_uuid,
 6437                )
 6438                .await
 6439                .log_err();
 6440            } else {
 6441                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6442                    .await
 6443                    .log_err();
 6444            }
 6445        })
 6446    }
 6447
 6448    /// Bypass the 200ms serialization throttle and write workspace state to
 6449    /// the DB immediately. Returns a task the caller can await to ensure the
 6450    /// write completes. Used by the quit handler so the most recent state
 6451    /// isn't lost to a pending throttle timer when the process exits.
 6452    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6453        self._schedule_serialize_workspace.take();
 6454        self._serialize_workspace_task.take();
 6455        self.bounds_save_task_queued.take();
 6456
 6457        let bounds_task = self.save_window_bounds(window, cx);
 6458        let serialize_task = self.serialize_workspace_internal(window, cx);
 6459        cx.spawn(async move |_| {
 6460            bounds_task.await;
 6461            serialize_task.await;
 6462        })
 6463    }
 6464
 6465    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6466        let project = self.project().read(cx);
 6467        project
 6468            .visible_worktrees(cx)
 6469            .map(|worktree| worktree.read(cx).abs_path())
 6470            .collect::<Vec<_>>()
 6471    }
 6472
 6473    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6474        match member {
 6475            Member::Axis(PaneAxis { members, .. }) => {
 6476                for child in members.iter() {
 6477                    self.remove_panes(child.clone(), window, cx)
 6478                }
 6479            }
 6480            Member::Pane(pane) => {
 6481                self.force_remove_pane(&pane, &None, window, cx);
 6482            }
 6483        }
 6484    }
 6485
 6486    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6487        self.session_id.take();
 6488        self.serialize_workspace_internal(window, cx)
 6489    }
 6490
 6491    fn force_remove_pane(
 6492        &mut self,
 6493        pane: &Entity<Pane>,
 6494        focus_on: &Option<Entity<Pane>>,
 6495        window: &mut Window,
 6496        cx: &mut Context<Workspace>,
 6497    ) {
 6498        self.panes.retain(|p| p != pane);
 6499        if let Some(focus_on) = focus_on {
 6500            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6501        } else if self.active_pane() == pane {
 6502            self.panes
 6503                .last()
 6504                .unwrap()
 6505                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6506        }
 6507        if self.last_active_center_pane == Some(pane.downgrade()) {
 6508            self.last_active_center_pane = None;
 6509        }
 6510        cx.notify();
 6511    }
 6512
 6513    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6514        if self._schedule_serialize_workspace.is_none() {
 6515            self._schedule_serialize_workspace =
 6516                Some(cx.spawn_in(window, async move |this, cx| {
 6517                    cx.background_executor()
 6518                        .timer(SERIALIZATION_THROTTLE_TIME)
 6519                        .await;
 6520                    this.update_in(cx, |this, window, cx| {
 6521                        this._serialize_workspace_task =
 6522                            Some(this.serialize_workspace_internal(window, cx));
 6523                        this._schedule_serialize_workspace.take();
 6524                    })
 6525                    .log_err();
 6526                }));
 6527        }
 6528    }
 6529
 6530    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6531        let Some(database_id) = self.database_id() else {
 6532            return Task::ready(());
 6533        };
 6534
 6535        fn serialize_pane_handle(
 6536            pane_handle: &Entity<Pane>,
 6537            window: &mut Window,
 6538            cx: &mut App,
 6539        ) -> SerializedPane {
 6540            let (items, active, pinned_count) = {
 6541                let pane = pane_handle.read(cx);
 6542                let active_item_id = pane.active_item().map(|item| item.item_id());
 6543                (
 6544                    pane.items()
 6545                        .filter_map(|handle| {
 6546                            let handle = handle.to_serializable_item_handle(cx)?;
 6547
 6548                            Some(SerializedItem {
 6549                                kind: Arc::from(handle.serialized_item_kind()),
 6550                                item_id: handle.item_id().as_u64(),
 6551                                active: Some(handle.item_id()) == active_item_id,
 6552                                preview: pane.is_active_preview_item(handle.item_id()),
 6553                            })
 6554                        })
 6555                        .collect::<Vec<_>>(),
 6556                    pane.has_focus(window, cx),
 6557                    pane.pinned_count(),
 6558                )
 6559            };
 6560
 6561            SerializedPane::new(items, active, pinned_count)
 6562        }
 6563
 6564        fn build_serialized_pane_group(
 6565            pane_group: &Member,
 6566            window: &mut Window,
 6567            cx: &mut App,
 6568        ) -> SerializedPaneGroup {
 6569            match pane_group {
 6570                Member::Axis(PaneAxis {
 6571                    axis,
 6572                    members,
 6573                    flexes,
 6574                    bounding_boxes: _,
 6575                }) => SerializedPaneGroup::Group {
 6576                    axis: SerializedAxis(*axis),
 6577                    children: members
 6578                        .iter()
 6579                        .map(|member| build_serialized_pane_group(member, window, cx))
 6580                        .collect::<Vec<_>>(),
 6581                    flexes: Some(flexes.lock().clone()),
 6582                },
 6583                Member::Pane(pane_handle) => {
 6584                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6585                }
 6586            }
 6587        }
 6588
 6589        fn build_serialized_docks(
 6590            this: &Workspace,
 6591            window: &mut Window,
 6592            cx: &mut App,
 6593        ) -> DockStructure {
 6594            this.capture_dock_state(window, cx)
 6595        }
 6596
 6597        match self.workspace_location(cx) {
 6598            WorkspaceLocation::Location(location, paths) => {
 6599                let breakpoints = self.project.update(cx, |project, cx| {
 6600                    project
 6601                        .breakpoint_store()
 6602                        .read(cx)
 6603                        .all_source_breakpoints(cx)
 6604                });
 6605                let user_toolchains = self
 6606                    .project
 6607                    .read(cx)
 6608                    .user_toolchains(cx)
 6609                    .unwrap_or_default();
 6610
 6611                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6612                let docks = build_serialized_docks(self, window, cx);
 6613                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6614
 6615                let serialized_workspace = SerializedWorkspace {
 6616                    id: database_id,
 6617                    location,
 6618                    paths,
 6619                    center_group,
 6620                    window_bounds,
 6621                    display: Default::default(),
 6622                    docks,
 6623                    centered_layout: self.centered_layout,
 6624                    session_id: self.session_id.clone(),
 6625                    breakpoints,
 6626                    window_id: Some(window.window_handle().window_id().as_u64()),
 6627                    user_toolchains,
 6628                };
 6629
 6630                let db = WorkspaceDb::global(cx);
 6631                window.spawn(cx, async move |_| {
 6632                    db.save_workspace(serialized_workspace).await;
 6633                })
 6634            }
 6635            WorkspaceLocation::DetachFromSession => {
 6636                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6637                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6638                // Save dock state for empty local workspaces
 6639                let docks = build_serialized_docks(self, window, cx);
 6640                let db = WorkspaceDb::global(cx);
 6641                let kvp = db::kvp::KeyValueStore::global(cx);
 6642                window.spawn(cx, async move |_| {
 6643                    db.set_window_open_status(
 6644                        database_id,
 6645                        window_bounds,
 6646                        display.unwrap_or_default(),
 6647                    )
 6648                    .await
 6649                    .log_err();
 6650                    db.set_session_id(database_id, None).await.log_err();
 6651                    persistence::write_default_dock_state(&kvp, docks)
 6652                        .await
 6653                        .log_err();
 6654                })
 6655            }
 6656            WorkspaceLocation::None => {
 6657                // Save dock state for empty non-local workspaces
 6658                let docks = build_serialized_docks(self, window, cx);
 6659                let kvp = db::kvp::KeyValueStore::global(cx);
 6660                window.spawn(cx, async move |_| {
 6661                    persistence::write_default_dock_state(&kvp, docks)
 6662                        .await
 6663                        .log_err();
 6664                })
 6665            }
 6666        }
 6667    }
 6668
 6669    fn has_any_items_open(&self, cx: &App) -> bool {
 6670        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6671    }
 6672
 6673    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6674        let paths = PathList::new(&self.root_paths(cx));
 6675        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6676            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6677        } else if self.project.read(cx).is_local() {
 6678            if !paths.is_empty() || self.has_any_items_open(cx) {
 6679                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6680            } else {
 6681                WorkspaceLocation::DetachFromSession
 6682            }
 6683        } else {
 6684            WorkspaceLocation::None
 6685        }
 6686    }
 6687
 6688    fn update_history(&self, cx: &mut App) {
 6689        let Some(id) = self.database_id() else {
 6690            return;
 6691        };
 6692        if !self.project.read(cx).is_local() {
 6693            return;
 6694        }
 6695        if let Some(manager) = HistoryManager::global(cx) {
 6696            let paths = PathList::new(&self.root_paths(cx));
 6697            manager.update(cx, |this, cx| {
 6698                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6699            });
 6700        }
 6701    }
 6702
 6703    async fn serialize_items(
 6704        this: &WeakEntity<Self>,
 6705        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6706        cx: &mut AsyncWindowContext,
 6707    ) -> Result<()> {
 6708        const CHUNK_SIZE: usize = 200;
 6709
 6710        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6711
 6712        while let Some(items_received) = serializable_items.next().await {
 6713            let unique_items =
 6714                items_received
 6715                    .into_iter()
 6716                    .fold(HashMap::default(), |mut acc, item| {
 6717                        acc.entry(item.item_id()).or_insert(item);
 6718                        acc
 6719                    });
 6720
 6721            // We use into_iter() here so that the references to the items are moved into
 6722            // the tasks and not kept alive while we're sleeping.
 6723            for (_, item) in unique_items.into_iter() {
 6724                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6725                    item.serialize(workspace, false, window, cx)
 6726                }) {
 6727                    cx.background_spawn(async move { task.await.log_err() })
 6728                        .detach();
 6729                }
 6730            }
 6731
 6732            cx.background_executor()
 6733                .timer(SERIALIZATION_THROTTLE_TIME)
 6734                .await;
 6735        }
 6736
 6737        Ok(())
 6738    }
 6739
 6740    pub(crate) fn enqueue_item_serialization(
 6741        &mut self,
 6742        item: Box<dyn SerializableItemHandle>,
 6743    ) -> Result<()> {
 6744        self.serializable_items_tx
 6745            .unbounded_send(item)
 6746            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6747    }
 6748
 6749    pub(crate) fn load_workspace(
 6750        serialized_workspace: SerializedWorkspace,
 6751        paths_to_open: Vec<Option<ProjectPath>>,
 6752        window: &mut Window,
 6753        cx: &mut Context<Workspace>,
 6754    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6755        cx.spawn_in(window, async move |workspace, cx| {
 6756            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6757
 6758            let mut center_group = None;
 6759            let mut center_items = None;
 6760
 6761            // Traverse the splits tree and add to things
 6762            if let Some((group, active_pane, items)) = serialized_workspace
 6763                .center_group
 6764                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6765                .await
 6766            {
 6767                center_items = Some(items);
 6768                center_group = Some((group, active_pane))
 6769            }
 6770
 6771            let mut items_by_project_path = HashMap::default();
 6772            let mut item_ids_by_kind = HashMap::default();
 6773            let mut all_deserialized_items = Vec::default();
 6774            cx.update(|_, cx| {
 6775                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6776                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6777                        item_ids_by_kind
 6778                            .entry(serializable_item_handle.serialized_item_kind())
 6779                            .or_insert(Vec::new())
 6780                            .push(item.item_id().as_u64() as ItemId);
 6781                    }
 6782
 6783                    if let Some(project_path) = item.project_path(cx) {
 6784                        items_by_project_path.insert(project_path, item.clone());
 6785                    }
 6786                    all_deserialized_items.push(item);
 6787                }
 6788            })?;
 6789
 6790            let opened_items = paths_to_open
 6791                .into_iter()
 6792                .map(|path_to_open| {
 6793                    path_to_open
 6794                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6795                })
 6796                .collect::<Vec<_>>();
 6797
 6798            // Remove old panes from workspace panes list
 6799            workspace.update_in(cx, |workspace, window, cx| {
 6800                if let Some((center_group, active_pane)) = center_group {
 6801                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6802
 6803                    // Swap workspace center group
 6804                    workspace.center = PaneGroup::with_root(center_group);
 6805                    workspace.center.set_is_center(true);
 6806                    workspace.center.mark_positions(cx);
 6807
 6808                    if let Some(active_pane) = active_pane {
 6809                        workspace.set_active_pane(&active_pane, window, cx);
 6810                        cx.focus_self(window);
 6811                    } else {
 6812                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6813                    }
 6814                }
 6815
 6816                let docks = serialized_workspace.docks;
 6817
 6818                for (dock, serialized_dock) in [
 6819                    (&mut workspace.right_dock, docks.right),
 6820                    (&mut workspace.left_dock, docks.left),
 6821                    (&mut workspace.bottom_dock, docks.bottom),
 6822                ]
 6823                .iter_mut()
 6824                {
 6825                    dock.update(cx, |dock, cx| {
 6826                        dock.serialized_dock = Some(serialized_dock.clone());
 6827                        dock.restore_state(window, cx);
 6828                    });
 6829                }
 6830
 6831                cx.notify();
 6832            })?;
 6833
 6834            let _ = project
 6835                .update(cx, |project, cx| {
 6836                    project
 6837                        .breakpoint_store()
 6838                        .update(cx, |breakpoint_store, cx| {
 6839                            breakpoint_store
 6840                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6841                        })
 6842                })
 6843                .await;
 6844
 6845            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6846            // after loading the items, we might have different items and in order to avoid
 6847            // the database filling up, we delete items that haven't been loaded now.
 6848            //
 6849            // The items that have been loaded, have been saved after they've been added to the workspace.
 6850            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6851                item_ids_by_kind
 6852                    .into_iter()
 6853                    .map(|(item_kind, loaded_items)| {
 6854                        SerializableItemRegistry::cleanup(
 6855                            item_kind,
 6856                            serialized_workspace.id,
 6857                            loaded_items,
 6858                            window,
 6859                            cx,
 6860                        )
 6861                        .log_err()
 6862                    })
 6863                    .collect::<Vec<_>>()
 6864            })?;
 6865
 6866            futures::future::join_all(clean_up_tasks).await;
 6867
 6868            workspace
 6869                .update_in(cx, |workspace, window, cx| {
 6870                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6871                    workspace.serialize_workspace_internal(window, cx).detach();
 6872
 6873                    // Ensure that we mark the window as edited if we did load dirty items
 6874                    workspace.update_window_edited(window, cx);
 6875                })
 6876                .ok();
 6877
 6878            Ok(opened_items)
 6879        })
 6880    }
 6881
 6882    pub fn key_context(&self, cx: &App) -> KeyContext {
 6883        let mut context = KeyContext::new_with_defaults();
 6884        context.add("Workspace");
 6885        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6886        if let Some(status) = self
 6887            .debugger_provider
 6888            .as_ref()
 6889            .and_then(|provider| provider.active_thread_state(cx))
 6890        {
 6891            match status {
 6892                ThreadStatus::Running | ThreadStatus::Stepping => {
 6893                    context.add("debugger_running");
 6894                }
 6895                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6896                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6897            }
 6898        }
 6899
 6900        if self.left_dock.read(cx).is_open() {
 6901            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6902                context.set("left_dock", active_panel.panel_key());
 6903            }
 6904        }
 6905
 6906        if self.right_dock.read(cx).is_open() {
 6907            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6908                context.set("right_dock", active_panel.panel_key());
 6909            }
 6910        }
 6911
 6912        if self.bottom_dock.read(cx).is_open() {
 6913            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6914                context.set("bottom_dock", active_panel.panel_key());
 6915            }
 6916        }
 6917
 6918        context
 6919    }
 6920
 6921    /// Multiworkspace uses this to add workspace action handling to itself
 6922    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6923        self.add_workspace_actions_listeners(div, window, cx)
 6924            .on_action(cx.listener(
 6925                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6926                    for action in &action_sequence.0 {
 6927                        window.dispatch_action(action.boxed_clone(), cx);
 6928                    }
 6929                },
 6930            ))
 6931            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6932            .on_action(cx.listener(Self::close_all_items_and_panes))
 6933            .on_action(cx.listener(Self::close_item_in_all_panes))
 6934            .on_action(cx.listener(Self::save_all))
 6935            .on_action(cx.listener(Self::send_keystrokes))
 6936            .on_action(cx.listener(Self::add_folder_to_project))
 6937            .on_action(cx.listener(Self::follow_next_collaborator))
 6938            .on_action(cx.listener(Self::activate_pane_at_index))
 6939            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6940            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6941            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6942            .on_action(cx.listener(Self::toggle_theme_mode))
 6943            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6944                let pane = workspace.active_pane().clone();
 6945                workspace.unfollow_in_pane(&pane, window, cx);
 6946            }))
 6947            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6948                workspace
 6949                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6950                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6951            }))
 6952            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6953                workspace
 6954                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6955                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6956            }))
 6957            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6958                workspace
 6959                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6960                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6961            }))
 6962            .on_action(
 6963                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6964                    workspace.activate_previous_pane(window, cx)
 6965                }),
 6966            )
 6967            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6968                workspace.activate_next_pane(window, cx)
 6969            }))
 6970            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6971                workspace.activate_last_pane(window, cx)
 6972            }))
 6973            .on_action(
 6974                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6975                    workspace.activate_next_window(cx)
 6976                }),
 6977            )
 6978            .on_action(
 6979                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6980                    workspace.activate_previous_window(cx)
 6981                }),
 6982            )
 6983            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6984                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6985            }))
 6986            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6987                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6988            }))
 6989            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6990                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6991            }))
 6992            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6993                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6994            }))
 6995            .on_action(cx.listener(
 6996                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6997                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6998                },
 6999            ))
 7000            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 7001                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 7002            }))
 7003            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 7004                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 7005            }))
 7006            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 7007                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 7008            }))
 7009            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 7010                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7011            }))
 7012            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7013                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7014                    SplitDirection::Down,
 7015                    SplitDirection::Up,
 7016                    SplitDirection::Right,
 7017                    SplitDirection::Left,
 7018                ];
 7019                for dir in DIRECTION_PRIORITY {
 7020                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7021                        workspace.swap_pane_in_direction(dir, cx);
 7022                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7023                        break;
 7024                    }
 7025                }
 7026            }))
 7027            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7028                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7029            }))
 7030            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7031                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7032            }))
 7033            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7034                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7035            }))
 7036            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7037                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7038            }))
 7039            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7040                this.toggle_dock(DockPosition::Left, window, cx);
 7041            }))
 7042            .on_action(cx.listener(
 7043                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7044                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7045                },
 7046            ))
 7047            .on_action(cx.listener(
 7048                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7049                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7050                },
 7051            ))
 7052            .on_action(cx.listener(
 7053                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7054                    if !workspace.close_active_dock(window, cx) {
 7055                        cx.propagate();
 7056                    }
 7057                },
 7058            ))
 7059            .on_action(
 7060                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7061                    workspace.close_all_docks(window, cx);
 7062                }),
 7063            )
 7064            .on_action(cx.listener(Self::toggle_all_docks))
 7065            .on_action(cx.listener(
 7066                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7067                    workspace.clear_all_notifications(cx);
 7068                },
 7069            ))
 7070            .on_action(cx.listener(
 7071                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7072                    workspace.clear_navigation_history(window, cx);
 7073                },
 7074            ))
 7075            .on_action(cx.listener(
 7076                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7077                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7078                        workspace.suppress_notification(&notification_id, cx);
 7079                    }
 7080                },
 7081            ))
 7082            .on_action(cx.listener(
 7083                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7084                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7085                },
 7086            ))
 7087            .on_action(
 7088                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7089                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7090                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7091                            trusted_worktrees.clear_trusted_paths()
 7092                        });
 7093                        let db = WorkspaceDb::global(cx);
 7094                        cx.spawn(async move |_, cx| {
 7095                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7096                                cx.update(|cx| reload(cx));
 7097                            }
 7098                        })
 7099                        .detach();
 7100                    }
 7101                }),
 7102            )
 7103            .on_action(cx.listener(
 7104                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7105                    workspace.reopen_closed_item(window, cx).detach();
 7106                },
 7107            ))
 7108            .on_action(cx.listener(
 7109                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7110                    for dock in workspace.all_docks() {
 7111                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7112                            let panel = dock.read(cx).active_panel().cloned();
 7113                            if let Some(panel) = panel {
 7114                                dock.update(cx, |dock, cx| {
 7115                                    dock.set_panel_size_state(
 7116                                        panel.as_ref(),
 7117                                        dock::PanelSizeState::default(),
 7118                                        cx,
 7119                                    );
 7120                                });
 7121                            }
 7122                            return;
 7123                        }
 7124                    }
 7125                },
 7126            ))
 7127            .on_action(cx.listener(
 7128                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7129                    for dock in workspace.all_docks() {
 7130                        let panel = dock.read(cx).visible_panel().cloned();
 7131                        if let Some(panel) = panel {
 7132                            dock.update(cx, |dock, cx| {
 7133                                dock.set_panel_size_state(
 7134                                    panel.as_ref(),
 7135                                    dock::PanelSizeState::default(),
 7136                                    cx,
 7137                                );
 7138                            });
 7139                        }
 7140                    }
 7141                },
 7142            ))
 7143            .on_action(cx.listener(
 7144                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7145                    adjust_active_dock_size_by_px(
 7146                        px_with_ui_font_fallback(act.px, cx),
 7147                        workspace,
 7148                        window,
 7149                        cx,
 7150                    );
 7151                },
 7152            ))
 7153            .on_action(cx.listener(
 7154                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7155                    adjust_active_dock_size_by_px(
 7156                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7157                        workspace,
 7158                        window,
 7159                        cx,
 7160                    );
 7161                },
 7162            ))
 7163            .on_action(cx.listener(
 7164                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7165                    adjust_open_docks_size_by_px(
 7166                        px_with_ui_font_fallback(act.px, cx),
 7167                        workspace,
 7168                        window,
 7169                        cx,
 7170                    );
 7171                },
 7172            ))
 7173            .on_action(cx.listener(
 7174                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7175                    adjust_open_docks_size_by_px(
 7176                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7177                        workspace,
 7178                        window,
 7179                        cx,
 7180                    );
 7181                },
 7182            ))
 7183            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7184            .on_action(cx.listener(
 7185                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7186                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7187                        let dock = active_dock.read(cx);
 7188                        if let Some(active_panel) = dock.active_panel() {
 7189                            if active_panel.pane(cx).is_none() {
 7190                                let mut recent_pane: Option<Entity<Pane>> = None;
 7191                                let mut recent_timestamp = 0;
 7192                                for pane_handle in workspace.panes() {
 7193                                    let pane = pane_handle.read(cx);
 7194                                    for entry in pane.activation_history() {
 7195                                        if entry.timestamp > recent_timestamp {
 7196                                            recent_timestamp = entry.timestamp;
 7197                                            recent_pane = Some(pane_handle.clone());
 7198                                        }
 7199                                    }
 7200                                }
 7201
 7202                                if let Some(pane) = recent_pane {
 7203                                    let wrap_around = action.wrap_around;
 7204                                    pane.update(cx, |pane, cx| {
 7205                                        let current_index = pane.active_item_index();
 7206                                        let items_len = pane.items_len();
 7207                                        if items_len > 0 {
 7208                                            let next_index = if current_index + 1 < items_len {
 7209                                                current_index + 1
 7210                                            } else if wrap_around {
 7211                                                0
 7212                                            } else {
 7213                                                return;
 7214                                            };
 7215                                            pane.activate_item(
 7216                                                next_index, false, false, window, cx,
 7217                                            );
 7218                                        }
 7219                                    });
 7220                                    return;
 7221                                }
 7222                            }
 7223                        }
 7224                    }
 7225                    cx.propagate();
 7226                },
 7227            ))
 7228            .on_action(cx.listener(
 7229                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7230                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7231                        let dock = active_dock.read(cx);
 7232                        if let Some(active_panel) = dock.active_panel() {
 7233                            if active_panel.pane(cx).is_none() {
 7234                                let mut recent_pane: Option<Entity<Pane>> = None;
 7235                                let mut recent_timestamp = 0;
 7236                                for pane_handle in workspace.panes() {
 7237                                    let pane = pane_handle.read(cx);
 7238                                    for entry in pane.activation_history() {
 7239                                        if entry.timestamp > recent_timestamp {
 7240                                            recent_timestamp = entry.timestamp;
 7241                                            recent_pane = Some(pane_handle.clone());
 7242                                        }
 7243                                    }
 7244                                }
 7245
 7246                                if let Some(pane) = recent_pane {
 7247                                    let wrap_around = action.wrap_around;
 7248                                    pane.update(cx, |pane, cx| {
 7249                                        let current_index = pane.active_item_index();
 7250                                        let items_len = pane.items_len();
 7251                                        if items_len > 0 {
 7252                                            let prev_index = if current_index > 0 {
 7253                                                current_index - 1
 7254                                            } else if wrap_around {
 7255                                                items_len.saturating_sub(1)
 7256                                            } else {
 7257                                                return;
 7258                                            };
 7259                                            pane.activate_item(
 7260                                                prev_index, false, false, window, cx,
 7261                                            );
 7262                                        }
 7263                                    });
 7264                                    return;
 7265                                }
 7266                            }
 7267                        }
 7268                    }
 7269                    cx.propagate();
 7270                },
 7271            ))
 7272            .on_action(cx.listener(
 7273                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7274                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7275                        let dock = active_dock.read(cx);
 7276                        if let Some(active_panel) = dock.active_panel() {
 7277                            if active_panel.pane(cx).is_none() {
 7278                                let active_pane = workspace.active_pane().clone();
 7279                                active_pane.update(cx, |pane, cx| {
 7280                                    pane.close_active_item(action, window, cx)
 7281                                        .detach_and_log_err(cx);
 7282                                });
 7283                                return;
 7284                            }
 7285                        }
 7286                    }
 7287                    cx.propagate();
 7288                },
 7289            ))
 7290            .on_action(
 7291                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7292                    let pane = workspace.active_pane().clone();
 7293                    if let Some(item) = pane.read(cx).active_item() {
 7294                        item.toggle_read_only(window, cx);
 7295                    }
 7296                }),
 7297            )
 7298            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7299                workspace.focus_center_pane(window, cx);
 7300            }))
 7301            .on_action(cx.listener(Workspace::cancel))
 7302    }
 7303
 7304    #[cfg(any(test, feature = "test-support"))]
 7305    pub fn set_random_database_id(&mut self) {
 7306        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7307    }
 7308
 7309    #[cfg(any(test, feature = "test-support"))]
 7310    pub(crate) fn test_new(
 7311        project: Entity<Project>,
 7312        window: &mut Window,
 7313        cx: &mut Context<Self>,
 7314    ) -> Self {
 7315        use node_runtime::NodeRuntime;
 7316        use session::Session;
 7317
 7318        let client = project.read(cx).client();
 7319        let user_store = project.read(cx).user_store();
 7320        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7321        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7322        window.activate_window();
 7323        let app_state = Arc::new(AppState {
 7324            languages: project.read(cx).languages().clone(),
 7325            workspace_store,
 7326            client,
 7327            user_store,
 7328            fs: project.read(cx).fs().clone(),
 7329            build_window_options: |_, _| Default::default(),
 7330            node_runtime: NodeRuntime::unavailable(),
 7331            session,
 7332        });
 7333        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7334        workspace
 7335            .active_pane
 7336            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7337        workspace
 7338    }
 7339
 7340    pub fn register_action<A: Action>(
 7341        &mut self,
 7342        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7343    ) -> &mut Self {
 7344        let callback = Arc::new(callback);
 7345
 7346        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7347            let callback = callback.clone();
 7348            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7349                (callback)(workspace, event, window, cx)
 7350            }))
 7351        }));
 7352        self
 7353    }
 7354    pub fn register_action_renderer(
 7355        &mut self,
 7356        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7357    ) -> &mut Self {
 7358        self.workspace_actions.push(Box::new(callback));
 7359        self
 7360    }
 7361
 7362    fn add_workspace_actions_listeners(
 7363        &self,
 7364        mut div: Div,
 7365        window: &mut Window,
 7366        cx: &mut Context<Self>,
 7367    ) -> Div {
 7368        for action in self.workspace_actions.iter() {
 7369            div = (action)(div, self, window, cx)
 7370        }
 7371        div
 7372    }
 7373
 7374    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7375        self.modal_layer.read(cx).has_active_modal()
 7376    }
 7377
 7378    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7379        self.modal_layer
 7380            .read(cx)
 7381            .is_active_modal_command_palette(cx)
 7382    }
 7383
 7384    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7385        self.modal_layer.read(cx).active_modal()
 7386    }
 7387
 7388    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7389    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7390    /// If no modal is active, the new modal will be shown.
 7391    ///
 7392    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7393    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7394    /// will not be shown.
 7395    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7396    where
 7397        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7398    {
 7399        self.modal_layer.update(cx, |modal_layer, cx| {
 7400            modal_layer.toggle_modal(window, cx, build)
 7401        })
 7402    }
 7403
 7404    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7405        self.modal_layer
 7406            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7407    }
 7408
 7409    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7410        self.toast_layer
 7411            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7412    }
 7413
 7414    pub fn toggle_centered_layout(
 7415        &mut self,
 7416        _: &ToggleCenteredLayout,
 7417        _: &mut Window,
 7418        cx: &mut Context<Self>,
 7419    ) {
 7420        self.centered_layout = !self.centered_layout;
 7421        if let Some(database_id) = self.database_id() {
 7422            let db = WorkspaceDb::global(cx);
 7423            let centered_layout = self.centered_layout;
 7424            cx.background_spawn(async move {
 7425                db.set_centered_layout(database_id, centered_layout).await
 7426            })
 7427            .detach_and_log_err(cx);
 7428        }
 7429        cx.notify();
 7430    }
 7431
 7432    fn adjust_padding(padding: Option<f32>) -> f32 {
 7433        padding
 7434            .unwrap_or(CenteredPaddingSettings::default().0)
 7435            .clamp(
 7436                CenteredPaddingSettings::MIN_PADDING,
 7437                CenteredPaddingSettings::MAX_PADDING,
 7438            )
 7439    }
 7440
 7441    fn render_dock(
 7442        &self,
 7443        position: DockPosition,
 7444        dock: &Entity<Dock>,
 7445        window: &mut Window,
 7446        cx: &mut App,
 7447    ) -> Option<Div> {
 7448        if self.zoomed_position == Some(position) {
 7449            return None;
 7450        }
 7451
 7452        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7453            let pane = panel.pane(cx)?;
 7454            let follower_states = &self.follower_states;
 7455            leader_border_for_pane(follower_states, &pane, window, cx)
 7456        });
 7457
 7458        let mut container = div()
 7459            .flex()
 7460            .overflow_hidden()
 7461            .flex_none()
 7462            .child(dock.clone())
 7463            .children(leader_border);
 7464
 7465        // Apply sizing only when the dock is open. When closed the dock is still
 7466        // included in the element tree so its focus handle remains mounted — without
 7467        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7468        let dock = dock.read(cx);
 7469        if let Some(panel) = dock.visible_panel() {
 7470            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7471            if position.axis() == Axis::Horizontal {
 7472                let use_flexible = panel.has_flexible_size(window, cx);
 7473                let flex_grow = if use_flexible {
 7474                    size_state
 7475                        .and_then(|state| state.flex)
 7476                        .or_else(|| self.default_dock_flex(position))
 7477                } else {
 7478                    None
 7479                };
 7480                if let Some(grow) = flex_grow {
 7481                    let grow = grow.max(0.001);
 7482                    let style = container.style();
 7483                    style.flex_grow = Some(grow);
 7484                    style.flex_shrink = Some(1.0);
 7485                    style.flex_basis = Some(relative(0.).into());
 7486                } else {
 7487                    let size = size_state
 7488                        .and_then(|state| state.size)
 7489                        .unwrap_or_else(|| panel.default_size(window, cx));
 7490                    container = container.w(size);
 7491                }
 7492            } else {
 7493                let size = size_state
 7494                    .and_then(|state| state.size)
 7495                    .unwrap_or_else(|| panel.default_size(window, cx));
 7496                container = container.h(size);
 7497            }
 7498        }
 7499
 7500        Some(container)
 7501    }
 7502
 7503    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7504        window
 7505            .root::<MultiWorkspace>()
 7506            .flatten()
 7507            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7508    }
 7509
 7510    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7511        self.zoomed.as_ref()
 7512    }
 7513
 7514    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7515        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7516            return;
 7517        };
 7518        let windows = cx.windows();
 7519        let next_window =
 7520            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7521                || {
 7522                    windows
 7523                        .iter()
 7524                        .cycle()
 7525                        .skip_while(|window| window.window_id() != current_window_id)
 7526                        .nth(1)
 7527                },
 7528            );
 7529
 7530        if let Some(window) = next_window {
 7531            window
 7532                .update(cx, |_, window, _| window.activate_window())
 7533                .ok();
 7534        }
 7535    }
 7536
 7537    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7538        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7539            return;
 7540        };
 7541        let windows = cx.windows();
 7542        let prev_window =
 7543            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7544                || {
 7545                    windows
 7546                        .iter()
 7547                        .rev()
 7548                        .cycle()
 7549                        .skip_while(|window| window.window_id() != current_window_id)
 7550                        .nth(1)
 7551                },
 7552            );
 7553
 7554        if let Some(window) = prev_window {
 7555            window
 7556                .update(cx, |_, window, _| window.activate_window())
 7557                .ok();
 7558        }
 7559    }
 7560
 7561    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7562        if cx.stop_active_drag(window) {
 7563        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7564            dismiss_app_notification(&notification_id, cx);
 7565        } else {
 7566            cx.propagate();
 7567        }
 7568    }
 7569
 7570    fn resize_dock(
 7571        &mut self,
 7572        dock_pos: DockPosition,
 7573        new_size: Pixels,
 7574        window: &mut Window,
 7575        cx: &mut Context<Self>,
 7576    ) {
 7577        match dock_pos {
 7578            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7579            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7580            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7581        }
 7582    }
 7583
 7584    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7585        let workspace_width = self.bounds.size.width;
 7586        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7587
 7588        self.right_dock.read_with(cx, |right_dock, cx| {
 7589            let right_dock_size = right_dock
 7590                .stored_active_panel_size(window, cx)
 7591                .unwrap_or(Pixels::ZERO);
 7592            if right_dock_size + size > workspace_width {
 7593                size = workspace_width - right_dock_size
 7594            }
 7595        });
 7596
 7597        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7598        self.left_dock.update(cx, |left_dock, cx| {
 7599            if WorkspaceSettings::get_global(cx)
 7600                .resize_all_panels_in_dock
 7601                .contains(&DockPosition::Left)
 7602            {
 7603                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7604            } else {
 7605                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7606            }
 7607        });
 7608    }
 7609
 7610    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7611        let workspace_width = self.bounds.size.width;
 7612        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7613        self.left_dock.read_with(cx, |left_dock, cx| {
 7614            let left_dock_size = left_dock
 7615                .stored_active_panel_size(window, cx)
 7616                .unwrap_or(Pixels::ZERO);
 7617            if left_dock_size + size > workspace_width {
 7618                size = workspace_width - left_dock_size
 7619            }
 7620        });
 7621        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7622        self.right_dock.update(cx, |right_dock, cx| {
 7623            if WorkspaceSettings::get_global(cx)
 7624                .resize_all_panels_in_dock
 7625                .contains(&DockPosition::Right)
 7626            {
 7627                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7628            } else {
 7629                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7630            }
 7631        });
 7632    }
 7633
 7634    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7635        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7636        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7637            if WorkspaceSettings::get_global(cx)
 7638                .resize_all_panels_in_dock
 7639                .contains(&DockPosition::Bottom)
 7640            {
 7641                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7642            } else {
 7643                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7644            }
 7645        });
 7646    }
 7647
 7648    fn toggle_edit_predictions_all_files(
 7649        &mut self,
 7650        _: &ToggleEditPrediction,
 7651        _window: &mut Window,
 7652        cx: &mut Context<Self>,
 7653    ) {
 7654        let fs = self.project().read(cx).fs().clone();
 7655        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7656        update_settings_file(fs, cx, move |file, _| {
 7657            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7658        });
 7659    }
 7660
 7661    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7662        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7663        let next_mode = match current_mode {
 7664            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7665                theme_settings::ThemeAppearanceMode::Dark
 7666            }
 7667            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7668                theme_settings::ThemeAppearanceMode::Light
 7669            }
 7670            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7671                match cx.theme().appearance() {
 7672                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7673                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7674                }
 7675            }
 7676        };
 7677
 7678        let fs = self.project().read(cx).fs().clone();
 7679        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7680            theme_settings::set_mode(settings, next_mode);
 7681        });
 7682    }
 7683
 7684    pub fn show_worktree_trust_security_modal(
 7685        &mut self,
 7686        toggle: bool,
 7687        window: &mut Window,
 7688        cx: &mut Context<Self>,
 7689    ) {
 7690        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7691            if toggle {
 7692                security_modal.update(cx, |security_modal, cx| {
 7693                    security_modal.dismiss(cx);
 7694                })
 7695            } else {
 7696                security_modal.update(cx, |security_modal, cx| {
 7697                    security_modal.refresh_restricted_paths(cx);
 7698                });
 7699            }
 7700        } else {
 7701            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7702                .map(|trusted_worktrees| {
 7703                    trusted_worktrees
 7704                        .read(cx)
 7705                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7706                })
 7707                .unwrap_or(false);
 7708            if has_restricted_worktrees {
 7709                let project = self.project().read(cx);
 7710                let remote_host = project
 7711                    .remote_connection_options(cx)
 7712                    .map(RemoteHostLocation::from);
 7713                let worktree_store = project.worktree_store().downgrade();
 7714                self.toggle_modal(window, cx, |_, cx| {
 7715                    SecurityModal::new(worktree_store, remote_host, cx)
 7716                });
 7717            }
 7718        }
 7719    }
 7720}
 7721
 7722pub trait AnyActiveCall {
 7723    fn entity(&self) -> AnyEntity;
 7724    fn is_in_room(&self, _: &App) -> bool;
 7725    fn room_id(&self, _: &App) -> Option<u64>;
 7726    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7727    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7728    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7729    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7730    fn is_sharing_project(&self, _: &App) -> bool;
 7731    fn has_remote_participants(&self, _: &App) -> bool;
 7732    fn local_participant_is_guest(&self, _: &App) -> bool;
 7733    fn client(&self, _: &App) -> Arc<Client>;
 7734    fn share_on_join(&self, _: &App) -> bool;
 7735    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7736    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7737    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7738    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7739    fn join_project(
 7740        &self,
 7741        _: u64,
 7742        _: Arc<LanguageRegistry>,
 7743        _: Arc<dyn Fs>,
 7744        _: &mut App,
 7745    ) -> Task<Result<Entity<Project>>>;
 7746    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7747    fn subscribe(
 7748        &self,
 7749        _: &mut Window,
 7750        _: &mut Context<Workspace>,
 7751        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7752    ) -> Subscription;
 7753    fn create_shared_screen(
 7754        &self,
 7755        _: PeerId,
 7756        _: &Entity<Pane>,
 7757        _: &mut Window,
 7758        _: &mut App,
 7759    ) -> Option<Entity<SharedScreen>>;
 7760}
 7761
 7762#[derive(Clone)]
 7763pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7764impl Global for GlobalAnyActiveCall {}
 7765
 7766impl GlobalAnyActiveCall {
 7767    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7768        cx.try_global()
 7769    }
 7770
 7771    pub(crate) fn global(cx: &App) -> &Self {
 7772        cx.global()
 7773    }
 7774}
 7775
 7776/// Workspace-local view of a remote participant's location.
 7777#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7778pub enum ParticipantLocation {
 7779    SharedProject { project_id: u64 },
 7780    UnsharedProject,
 7781    External,
 7782}
 7783
 7784impl ParticipantLocation {
 7785    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7786        match location
 7787            .and_then(|l| l.variant)
 7788            .context("participant location was not provided")?
 7789        {
 7790            proto::participant_location::Variant::SharedProject(project) => {
 7791                Ok(Self::SharedProject {
 7792                    project_id: project.id,
 7793                })
 7794            }
 7795            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7796            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7797        }
 7798    }
 7799}
 7800/// Workspace-local view of a remote collaborator's state.
 7801/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7802#[derive(Clone)]
 7803pub struct RemoteCollaborator {
 7804    pub user: Arc<User>,
 7805    pub peer_id: PeerId,
 7806    pub location: ParticipantLocation,
 7807    pub participant_index: ParticipantIndex,
 7808}
 7809
 7810pub enum ActiveCallEvent {
 7811    ParticipantLocationChanged { participant_id: PeerId },
 7812    RemoteVideoTracksChanged { participant_id: PeerId },
 7813}
 7814
 7815fn leader_border_for_pane(
 7816    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7817    pane: &Entity<Pane>,
 7818    _: &Window,
 7819    cx: &App,
 7820) -> Option<Div> {
 7821    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7822        if state.pane() == pane {
 7823            Some((*leader_id, state))
 7824        } else {
 7825            None
 7826        }
 7827    })?;
 7828
 7829    let mut leader_color = match leader_id {
 7830        CollaboratorId::PeerId(leader_peer_id) => {
 7831            let leader = GlobalAnyActiveCall::try_global(cx)?
 7832                .0
 7833                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7834
 7835            cx.theme()
 7836                .players()
 7837                .color_for_participant(leader.participant_index.0)
 7838                .cursor
 7839        }
 7840        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7841    };
 7842    leader_color.fade_out(0.3);
 7843    Some(
 7844        div()
 7845            .absolute()
 7846            .size_full()
 7847            .left_0()
 7848            .top_0()
 7849            .border_2()
 7850            .border_color(leader_color),
 7851    )
 7852}
 7853
 7854fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7855    ZED_WINDOW_POSITION
 7856        .zip(*ZED_WINDOW_SIZE)
 7857        .map(|(position, size)| Bounds {
 7858            origin: position,
 7859            size,
 7860        })
 7861}
 7862
 7863fn open_items(
 7864    serialized_workspace: Option<SerializedWorkspace>,
 7865    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7866    window: &mut Window,
 7867    cx: &mut Context<Workspace>,
 7868) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7869    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7870        Workspace::load_workspace(
 7871            serialized_workspace,
 7872            project_paths_to_open
 7873                .iter()
 7874                .map(|(_, project_path)| project_path)
 7875                .cloned()
 7876                .collect(),
 7877            window,
 7878            cx,
 7879        )
 7880    });
 7881
 7882    cx.spawn_in(window, async move |workspace, cx| {
 7883        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7884
 7885        if let Some(restored_items) = restored_items {
 7886            let restored_items = restored_items.await?;
 7887
 7888            let restored_project_paths = restored_items
 7889                .iter()
 7890                .filter_map(|item| {
 7891                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7892                        .ok()
 7893                        .flatten()
 7894                })
 7895                .collect::<HashSet<_>>();
 7896
 7897            for restored_item in restored_items {
 7898                opened_items.push(restored_item.map(Ok));
 7899            }
 7900
 7901            project_paths_to_open
 7902                .iter_mut()
 7903                .for_each(|(_, project_path)| {
 7904                    if let Some(project_path_to_open) = project_path
 7905                        && restored_project_paths.contains(project_path_to_open)
 7906                    {
 7907                        *project_path = None;
 7908                    }
 7909                });
 7910        } else {
 7911            for _ in 0..project_paths_to_open.len() {
 7912                opened_items.push(None);
 7913            }
 7914        }
 7915        assert!(opened_items.len() == project_paths_to_open.len());
 7916
 7917        let tasks =
 7918            project_paths_to_open
 7919                .into_iter()
 7920                .enumerate()
 7921                .map(|(ix, (abs_path, project_path))| {
 7922                    let workspace = workspace.clone();
 7923                    cx.spawn(async move |cx| {
 7924                        let file_project_path = project_path?;
 7925                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7926                            workspace.project().update(cx, |project, cx| {
 7927                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7928                            })
 7929                        });
 7930
 7931                        // We only want to open file paths here. If one of the items
 7932                        // here is a directory, it was already opened further above
 7933                        // with a `find_or_create_worktree`.
 7934                        if let Ok(task) = abs_path_task
 7935                            && task.await.is_none_or(|p| p.is_file())
 7936                        {
 7937                            return Some((
 7938                                ix,
 7939                                workspace
 7940                                    .update_in(cx, |workspace, window, cx| {
 7941                                        workspace.open_path(
 7942                                            file_project_path,
 7943                                            None,
 7944                                            true,
 7945                                            window,
 7946                                            cx,
 7947                                        )
 7948                                    })
 7949                                    .log_err()?
 7950                                    .await,
 7951                            ));
 7952                        }
 7953                        None
 7954                    })
 7955                });
 7956
 7957        let tasks = tasks.collect::<Vec<_>>();
 7958
 7959        let tasks = futures::future::join_all(tasks);
 7960        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7961            opened_items[ix] = Some(path_open_result);
 7962        }
 7963
 7964        Ok(opened_items)
 7965    })
 7966}
 7967
 7968#[derive(Clone)]
 7969enum ActivateInDirectionTarget {
 7970    Pane(Entity<Pane>),
 7971    Dock(Entity<Dock>),
 7972    Sidebar(FocusHandle),
 7973}
 7974
 7975fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7976    window
 7977        .update(cx, |multi_workspace, _, cx| {
 7978            let workspace = multi_workspace.workspace().clone();
 7979            workspace.update(cx, |workspace, cx| {
 7980                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7981                    struct DatabaseFailedNotification;
 7982
 7983                    workspace.show_notification(
 7984                        NotificationId::unique::<DatabaseFailedNotification>(),
 7985                        cx,
 7986                        |cx| {
 7987                            cx.new(|cx| {
 7988                                MessageNotification::new("Failed to load the database file.", cx)
 7989                                    .primary_message("File an Issue")
 7990                                    .primary_icon(IconName::Plus)
 7991                                    .primary_on_click(|window, cx| {
 7992                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7993                                    })
 7994                            })
 7995                        },
 7996                    );
 7997                }
 7998            });
 7999        })
 8000        .log_err();
 8001}
 8002
 8003fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 8004    if val == 0 {
 8005        ThemeSettings::get_global(cx).ui_font_size(cx)
 8006    } else {
 8007        px(val as f32)
 8008    }
 8009}
 8010
 8011fn adjust_active_dock_size_by_px(
 8012    px: Pixels,
 8013    workspace: &mut Workspace,
 8014    window: &mut Window,
 8015    cx: &mut Context<Workspace>,
 8016) {
 8017    let Some(active_dock) = workspace
 8018        .all_docks()
 8019        .into_iter()
 8020        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8021    else {
 8022        return;
 8023    };
 8024    let dock = active_dock.read(cx);
 8025    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8026        return;
 8027    };
 8028    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8029}
 8030
 8031fn adjust_open_docks_size_by_px(
 8032    px: Pixels,
 8033    workspace: &mut Workspace,
 8034    window: &mut Window,
 8035    cx: &mut Context<Workspace>,
 8036) {
 8037    let docks = workspace
 8038        .all_docks()
 8039        .into_iter()
 8040        .filter_map(|dock_entity| {
 8041            let dock = dock_entity.read(cx);
 8042            if dock.is_open() {
 8043                let dock_pos = dock.position();
 8044                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8045                Some((dock_pos, panel_size + px))
 8046            } else {
 8047                None
 8048            }
 8049        })
 8050        .collect::<Vec<_>>();
 8051
 8052    for (position, new_size) in docks {
 8053        workspace.resize_dock(position, new_size, window, cx);
 8054    }
 8055}
 8056
 8057impl Focusable for Workspace {
 8058    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8059        self.active_pane.focus_handle(cx)
 8060    }
 8061}
 8062
 8063#[derive(Clone)]
 8064struct DraggedDock(DockPosition);
 8065
 8066impl Render for DraggedDock {
 8067    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8068        gpui::Empty
 8069    }
 8070}
 8071
 8072impl Render for Workspace {
 8073    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8074        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8075        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8076            log::info!("Rendered first frame");
 8077        }
 8078
 8079        let centered_layout = self.centered_layout
 8080            && self.center.panes().len() == 1
 8081            && self.active_item(cx).is_some();
 8082        let render_padding = |size| {
 8083            (size > 0.0).then(|| {
 8084                div()
 8085                    .h_full()
 8086                    .w(relative(size))
 8087                    .bg(cx.theme().colors().editor_background)
 8088                    .border_color(cx.theme().colors().pane_group_border)
 8089            })
 8090        };
 8091        let paddings = if centered_layout {
 8092            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8093            (
 8094                render_padding(Self::adjust_padding(
 8095                    settings.left_padding.map(|padding| padding.0),
 8096                )),
 8097                render_padding(Self::adjust_padding(
 8098                    settings.right_padding.map(|padding| padding.0),
 8099                )),
 8100            )
 8101        } else {
 8102            (None, None)
 8103        };
 8104        let ui_font = theme_settings::setup_ui_font(window, cx);
 8105
 8106        let theme = cx.theme().clone();
 8107        let colors = theme.colors();
 8108        let notification_entities = self
 8109            .notifications
 8110            .iter()
 8111            .map(|(_, notification)| notification.entity_id())
 8112            .collect::<Vec<_>>();
 8113        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8114
 8115        div()
 8116            .relative()
 8117            .size_full()
 8118            .flex()
 8119            .flex_col()
 8120            .font(ui_font)
 8121            .gap_0()
 8122                .justify_start()
 8123                .items_start()
 8124                .text_color(colors.text)
 8125                .overflow_hidden()
 8126                .children(self.titlebar_item.clone())
 8127                .on_modifiers_changed(move |_, _, cx| {
 8128                    for &id in &notification_entities {
 8129                        cx.notify(id);
 8130                    }
 8131                })
 8132                .child(
 8133                    div()
 8134                        .size_full()
 8135                        .relative()
 8136                        .flex_1()
 8137                        .flex()
 8138                        .flex_col()
 8139                        .child(
 8140                            div()
 8141                                .id("workspace")
 8142                                .bg(colors.background)
 8143                                .relative()
 8144                                .flex_1()
 8145                                .w_full()
 8146                                .flex()
 8147                                .flex_col()
 8148                                .overflow_hidden()
 8149                                .border_t_1()
 8150                                .border_b_1()
 8151                                .border_color(colors.border)
 8152                                .child({
 8153                                    let this = cx.entity();
 8154                                    canvas(
 8155                                        move |bounds, window, cx| {
 8156                                            this.update(cx, |this, cx| {
 8157                                                let bounds_changed = this.bounds != bounds;
 8158                                                this.bounds = bounds;
 8159
 8160                                                if bounds_changed {
 8161                                                    this.left_dock.update(cx, |dock, cx| {
 8162                                                        dock.clamp_panel_size(
 8163                                                            bounds.size.width,
 8164                                                            window,
 8165                                                            cx,
 8166                                                        )
 8167                                                    });
 8168
 8169                                                    this.right_dock.update(cx, |dock, cx| {
 8170                                                        dock.clamp_panel_size(
 8171                                                            bounds.size.width,
 8172                                                            window,
 8173                                                            cx,
 8174                                                        )
 8175                                                    });
 8176
 8177                                                    this.bottom_dock.update(cx, |dock, cx| {
 8178                                                        dock.clamp_panel_size(
 8179                                                            bounds.size.height,
 8180                                                            window,
 8181                                                            cx,
 8182                                                        )
 8183                                                    });
 8184                                                }
 8185                                            })
 8186                                        },
 8187                                        |_, _, _, _| {},
 8188                                    )
 8189                                    .absolute()
 8190                                    .size_full()
 8191                                })
 8192                                .when(self.zoomed.is_none(), |this| {
 8193                                    this.on_drag_move(cx.listener(
 8194                                        move |workspace,
 8195                                              e: &DragMoveEvent<DraggedDock>,
 8196                                              window,
 8197                                              cx| {
 8198                                            if workspace.previous_dock_drag_coordinates
 8199                                                != Some(e.event.position)
 8200                                            {
 8201                                                workspace.previous_dock_drag_coordinates =
 8202                                                    Some(e.event.position);
 8203
 8204                                                match e.drag(cx).0 {
 8205                                                    DockPosition::Left => {
 8206                                                        workspace.resize_left_dock(
 8207                                                            e.event.position.x
 8208                                                                - workspace.bounds.left(),
 8209                                                            window,
 8210                                                            cx,
 8211                                                        );
 8212                                                    }
 8213                                                    DockPosition::Right => {
 8214                                                        workspace.resize_right_dock(
 8215                                                            workspace.bounds.right()
 8216                                                                - e.event.position.x,
 8217                                                            window,
 8218                                                            cx,
 8219                                                        );
 8220                                                    }
 8221                                                    DockPosition::Bottom => {
 8222                                                        workspace.resize_bottom_dock(
 8223                                                            workspace.bounds.bottom()
 8224                                                                - e.event.position.y,
 8225                                                            window,
 8226                                                            cx,
 8227                                                        );
 8228                                                    }
 8229                                                };
 8230                                                workspace.serialize_workspace(window, cx);
 8231                                            }
 8232                                        },
 8233                                    ))
 8234
 8235                                })
 8236                                .child({
 8237                                    match bottom_dock_layout {
 8238                                        BottomDockLayout::Full => div()
 8239                                            .flex()
 8240                                            .flex_col()
 8241                                            .h_full()
 8242                                            .child(
 8243                                                div()
 8244                                                    .flex()
 8245                                                    .flex_row()
 8246                                                    .flex_1()
 8247                                                    .overflow_hidden()
 8248                                                    .children(self.render_dock(
 8249                                                        DockPosition::Left,
 8250                                                        &self.left_dock,
 8251                                                        window,
 8252                                                        cx,
 8253                                                    ))
 8254
 8255                                                    .child(
 8256                                                        div()
 8257                                                            .flex()
 8258                                                            .flex_col()
 8259                                                            .flex_1()
 8260                                                            .overflow_hidden()
 8261                                                            .child(
 8262                                                                h_flex()
 8263                                                                    .flex_1()
 8264                                                                    .when_some(
 8265                                                                        paddings.0,
 8266                                                                        |this, p| {
 8267                                                                            this.child(
 8268                                                                                p.border_r_1(),
 8269                                                                            )
 8270                                                                        },
 8271                                                                    )
 8272                                                                    .child(self.center.render(
 8273                                                                        self.zoomed.as_ref(),
 8274                                                                        &PaneRenderContext {
 8275                                                                            follower_states:
 8276                                                                                &self.follower_states,
 8277                                                                            active_call: self.active_call(),
 8278                                                                            active_pane: &self.active_pane,
 8279                                                                            app_state: &self.app_state,
 8280                                                                            project: &self.project,
 8281                                                                            workspace: &self.weak_self,
 8282                                                                        },
 8283                                                                        window,
 8284                                                                        cx,
 8285                                                                    ))
 8286                                                                    .when_some(
 8287                                                                        paddings.1,
 8288                                                                        |this, p| {
 8289                                                                            this.child(
 8290                                                                                p.border_l_1(),
 8291                                                                            )
 8292                                                                        },
 8293                                                                    ),
 8294                                                            ),
 8295                                                    )
 8296
 8297                                                    .children(self.render_dock(
 8298                                                        DockPosition::Right,
 8299                                                        &self.right_dock,
 8300                                                        window,
 8301                                                        cx,
 8302                                                    )),
 8303                                            )
 8304                                            .child(div().w_full().children(self.render_dock(
 8305                                                DockPosition::Bottom,
 8306                                                &self.bottom_dock,
 8307                                                window,
 8308                                                cx
 8309                                            ))),
 8310
 8311                                        BottomDockLayout::LeftAligned => div()
 8312                                            .flex()
 8313                                            .flex_row()
 8314                                            .h_full()
 8315                                            .child(
 8316                                                div()
 8317                                                    .flex()
 8318                                                    .flex_col()
 8319                                                    .flex_1()
 8320                                                    .h_full()
 8321                                                    .child(
 8322                                                        div()
 8323                                                            .flex()
 8324                                                            .flex_row()
 8325                                                            .flex_1()
 8326                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8327
 8328                                                            .child(
 8329                                                                div()
 8330                                                                    .flex()
 8331                                                                    .flex_col()
 8332                                                                    .flex_1()
 8333                                                                    .overflow_hidden()
 8334                                                                    .child(
 8335                                                                        h_flex()
 8336                                                                            .flex_1()
 8337                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8338                                                                            .child(self.center.render(
 8339                                                                                self.zoomed.as_ref(),
 8340                                                                                &PaneRenderContext {
 8341                                                                                    follower_states:
 8342                                                                                        &self.follower_states,
 8343                                                                                    active_call: self.active_call(),
 8344                                                                                    active_pane: &self.active_pane,
 8345                                                                                    app_state: &self.app_state,
 8346                                                                                    project: &self.project,
 8347                                                                                    workspace: &self.weak_self,
 8348                                                                                },
 8349                                                                                window,
 8350                                                                                cx,
 8351                                                                            ))
 8352                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8353                                                                    )
 8354                                                            )
 8355
 8356                                                    )
 8357                                                    .child(
 8358                                                        div()
 8359                                                            .w_full()
 8360                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8361                                                    ),
 8362                                            )
 8363                                            .children(self.render_dock(
 8364                                                DockPosition::Right,
 8365                                                &self.right_dock,
 8366                                                window,
 8367                                                cx,
 8368                                            )),
 8369                                        BottomDockLayout::RightAligned => div()
 8370                                            .flex()
 8371                                            .flex_row()
 8372                                            .h_full()
 8373                                            .children(self.render_dock(
 8374                                                DockPosition::Left,
 8375                                                &self.left_dock,
 8376                                                window,
 8377                                                cx,
 8378                                            ))
 8379
 8380                                            .child(
 8381                                                div()
 8382                                                    .flex()
 8383                                                    .flex_col()
 8384                                                    .flex_1()
 8385                                                    .h_full()
 8386                                                    .child(
 8387                                                        div()
 8388                                                            .flex()
 8389                                                            .flex_row()
 8390                                                            .flex_1()
 8391                                                            .child(
 8392                                                                div()
 8393                                                                    .flex()
 8394                                                                    .flex_col()
 8395                                                                    .flex_1()
 8396                                                                    .overflow_hidden()
 8397                                                                    .child(
 8398                                                                        h_flex()
 8399                                                                            .flex_1()
 8400                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8401                                                                            .child(self.center.render(
 8402                                                                                self.zoomed.as_ref(),
 8403                                                                                &PaneRenderContext {
 8404                                                                                    follower_states:
 8405                                                                                        &self.follower_states,
 8406                                                                                    active_call: self.active_call(),
 8407                                                                                    active_pane: &self.active_pane,
 8408                                                                                    app_state: &self.app_state,
 8409                                                                                    project: &self.project,
 8410                                                                                    workspace: &self.weak_self,
 8411                                                                                },
 8412                                                                                window,
 8413                                                                                cx,
 8414                                                                            ))
 8415                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8416                                                                    )
 8417                                                            )
 8418
 8419                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8420                                                    )
 8421                                                    .child(
 8422                                                        div()
 8423                                                            .w_full()
 8424                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8425                                                    ),
 8426                                            ),
 8427                                        BottomDockLayout::Contained => div()
 8428                                            .flex()
 8429                                            .flex_row()
 8430                                            .h_full()
 8431                                            .children(self.render_dock(
 8432                                                DockPosition::Left,
 8433                                                &self.left_dock,
 8434                                                window,
 8435                                                cx,
 8436                                            ))
 8437
 8438                                            .child(
 8439                                                div()
 8440                                                    .flex()
 8441                                                    .flex_col()
 8442                                                    .flex_1()
 8443                                                    .overflow_hidden()
 8444                                                    .child(
 8445                                                        h_flex()
 8446                                                            .flex_1()
 8447                                                            .when_some(paddings.0, |this, p| {
 8448                                                                this.child(p.border_r_1())
 8449                                                            })
 8450                                                            .child(self.center.render(
 8451                                                                self.zoomed.as_ref(),
 8452                                                                &PaneRenderContext {
 8453                                                                    follower_states:
 8454                                                                        &self.follower_states,
 8455                                                                    active_call: self.active_call(),
 8456                                                                    active_pane: &self.active_pane,
 8457                                                                    app_state: &self.app_state,
 8458                                                                    project: &self.project,
 8459                                                                    workspace: &self.weak_self,
 8460                                                                },
 8461                                                                window,
 8462                                                                cx,
 8463                                                            ))
 8464                                                            .when_some(paddings.1, |this, p| {
 8465                                                                this.child(p.border_l_1())
 8466                                                            }),
 8467                                                    )
 8468                                                    .children(self.render_dock(
 8469                                                        DockPosition::Bottom,
 8470                                                        &self.bottom_dock,
 8471                                                        window,
 8472                                                        cx,
 8473                                                    )),
 8474                                            )
 8475
 8476                                            .children(self.render_dock(
 8477                                                DockPosition::Right,
 8478                                                &self.right_dock,
 8479                                                window,
 8480                                                cx,
 8481                                            )),
 8482                                    }
 8483                                })
 8484                                .children(self.zoomed.as_ref().and_then(|view| {
 8485                                    let zoomed_view = view.upgrade()?;
 8486                                    let div = div()
 8487                                        .occlude()
 8488                                        .absolute()
 8489                                        .overflow_hidden()
 8490                                        .border_color(colors.border)
 8491                                        .bg(colors.background)
 8492                                        .child(zoomed_view)
 8493                                        .inset_0()
 8494                                        .shadow_lg();
 8495
 8496                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8497                                       return Some(div);
 8498                                    }
 8499
 8500                                    Some(match self.zoomed_position {
 8501                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8502                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8503                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8504                                        None => {
 8505                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8506                                        }
 8507                                    })
 8508                                }))
 8509                                .children(self.render_notifications(window, cx)),
 8510                        )
 8511                        .when(self.status_bar_visible(cx), |parent| {
 8512                            parent.child(self.status_bar.clone())
 8513                        })
 8514                        .child(self.toast_layer.clone()),
 8515                )
 8516    }
 8517}
 8518
 8519impl WorkspaceStore {
 8520    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8521        Self {
 8522            workspaces: Default::default(),
 8523            _subscriptions: vec![
 8524                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8525                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8526            ],
 8527            client,
 8528        }
 8529    }
 8530
 8531    pub fn update_followers(
 8532        &self,
 8533        project_id: Option<u64>,
 8534        update: proto::update_followers::Variant,
 8535        cx: &App,
 8536    ) -> Option<()> {
 8537        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8538        let room_id = active_call.0.room_id(cx)?;
 8539        self.client
 8540            .send(proto::UpdateFollowers {
 8541                room_id,
 8542                project_id,
 8543                variant: Some(update),
 8544            })
 8545            .log_err()
 8546    }
 8547
 8548    pub async fn handle_follow(
 8549        this: Entity<Self>,
 8550        envelope: TypedEnvelope<proto::Follow>,
 8551        mut cx: AsyncApp,
 8552    ) -> Result<proto::FollowResponse> {
 8553        this.update(&mut cx, |this, cx| {
 8554            let follower = Follower {
 8555                project_id: envelope.payload.project_id,
 8556                peer_id: envelope.original_sender_id()?,
 8557            };
 8558
 8559            let mut response = proto::FollowResponse::default();
 8560
 8561            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8562                let Some(workspace) = weak_workspace.upgrade() else {
 8563                    return false;
 8564                };
 8565                window_handle
 8566                    .update(cx, |_, window, cx| {
 8567                        workspace.update(cx, |workspace, cx| {
 8568                            let handler_response =
 8569                                workspace.handle_follow(follower.project_id, window, cx);
 8570                            if let Some(active_view) = handler_response.active_view
 8571                                && workspace.project.read(cx).remote_id() == follower.project_id
 8572                            {
 8573                                response.active_view = Some(active_view)
 8574                            }
 8575                        });
 8576                    })
 8577                    .is_ok()
 8578            });
 8579
 8580            Ok(response)
 8581        })
 8582    }
 8583
 8584    async fn handle_update_followers(
 8585        this: Entity<Self>,
 8586        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8587        mut cx: AsyncApp,
 8588    ) -> Result<()> {
 8589        let leader_id = envelope.original_sender_id()?;
 8590        let update = envelope.payload;
 8591
 8592        this.update(&mut cx, |this, cx| {
 8593            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8594                let Some(workspace) = weak_workspace.upgrade() else {
 8595                    return false;
 8596                };
 8597                window_handle
 8598                    .update(cx, |_, window, cx| {
 8599                        workspace.update(cx, |workspace, cx| {
 8600                            let project_id = workspace.project.read(cx).remote_id();
 8601                            if update.project_id != project_id && update.project_id.is_some() {
 8602                                return;
 8603                            }
 8604                            workspace.handle_update_followers(
 8605                                leader_id,
 8606                                update.clone(),
 8607                                window,
 8608                                cx,
 8609                            );
 8610                        });
 8611                    })
 8612                    .is_ok()
 8613            });
 8614            Ok(())
 8615        })
 8616    }
 8617
 8618    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8619        self.workspaces.iter().map(|(_, weak)| weak)
 8620    }
 8621
 8622    pub fn workspaces_with_windows(
 8623        &self,
 8624    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8625        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8626    }
 8627}
 8628
 8629impl ViewId {
 8630    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8631        Ok(Self {
 8632            creator: message
 8633                .creator
 8634                .map(CollaboratorId::PeerId)
 8635                .context("creator is missing")?,
 8636            id: message.id,
 8637        })
 8638    }
 8639
 8640    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8641        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8642            Some(proto::ViewId {
 8643                creator: Some(peer_id),
 8644                id: self.id,
 8645            })
 8646        } else {
 8647            None
 8648        }
 8649    }
 8650}
 8651
 8652impl FollowerState {
 8653    fn pane(&self) -> &Entity<Pane> {
 8654        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8655    }
 8656}
 8657
 8658pub trait WorkspaceHandle {
 8659    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8660}
 8661
 8662impl WorkspaceHandle for Entity<Workspace> {
 8663    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8664        self.read(cx)
 8665            .worktrees(cx)
 8666            .flat_map(|worktree| {
 8667                let worktree_id = worktree.read(cx).id();
 8668                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8669                    worktree_id,
 8670                    path: f.path.clone(),
 8671                })
 8672            })
 8673            .collect::<Vec<_>>()
 8674    }
 8675}
 8676
 8677pub async fn last_opened_workspace_location(
 8678    db: &WorkspaceDb,
 8679    fs: &dyn fs::Fs,
 8680) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8681    db.last_workspace(fs)
 8682        .await
 8683        .log_err()
 8684        .flatten()
 8685        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8686}
 8687
 8688pub async fn last_session_workspace_locations(
 8689    db: &WorkspaceDb,
 8690    last_session_id: &str,
 8691    last_session_window_stack: Option<Vec<WindowId>>,
 8692    fs: &dyn fs::Fs,
 8693) -> Option<Vec<SessionWorkspace>> {
 8694    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8695        .await
 8696        .log_err()
 8697}
 8698
 8699pub async fn restore_multiworkspace(
 8700    multi_workspace: SerializedMultiWorkspace,
 8701    app_state: Arc<AppState>,
 8702    cx: &mut AsyncApp,
 8703) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8704    let SerializedMultiWorkspace {
 8705        active_workspace,
 8706        state,
 8707    } = multi_workspace;
 8708    let MultiWorkspaceState {
 8709        sidebar_open,
 8710        project_group_keys,
 8711        sidebar_state,
 8712        ..
 8713    } = state;
 8714
 8715    let workspace_result = if active_workspace.paths.is_empty() {
 8716        cx.update(|cx| {
 8717            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8718        })
 8719        .await
 8720    } else {
 8721        cx.update(|cx| {
 8722            Workspace::new_local(
 8723                active_workspace.paths.paths().to_vec(),
 8724                app_state.clone(),
 8725                None,
 8726                None,
 8727                None,
 8728                OpenMode::Activate,
 8729                cx,
 8730            )
 8731        })
 8732        .await
 8733        .map(|result| result.window)
 8734    };
 8735
 8736    let window_handle = match workspace_result {
 8737        Ok(handle) => handle,
 8738        Err(err) => {
 8739            log::error!("Failed to restore active workspace: {err:#}");
 8740
 8741            // Try each project group's paths as a fallback.
 8742            let mut fallback_handle = None;
 8743            for key in &project_group_keys {
 8744                let key: ProjectGroupKey = key.clone().into();
 8745                let paths = key.path_list().paths().to_vec();
 8746                match cx
 8747                    .update(|cx| {
 8748                        Workspace::new_local(
 8749                            paths,
 8750                            app_state.clone(),
 8751                            None,
 8752                            None,
 8753                            None,
 8754                            OpenMode::Activate,
 8755                            cx,
 8756                        )
 8757                    })
 8758                    .await
 8759                {
 8760                    Ok(OpenResult { window, .. }) => {
 8761                        fallback_handle = Some(window);
 8762                        break;
 8763                    }
 8764                    Err(fallback_err) => {
 8765                        log::error!("Fallback project group also failed: {fallback_err:#}");
 8766                    }
 8767                }
 8768            }
 8769
 8770            fallback_handle.ok_or(err)?
 8771        }
 8772    };
 8773
 8774    if !project_group_keys.is_empty() {
 8775        let fs = app_state.fs.clone();
 8776
 8777        // Resolve linked worktree paths to their main repo paths so
 8778        // stale keys from previous sessions get normalized and deduped.
 8779        let mut resolved_keys: Vec<ProjectGroupKey> = Vec::new();
 8780        for key in project_group_keys.into_iter().map(ProjectGroupKey::from) {
 8781            if key.path_list().paths().is_empty() {
 8782                continue;
 8783            }
 8784            let mut resolved_paths = Vec::new();
 8785            for path in key.path_list().paths() {
 8786                if let Some(common_dir) =
 8787                    project::discover_root_repo_common_dir(path, fs.as_ref()).await
 8788                {
 8789                    let main_path = common_dir.parent().unwrap_or(&common_dir);
 8790                    resolved_paths.push(main_path.to_path_buf());
 8791                } else {
 8792                    resolved_paths.push(path.to_path_buf());
 8793                }
 8794            }
 8795            let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
 8796            if !resolved_keys.contains(&resolved) {
 8797                resolved_keys.push(resolved);
 8798            }
 8799        }
 8800
 8801        window_handle
 8802            .update(cx, |multi_workspace, _window, _cx| {
 8803                multi_workspace.restore_project_group_keys(resolved_keys);
 8804            })
 8805            .ok();
 8806    }
 8807
 8808    if sidebar_open {
 8809        window_handle
 8810            .update(cx, |multi_workspace, _, cx| {
 8811                multi_workspace.restore_open_sidebar(cx);
 8812            })
 8813            .ok();
 8814    }
 8815
 8816    if let Some(sidebar_state) = sidebar_state {
 8817        window_handle
 8818            .update(cx, |multi_workspace, window, cx| {
 8819                if let Some(sidebar) = multi_workspace.sidebar() {
 8820                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8821                }
 8822                multi_workspace.serialize(cx);
 8823            })
 8824            .ok();
 8825    }
 8826
 8827    window_handle
 8828        .update(cx, |_, window, _cx| {
 8829            window.activate_window();
 8830        })
 8831        .ok();
 8832
 8833    Ok(window_handle)
 8834}
 8835
 8836actions!(
 8837    collab,
 8838    [
 8839        /// Opens the channel notes for the current call.
 8840        ///
 8841        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8842        /// channel in the collab panel.
 8843        ///
 8844        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8845        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8846        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8847        OpenChannelNotes,
 8848        /// Mutes your microphone.
 8849        Mute,
 8850        /// Deafens yourself (mute both microphone and speakers).
 8851        Deafen,
 8852        /// Leaves the current call.
 8853        LeaveCall,
 8854        /// Shares the current project with collaborators.
 8855        ShareProject,
 8856        /// Shares your screen with collaborators.
 8857        ScreenShare,
 8858        /// Copies the current room name and session id for debugging purposes.
 8859        CopyRoomId,
 8860    ]
 8861);
 8862
 8863/// Opens the channel notes for a specific channel by its ID.
 8864#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8865#[action(namespace = collab)]
 8866#[serde(deny_unknown_fields)]
 8867pub struct OpenChannelNotesById {
 8868    pub channel_id: u64,
 8869}
 8870
 8871actions!(
 8872    zed,
 8873    [
 8874        /// Opens the Zed log file.
 8875        OpenLog,
 8876        /// Reveals the Zed log file in the system file manager.
 8877        RevealLogInFileManager
 8878    ]
 8879);
 8880
 8881async fn join_channel_internal(
 8882    channel_id: ChannelId,
 8883    app_state: &Arc<AppState>,
 8884    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8885    requesting_workspace: Option<WeakEntity<Workspace>>,
 8886    active_call: &dyn AnyActiveCall,
 8887    cx: &mut AsyncApp,
 8888) -> Result<bool> {
 8889    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8890        if !active_call.is_in_room(cx) {
 8891            return (false, false);
 8892        }
 8893
 8894        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8895        let should_prompt = active_call.is_sharing_project(cx)
 8896            && active_call.has_remote_participants(cx)
 8897            && !already_in_channel;
 8898        (should_prompt, already_in_channel)
 8899    });
 8900
 8901    if already_in_channel {
 8902        let task = cx.update(|cx| {
 8903            if let Some((project, host)) = active_call.most_active_project(cx) {
 8904                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8905            } else {
 8906                None
 8907            }
 8908        });
 8909        if let Some(task) = task {
 8910            task.await?;
 8911        }
 8912        return anyhow::Ok(true);
 8913    }
 8914
 8915    if should_prompt {
 8916        if let Some(multi_workspace) = requesting_window {
 8917            let answer = multi_workspace
 8918                .update(cx, |_, window, cx| {
 8919                    window.prompt(
 8920                        PromptLevel::Warning,
 8921                        "Do you want to switch channels?",
 8922                        Some("Leaving this call will unshare your current project."),
 8923                        &["Yes, Join Channel", "Cancel"],
 8924                        cx,
 8925                    )
 8926                })?
 8927                .await;
 8928
 8929            if answer == Ok(1) {
 8930                return Ok(false);
 8931            }
 8932        } else {
 8933            return Ok(false);
 8934        }
 8935    }
 8936
 8937    let client = cx.update(|cx| active_call.client(cx));
 8938
 8939    let mut client_status = client.status();
 8940
 8941    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8942    'outer: loop {
 8943        let Some(status) = client_status.recv().await else {
 8944            anyhow::bail!("error connecting");
 8945        };
 8946
 8947        match status {
 8948            Status::Connecting
 8949            | Status::Authenticating
 8950            | Status::Authenticated
 8951            | Status::Reconnecting
 8952            | Status::Reauthenticating
 8953            | Status::Reauthenticated => continue,
 8954            Status::Connected { .. } => break 'outer,
 8955            Status::SignedOut | Status::AuthenticationError => {
 8956                return Err(ErrorCode::SignedOut.into());
 8957            }
 8958            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8959            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8960                return Err(ErrorCode::Disconnected.into());
 8961            }
 8962        }
 8963    }
 8964
 8965    let joined = cx
 8966        .update(|cx| active_call.join_channel(channel_id, cx))
 8967        .await?;
 8968
 8969    if !joined {
 8970        return anyhow::Ok(true);
 8971    }
 8972
 8973    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8974
 8975    let task = cx.update(|cx| {
 8976        if let Some((project, host)) = active_call.most_active_project(cx) {
 8977            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8978        }
 8979
 8980        // If you are the first to join a channel, see if you should share your project.
 8981        if !active_call.has_remote_participants(cx)
 8982            && !active_call.local_participant_is_guest(cx)
 8983            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8984        {
 8985            let project = workspace.update(cx, |workspace, cx| {
 8986                let project = workspace.project.read(cx);
 8987
 8988                if !active_call.share_on_join(cx) {
 8989                    return None;
 8990                }
 8991
 8992                if (project.is_local() || project.is_via_remote_server())
 8993                    && project.visible_worktrees(cx).any(|tree| {
 8994                        tree.read(cx)
 8995                            .root_entry()
 8996                            .is_some_and(|entry| entry.is_dir())
 8997                    })
 8998                {
 8999                    Some(workspace.project.clone())
 9000                } else {
 9001                    None
 9002                }
 9003            });
 9004            if let Some(project) = project {
 9005                let share_task = active_call.share_project(project, cx);
 9006                return Some(cx.spawn(async move |_cx| -> Result<()> {
 9007                    share_task.await?;
 9008                    Ok(())
 9009                }));
 9010            }
 9011        }
 9012
 9013        None
 9014    });
 9015    if let Some(task) = task {
 9016        task.await?;
 9017        return anyhow::Ok(true);
 9018    }
 9019    anyhow::Ok(false)
 9020}
 9021
 9022pub fn join_channel(
 9023    channel_id: ChannelId,
 9024    app_state: Arc<AppState>,
 9025    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9026    requesting_workspace: Option<WeakEntity<Workspace>>,
 9027    cx: &mut App,
 9028) -> Task<Result<()>> {
 9029    let active_call = GlobalAnyActiveCall::global(cx).clone();
 9030    cx.spawn(async move |cx| {
 9031        let result = join_channel_internal(
 9032            channel_id,
 9033            &app_state,
 9034            requesting_window,
 9035            requesting_workspace,
 9036            &*active_call.0,
 9037            cx,
 9038        )
 9039        .await;
 9040
 9041        // join channel succeeded, and opened a window
 9042        if matches!(result, Ok(true)) {
 9043            return anyhow::Ok(());
 9044        }
 9045
 9046        // find an existing workspace to focus and show call controls
 9047        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 9048        if active_window.is_none() {
 9049            // no open workspaces, make one to show the error in (blergh)
 9050            let OpenResult {
 9051                window: window_handle,
 9052                ..
 9053            } = cx
 9054                .update(|cx| {
 9055                    Workspace::new_local(
 9056                        vec![],
 9057                        app_state.clone(),
 9058                        requesting_window,
 9059                        None,
 9060                        None,
 9061                        OpenMode::Activate,
 9062                        cx,
 9063                    )
 9064                })
 9065                .await?;
 9066
 9067            window_handle
 9068                .update(cx, |_, window, _cx| {
 9069                    window.activate_window();
 9070                })
 9071                .ok();
 9072
 9073            if result.is_ok() {
 9074                cx.update(|cx| {
 9075                    cx.dispatch_action(&OpenChannelNotes);
 9076                });
 9077            }
 9078
 9079            active_window = Some(window_handle);
 9080        }
 9081
 9082        if let Err(err) = result {
 9083            log::error!("failed to join channel: {}", err);
 9084            if let Some(active_window) = active_window {
 9085                active_window
 9086                    .update(cx, |_, window, cx| {
 9087                        let detail: SharedString = match err.error_code() {
 9088                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9089                            ErrorCode::UpgradeRequired => concat!(
 9090                                "Your are running an unsupported version of Zed. ",
 9091                                "Please update to continue."
 9092                            )
 9093                            .into(),
 9094                            ErrorCode::NoSuchChannel => concat!(
 9095                                "No matching channel was found. ",
 9096                                "Please check the link and try again."
 9097                            )
 9098                            .into(),
 9099                            ErrorCode::Forbidden => concat!(
 9100                                "This channel is private, and you do not have access. ",
 9101                                "Please ask someone to add you and try again."
 9102                            )
 9103                            .into(),
 9104                            ErrorCode::Disconnected => {
 9105                                "Please check your internet connection and try again.".into()
 9106                            }
 9107                            _ => format!("{}\n\nPlease try again.", err).into(),
 9108                        };
 9109                        window.prompt(
 9110                            PromptLevel::Critical,
 9111                            "Failed to join channel",
 9112                            Some(&detail),
 9113                            &["Ok"],
 9114                            cx,
 9115                        )
 9116                    })?
 9117                    .await
 9118                    .ok();
 9119            }
 9120        }
 9121
 9122        // return ok, we showed the error to the user.
 9123        anyhow::Ok(())
 9124    })
 9125}
 9126
 9127pub async fn get_any_active_multi_workspace(
 9128    app_state: Arc<AppState>,
 9129    mut cx: AsyncApp,
 9130) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9131    // find an existing workspace to focus and show call controls
 9132    let active_window = activate_any_workspace_window(&mut cx);
 9133    if active_window.is_none() {
 9134        cx.update(|cx| {
 9135            Workspace::new_local(
 9136                vec![],
 9137                app_state.clone(),
 9138                None,
 9139                None,
 9140                None,
 9141                OpenMode::Activate,
 9142                cx,
 9143            )
 9144        })
 9145        .await?;
 9146    }
 9147    activate_any_workspace_window(&mut cx).context("could not open zed")
 9148}
 9149
 9150fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9151    cx.update(|cx| {
 9152        if let Some(workspace_window) = cx
 9153            .active_window()
 9154            .and_then(|window| window.downcast::<MultiWorkspace>())
 9155        {
 9156            return Some(workspace_window);
 9157        }
 9158
 9159        for window in cx.windows() {
 9160            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9161                workspace_window
 9162                    .update(cx, |_, window, _| window.activate_window())
 9163                    .ok();
 9164                return Some(workspace_window);
 9165            }
 9166        }
 9167        None
 9168    })
 9169}
 9170
 9171pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9172    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9173}
 9174
 9175pub fn workspace_windows_for_location(
 9176    serialized_location: &SerializedWorkspaceLocation,
 9177    cx: &App,
 9178) -> Vec<WindowHandle<MultiWorkspace>> {
 9179    cx.windows()
 9180        .into_iter()
 9181        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9182        .filter(|multi_workspace| {
 9183            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9184                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9185                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9186                }
 9187                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9188                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9189                    a.distro_name == b.distro_name
 9190                }
 9191                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9192                    a.container_id == b.container_id
 9193                }
 9194                #[cfg(any(test, feature = "test-support"))]
 9195                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9196                    a.id == b.id
 9197                }
 9198                _ => false,
 9199            };
 9200
 9201            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9202                multi_workspace.workspaces().any(|workspace| {
 9203                    match workspace.read(cx).workspace_location(cx) {
 9204                        WorkspaceLocation::Location(location, _) => {
 9205                            match (&location, serialized_location) {
 9206                                (
 9207                                    SerializedWorkspaceLocation::Local,
 9208                                    SerializedWorkspaceLocation::Local,
 9209                                ) => true,
 9210                                (
 9211                                    SerializedWorkspaceLocation::Remote(a),
 9212                                    SerializedWorkspaceLocation::Remote(b),
 9213                                ) => same_host(a, b),
 9214                                _ => false,
 9215                            }
 9216                        }
 9217                        _ => false,
 9218                    }
 9219                })
 9220            })
 9221        })
 9222        .collect()
 9223}
 9224
 9225pub async fn find_existing_workspace(
 9226    abs_paths: &[PathBuf],
 9227    open_options: &OpenOptions,
 9228    location: &SerializedWorkspaceLocation,
 9229    cx: &mut AsyncApp,
 9230) -> (
 9231    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9232    OpenVisible,
 9233) {
 9234    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9235    let mut open_visible = OpenVisible::All;
 9236    let mut best_match = None;
 9237
 9238    cx.update(|cx| {
 9239        for window in workspace_windows_for_location(location, cx) {
 9240            if let Ok(multi_workspace) = window.read(cx) {
 9241                for workspace in multi_workspace.workspaces() {
 9242                    let project = workspace.read(cx).project.read(cx);
 9243                    let m = project.visibility_for_paths(
 9244                        abs_paths,
 9245                        open_options.open_new_workspace == None,
 9246                        cx,
 9247                    );
 9248                    if m > best_match {
 9249                        existing = Some((window, workspace.clone()));
 9250                        best_match = m;
 9251                    } else if best_match.is_none() && open_options.open_new_workspace == Some(false)
 9252                    {
 9253                        existing = Some((window, workspace.clone()))
 9254                    }
 9255                }
 9256            }
 9257        }
 9258    });
 9259
 9260    // With -n, only reuse a window if the path is genuinely contained
 9261    // within an existing worktree (don't fall back to any arbitrary window).
 9262    if open_options.open_new_workspace == Some(true) && best_match.is_none() {
 9263        existing = None;
 9264    }
 9265
 9266    if open_options.open_new_workspace != Some(true) {
 9267        let all_paths_are_files = existing
 9268            .as_ref()
 9269            .and_then(|(_, target_workspace)| {
 9270                cx.update(|cx| {
 9271                    let workspace = target_workspace.read(cx);
 9272                    let project = workspace.project.read(cx);
 9273                    let path_style = workspace.path_style(cx);
 9274                    Some(!abs_paths.iter().any(|path| {
 9275                        let path = util::paths::SanitizedPath::new(path);
 9276                        project.worktrees(cx).any(|worktree| {
 9277                            let worktree = worktree.read(cx);
 9278                            let abs_path = worktree.abs_path();
 9279                            path_style
 9280                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9281                                .and_then(|rel| worktree.entry_for_path(&rel))
 9282                                .is_some_and(|e| e.is_dir())
 9283                        })
 9284                    }))
 9285                })
 9286            })
 9287            .unwrap_or(false);
 9288
 9289        if open_options.open_new_workspace.is_none()
 9290            && existing.is_some()
 9291            && open_options.wait
 9292            && all_paths_are_files
 9293        {
 9294            cx.update(|cx| {
 9295                let windows = workspace_windows_for_location(location, cx);
 9296                let window = cx
 9297                    .active_window()
 9298                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9299                    .filter(|window| windows.contains(window))
 9300                    .or_else(|| windows.into_iter().next());
 9301                if let Some(window) = window {
 9302                    if let Ok(multi_workspace) = window.read(cx) {
 9303                        let active_workspace = multi_workspace.workspace().clone();
 9304                        existing = Some((window, active_workspace));
 9305                        open_visible = OpenVisible::None;
 9306                    }
 9307                }
 9308            });
 9309        }
 9310    }
 9311    (existing, open_visible)
 9312}
 9313
 9314#[derive(Default, Clone)]
 9315pub struct OpenOptions {
 9316    pub visible: Option<OpenVisible>,
 9317    pub focus: Option<bool>,
 9318    pub open_new_workspace: Option<bool>,
 9319    pub wait: bool,
 9320    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9321    pub open_mode: OpenMode,
 9322    pub env: Option<HashMap<String, String>>,
 9323    pub open_in_dev_container: bool,
 9324}
 9325
 9326/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9327/// or [`Workspace::open_workspace_for_paths`].
 9328pub struct OpenResult {
 9329    pub window: WindowHandle<MultiWorkspace>,
 9330    pub workspace: Entity<Workspace>,
 9331    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9332}
 9333
 9334/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9335pub fn open_workspace_by_id(
 9336    workspace_id: WorkspaceId,
 9337    app_state: Arc<AppState>,
 9338    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9339    cx: &mut App,
 9340) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9341    let project_handle = Project::local(
 9342        app_state.client.clone(),
 9343        app_state.node_runtime.clone(),
 9344        app_state.user_store.clone(),
 9345        app_state.languages.clone(),
 9346        app_state.fs.clone(),
 9347        None,
 9348        project::LocalProjectFlags {
 9349            init_worktree_trust: true,
 9350            ..project::LocalProjectFlags::default()
 9351        },
 9352        cx,
 9353    );
 9354
 9355    let db = WorkspaceDb::global(cx);
 9356    let kvp = db::kvp::KeyValueStore::global(cx);
 9357    cx.spawn(async move |cx| {
 9358        let serialized_workspace = db
 9359            .workspace_for_id(workspace_id)
 9360            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9361
 9362        let centered_layout = serialized_workspace.centered_layout;
 9363
 9364        let (window, workspace) = if let Some(window) = requesting_window {
 9365            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9366                let workspace = cx.new(|cx| {
 9367                    let mut workspace = Workspace::new(
 9368                        Some(workspace_id),
 9369                        project_handle.clone(),
 9370                        app_state.clone(),
 9371                        window,
 9372                        cx,
 9373                    );
 9374                    workspace.centered_layout = centered_layout;
 9375                    workspace
 9376                });
 9377                multi_workspace.add(workspace.clone(), &*window, cx);
 9378                workspace
 9379            })?;
 9380            (window, workspace)
 9381        } else {
 9382            let window_bounds_override = window_bounds_env_override();
 9383
 9384            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9385                (Some(WindowBounds::Windowed(bounds)), None)
 9386            } else if let Some(display) = serialized_workspace.display
 9387                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9388            {
 9389                (Some(bounds.0), Some(display))
 9390            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9391                (Some(bounds), Some(display))
 9392            } else {
 9393                (None, None)
 9394            };
 9395
 9396            let options = cx.update(|cx| {
 9397                let mut options = (app_state.build_window_options)(display, cx);
 9398                options.window_bounds = window_bounds;
 9399                options
 9400            });
 9401
 9402            let window = cx.open_window(options, {
 9403                let app_state = app_state.clone();
 9404                let project_handle = project_handle.clone();
 9405                move |window, cx| {
 9406                    let workspace = cx.new(|cx| {
 9407                        let mut workspace = Workspace::new(
 9408                            Some(workspace_id),
 9409                            project_handle,
 9410                            app_state,
 9411                            window,
 9412                            cx,
 9413                        );
 9414                        workspace.centered_layout = centered_layout;
 9415                        workspace
 9416                    });
 9417                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9418                }
 9419            })?;
 9420
 9421            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9422                multi_workspace.workspace().clone()
 9423            })?;
 9424
 9425            (window, workspace)
 9426        };
 9427
 9428        notify_if_database_failed(window, cx);
 9429
 9430        // Restore items from the serialized workspace
 9431        window
 9432            .update(cx, |_, window, cx| {
 9433                workspace.update(cx, |_workspace, cx| {
 9434                    open_items(Some(serialized_workspace), vec![], window, cx)
 9435                })
 9436            })?
 9437            .await?;
 9438
 9439        window.update(cx, |_, window, cx| {
 9440            workspace.update(cx, |workspace, cx| {
 9441                workspace.serialize_workspace(window, cx);
 9442            });
 9443        })?;
 9444
 9445        Ok(window)
 9446    })
 9447}
 9448
 9449#[allow(clippy::type_complexity)]
 9450pub fn open_paths(
 9451    abs_paths: &[PathBuf],
 9452    app_state: Arc<AppState>,
 9453    mut open_options: OpenOptions,
 9454    cx: &mut App,
 9455) -> Task<anyhow::Result<OpenResult>> {
 9456    let abs_paths = abs_paths.to_vec();
 9457    #[cfg(target_os = "windows")]
 9458    let wsl_path = abs_paths
 9459        .iter()
 9460        .find_map(|p| util::paths::WslPath::from_path(p));
 9461
 9462    cx.spawn(async move |cx| {
 9463        let (mut existing, mut open_visible) = find_existing_workspace(
 9464            &abs_paths,
 9465            &open_options,
 9466            &SerializedWorkspaceLocation::Local,
 9467            cx,
 9468        )
 9469        .await;
 9470
 9471        // Fallback: if no workspace contains the paths and all paths are files,
 9472        // prefer an existing local workspace window (active window first).
 9473        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9474            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9475            let all_metadatas = futures::future::join_all(all_paths)
 9476                .await
 9477                .into_iter()
 9478                .filter_map(|result| result.ok().flatten());
 9479
 9480            if all_metadatas.into_iter().all(|file| !file.is_dir) {
 9481                cx.update(|cx| {
 9482                    let windows = workspace_windows_for_location(
 9483                        &SerializedWorkspaceLocation::Local,
 9484                        cx,
 9485                    );
 9486                    let window = cx
 9487                        .active_window()
 9488                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9489                        .filter(|window| windows.contains(window))
 9490                        .or_else(|| windows.into_iter().next());
 9491                    if let Some(window) = window {
 9492                        if let Ok(multi_workspace) = window.read(cx) {
 9493                            let active_workspace = multi_workspace.workspace().clone();
 9494                            existing = Some((window, active_workspace));
 9495                            open_visible = OpenVisible::None;
 9496                        }
 9497                    }
 9498                });
 9499            }
 9500        }
 9501
 9502        // Fallback for directories: when no flag is specified and no existing
 9503        // workspace matched, add the directory as a new workspace in the
 9504        // active window's MultiWorkspace (instead of opening a new window).
 9505        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9506            let target_window = cx.update(|cx| {
 9507                let windows = workspace_windows_for_location(
 9508                    &SerializedWorkspaceLocation::Local,
 9509                    cx,
 9510                );
 9511                let window = cx
 9512                    .active_window()
 9513                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9514                    .filter(|window| windows.contains(window))
 9515                    .or_else(|| windows.into_iter().next());
 9516                window.filter(|window| {
 9517                    window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
 9518                })
 9519            });
 9520
 9521            if let Some(window) = target_window {
 9522                open_options.requesting_window = Some(window);
 9523                window
 9524                    .update(cx, |multi_workspace, _, cx| {
 9525                        multi_workspace.open_sidebar(cx);
 9526                    })
 9527                    .log_err();
 9528            }
 9529        }
 9530
 9531        let open_in_dev_container = open_options.open_in_dev_container;
 9532
 9533        let result = if let Some((existing, target_workspace)) = existing {
 9534            let open_task = existing
 9535                .update(cx, |multi_workspace, window, cx| {
 9536                    window.activate_window();
 9537                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9538                    target_workspace.update(cx, |workspace, cx| {
 9539                        if open_in_dev_container {
 9540                            workspace.set_open_in_dev_container(true);
 9541                        }
 9542                        workspace.open_paths(
 9543                            abs_paths,
 9544                            OpenOptions {
 9545                                visible: Some(open_visible),
 9546                                ..Default::default()
 9547                            },
 9548                            None,
 9549                            window,
 9550                            cx,
 9551                        )
 9552                    })
 9553                })?
 9554                .await;
 9555
 9556            _ = existing.update(cx, |multi_workspace, _, cx| {
 9557                let workspace = multi_workspace.workspace().clone();
 9558                workspace.update(cx, |workspace, cx| {
 9559                    for item in open_task.iter().flatten() {
 9560                        if let Err(e) = item {
 9561                            workspace.show_error(&e, cx);
 9562                        }
 9563                    }
 9564                });
 9565            });
 9566
 9567            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9568        } else {
 9569            let init = if open_in_dev_container {
 9570                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9571                    workspace.set_open_in_dev_container(true);
 9572                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9573            } else {
 9574                None
 9575            };
 9576            let result = cx
 9577                .update(move |cx| {
 9578                    Workspace::new_local(
 9579                        abs_paths,
 9580                        app_state.clone(),
 9581                        open_options.requesting_window,
 9582                        open_options.env,
 9583                        init,
 9584                        open_options.open_mode,
 9585                        cx,
 9586                    )
 9587                })
 9588                .await;
 9589
 9590            if let Ok(ref result) = result {
 9591                result.window
 9592                    .update(cx, |_, window, _cx| {
 9593                        window.activate_window();
 9594                    })
 9595                    .log_err();
 9596            }
 9597
 9598            result
 9599        };
 9600
 9601        #[cfg(target_os = "windows")]
 9602        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9603            && let Ok(ref result) = result
 9604        {
 9605            result.window
 9606                .update(cx, move |multi_workspace, _window, cx| {
 9607                    struct OpenInWsl;
 9608                    let workspace = multi_workspace.workspace().clone();
 9609                    workspace.update(cx, |workspace, cx| {
 9610                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9611                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9612                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9613                            cx.new(move |cx| {
 9614                                MessageNotification::new(msg, cx)
 9615                                    .primary_message("Open in WSL")
 9616                                    .primary_icon(IconName::FolderOpen)
 9617                                    .primary_on_click(move |window, cx| {
 9618                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9619                                                distro: remote::WslConnectionOptions {
 9620                                                        distro_name: distro.clone(),
 9621                                                    user: None,
 9622                                                },
 9623                                                paths: vec![path.clone().into()],
 9624                                            }), cx)
 9625                                    })
 9626                            })
 9627                        });
 9628                    });
 9629                })
 9630                .unwrap();
 9631        };
 9632        result
 9633    })
 9634}
 9635
 9636pub fn open_new(
 9637    open_options: OpenOptions,
 9638    app_state: Arc<AppState>,
 9639    cx: &mut App,
 9640    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9641) -> Task<anyhow::Result<()>> {
 9642    let addition = open_options.open_mode;
 9643    let task = Workspace::new_local(
 9644        Vec::new(),
 9645        app_state,
 9646        open_options.requesting_window,
 9647        open_options.env,
 9648        Some(Box::new(init)),
 9649        addition,
 9650        cx,
 9651    );
 9652    cx.spawn(async move |cx| {
 9653        let OpenResult { window, .. } = task.await?;
 9654        window
 9655            .update(cx, |_, window, _cx| {
 9656                window.activate_window();
 9657            })
 9658            .ok();
 9659        Ok(())
 9660    })
 9661}
 9662
 9663pub fn create_and_open_local_file(
 9664    path: &'static Path,
 9665    window: &mut Window,
 9666    cx: &mut Context<Workspace>,
 9667    default_content: impl 'static + Send + FnOnce() -> Rope,
 9668) -> Task<Result<Box<dyn ItemHandle>>> {
 9669    cx.spawn_in(window, async move |workspace, cx| {
 9670        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9671        if !fs.is_file(path).await {
 9672            fs.create_file(path, Default::default()).await?;
 9673            fs.save(path, &default_content(), Default::default())
 9674                .await?;
 9675        }
 9676
 9677        workspace
 9678            .update_in(cx, |workspace, window, cx| {
 9679                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9680                    let path = workspace
 9681                        .project
 9682                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9683                    cx.spawn_in(window, async move |workspace, cx| {
 9684                        let path = path.await?;
 9685
 9686                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9687
 9688                        let mut items = workspace
 9689                            .update_in(cx, |workspace, window, cx| {
 9690                                workspace.open_paths(
 9691                                    vec![path.to_path_buf()],
 9692                                    OpenOptions {
 9693                                        visible: Some(OpenVisible::None),
 9694                                        ..Default::default()
 9695                                    },
 9696                                    None,
 9697                                    window,
 9698                                    cx,
 9699                                )
 9700                            })?
 9701                            .await;
 9702                        let item = items.pop().flatten();
 9703                        item.with_context(|| format!("path {path:?} is not a file"))?
 9704                    })
 9705                })
 9706            })?
 9707            .await?
 9708            .await
 9709    })
 9710}
 9711
 9712pub fn open_remote_project_with_new_connection(
 9713    window: WindowHandle<MultiWorkspace>,
 9714    remote_connection: Arc<dyn RemoteConnection>,
 9715    cancel_rx: oneshot::Receiver<()>,
 9716    delegate: Arc<dyn RemoteClientDelegate>,
 9717    app_state: Arc<AppState>,
 9718    paths: Vec<PathBuf>,
 9719    cx: &mut App,
 9720) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9721    cx.spawn(async move |cx| {
 9722        let (workspace_id, serialized_workspace) =
 9723            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9724                .await?;
 9725
 9726        let session = match cx
 9727            .update(|cx| {
 9728                remote::RemoteClient::new(
 9729                    ConnectionIdentifier::Workspace(workspace_id.0),
 9730                    remote_connection,
 9731                    cancel_rx,
 9732                    delegate,
 9733                    cx,
 9734                )
 9735            })
 9736            .await?
 9737        {
 9738            Some(result) => result,
 9739            None => return Ok(Vec::new()),
 9740        };
 9741
 9742        let project = cx.update(|cx| {
 9743            project::Project::remote(
 9744                session,
 9745                app_state.client.clone(),
 9746                app_state.node_runtime.clone(),
 9747                app_state.user_store.clone(),
 9748                app_state.languages.clone(),
 9749                app_state.fs.clone(),
 9750                true,
 9751                cx,
 9752            )
 9753        });
 9754
 9755        open_remote_project_inner(
 9756            project,
 9757            paths,
 9758            workspace_id,
 9759            serialized_workspace,
 9760            app_state,
 9761            window,
 9762            cx,
 9763        )
 9764        .await
 9765    })
 9766}
 9767
 9768pub fn open_remote_project_with_existing_connection(
 9769    connection_options: RemoteConnectionOptions,
 9770    project: Entity<Project>,
 9771    paths: Vec<PathBuf>,
 9772    app_state: Arc<AppState>,
 9773    window: WindowHandle<MultiWorkspace>,
 9774    cx: &mut AsyncApp,
 9775) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9776    cx.spawn(async move |cx| {
 9777        let (workspace_id, serialized_workspace) =
 9778            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9779
 9780        open_remote_project_inner(
 9781            project,
 9782            paths,
 9783            workspace_id,
 9784            serialized_workspace,
 9785            app_state,
 9786            window,
 9787            cx,
 9788        )
 9789        .await
 9790    })
 9791}
 9792
 9793async fn open_remote_project_inner(
 9794    project: Entity<Project>,
 9795    paths: Vec<PathBuf>,
 9796    workspace_id: WorkspaceId,
 9797    serialized_workspace: Option<SerializedWorkspace>,
 9798    app_state: Arc<AppState>,
 9799    window: WindowHandle<MultiWorkspace>,
 9800    cx: &mut AsyncApp,
 9801) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9802    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9803    let toolchains = db.toolchains(workspace_id).await?;
 9804    for (toolchain, worktree_path, path) in toolchains {
 9805        project
 9806            .update(cx, |this, cx| {
 9807                let Some(worktree_id) =
 9808                    this.find_worktree(&worktree_path, cx)
 9809                        .and_then(|(worktree, rel_path)| {
 9810                            if rel_path.is_empty() {
 9811                                Some(worktree.read(cx).id())
 9812                            } else {
 9813                                None
 9814                            }
 9815                        })
 9816                else {
 9817                    return Task::ready(None);
 9818                };
 9819
 9820                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9821            })
 9822            .await;
 9823    }
 9824    let mut project_paths_to_open = vec![];
 9825    let mut project_path_errors = vec![];
 9826
 9827    for path in paths {
 9828        let result = cx
 9829            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9830            .await;
 9831        match result {
 9832            Ok((_, project_path)) => {
 9833                project_paths_to_open.push((path.clone(), Some(project_path)));
 9834            }
 9835            Err(error) => {
 9836                project_path_errors.push(error);
 9837            }
 9838        };
 9839    }
 9840
 9841    if project_paths_to_open.is_empty() {
 9842        return Err(project_path_errors.pop().context("no paths given")?);
 9843    }
 9844
 9845    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9846        telemetry::event!("SSH Project Opened");
 9847
 9848        let new_workspace = cx.new(|cx| {
 9849            let mut workspace =
 9850                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9851            workspace.update_history(cx);
 9852
 9853            if let Some(ref serialized) = serialized_workspace {
 9854                workspace.centered_layout = serialized.centered_layout;
 9855            }
 9856
 9857            workspace
 9858        });
 9859
 9860        multi_workspace.activate(new_workspace.clone(), window, cx);
 9861        new_workspace
 9862    })?;
 9863
 9864    let items = window
 9865        .update(cx, |_, window, cx| {
 9866            window.activate_window();
 9867            workspace.update(cx, |_workspace, cx| {
 9868                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9869            })
 9870        })?
 9871        .await?;
 9872
 9873    workspace.update(cx, |workspace, cx| {
 9874        for error in project_path_errors {
 9875            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9876                if let Some(path) = error.error_tag("path") {
 9877                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9878                }
 9879            } else {
 9880                workspace.show_error(&error, cx)
 9881            }
 9882        }
 9883    });
 9884
 9885    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9886}
 9887
 9888fn deserialize_remote_project(
 9889    connection_options: RemoteConnectionOptions,
 9890    paths: Vec<PathBuf>,
 9891    cx: &AsyncApp,
 9892) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9893    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9894    cx.background_spawn(async move {
 9895        let remote_connection_id = db
 9896            .get_or_create_remote_connection(connection_options)
 9897            .await?;
 9898
 9899        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9900
 9901        let workspace_id = if let Some(workspace_id) =
 9902            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9903        {
 9904            workspace_id
 9905        } else {
 9906            db.next_id().await?
 9907        };
 9908
 9909        Ok((workspace_id, serialized_workspace))
 9910    })
 9911}
 9912
 9913pub fn join_in_room_project(
 9914    project_id: u64,
 9915    follow_user_id: u64,
 9916    app_state: Arc<AppState>,
 9917    cx: &mut App,
 9918) -> Task<Result<()>> {
 9919    let windows = cx.windows();
 9920    cx.spawn(async move |cx| {
 9921        let existing_window_and_workspace: Option<(
 9922            WindowHandle<MultiWorkspace>,
 9923            Entity<Workspace>,
 9924        )> = windows.into_iter().find_map(|window_handle| {
 9925            window_handle
 9926                .downcast::<MultiWorkspace>()
 9927                .and_then(|window_handle| {
 9928                    window_handle
 9929                        .update(cx, |multi_workspace, _window, cx| {
 9930                            for workspace in multi_workspace.workspaces() {
 9931                                if workspace.read(cx).project().read(cx).remote_id()
 9932                                    == Some(project_id)
 9933                                {
 9934                                    return Some((window_handle, workspace.clone()));
 9935                                }
 9936                            }
 9937                            None
 9938                        })
 9939                        .unwrap_or(None)
 9940                })
 9941        });
 9942
 9943        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9944            existing_window_and_workspace
 9945        {
 9946            existing_window
 9947                .update(cx, |multi_workspace, window, cx| {
 9948                    multi_workspace.activate(target_workspace, window, cx);
 9949                })
 9950                .ok();
 9951            existing_window
 9952        } else {
 9953            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9954            let project = cx
 9955                .update(|cx| {
 9956                    active_call.0.join_project(
 9957                        project_id,
 9958                        app_state.languages.clone(),
 9959                        app_state.fs.clone(),
 9960                        cx,
 9961                    )
 9962                })
 9963                .await?;
 9964
 9965            let window_bounds_override = window_bounds_env_override();
 9966            cx.update(|cx| {
 9967                let mut options = (app_state.build_window_options)(None, cx);
 9968                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9969                cx.open_window(options, |window, cx| {
 9970                    let workspace = cx.new(|cx| {
 9971                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9972                    });
 9973                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9974                })
 9975            })?
 9976        };
 9977
 9978        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9979            cx.activate(true);
 9980            window.activate_window();
 9981
 9982            // We set the active workspace above, so this is the correct workspace.
 9983            let workspace = multi_workspace.workspace().clone();
 9984            workspace.update(cx, |workspace, cx| {
 9985                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9986                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9987                    .or_else(|| {
 9988                        // If we couldn't follow the given user, follow the host instead.
 9989                        let collaborator = workspace
 9990                            .project()
 9991                            .read(cx)
 9992                            .collaborators()
 9993                            .values()
 9994                            .find(|collaborator| collaborator.is_host)?;
 9995                        Some(collaborator.peer_id)
 9996                    });
 9997
 9998                if let Some(follow_peer_id) = follow_peer_id {
 9999                    workspace.follow(follow_peer_id, window, cx);
10000                }
10001            });
10002        })?;
10003
10004        anyhow::Ok(())
10005    })
10006}
10007
10008pub fn reload(cx: &mut App) {
10009    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10010    let mut workspace_windows = cx
10011        .windows()
10012        .into_iter()
10013        .filter_map(|window| window.downcast::<MultiWorkspace>())
10014        .collect::<Vec<_>>();
10015
10016    // If multiple windows have unsaved changes, and need a save prompt,
10017    // prompt in the active window before switching to a different window.
10018    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10019
10020    let mut prompt = None;
10021    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10022        prompt = window
10023            .update(cx, |_, window, cx| {
10024                window.prompt(
10025                    PromptLevel::Info,
10026                    "Are you sure you want to restart?",
10027                    None,
10028                    &["Restart", "Cancel"],
10029                    cx,
10030                )
10031            })
10032            .ok();
10033    }
10034
10035    cx.spawn(async move |cx| {
10036        if let Some(prompt) = prompt {
10037            let answer = prompt.await?;
10038            if answer != 0 {
10039                return anyhow::Ok(());
10040            }
10041        }
10042
10043        // If the user cancels any save prompt, then keep the app open.
10044        for window in workspace_windows {
10045            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10046                let workspace = multi_workspace.workspace().clone();
10047                workspace.update(cx, |workspace, cx| {
10048                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10049                })
10050            }) && !should_close.await?
10051            {
10052                return anyhow::Ok(());
10053            }
10054        }
10055        cx.update(|cx| cx.restart());
10056        anyhow::Ok(())
10057    })
10058    .detach_and_log_err(cx);
10059}
10060
10061fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10062    let mut parts = value.split(',');
10063    let x: usize = parts.next()?.parse().ok()?;
10064    let y: usize = parts.next()?.parse().ok()?;
10065    Some(point(px(x as f32), px(y as f32)))
10066}
10067
10068fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10069    let mut parts = value.split(',');
10070    let width: usize = parts.next()?.parse().ok()?;
10071    let height: usize = parts.next()?.parse().ok()?;
10072    Some(size(px(width as f32), px(height as f32)))
10073}
10074
10075/// Add client-side decorations (rounded corners, shadows, resize handling) when
10076/// appropriate.
10077///
10078/// The `border_radius_tiling` parameter allows overriding which corners get
10079/// rounded, independently of the actual window tiling state. This is used
10080/// specifically for the workspace switcher sidebar: when the sidebar is open,
10081/// we want square corners on the left (so the sidebar appears flush with the
10082/// window edge) but we still need the shadow padding for proper visual
10083/// appearance. Unlike actual window tiling, this only affects border radius -
10084/// not padding or shadows.
10085pub fn client_side_decorations(
10086    element: impl IntoElement,
10087    window: &mut Window,
10088    cx: &mut App,
10089    border_radius_tiling: Tiling,
10090) -> Stateful<Div> {
10091    const BORDER_SIZE: Pixels = px(1.0);
10092    let decorations = window.window_decorations();
10093    let tiling = match decorations {
10094        Decorations::Server => Tiling::default(),
10095        Decorations::Client { tiling } => tiling,
10096    };
10097
10098    match decorations {
10099        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10100        Decorations::Server => window.set_client_inset(px(0.0)),
10101    }
10102
10103    struct GlobalResizeEdge(ResizeEdge);
10104    impl Global for GlobalResizeEdge {}
10105
10106    div()
10107        .id("window-backdrop")
10108        .bg(transparent_black())
10109        .map(|div| match decorations {
10110            Decorations::Server => div,
10111            Decorations::Client { .. } => div
10112                .when(
10113                    !(tiling.top
10114                        || tiling.right
10115                        || border_radius_tiling.top
10116                        || border_radius_tiling.right),
10117                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10118                )
10119                .when(
10120                    !(tiling.top
10121                        || tiling.left
10122                        || border_radius_tiling.top
10123                        || border_radius_tiling.left),
10124                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10125                )
10126                .when(
10127                    !(tiling.bottom
10128                        || tiling.right
10129                        || border_radius_tiling.bottom
10130                        || border_radius_tiling.right),
10131                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10132                )
10133                .when(
10134                    !(tiling.bottom
10135                        || tiling.left
10136                        || border_radius_tiling.bottom
10137                        || border_radius_tiling.left),
10138                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10139                )
10140                .when(!tiling.top, |div| {
10141                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10142                })
10143                .when(!tiling.bottom, |div| {
10144                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10145                })
10146                .when(!tiling.left, |div| {
10147                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10148                })
10149                .when(!tiling.right, |div| {
10150                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10151                })
10152                .on_mouse_move(move |e, window, cx| {
10153                    let size = window.window_bounds().get_bounds().size;
10154                    let pos = e.position;
10155
10156                    let new_edge =
10157                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10158
10159                    let edge = cx.try_global::<GlobalResizeEdge>();
10160                    if new_edge != edge.map(|edge| edge.0) {
10161                        window
10162                            .window_handle()
10163                            .update(cx, |workspace, _, cx| {
10164                                cx.notify(workspace.entity_id());
10165                            })
10166                            .ok();
10167                    }
10168                })
10169                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10170                    let size = window.window_bounds().get_bounds().size;
10171                    let pos = e.position;
10172
10173                    let edge = match resize_edge(
10174                        pos,
10175                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10176                        size,
10177                        tiling,
10178                    ) {
10179                        Some(value) => value,
10180                        None => return,
10181                    };
10182
10183                    window.start_window_resize(edge);
10184                }),
10185        })
10186        .size_full()
10187        .child(
10188            div()
10189                .cursor(CursorStyle::Arrow)
10190                .map(|div| match decorations {
10191                    Decorations::Server => div,
10192                    Decorations::Client { .. } => div
10193                        .border_color(cx.theme().colors().border)
10194                        .when(
10195                            !(tiling.top
10196                                || tiling.right
10197                                || border_radius_tiling.top
10198                                || border_radius_tiling.right),
10199                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10200                        )
10201                        .when(
10202                            !(tiling.top
10203                                || tiling.left
10204                                || border_radius_tiling.top
10205                                || border_radius_tiling.left),
10206                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10207                        )
10208                        .when(
10209                            !(tiling.bottom
10210                                || tiling.right
10211                                || border_radius_tiling.bottom
10212                                || border_radius_tiling.right),
10213                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10214                        )
10215                        .when(
10216                            !(tiling.bottom
10217                                || tiling.left
10218                                || border_radius_tiling.bottom
10219                                || border_radius_tiling.left),
10220                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10221                        )
10222                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10223                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10224                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10225                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10226                        .when(!tiling.is_tiled(), |div| {
10227                            div.shadow(vec![gpui::BoxShadow {
10228                                color: Hsla {
10229                                    h: 0.,
10230                                    s: 0.,
10231                                    l: 0.,
10232                                    a: 0.4,
10233                                },
10234                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10235                                spread_radius: px(0.),
10236                                offset: point(px(0.0), px(0.0)),
10237                            }])
10238                        }),
10239                })
10240                .on_mouse_move(|_e, _, cx| {
10241                    cx.stop_propagation();
10242                })
10243                .size_full()
10244                .child(element),
10245        )
10246        .map(|div| match decorations {
10247            Decorations::Server => div,
10248            Decorations::Client { tiling, .. } => div.child(
10249                canvas(
10250                    |_bounds, window, _| {
10251                        window.insert_hitbox(
10252                            Bounds::new(
10253                                point(px(0.0), px(0.0)),
10254                                window.window_bounds().get_bounds().size,
10255                            ),
10256                            HitboxBehavior::Normal,
10257                        )
10258                    },
10259                    move |_bounds, hitbox, window, cx| {
10260                        let mouse = window.mouse_position();
10261                        let size = window.window_bounds().get_bounds().size;
10262                        let Some(edge) =
10263                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10264                        else {
10265                            return;
10266                        };
10267                        cx.set_global(GlobalResizeEdge(edge));
10268                        window.set_cursor_style(
10269                            match edge {
10270                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10271                                ResizeEdge::Left | ResizeEdge::Right => {
10272                                    CursorStyle::ResizeLeftRight
10273                                }
10274                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10275                                    CursorStyle::ResizeUpLeftDownRight
10276                                }
10277                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10278                                    CursorStyle::ResizeUpRightDownLeft
10279                                }
10280                            },
10281                            &hitbox,
10282                        );
10283                    },
10284                )
10285                .size_full()
10286                .absolute(),
10287            ),
10288        })
10289}
10290
10291fn resize_edge(
10292    pos: Point<Pixels>,
10293    shadow_size: Pixels,
10294    window_size: Size<Pixels>,
10295    tiling: Tiling,
10296) -> Option<ResizeEdge> {
10297    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10298    if bounds.contains(&pos) {
10299        return None;
10300    }
10301
10302    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10303    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10304    if !tiling.top && top_left_bounds.contains(&pos) {
10305        return Some(ResizeEdge::TopLeft);
10306    }
10307
10308    let top_right_bounds = Bounds::new(
10309        Point::new(window_size.width - corner_size.width, px(0.)),
10310        corner_size,
10311    );
10312    if !tiling.top && top_right_bounds.contains(&pos) {
10313        return Some(ResizeEdge::TopRight);
10314    }
10315
10316    let bottom_left_bounds = Bounds::new(
10317        Point::new(px(0.), window_size.height - corner_size.height),
10318        corner_size,
10319    );
10320    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10321        return Some(ResizeEdge::BottomLeft);
10322    }
10323
10324    let bottom_right_bounds = Bounds::new(
10325        Point::new(
10326            window_size.width - corner_size.width,
10327            window_size.height - corner_size.height,
10328        ),
10329        corner_size,
10330    );
10331    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10332        return Some(ResizeEdge::BottomRight);
10333    }
10334
10335    if !tiling.top && pos.y < shadow_size {
10336        Some(ResizeEdge::Top)
10337    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10338        Some(ResizeEdge::Bottom)
10339    } else if !tiling.left && pos.x < shadow_size {
10340        Some(ResizeEdge::Left)
10341    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10342        Some(ResizeEdge::Right)
10343    } else {
10344        None
10345    }
10346}
10347
10348fn join_pane_into_active(
10349    active_pane: &Entity<Pane>,
10350    pane: &Entity<Pane>,
10351    window: &mut Window,
10352    cx: &mut App,
10353) {
10354    if pane == active_pane {
10355    } else if pane.read(cx).items_len() == 0 {
10356        pane.update(cx, |_, cx| {
10357            cx.emit(pane::Event::Remove {
10358                focus_on_pane: None,
10359            });
10360        })
10361    } else {
10362        move_all_items(pane, active_pane, window, cx);
10363    }
10364}
10365
10366fn move_all_items(
10367    from_pane: &Entity<Pane>,
10368    to_pane: &Entity<Pane>,
10369    window: &mut Window,
10370    cx: &mut App,
10371) {
10372    let destination_is_different = from_pane != to_pane;
10373    let mut moved_items = 0;
10374    for (item_ix, item_handle) in from_pane
10375        .read(cx)
10376        .items()
10377        .enumerate()
10378        .map(|(ix, item)| (ix, item.clone()))
10379        .collect::<Vec<_>>()
10380    {
10381        let ix = item_ix - moved_items;
10382        if destination_is_different {
10383            // Close item from previous pane
10384            from_pane.update(cx, |source, cx| {
10385                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10386            });
10387            moved_items += 1;
10388        }
10389
10390        // This automatically removes duplicate items in the pane
10391        to_pane.update(cx, |destination, cx| {
10392            destination.add_item(item_handle, true, true, None, window, cx);
10393            window.focus(&destination.focus_handle(cx), cx)
10394        });
10395    }
10396}
10397
10398pub fn move_item(
10399    source: &Entity<Pane>,
10400    destination: &Entity<Pane>,
10401    item_id_to_move: EntityId,
10402    destination_index: usize,
10403    activate: bool,
10404    window: &mut Window,
10405    cx: &mut App,
10406) {
10407    let Some((item_ix, item_handle)) = source
10408        .read(cx)
10409        .items()
10410        .enumerate()
10411        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10412        .map(|(ix, item)| (ix, item.clone()))
10413    else {
10414        // Tab was closed during drag
10415        return;
10416    };
10417
10418    if source != destination {
10419        // Close item from previous pane
10420        source.update(cx, |source, cx| {
10421            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10422        });
10423    }
10424
10425    // This automatically removes duplicate items in the pane
10426    destination.update(cx, |destination, cx| {
10427        destination.add_item_inner(
10428            item_handle,
10429            activate,
10430            activate,
10431            activate,
10432            Some(destination_index),
10433            window,
10434            cx,
10435        );
10436        if activate {
10437            window.focus(&destination.focus_handle(cx), cx)
10438        }
10439    });
10440}
10441
10442pub fn move_active_item(
10443    source: &Entity<Pane>,
10444    destination: &Entity<Pane>,
10445    focus_destination: bool,
10446    close_if_empty: bool,
10447    window: &mut Window,
10448    cx: &mut App,
10449) {
10450    if source == destination {
10451        return;
10452    }
10453    let Some(active_item) = source.read(cx).active_item() else {
10454        return;
10455    };
10456    source.update(cx, |source_pane, cx| {
10457        let item_id = active_item.item_id();
10458        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10459        destination.update(cx, |target_pane, cx| {
10460            target_pane.add_item(
10461                active_item,
10462                focus_destination,
10463                focus_destination,
10464                Some(target_pane.items_len()),
10465                window,
10466                cx,
10467            );
10468        });
10469    });
10470}
10471
10472pub fn clone_active_item(
10473    workspace_id: Option<WorkspaceId>,
10474    source: &Entity<Pane>,
10475    destination: &Entity<Pane>,
10476    focus_destination: bool,
10477    window: &mut Window,
10478    cx: &mut App,
10479) {
10480    if source == destination {
10481        return;
10482    }
10483    let Some(active_item) = source.read(cx).active_item() else {
10484        return;
10485    };
10486    if !active_item.can_split(cx) {
10487        return;
10488    }
10489    let destination = destination.downgrade();
10490    let task = active_item.clone_on_split(workspace_id, window, cx);
10491    window
10492        .spawn(cx, async move |cx| {
10493            let Some(clone) = task.await else {
10494                return;
10495            };
10496            destination
10497                .update_in(cx, |target_pane, window, cx| {
10498                    target_pane.add_item(
10499                        clone,
10500                        focus_destination,
10501                        focus_destination,
10502                        Some(target_pane.items_len()),
10503                        window,
10504                        cx,
10505                    );
10506                })
10507                .log_err();
10508        })
10509        .detach();
10510}
10511
10512#[derive(Debug)]
10513pub struct WorkspacePosition {
10514    pub window_bounds: Option<WindowBounds>,
10515    pub display: Option<Uuid>,
10516    pub centered_layout: bool,
10517}
10518
10519pub fn remote_workspace_position_from_db(
10520    connection_options: RemoteConnectionOptions,
10521    paths_to_open: &[PathBuf],
10522    cx: &App,
10523) -> Task<Result<WorkspacePosition>> {
10524    let paths = paths_to_open.to_vec();
10525    let db = WorkspaceDb::global(cx);
10526    let kvp = db::kvp::KeyValueStore::global(cx);
10527
10528    cx.background_spawn(async move {
10529        let remote_connection_id = db
10530            .get_or_create_remote_connection(connection_options)
10531            .await
10532            .context("fetching serialized ssh project")?;
10533        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10534
10535        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10536            (Some(WindowBounds::Windowed(bounds)), None)
10537        } else {
10538            let restorable_bounds = serialized_workspace
10539                .as_ref()
10540                .and_then(|workspace| {
10541                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10542                })
10543                .or_else(|| persistence::read_default_window_bounds(&kvp));
10544
10545            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10546                (Some(serialized_bounds), Some(serialized_display))
10547            } else {
10548                (None, None)
10549            }
10550        };
10551
10552        let centered_layout = serialized_workspace
10553            .as_ref()
10554            .map(|w| w.centered_layout)
10555            .unwrap_or(false);
10556
10557        Ok(WorkspacePosition {
10558            window_bounds,
10559            display,
10560            centered_layout,
10561        })
10562    })
10563}
10564
10565pub fn with_active_or_new_workspace(
10566    cx: &mut App,
10567    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10568) {
10569    match cx
10570        .active_window()
10571        .and_then(|w| w.downcast::<MultiWorkspace>())
10572    {
10573        Some(multi_workspace) => {
10574            cx.defer(move |cx| {
10575                multi_workspace
10576                    .update(cx, |multi_workspace, window, cx| {
10577                        let workspace = multi_workspace.workspace().clone();
10578                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10579                    })
10580                    .log_err();
10581            });
10582        }
10583        None => {
10584            let app_state = AppState::global(cx);
10585            open_new(
10586                OpenOptions::default(),
10587                app_state,
10588                cx,
10589                move |workspace, window, cx| f(workspace, window, cx),
10590            )
10591            .detach_and_log_err(cx);
10592        }
10593    }
10594}
10595
10596/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10597/// key. This migration path only runs once per panel per workspace.
10598fn load_legacy_panel_size(
10599    panel_key: &str,
10600    dock_position: DockPosition,
10601    workspace: &Workspace,
10602    cx: &mut App,
10603) -> Option<Pixels> {
10604    #[derive(Deserialize)]
10605    struct LegacyPanelState {
10606        #[serde(default)]
10607        width: Option<Pixels>,
10608        #[serde(default)]
10609        height: Option<Pixels>,
10610    }
10611
10612    let workspace_id = workspace
10613        .database_id()
10614        .map(|id| i64::from(id).to_string())
10615        .or_else(|| workspace.session_id())?;
10616
10617    let legacy_key = match panel_key {
10618        "ProjectPanel" => {
10619            format!("{}-{:?}", "ProjectPanel", workspace_id)
10620        }
10621        "OutlinePanel" => {
10622            format!("{}-{:?}", "OutlinePanel", workspace_id)
10623        }
10624        "GitPanel" => {
10625            format!("{}-{:?}", "GitPanel", workspace_id)
10626        }
10627        "TerminalPanel" => {
10628            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10629        }
10630        _ => return None,
10631    };
10632
10633    let kvp = db::kvp::KeyValueStore::global(cx);
10634    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10635    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10636    let size = match dock_position {
10637        DockPosition::Bottom => state.height,
10638        DockPosition::Left | DockPosition::Right => state.width,
10639    }?;
10640
10641    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10642        .detach_and_log_err(cx);
10643
10644    Some(size)
10645}
10646
10647#[cfg(test)]
10648mod tests {
10649    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10650
10651    use super::*;
10652    use crate::{
10653        dock::{PanelEvent, test::TestPanel},
10654        item::{
10655            ItemBufferKind, ItemEvent,
10656            test::{TestItem, TestProjectItem},
10657        },
10658    };
10659    use fs::FakeFs;
10660    use gpui::{
10661        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10662        UpdateGlobal, VisualTestContext, px,
10663    };
10664    use project::{Project, ProjectEntryId};
10665    use serde_json::json;
10666    use settings::SettingsStore;
10667    use util::path;
10668    use util::rel_path::rel_path;
10669
10670    #[gpui::test]
10671    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10672        init_test(cx);
10673
10674        let fs = FakeFs::new(cx.executor());
10675        let project = Project::test(fs, [], cx).await;
10676        let (workspace, cx) =
10677            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10678
10679        // Adding an item with no ambiguity renders the tab without detail.
10680        let item1 = cx.new(|cx| {
10681            let mut item = TestItem::new(cx);
10682            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10683            item
10684        });
10685        workspace.update_in(cx, |workspace, window, cx| {
10686            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10687        });
10688        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10689
10690        // Adding an item that creates ambiguity increases the level of detail on
10691        // both tabs.
10692        let item2 = cx.new_window_entity(|_window, cx| {
10693            let mut item = TestItem::new(cx);
10694            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10695            item
10696        });
10697        workspace.update_in(cx, |workspace, window, cx| {
10698            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10699        });
10700        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10701        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10702
10703        // Adding an item that creates ambiguity increases the level of detail only
10704        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10705        // we stop at the highest detail available.
10706        let item3 = cx.new(|cx| {
10707            let mut item = TestItem::new(cx);
10708            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10709            item
10710        });
10711        workspace.update_in(cx, |workspace, window, cx| {
10712            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10713        });
10714        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10715        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10716        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10717    }
10718
10719    #[gpui::test]
10720    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10721        init_test(cx);
10722
10723        let fs = FakeFs::new(cx.executor());
10724        fs.insert_tree(
10725            "/root1",
10726            json!({
10727                "one.txt": "",
10728                "two.txt": "",
10729            }),
10730        )
10731        .await;
10732        fs.insert_tree(
10733            "/root2",
10734            json!({
10735                "three.txt": "",
10736            }),
10737        )
10738        .await;
10739
10740        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10741        let (workspace, cx) =
10742            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10743        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10744        let worktree_id = project.update(cx, |project, cx| {
10745            project.worktrees(cx).next().unwrap().read(cx).id()
10746        });
10747
10748        let item1 = cx.new(|cx| {
10749            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10750        });
10751        let item2 = cx.new(|cx| {
10752            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10753        });
10754
10755        // Add an item to an empty pane
10756        workspace.update_in(cx, |workspace, window, cx| {
10757            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10758        });
10759        project.update(cx, |project, cx| {
10760            assert_eq!(
10761                project.active_entry(),
10762                project
10763                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10764                    .map(|e| e.id)
10765            );
10766        });
10767        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10768
10769        // Add a second item to a non-empty pane
10770        workspace.update_in(cx, |workspace, window, cx| {
10771            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10772        });
10773        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10774        project.update(cx, |project, cx| {
10775            assert_eq!(
10776                project.active_entry(),
10777                project
10778                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10779                    .map(|e| e.id)
10780            );
10781        });
10782
10783        // Close the active item
10784        pane.update_in(cx, |pane, window, cx| {
10785            pane.close_active_item(&Default::default(), window, cx)
10786        })
10787        .await
10788        .unwrap();
10789        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10790        project.update(cx, |project, cx| {
10791            assert_eq!(
10792                project.active_entry(),
10793                project
10794                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10795                    .map(|e| e.id)
10796            );
10797        });
10798
10799        // Add a project folder
10800        project
10801            .update(cx, |project, cx| {
10802                project.find_or_create_worktree("root2", true, cx)
10803            })
10804            .await
10805            .unwrap();
10806        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10807
10808        // Remove a project folder
10809        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10810        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10811    }
10812
10813    #[gpui::test]
10814    async fn test_close_window(cx: &mut TestAppContext) {
10815        init_test(cx);
10816
10817        let fs = FakeFs::new(cx.executor());
10818        fs.insert_tree("/root", json!({ "one": "" })).await;
10819
10820        let project = Project::test(fs, ["root".as_ref()], cx).await;
10821        let (workspace, cx) =
10822            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10823
10824        // When there are no dirty items, there's nothing to do.
10825        let item1 = cx.new(TestItem::new);
10826        workspace.update_in(cx, |w, window, cx| {
10827            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10828        });
10829        let task = workspace.update_in(cx, |w, window, cx| {
10830            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10831        });
10832        assert!(task.await.unwrap());
10833
10834        // When there are dirty untitled items, prompt to save each one. If the user
10835        // cancels any prompt, then abort.
10836        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10837        let item3 = cx.new(|cx| {
10838            TestItem::new(cx)
10839                .with_dirty(true)
10840                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10841        });
10842        workspace.update_in(cx, |w, window, cx| {
10843            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10844            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10845        });
10846        let task = workspace.update_in(cx, |w, window, cx| {
10847            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10848        });
10849        cx.executor().run_until_parked();
10850        cx.simulate_prompt_answer("Cancel"); // cancel save all
10851        cx.executor().run_until_parked();
10852        assert!(!cx.has_pending_prompt());
10853        assert!(!task.await.unwrap());
10854    }
10855
10856    #[gpui::test]
10857    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10858        init_test(cx);
10859
10860        let fs = FakeFs::new(cx.executor());
10861        fs.insert_tree("/root", json!({ "one": "" })).await;
10862
10863        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10864        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10865        let multi_workspace_handle =
10866            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10867        cx.run_until_parked();
10868
10869        multi_workspace_handle
10870            .update(cx, |mw, _window, cx| {
10871                mw.open_sidebar(cx);
10872            })
10873            .unwrap();
10874
10875        let workspace_a = multi_workspace_handle
10876            .read_with(cx, |mw, _| mw.workspace().clone())
10877            .unwrap();
10878
10879        let workspace_b = multi_workspace_handle
10880            .update(cx, |mw, window, cx| {
10881                mw.test_add_workspace(project_b, window, cx)
10882            })
10883            .unwrap();
10884
10885        // Activate workspace A
10886        multi_workspace_handle
10887            .update(cx, |mw, window, cx| {
10888                let workspace = mw.workspaces().next().unwrap().clone();
10889                mw.activate(workspace, window, cx);
10890            })
10891            .unwrap();
10892
10893        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10894
10895        // Workspace A has a clean item
10896        let item_a = cx.new(TestItem::new);
10897        workspace_a.update_in(cx, |w, window, cx| {
10898            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10899        });
10900
10901        // Workspace B has a dirty item
10902        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10903        workspace_b.update_in(cx, |w, window, cx| {
10904            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10905        });
10906
10907        // Verify workspace A is active
10908        multi_workspace_handle
10909            .read_with(cx, |mw, _| {
10910                assert_eq!(mw.workspace(), &workspace_a);
10911            })
10912            .unwrap();
10913
10914        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10915        multi_workspace_handle
10916            .update(cx, |mw, window, cx| {
10917                mw.close_window(&CloseWindow, window, cx);
10918            })
10919            .unwrap();
10920        cx.run_until_parked();
10921
10922        // Workspace B should now be active since it has dirty items that need attention
10923        multi_workspace_handle
10924            .read_with(cx, |mw, _| {
10925                assert_eq!(
10926                    mw.workspace(),
10927                    &workspace_b,
10928                    "workspace B should be activated when it prompts"
10929                );
10930            })
10931            .unwrap();
10932
10933        // User cancels the save prompt from workspace B
10934        cx.simulate_prompt_answer("Cancel");
10935        cx.run_until_parked();
10936
10937        // Window should still exist because workspace B's close was cancelled
10938        assert!(
10939            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10940            "window should still exist after cancelling one workspace's close"
10941        );
10942    }
10943
10944    #[gpui::test]
10945    async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
10946        init_test(cx);
10947
10948        let fs = FakeFs::new(cx.executor());
10949        fs.insert_tree("/root", json!({ "one": "" })).await;
10950
10951        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10952        let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10953        let multi_workspace_handle =
10954            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10955        cx.run_until_parked();
10956
10957        multi_workspace_handle
10958            .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
10959            .unwrap();
10960
10961        let workspace_a = multi_workspace_handle
10962            .read_with(cx, |mw, _| mw.workspace().clone())
10963            .unwrap();
10964
10965        let workspace_b = multi_workspace_handle
10966            .update(cx, |mw, window, cx| {
10967                mw.test_add_workspace(project_b, window, cx)
10968            })
10969            .unwrap();
10970
10971        // Activate workspace A.
10972        multi_workspace_handle
10973            .update(cx, |mw, window, cx| {
10974                mw.activate(workspace_a.clone(), window, cx);
10975            })
10976            .unwrap();
10977
10978        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10979
10980        // Workspace B has a dirty item.
10981        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10982        workspace_b.update_in(cx, |w, window, cx| {
10983            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10984        });
10985
10986        // Try to remove workspace B. It should prompt because of the dirty item.
10987        let remove_task = multi_workspace_handle
10988            .update(cx, |mw, window, cx| {
10989                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
10990            })
10991            .unwrap();
10992        cx.run_until_parked();
10993
10994        // The prompt should have activated workspace B.
10995        multi_workspace_handle
10996            .read_with(cx, |mw, _| {
10997                assert_eq!(
10998                    mw.workspace(),
10999                    &workspace_b,
11000                    "workspace B should be active while prompting"
11001                );
11002            })
11003            .unwrap();
11004
11005        // Cancel the prompt — user stays on workspace B.
11006        cx.simulate_prompt_answer("Cancel");
11007        cx.run_until_parked();
11008        let removed = remove_task.await.unwrap();
11009        assert!(!removed, "removal should have been cancelled");
11010
11011        multi_workspace_handle
11012            .read_with(cx, |mw, _| {
11013                assert_eq!(
11014                    mw.workspace(),
11015                    &workspace_b,
11016                    "user should stay on workspace B after cancelling"
11017                );
11018                assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11019            })
11020            .unwrap();
11021
11022        // Try again. This time accept the prompt.
11023        let remove_task = multi_workspace_handle
11024            .update(cx, |mw, window, cx| {
11025                // First switch back to A.
11026                mw.activate(workspace_a.clone(), window, cx);
11027                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11028            })
11029            .unwrap();
11030        cx.run_until_parked();
11031
11032        // Accept the save prompt.
11033        cx.simulate_prompt_answer("Don't Save");
11034        cx.run_until_parked();
11035        let removed = remove_task.await.unwrap();
11036        assert!(removed, "removal should have succeeded");
11037
11038        // Should be back on workspace A, and B should be gone.
11039        multi_workspace_handle
11040            .read_with(cx, |mw, _| {
11041                assert_eq!(
11042                    mw.workspace(),
11043                    &workspace_a,
11044                    "should be back on workspace A after removing B"
11045                );
11046                assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11047            })
11048            .unwrap();
11049    }
11050
11051    #[gpui::test]
11052    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11053        init_test(cx);
11054
11055        // Register TestItem as a serializable item
11056        cx.update(|cx| {
11057            register_serializable_item::<TestItem>(cx);
11058        });
11059
11060        let fs = FakeFs::new(cx.executor());
11061        fs.insert_tree("/root", json!({ "one": "" })).await;
11062
11063        let project = Project::test(fs, ["root".as_ref()], cx).await;
11064        let (workspace, cx) =
11065            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11066
11067        // When there are dirty untitled items, but they can serialize, then there is no prompt.
11068        let item1 = cx.new(|cx| {
11069            TestItem::new(cx)
11070                .with_dirty(true)
11071                .with_serialize(|| Some(Task::ready(Ok(()))))
11072        });
11073        let item2 = cx.new(|cx| {
11074            TestItem::new(cx)
11075                .with_dirty(true)
11076                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11077                .with_serialize(|| Some(Task::ready(Ok(()))))
11078        });
11079        workspace.update_in(cx, |w, window, cx| {
11080            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11081            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11082        });
11083        let task = workspace.update_in(cx, |w, window, cx| {
11084            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11085        });
11086        assert!(task.await.unwrap());
11087    }
11088
11089    #[gpui::test]
11090    async fn test_close_pane_items(cx: &mut TestAppContext) {
11091        init_test(cx);
11092
11093        let fs = FakeFs::new(cx.executor());
11094
11095        let project = Project::test(fs, None, cx).await;
11096        let (workspace, cx) =
11097            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11098
11099        let item1 = cx.new(|cx| {
11100            TestItem::new(cx)
11101                .with_dirty(true)
11102                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11103        });
11104        let item2 = cx.new(|cx| {
11105            TestItem::new(cx)
11106                .with_dirty(true)
11107                .with_conflict(true)
11108                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11109        });
11110        let item3 = cx.new(|cx| {
11111            TestItem::new(cx)
11112                .with_dirty(true)
11113                .with_conflict(true)
11114                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11115        });
11116        let item4 = cx.new(|cx| {
11117            TestItem::new(cx).with_dirty(true).with_project_items(&[{
11118                let project_item = TestProjectItem::new_untitled(cx);
11119                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11120                project_item
11121            }])
11122        });
11123        let pane = workspace.update_in(cx, |workspace, window, cx| {
11124            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11125            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11126            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11127            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11128            workspace.active_pane().clone()
11129        });
11130
11131        let close_items = pane.update_in(cx, |pane, window, cx| {
11132            pane.activate_item(1, true, true, window, cx);
11133            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11134            let item1_id = item1.item_id();
11135            let item3_id = item3.item_id();
11136            let item4_id = item4.item_id();
11137            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11138                [item1_id, item3_id, item4_id].contains(&id)
11139            })
11140        });
11141        cx.executor().run_until_parked();
11142
11143        assert!(cx.has_pending_prompt());
11144        cx.simulate_prompt_answer("Save all");
11145
11146        cx.executor().run_until_parked();
11147
11148        // Item 1 is saved. There's a prompt to save item 3.
11149        pane.update(cx, |pane, cx| {
11150            assert_eq!(item1.read(cx).save_count, 1);
11151            assert_eq!(item1.read(cx).save_as_count, 0);
11152            assert_eq!(item1.read(cx).reload_count, 0);
11153            assert_eq!(pane.items_len(), 3);
11154            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11155        });
11156        assert!(cx.has_pending_prompt());
11157
11158        // Cancel saving item 3.
11159        cx.simulate_prompt_answer("Discard");
11160        cx.executor().run_until_parked();
11161
11162        // Item 3 is reloaded. There's a prompt to save item 4.
11163        pane.update(cx, |pane, cx| {
11164            assert_eq!(item3.read(cx).save_count, 0);
11165            assert_eq!(item3.read(cx).save_as_count, 0);
11166            assert_eq!(item3.read(cx).reload_count, 1);
11167            assert_eq!(pane.items_len(), 2);
11168            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11169        });
11170
11171        // There's a prompt for a path for item 4.
11172        cx.simulate_new_path_selection(|_| Some(Default::default()));
11173        close_items.await.unwrap();
11174
11175        // The requested items are closed.
11176        pane.update(cx, |pane, cx| {
11177            assert_eq!(item4.read(cx).save_count, 0);
11178            assert_eq!(item4.read(cx).save_as_count, 1);
11179            assert_eq!(item4.read(cx).reload_count, 0);
11180            assert_eq!(pane.items_len(), 1);
11181            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11182        });
11183    }
11184
11185    #[gpui::test]
11186    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11187        init_test(cx);
11188
11189        let fs = FakeFs::new(cx.executor());
11190        let project = Project::test(fs, [], cx).await;
11191        let (workspace, cx) =
11192            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11193
11194        // Create several workspace items with single project entries, and two
11195        // workspace items with multiple project entries.
11196        let single_entry_items = (0..=4)
11197            .map(|project_entry_id| {
11198                cx.new(|cx| {
11199                    TestItem::new(cx)
11200                        .with_dirty(true)
11201                        .with_project_items(&[dirty_project_item(
11202                            project_entry_id,
11203                            &format!("{project_entry_id}.txt"),
11204                            cx,
11205                        )])
11206                })
11207            })
11208            .collect::<Vec<_>>();
11209        let item_2_3 = cx.new(|cx| {
11210            TestItem::new(cx)
11211                .with_dirty(true)
11212                .with_buffer_kind(ItemBufferKind::Multibuffer)
11213                .with_project_items(&[
11214                    single_entry_items[2].read(cx).project_items[0].clone(),
11215                    single_entry_items[3].read(cx).project_items[0].clone(),
11216                ])
11217        });
11218        let item_3_4 = cx.new(|cx| {
11219            TestItem::new(cx)
11220                .with_dirty(true)
11221                .with_buffer_kind(ItemBufferKind::Multibuffer)
11222                .with_project_items(&[
11223                    single_entry_items[3].read(cx).project_items[0].clone(),
11224                    single_entry_items[4].read(cx).project_items[0].clone(),
11225                ])
11226        });
11227
11228        // Create two panes that contain the following project entries:
11229        //   left pane:
11230        //     multi-entry items:   (2, 3)
11231        //     single-entry items:  0, 2, 3, 4
11232        //   right pane:
11233        //     single-entry items:  4, 1
11234        //     multi-entry items:   (3, 4)
11235        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11236            let left_pane = workspace.active_pane().clone();
11237            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11238            workspace.add_item_to_active_pane(
11239                single_entry_items[0].boxed_clone(),
11240                None,
11241                true,
11242                window,
11243                cx,
11244            );
11245            workspace.add_item_to_active_pane(
11246                single_entry_items[2].boxed_clone(),
11247                None,
11248                true,
11249                window,
11250                cx,
11251            );
11252            workspace.add_item_to_active_pane(
11253                single_entry_items[3].boxed_clone(),
11254                None,
11255                true,
11256                window,
11257                cx,
11258            );
11259            workspace.add_item_to_active_pane(
11260                single_entry_items[4].boxed_clone(),
11261                None,
11262                true,
11263                window,
11264                cx,
11265            );
11266
11267            let right_pane =
11268                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11269
11270            let boxed_clone = single_entry_items[1].boxed_clone();
11271            let right_pane = window.spawn(cx, async move |cx| {
11272                right_pane.await.inspect(|right_pane| {
11273                    right_pane
11274                        .update_in(cx, |pane, window, cx| {
11275                            pane.add_item(boxed_clone, true, true, None, window, cx);
11276                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11277                        })
11278                        .unwrap();
11279                })
11280            });
11281
11282            (left_pane, right_pane)
11283        });
11284        let right_pane = right_pane.await.unwrap();
11285        cx.focus(&right_pane);
11286
11287        let close = right_pane.update_in(cx, |pane, window, cx| {
11288            pane.close_all_items(&CloseAllItems::default(), window, cx)
11289                .unwrap()
11290        });
11291        cx.executor().run_until_parked();
11292
11293        let msg = cx.pending_prompt().unwrap().0;
11294        assert!(msg.contains("1.txt"));
11295        assert!(!msg.contains("2.txt"));
11296        assert!(!msg.contains("3.txt"));
11297        assert!(!msg.contains("4.txt"));
11298
11299        // With best-effort close, cancelling item 1 keeps it open but items 4
11300        // and (3,4) still close since their entries exist in left pane.
11301        cx.simulate_prompt_answer("Cancel");
11302        close.await;
11303
11304        right_pane.read_with(cx, |pane, _| {
11305            assert_eq!(pane.items_len(), 1);
11306        });
11307
11308        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11309        left_pane
11310            .update_in(cx, |left_pane, window, cx| {
11311                left_pane.close_item_by_id(
11312                    single_entry_items[3].entity_id(),
11313                    SaveIntent::Skip,
11314                    window,
11315                    cx,
11316                )
11317            })
11318            .await
11319            .unwrap();
11320
11321        let close = left_pane.update_in(cx, |pane, window, cx| {
11322            pane.close_all_items(&CloseAllItems::default(), window, cx)
11323                .unwrap()
11324        });
11325        cx.executor().run_until_parked();
11326
11327        let details = cx.pending_prompt().unwrap().1;
11328        assert!(details.contains("0.txt"));
11329        assert!(details.contains("3.txt"));
11330        assert!(details.contains("4.txt"));
11331        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11332        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11333        // assert!(!details.contains("2.txt"));
11334
11335        cx.simulate_prompt_answer("Save all");
11336        cx.executor().run_until_parked();
11337        close.await;
11338
11339        left_pane.read_with(cx, |pane, _| {
11340            assert_eq!(pane.items_len(), 0);
11341        });
11342    }
11343
11344    #[gpui::test]
11345    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11346        init_test(cx);
11347
11348        let fs = FakeFs::new(cx.executor());
11349        let project = Project::test(fs, [], cx).await;
11350        let (workspace, cx) =
11351            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11352        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11353
11354        let item = cx.new(|cx| {
11355            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11356        });
11357        let item_id = item.entity_id();
11358        workspace.update_in(cx, |workspace, window, cx| {
11359            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11360        });
11361
11362        // Autosave on window change.
11363        item.update(cx, |item, cx| {
11364            SettingsStore::update_global(cx, |settings, cx| {
11365                settings.update_user_settings(cx, |settings| {
11366                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11367                })
11368            });
11369            item.is_dirty = true;
11370        });
11371
11372        // Deactivating the window saves the file.
11373        cx.deactivate_window();
11374        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11375
11376        // Re-activating the window doesn't save the file.
11377        cx.update(|window, _| window.activate_window());
11378        cx.executor().run_until_parked();
11379        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11380
11381        // Autosave on focus change.
11382        item.update_in(cx, |item, window, cx| {
11383            cx.focus_self(window);
11384            SettingsStore::update_global(cx, |settings, cx| {
11385                settings.update_user_settings(cx, |settings| {
11386                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11387                })
11388            });
11389            item.is_dirty = true;
11390        });
11391        // Blurring the item saves the file.
11392        item.update_in(cx, |_, window, _| window.blur());
11393        cx.executor().run_until_parked();
11394        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11395
11396        // Deactivating the window still saves the file.
11397        item.update_in(cx, |item, window, cx| {
11398            cx.focus_self(window);
11399            item.is_dirty = true;
11400        });
11401        cx.deactivate_window();
11402        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11403
11404        // Autosave after delay.
11405        item.update(cx, |item, cx| {
11406            SettingsStore::update_global(cx, |settings, cx| {
11407                settings.update_user_settings(cx, |settings| {
11408                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11409                        milliseconds: 500.into(),
11410                    });
11411                })
11412            });
11413            item.is_dirty = true;
11414            cx.emit(ItemEvent::Edit);
11415        });
11416
11417        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11418        cx.executor().advance_clock(Duration::from_millis(250));
11419        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11420
11421        // After delay expires, the file is saved.
11422        cx.executor().advance_clock(Duration::from_millis(250));
11423        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11424
11425        // Autosave after delay, should save earlier than delay if tab is closed
11426        item.update(cx, |item, cx| {
11427            item.is_dirty = true;
11428            cx.emit(ItemEvent::Edit);
11429        });
11430        cx.executor().advance_clock(Duration::from_millis(250));
11431        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11432
11433        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11434        pane.update_in(cx, |pane, window, cx| {
11435            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11436        })
11437        .await
11438        .unwrap();
11439        assert!(!cx.has_pending_prompt());
11440        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11441
11442        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11443        workspace.update_in(cx, |workspace, window, cx| {
11444            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11445        });
11446        item.update_in(cx, |item, _window, cx| {
11447            item.is_dirty = true;
11448            for project_item in &mut item.project_items {
11449                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11450            }
11451        });
11452        cx.run_until_parked();
11453        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11454
11455        // Autosave on focus change, ensuring closing the tab counts as such.
11456        item.update(cx, |item, cx| {
11457            SettingsStore::update_global(cx, |settings, cx| {
11458                settings.update_user_settings(cx, |settings| {
11459                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11460                })
11461            });
11462            item.is_dirty = true;
11463            for project_item in &mut item.project_items {
11464                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11465            }
11466        });
11467
11468        pane.update_in(cx, |pane, window, cx| {
11469            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11470        })
11471        .await
11472        .unwrap();
11473        assert!(!cx.has_pending_prompt());
11474        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11475
11476        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11477        workspace.update_in(cx, |workspace, window, cx| {
11478            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11479        });
11480        item.update_in(cx, |item, window, cx| {
11481            item.project_items[0].update(cx, |item, _| {
11482                item.entry_id = None;
11483            });
11484            item.is_dirty = true;
11485            window.blur();
11486        });
11487        cx.run_until_parked();
11488        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11489
11490        // Ensure autosave is prevented for deleted files also when closing the buffer.
11491        let _close_items = pane.update_in(cx, |pane, window, cx| {
11492            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11493        });
11494        cx.run_until_parked();
11495        assert!(cx.has_pending_prompt());
11496        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11497    }
11498
11499    #[gpui::test]
11500    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11501        init_test(cx);
11502
11503        let fs = FakeFs::new(cx.executor());
11504        let project = Project::test(fs, [], cx).await;
11505        let (workspace, cx) =
11506            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11507
11508        // Create a multibuffer-like item with two child focus handles,
11509        // simulating individual buffer editors within a multibuffer.
11510        let item = cx.new(|cx| {
11511            TestItem::new(cx)
11512                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11513                .with_child_focus_handles(2, cx)
11514        });
11515        workspace.update_in(cx, |workspace, window, cx| {
11516            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11517        });
11518
11519        // Set autosave to OnFocusChange and focus the first child handle,
11520        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11521        item.update_in(cx, |item, window, cx| {
11522            SettingsStore::update_global(cx, |settings, cx| {
11523                settings.update_user_settings(cx, |settings| {
11524                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11525                })
11526            });
11527            item.is_dirty = true;
11528            window.focus(&item.child_focus_handles[0], cx);
11529        });
11530        cx.executor().run_until_parked();
11531        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11532
11533        // Moving focus from one child to another within the same item should
11534        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11535        item.update_in(cx, |item, window, cx| {
11536            window.focus(&item.child_focus_handles[1], cx);
11537        });
11538        cx.executor().run_until_parked();
11539        item.read_with(cx, |item, _| {
11540            assert_eq!(
11541                item.save_count, 0,
11542                "Switching focus between children within the same item should not autosave"
11543            );
11544        });
11545
11546        // Blurring the item saves the file. This is the core regression scenario:
11547        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11548        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11549        // the leaf is always a child focus handle, so `on_blur` never detected
11550        // focus leaving the item.
11551        item.update_in(cx, |_, window, _| window.blur());
11552        cx.executor().run_until_parked();
11553        item.read_with(cx, |item, _| {
11554            assert_eq!(
11555                item.save_count, 1,
11556                "Blurring should trigger autosave when focus was on a child of the item"
11557            );
11558        });
11559
11560        // Deactivating the window should also trigger autosave when a child of
11561        // the multibuffer item currently owns focus.
11562        item.update_in(cx, |item, window, cx| {
11563            item.is_dirty = true;
11564            window.focus(&item.child_focus_handles[0], cx);
11565        });
11566        cx.executor().run_until_parked();
11567        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11568
11569        cx.deactivate_window();
11570        item.read_with(cx, |item, _| {
11571            assert_eq!(
11572                item.save_count, 2,
11573                "Deactivating window should trigger autosave when focus was on a child"
11574            );
11575        });
11576    }
11577
11578    #[gpui::test]
11579    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11580        init_test(cx);
11581
11582        let fs = FakeFs::new(cx.executor());
11583
11584        let project = Project::test(fs, [], cx).await;
11585        let (workspace, cx) =
11586            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11587
11588        let item = cx.new(|cx| {
11589            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11590        });
11591        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11592        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11593        let toolbar_notify_count = Rc::new(RefCell::new(0));
11594
11595        workspace.update_in(cx, |workspace, window, cx| {
11596            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11597            let toolbar_notification_count = toolbar_notify_count.clone();
11598            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11599                *toolbar_notification_count.borrow_mut() += 1
11600            })
11601            .detach();
11602        });
11603
11604        pane.read_with(cx, |pane, _| {
11605            assert!(!pane.can_navigate_backward());
11606            assert!(!pane.can_navigate_forward());
11607        });
11608
11609        item.update_in(cx, |item, _, cx| {
11610            item.set_state("one".to_string(), cx);
11611        });
11612
11613        // Toolbar must be notified to re-render the navigation buttons
11614        assert_eq!(*toolbar_notify_count.borrow(), 1);
11615
11616        pane.read_with(cx, |pane, _| {
11617            assert!(pane.can_navigate_backward());
11618            assert!(!pane.can_navigate_forward());
11619        });
11620
11621        workspace
11622            .update_in(cx, |workspace, window, cx| {
11623                workspace.go_back(pane.downgrade(), window, cx)
11624            })
11625            .await
11626            .unwrap();
11627
11628        assert_eq!(*toolbar_notify_count.borrow(), 2);
11629        pane.read_with(cx, |pane, _| {
11630            assert!(!pane.can_navigate_backward());
11631            assert!(pane.can_navigate_forward());
11632        });
11633    }
11634
11635    /// Tests that the navigation history deduplicates entries for the same item.
11636    ///
11637    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11638    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11639    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11640    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11641    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11642    ///
11643    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11644    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11645    #[gpui::test]
11646    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11647        init_test(cx);
11648
11649        let fs = FakeFs::new(cx.executor());
11650        let project = Project::test(fs, [], cx).await;
11651        let (workspace, cx) =
11652            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11653
11654        let item_a = cx.new(|cx| {
11655            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11656        });
11657        let item_b = cx.new(|cx| {
11658            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11659        });
11660        let item_c = cx.new(|cx| {
11661            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11662        });
11663
11664        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11665
11666        workspace.update_in(cx, |workspace, window, cx| {
11667            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11668            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11669            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11670        });
11671
11672        workspace.update_in(cx, |workspace, window, cx| {
11673            workspace.activate_item(&item_a, false, false, window, cx);
11674        });
11675        cx.run_until_parked();
11676
11677        workspace.update_in(cx, |workspace, window, cx| {
11678            workspace.activate_item(&item_b, false, false, window, cx);
11679        });
11680        cx.run_until_parked();
11681
11682        workspace.update_in(cx, |workspace, window, cx| {
11683            workspace.activate_item(&item_a, false, false, window, cx);
11684        });
11685        cx.run_until_parked();
11686
11687        workspace.update_in(cx, |workspace, window, cx| {
11688            workspace.activate_item(&item_b, false, false, window, cx);
11689        });
11690        cx.run_until_parked();
11691
11692        workspace.update_in(cx, |workspace, window, cx| {
11693            workspace.activate_item(&item_a, false, false, window, cx);
11694        });
11695        cx.run_until_parked();
11696
11697        workspace.update_in(cx, |workspace, window, cx| {
11698            workspace.activate_item(&item_b, false, false, window, cx);
11699        });
11700        cx.run_until_parked();
11701
11702        workspace.update_in(cx, |workspace, window, cx| {
11703            workspace.activate_item(&item_c, false, false, window, cx);
11704        });
11705        cx.run_until_parked();
11706
11707        let backward_count = pane.read_with(cx, |pane, cx| {
11708            let mut count = 0;
11709            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11710                count += 1;
11711            });
11712            count
11713        });
11714        assert!(
11715            backward_count <= 4,
11716            "Should have at most 4 entries, got {}",
11717            backward_count
11718        );
11719
11720        workspace
11721            .update_in(cx, |workspace, window, cx| {
11722                workspace.go_back(pane.downgrade(), window, cx)
11723            })
11724            .await
11725            .unwrap();
11726
11727        let active_item = workspace.read_with(cx, |workspace, cx| {
11728            workspace.active_item(cx).unwrap().item_id()
11729        });
11730        assert_eq!(
11731            active_item,
11732            item_b.entity_id(),
11733            "After first go_back, should be at item B"
11734        );
11735
11736        workspace
11737            .update_in(cx, |workspace, window, cx| {
11738                workspace.go_back(pane.downgrade(), window, cx)
11739            })
11740            .await
11741            .unwrap();
11742
11743        let active_item = workspace.read_with(cx, |workspace, cx| {
11744            workspace.active_item(cx).unwrap().item_id()
11745        });
11746        assert_eq!(
11747            active_item,
11748            item_a.entity_id(),
11749            "After second go_back, should be at item A"
11750        );
11751
11752        pane.read_with(cx, |pane, _| {
11753            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11754        });
11755    }
11756
11757    #[gpui::test]
11758    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11759        init_test(cx);
11760        let fs = FakeFs::new(cx.executor());
11761        let project = Project::test(fs, [], cx).await;
11762        let (multi_workspace, cx) =
11763            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11764        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11765
11766        workspace.update_in(cx, |workspace, window, cx| {
11767            let first_item = cx.new(|cx| {
11768                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11769            });
11770            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11771            workspace.split_pane(
11772                workspace.active_pane().clone(),
11773                SplitDirection::Right,
11774                window,
11775                cx,
11776            );
11777            workspace.split_pane(
11778                workspace.active_pane().clone(),
11779                SplitDirection::Right,
11780                window,
11781                cx,
11782            );
11783        });
11784
11785        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11786            let panes = workspace.center.panes();
11787            assert!(panes.len() >= 2);
11788            (
11789                panes.first().expect("at least one pane").entity_id(),
11790                panes.last().expect("at least one pane").entity_id(),
11791            )
11792        });
11793
11794        workspace.update_in(cx, |workspace, window, cx| {
11795            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11796        });
11797        workspace.update(cx, |workspace, _| {
11798            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11799            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11800        });
11801
11802        cx.dispatch_action(ActivateLastPane);
11803
11804        workspace.update(cx, |workspace, _| {
11805            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11806        });
11807    }
11808
11809    #[gpui::test]
11810    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11811        init_test(cx);
11812        let fs = FakeFs::new(cx.executor());
11813
11814        let project = Project::test(fs, [], cx).await;
11815        let (workspace, cx) =
11816            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11817
11818        let panel = workspace.update_in(cx, |workspace, window, cx| {
11819            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11820            workspace.add_panel(panel.clone(), window, cx);
11821
11822            workspace
11823                .right_dock()
11824                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11825
11826            panel
11827        });
11828
11829        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11830        pane.update_in(cx, |pane, window, cx| {
11831            let item = cx.new(TestItem::new);
11832            pane.add_item(Box::new(item), true, true, None, window, cx);
11833        });
11834
11835        // Transfer focus from center to panel
11836        workspace.update_in(cx, |workspace, window, cx| {
11837            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11838        });
11839
11840        workspace.update_in(cx, |workspace, window, cx| {
11841            assert!(workspace.right_dock().read(cx).is_open());
11842            assert!(!panel.is_zoomed(window, cx));
11843            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11844        });
11845
11846        // Transfer focus from panel to center
11847        workspace.update_in(cx, |workspace, window, cx| {
11848            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11849        });
11850
11851        workspace.update_in(cx, |workspace, window, cx| {
11852            assert!(workspace.right_dock().read(cx).is_open());
11853            assert!(!panel.is_zoomed(window, cx));
11854            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11855            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11856        });
11857
11858        // Close the dock
11859        workspace.update_in(cx, |workspace, window, cx| {
11860            workspace.toggle_dock(DockPosition::Right, window, cx);
11861        });
11862
11863        workspace.update_in(cx, |workspace, window, cx| {
11864            assert!(!workspace.right_dock().read(cx).is_open());
11865            assert!(!panel.is_zoomed(window, cx));
11866            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11867            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11868        });
11869
11870        // Open the dock
11871        workspace.update_in(cx, |workspace, window, cx| {
11872            workspace.toggle_dock(DockPosition::Right, window, cx);
11873        });
11874
11875        workspace.update_in(cx, |workspace, window, cx| {
11876            assert!(workspace.right_dock().read(cx).is_open());
11877            assert!(!panel.is_zoomed(window, cx));
11878            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11879        });
11880
11881        // Focus and zoom panel
11882        panel.update_in(cx, |panel, window, cx| {
11883            cx.focus_self(window);
11884            panel.set_zoomed(true, window, cx)
11885        });
11886
11887        workspace.update_in(cx, |workspace, window, cx| {
11888            assert!(workspace.right_dock().read(cx).is_open());
11889            assert!(panel.is_zoomed(window, cx));
11890            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11891        });
11892
11893        // Transfer focus to the center closes the dock
11894        workspace.update_in(cx, |workspace, window, cx| {
11895            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11896        });
11897
11898        workspace.update_in(cx, |workspace, window, cx| {
11899            assert!(!workspace.right_dock().read(cx).is_open());
11900            assert!(panel.is_zoomed(window, cx));
11901            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11902        });
11903
11904        // Transferring focus back to the panel keeps it zoomed
11905        workspace.update_in(cx, |workspace, window, cx| {
11906            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11907        });
11908
11909        workspace.update_in(cx, |workspace, window, cx| {
11910            assert!(workspace.right_dock().read(cx).is_open());
11911            assert!(panel.is_zoomed(window, cx));
11912            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11913        });
11914
11915        // Close the dock while it is zoomed
11916        workspace.update_in(cx, |workspace, window, cx| {
11917            workspace.toggle_dock(DockPosition::Right, window, cx)
11918        });
11919
11920        workspace.update_in(cx, |workspace, window, cx| {
11921            assert!(!workspace.right_dock().read(cx).is_open());
11922            assert!(panel.is_zoomed(window, cx));
11923            assert!(workspace.zoomed.is_none());
11924            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11925        });
11926
11927        // Opening the dock, when it's zoomed, retains focus
11928        workspace.update_in(cx, |workspace, window, cx| {
11929            workspace.toggle_dock(DockPosition::Right, window, cx)
11930        });
11931
11932        workspace.update_in(cx, |workspace, window, cx| {
11933            assert!(workspace.right_dock().read(cx).is_open());
11934            assert!(panel.is_zoomed(window, cx));
11935            assert!(workspace.zoomed.is_some());
11936            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11937        });
11938
11939        // Unzoom and close the panel, zoom the active pane.
11940        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11941        workspace.update_in(cx, |workspace, window, cx| {
11942            workspace.toggle_dock(DockPosition::Right, window, cx)
11943        });
11944        pane.update_in(cx, |pane, window, cx| {
11945            pane.toggle_zoom(&Default::default(), window, cx)
11946        });
11947
11948        // Opening a dock unzooms the pane.
11949        workspace.update_in(cx, |workspace, window, cx| {
11950            workspace.toggle_dock(DockPosition::Right, window, cx)
11951        });
11952        workspace.update_in(cx, |workspace, window, cx| {
11953            let pane = pane.read(cx);
11954            assert!(!pane.is_zoomed());
11955            assert!(!pane.focus_handle(cx).is_focused(window));
11956            assert!(workspace.right_dock().read(cx).is_open());
11957            assert!(workspace.zoomed.is_none());
11958        });
11959    }
11960
11961    #[gpui::test]
11962    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11963        init_test(cx);
11964        let fs = FakeFs::new(cx.executor());
11965
11966        let project = Project::test(fs, [], cx).await;
11967        let (workspace, cx) =
11968            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11969
11970        let panel = workspace.update_in(cx, |workspace, window, cx| {
11971            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11972            workspace.add_panel(panel.clone(), window, cx);
11973            panel
11974        });
11975
11976        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11977        pane.update_in(cx, |pane, window, cx| {
11978            let item = cx.new(TestItem::new);
11979            pane.add_item(Box::new(item), true, true, None, window, cx);
11980        });
11981
11982        // Enable close_panel_on_toggle
11983        cx.update_global(|store: &mut SettingsStore, cx| {
11984            store.update_user_settings(cx, |settings| {
11985                settings.workspace.close_panel_on_toggle = Some(true);
11986            });
11987        });
11988
11989        // Panel starts closed. Toggling should open and focus it.
11990        workspace.update_in(cx, |workspace, window, cx| {
11991            assert!(!workspace.right_dock().read(cx).is_open());
11992            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11993        });
11994
11995        workspace.update_in(cx, |workspace, window, cx| {
11996            assert!(
11997                workspace.right_dock().read(cx).is_open(),
11998                "Dock should be open after toggling from center"
11999            );
12000            assert!(
12001                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12002                "Panel should be focused after toggling from center"
12003            );
12004        });
12005
12006        // Panel is open and focused. Toggling should close the panel and
12007        // return focus to the center.
12008        workspace.update_in(cx, |workspace, window, cx| {
12009            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12010        });
12011
12012        workspace.update_in(cx, |workspace, window, cx| {
12013            assert!(
12014                !workspace.right_dock().read(cx).is_open(),
12015                "Dock should be closed after toggling from focused panel"
12016            );
12017            assert!(
12018                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12019                "Panel should not be focused after toggling from focused panel"
12020            );
12021        });
12022
12023        // Open the dock and focus something else so the panel is open but not
12024        // focused. Toggling should focus the panel (not close it).
12025        workspace.update_in(cx, |workspace, window, cx| {
12026            workspace
12027                .right_dock()
12028                .update(cx, |dock, cx| dock.set_open(true, window, cx));
12029            window.focus(&pane.read(cx).focus_handle(cx), cx);
12030        });
12031
12032        workspace.update_in(cx, |workspace, window, cx| {
12033            assert!(workspace.right_dock().read(cx).is_open());
12034            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12035            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12036        });
12037
12038        workspace.update_in(cx, |workspace, window, cx| {
12039            assert!(
12040                workspace.right_dock().read(cx).is_open(),
12041                "Dock should remain open when toggling focuses an open-but-unfocused panel"
12042            );
12043            assert!(
12044                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12045                "Panel should be focused after toggling an open-but-unfocused panel"
12046            );
12047        });
12048
12049        // Now disable the setting and verify the original behavior: toggling
12050        // from a focused panel moves focus to center but leaves the dock open.
12051        cx.update_global(|store: &mut SettingsStore, cx| {
12052            store.update_user_settings(cx, |settings| {
12053                settings.workspace.close_panel_on_toggle = Some(false);
12054            });
12055        });
12056
12057        workspace.update_in(cx, |workspace, window, cx| {
12058            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12059        });
12060
12061        workspace.update_in(cx, |workspace, window, cx| {
12062            assert!(
12063                workspace.right_dock().read(cx).is_open(),
12064                "Dock should remain open when setting is disabled"
12065            );
12066            assert!(
12067                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12068                "Panel should not be focused after toggling with setting disabled"
12069            );
12070        });
12071    }
12072
12073    #[gpui::test]
12074    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12075        init_test(cx);
12076        let fs = FakeFs::new(cx.executor());
12077
12078        let project = Project::test(fs, [], cx).await;
12079        let (workspace, cx) =
12080            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12081
12082        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12083            workspace.active_pane().clone()
12084        });
12085
12086        // Add an item to the pane so it can be zoomed
12087        workspace.update_in(cx, |workspace, window, cx| {
12088            let item = cx.new(TestItem::new);
12089            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12090        });
12091
12092        // Initially not zoomed
12093        workspace.update_in(cx, |workspace, _window, cx| {
12094            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12095            assert!(
12096                workspace.zoomed.is_none(),
12097                "Workspace should track no zoomed pane"
12098            );
12099            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12100        });
12101
12102        // Zoom In
12103        pane.update_in(cx, |pane, window, cx| {
12104            pane.zoom_in(&crate::ZoomIn, window, cx);
12105        });
12106
12107        workspace.update_in(cx, |workspace, window, cx| {
12108            assert!(
12109                pane.read(cx).is_zoomed(),
12110                "Pane should be zoomed after ZoomIn"
12111            );
12112            assert!(
12113                workspace.zoomed.is_some(),
12114                "Workspace should track the zoomed pane"
12115            );
12116            assert!(
12117                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12118                "ZoomIn should focus the pane"
12119            );
12120        });
12121
12122        // Zoom In again is a no-op
12123        pane.update_in(cx, |pane, window, cx| {
12124            pane.zoom_in(&crate::ZoomIn, window, cx);
12125        });
12126
12127        workspace.update_in(cx, |workspace, window, cx| {
12128            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12129            assert!(
12130                workspace.zoomed.is_some(),
12131                "Workspace still tracks zoomed pane"
12132            );
12133            assert!(
12134                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12135                "Pane remains focused after repeated ZoomIn"
12136            );
12137        });
12138
12139        // Zoom Out
12140        pane.update_in(cx, |pane, window, cx| {
12141            pane.zoom_out(&crate::ZoomOut, window, cx);
12142        });
12143
12144        workspace.update_in(cx, |workspace, _window, cx| {
12145            assert!(
12146                !pane.read(cx).is_zoomed(),
12147                "Pane should unzoom after ZoomOut"
12148            );
12149            assert!(
12150                workspace.zoomed.is_none(),
12151                "Workspace clears zoom tracking after ZoomOut"
12152            );
12153        });
12154
12155        // Zoom Out again is a no-op
12156        pane.update_in(cx, |pane, window, cx| {
12157            pane.zoom_out(&crate::ZoomOut, window, cx);
12158        });
12159
12160        workspace.update_in(cx, |workspace, _window, cx| {
12161            assert!(
12162                !pane.read(cx).is_zoomed(),
12163                "Second ZoomOut keeps pane unzoomed"
12164            );
12165            assert!(
12166                workspace.zoomed.is_none(),
12167                "Workspace remains without zoomed pane"
12168            );
12169        });
12170    }
12171
12172    #[gpui::test]
12173    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12174        init_test(cx);
12175        let fs = FakeFs::new(cx.executor());
12176
12177        let project = Project::test(fs, [], cx).await;
12178        let (workspace, cx) =
12179            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12180        workspace.update_in(cx, |workspace, window, cx| {
12181            // Open two docks
12182            let left_dock = workspace.dock_at_position(DockPosition::Left);
12183            let right_dock = workspace.dock_at_position(DockPosition::Right);
12184
12185            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12186            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12187
12188            assert!(left_dock.read(cx).is_open());
12189            assert!(right_dock.read(cx).is_open());
12190        });
12191
12192        workspace.update_in(cx, |workspace, window, cx| {
12193            // Toggle all docks - should close both
12194            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12195
12196            let left_dock = workspace.dock_at_position(DockPosition::Left);
12197            let right_dock = workspace.dock_at_position(DockPosition::Right);
12198            assert!(!left_dock.read(cx).is_open());
12199            assert!(!right_dock.read(cx).is_open());
12200        });
12201
12202        workspace.update_in(cx, |workspace, window, cx| {
12203            // Toggle again - should reopen both
12204            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12205
12206            let left_dock = workspace.dock_at_position(DockPosition::Left);
12207            let right_dock = workspace.dock_at_position(DockPosition::Right);
12208            assert!(left_dock.read(cx).is_open());
12209            assert!(right_dock.read(cx).is_open());
12210        });
12211    }
12212
12213    #[gpui::test]
12214    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12215        init_test(cx);
12216        let fs = FakeFs::new(cx.executor());
12217
12218        let project = Project::test(fs, [], cx).await;
12219        let (workspace, cx) =
12220            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12221        workspace.update_in(cx, |workspace, window, cx| {
12222            // Open two docks
12223            let left_dock = workspace.dock_at_position(DockPosition::Left);
12224            let right_dock = workspace.dock_at_position(DockPosition::Right);
12225
12226            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12227            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12228
12229            assert!(left_dock.read(cx).is_open());
12230            assert!(right_dock.read(cx).is_open());
12231        });
12232
12233        workspace.update_in(cx, |workspace, window, cx| {
12234            // Close them manually
12235            workspace.toggle_dock(DockPosition::Left, window, cx);
12236            workspace.toggle_dock(DockPosition::Right, window, cx);
12237
12238            let left_dock = workspace.dock_at_position(DockPosition::Left);
12239            let right_dock = workspace.dock_at_position(DockPosition::Right);
12240            assert!(!left_dock.read(cx).is_open());
12241            assert!(!right_dock.read(cx).is_open());
12242        });
12243
12244        workspace.update_in(cx, |workspace, window, cx| {
12245            // Toggle all docks - only last closed (right dock) should reopen
12246            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12247
12248            let left_dock = workspace.dock_at_position(DockPosition::Left);
12249            let right_dock = workspace.dock_at_position(DockPosition::Right);
12250            assert!(!left_dock.read(cx).is_open());
12251            assert!(right_dock.read(cx).is_open());
12252        });
12253    }
12254
12255    #[gpui::test]
12256    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12257        init_test(cx);
12258        let fs = FakeFs::new(cx.executor());
12259        let project = Project::test(fs, [], cx).await;
12260        let (multi_workspace, cx) =
12261            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12262        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12263
12264        // Open two docks (left and right) with one panel each
12265        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12266            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12267            workspace.add_panel(left_panel.clone(), window, cx);
12268
12269            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12270            workspace.add_panel(right_panel.clone(), window, cx);
12271
12272            workspace.toggle_dock(DockPosition::Left, window, cx);
12273            workspace.toggle_dock(DockPosition::Right, window, cx);
12274
12275            // Verify initial state
12276            assert!(
12277                workspace.left_dock().read(cx).is_open(),
12278                "Left dock should be open"
12279            );
12280            assert_eq!(
12281                workspace
12282                    .left_dock()
12283                    .read(cx)
12284                    .visible_panel()
12285                    .unwrap()
12286                    .panel_id(),
12287                left_panel.panel_id(),
12288                "Left panel should be visible in left dock"
12289            );
12290            assert!(
12291                workspace.right_dock().read(cx).is_open(),
12292                "Right dock should be open"
12293            );
12294            assert_eq!(
12295                workspace
12296                    .right_dock()
12297                    .read(cx)
12298                    .visible_panel()
12299                    .unwrap()
12300                    .panel_id(),
12301                right_panel.panel_id(),
12302                "Right panel should be visible in right dock"
12303            );
12304            assert!(
12305                !workspace.bottom_dock().read(cx).is_open(),
12306                "Bottom dock should be closed"
12307            );
12308
12309            (left_panel, right_panel)
12310        });
12311
12312        // Focus the left panel and move it to the next position (bottom dock)
12313        workspace.update_in(cx, |workspace, window, cx| {
12314            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12315            assert!(
12316                left_panel.read(cx).focus_handle(cx).is_focused(window),
12317                "Left panel should be focused"
12318            );
12319        });
12320
12321        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12322
12323        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12324        workspace.update(cx, |workspace, cx| {
12325            assert!(
12326                !workspace.left_dock().read(cx).is_open(),
12327                "Left dock should be closed"
12328            );
12329            assert!(
12330                workspace.bottom_dock().read(cx).is_open(),
12331                "Bottom dock should now be open"
12332            );
12333            assert_eq!(
12334                left_panel.read(cx).position,
12335                DockPosition::Bottom,
12336                "Left panel should now be in the bottom dock"
12337            );
12338            assert_eq!(
12339                workspace
12340                    .bottom_dock()
12341                    .read(cx)
12342                    .visible_panel()
12343                    .unwrap()
12344                    .panel_id(),
12345                left_panel.panel_id(),
12346                "Left panel should be the visible panel in the bottom dock"
12347            );
12348        });
12349
12350        // Toggle all docks off
12351        workspace.update_in(cx, |workspace, window, cx| {
12352            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12353            assert!(
12354                !workspace.left_dock().read(cx).is_open(),
12355                "Left dock should be closed"
12356            );
12357            assert!(
12358                !workspace.right_dock().read(cx).is_open(),
12359                "Right dock should be closed"
12360            );
12361            assert!(
12362                !workspace.bottom_dock().read(cx).is_open(),
12363                "Bottom dock should be closed"
12364            );
12365        });
12366
12367        // Toggle all docks back on and verify positions are restored
12368        workspace.update_in(cx, |workspace, window, cx| {
12369            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12370            assert!(
12371                !workspace.left_dock().read(cx).is_open(),
12372                "Left dock should remain closed"
12373            );
12374            assert!(
12375                workspace.right_dock().read(cx).is_open(),
12376                "Right dock should remain open"
12377            );
12378            assert!(
12379                workspace.bottom_dock().read(cx).is_open(),
12380                "Bottom dock should remain open"
12381            );
12382            assert_eq!(
12383                left_panel.read(cx).position,
12384                DockPosition::Bottom,
12385                "Left panel should remain in the bottom dock"
12386            );
12387            assert_eq!(
12388                right_panel.read(cx).position,
12389                DockPosition::Right,
12390                "Right panel should remain in the right dock"
12391            );
12392            assert_eq!(
12393                workspace
12394                    .bottom_dock()
12395                    .read(cx)
12396                    .visible_panel()
12397                    .unwrap()
12398                    .panel_id(),
12399                left_panel.panel_id(),
12400                "Left panel should be the visible panel in the right dock"
12401            );
12402        });
12403    }
12404
12405    #[gpui::test]
12406    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12407        init_test(cx);
12408
12409        let fs = FakeFs::new(cx.executor());
12410
12411        let project = Project::test(fs, None, cx).await;
12412        let (workspace, cx) =
12413            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12414
12415        // Let's arrange the panes like this:
12416        //
12417        // +-----------------------+
12418        // |         top           |
12419        // +------+--------+-------+
12420        // | left | center | right |
12421        // +------+--------+-------+
12422        // |        bottom         |
12423        // +-----------------------+
12424
12425        let top_item = cx.new(|cx| {
12426            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12427        });
12428        let bottom_item = cx.new(|cx| {
12429            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12430        });
12431        let left_item = cx.new(|cx| {
12432            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12433        });
12434        let right_item = cx.new(|cx| {
12435            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12436        });
12437        let center_item = cx.new(|cx| {
12438            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12439        });
12440
12441        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12442            let top_pane_id = workspace.active_pane().entity_id();
12443            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12444            workspace.split_pane(
12445                workspace.active_pane().clone(),
12446                SplitDirection::Down,
12447                window,
12448                cx,
12449            );
12450            top_pane_id
12451        });
12452        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12453            let bottom_pane_id = workspace.active_pane().entity_id();
12454            workspace.add_item_to_active_pane(
12455                Box::new(bottom_item.clone()),
12456                None,
12457                false,
12458                window,
12459                cx,
12460            );
12461            workspace.split_pane(
12462                workspace.active_pane().clone(),
12463                SplitDirection::Up,
12464                window,
12465                cx,
12466            );
12467            bottom_pane_id
12468        });
12469        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12470            let left_pane_id = workspace.active_pane().entity_id();
12471            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12472            workspace.split_pane(
12473                workspace.active_pane().clone(),
12474                SplitDirection::Right,
12475                window,
12476                cx,
12477            );
12478            left_pane_id
12479        });
12480        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12481            let right_pane_id = workspace.active_pane().entity_id();
12482            workspace.add_item_to_active_pane(
12483                Box::new(right_item.clone()),
12484                None,
12485                false,
12486                window,
12487                cx,
12488            );
12489            workspace.split_pane(
12490                workspace.active_pane().clone(),
12491                SplitDirection::Left,
12492                window,
12493                cx,
12494            );
12495            right_pane_id
12496        });
12497        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12498            let center_pane_id = workspace.active_pane().entity_id();
12499            workspace.add_item_to_active_pane(
12500                Box::new(center_item.clone()),
12501                None,
12502                false,
12503                window,
12504                cx,
12505            );
12506            center_pane_id
12507        });
12508        cx.executor().run_until_parked();
12509
12510        workspace.update_in(cx, |workspace, window, cx| {
12511            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12512
12513            // Join into next from center pane into right
12514            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12515        });
12516
12517        workspace.update_in(cx, |workspace, window, cx| {
12518            let active_pane = workspace.active_pane();
12519            assert_eq!(right_pane_id, active_pane.entity_id());
12520            assert_eq!(2, active_pane.read(cx).items_len());
12521            let item_ids_in_pane =
12522                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12523            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12524            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12525
12526            // Join into next from right pane into bottom
12527            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12528        });
12529
12530        workspace.update_in(cx, |workspace, window, cx| {
12531            let active_pane = workspace.active_pane();
12532            assert_eq!(bottom_pane_id, active_pane.entity_id());
12533            assert_eq!(3, active_pane.read(cx).items_len());
12534            let item_ids_in_pane =
12535                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12536            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12537            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12538            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12539
12540            // Join into next from bottom pane into left
12541            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12542        });
12543
12544        workspace.update_in(cx, |workspace, window, cx| {
12545            let active_pane = workspace.active_pane();
12546            assert_eq!(left_pane_id, active_pane.entity_id());
12547            assert_eq!(4, active_pane.read(cx).items_len());
12548            let item_ids_in_pane =
12549                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12550            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12551            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12552            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12553            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12554
12555            // Join into next from left pane into top
12556            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12557        });
12558
12559        workspace.update_in(cx, |workspace, window, cx| {
12560            let active_pane = workspace.active_pane();
12561            assert_eq!(top_pane_id, active_pane.entity_id());
12562            assert_eq!(5, active_pane.read(cx).items_len());
12563            let item_ids_in_pane =
12564                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12565            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12566            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12567            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12568            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12569            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12570
12571            // Single pane left: no-op
12572            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12573        });
12574
12575        workspace.update(cx, |workspace, _cx| {
12576            let active_pane = workspace.active_pane();
12577            assert_eq!(top_pane_id, active_pane.entity_id());
12578        });
12579    }
12580
12581    fn add_an_item_to_active_pane(
12582        cx: &mut VisualTestContext,
12583        workspace: &Entity<Workspace>,
12584        item_id: u64,
12585    ) -> Entity<TestItem> {
12586        let item = cx.new(|cx| {
12587            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12588                item_id,
12589                "item{item_id}.txt",
12590                cx,
12591            )])
12592        });
12593        workspace.update_in(cx, |workspace, window, cx| {
12594            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12595        });
12596        item
12597    }
12598
12599    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12600        workspace.update_in(cx, |workspace, window, cx| {
12601            workspace.split_pane(
12602                workspace.active_pane().clone(),
12603                SplitDirection::Right,
12604                window,
12605                cx,
12606            )
12607        })
12608    }
12609
12610    #[gpui::test]
12611    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12612        init_test(cx);
12613        let fs = FakeFs::new(cx.executor());
12614        let project = Project::test(fs, None, cx).await;
12615        let (workspace, cx) =
12616            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12617
12618        add_an_item_to_active_pane(cx, &workspace, 1);
12619        split_pane(cx, &workspace);
12620        add_an_item_to_active_pane(cx, &workspace, 2);
12621        split_pane(cx, &workspace); // empty pane
12622        split_pane(cx, &workspace);
12623        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12624
12625        cx.executor().run_until_parked();
12626
12627        workspace.update(cx, |workspace, cx| {
12628            let num_panes = workspace.panes().len();
12629            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12630            let active_item = workspace
12631                .active_pane()
12632                .read(cx)
12633                .active_item()
12634                .expect("item is in focus");
12635
12636            assert_eq!(num_panes, 4);
12637            assert_eq!(num_items_in_current_pane, 1);
12638            assert_eq!(active_item.item_id(), last_item.item_id());
12639        });
12640
12641        workspace.update_in(cx, |workspace, window, cx| {
12642            workspace.join_all_panes(window, cx);
12643        });
12644
12645        workspace.update(cx, |workspace, cx| {
12646            let num_panes = workspace.panes().len();
12647            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12648            let active_item = workspace
12649                .active_pane()
12650                .read(cx)
12651                .active_item()
12652                .expect("item is in focus");
12653
12654            assert_eq!(num_panes, 1);
12655            assert_eq!(num_items_in_current_pane, 3);
12656            assert_eq!(active_item.item_id(), last_item.item_id());
12657        });
12658    }
12659
12660    #[gpui::test]
12661    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12662        init_test(cx);
12663        let fs = FakeFs::new(cx.executor());
12664
12665        let project = Project::test(fs, [], cx).await;
12666        let (multi_workspace, cx) =
12667            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12668        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12669
12670        workspace.update(cx, |workspace, _cx| {
12671            workspace.bounds.size.width = px(800.);
12672        });
12673
12674        workspace.update_in(cx, |workspace, window, cx| {
12675            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12676            workspace.add_panel(panel, window, cx);
12677            workspace.toggle_dock(DockPosition::Right, window, cx);
12678        });
12679
12680        let (panel, resized_width, ratio_basis_width) =
12681            workspace.update_in(cx, |workspace, window, cx| {
12682                let item = cx.new(|cx| {
12683                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12684                });
12685                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12686
12687                let dock = workspace.right_dock().read(cx);
12688                let workspace_width = workspace.bounds.size.width;
12689                let initial_width = workspace
12690                    .dock_size(&dock, window, cx)
12691                    .expect("flexible dock should have an initial width");
12692
12693                assert_eq!(initial_width, workspace_width / 2.);
12694
12695                workspace.resize_right_dock(px(300.), window, cx);
12696
12697                let dock = workspace.right_dock().read(cx);
12698                let resized_width = workspace
12699                    .dock_size(&dock, window, cx)
12700                    .expect("flexible dock should keep its resized width");
12701
12702                assert_eq!(resized_width, px(300.));
12703
12704                let panel = workspace
12705                    .right_dock()
12706                    .read(cx)
12707                    .visible_panel()
12708                    .expect("flexible dock should have a visible panel")
12709                    .panel_id();
12710
12711                (panel, resized_width, workspace_width)
12712            });
12713
12714        workspace.update_in(cx, |workspace, window, cx| {
12715            workspace.toggle_dock(DockPosition::Right, window, cx);
12716            workspace.toggle_dock(DockPosition::Right, window, cx);
12717
12718            let dock = workspace.right_dock().read(cx);
12719            let reopened_width = workspace
12720                .dock_size(&dock, window, cx)
12721                .expect("flexible dock should restore when reopened");
12722
12723            assert_eq!(reopened_width, resized_width);
12724
12725            let right_dock = workspace.right_dock().read(cx);
12726            let flexible_panel = right_dock
12727                .visible_panel()
12728                .expect("flexible dock should still have a visible panel");
12729            assert_eq!(flexible_panel.panel_id(), panel);
12730            assert_eq!(
12731                right_dock
12732                    .stored_panel_size_state(flexible_panel.as_ref())
12733                    .and_then(|size_state| size_state.flex),
12734                Some(
12735                    resized_width.to_f64() as f32
12736                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12737                )
12738            );
12739        });
12740
12741        workspace.update_in(cx, |workspace, window, cx| {
12742            workspace.split_pane(
12743                workspace.active_pane().clone(),
12744                SplitDirection::Right,
12745                window,
12746                cx,
12747            );
12748
12749            let dock = workspace.right_dock().read(cx);
12750            let split_width = workspace
12751                .dock_size(&dock, window, cx)
12752                .expect("flexible dock should keep its user-resized proportion");
12753
12754            assert_eq!(split_width, px(300.));
12755
12756            workspace.bounds.size.width = px(1600.);
12757
12758            let dock = workspace.right_dock().read(cx);
12759            let resized_window_width = workspace
12760                .dock_size(&dock, window, cx)
12761                .expect("flexible dock should preserve proportional size on window resize");
12762
12763            assert_eq!(
12764                resized_window_width,
12765                workspace.bounds.size.width
12766                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12767            );
12768        });
12769    }
12770
12771    #[gpui::test]
12772    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12773        init_test(cx);
12774        let fs = FakeFs::new(cx.executor());
12775
12776        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12777        {
12778            let project = Project::test(fs.clone(), [], cx).await;
12779            let (multi_workspace, cx) =
12780                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12781            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12782
12783            workspace.update(cx, |workspace, _cx| {
12784                workspace.set_random_database_id();
12785                workspace.bounds.size.width = px(800.);
12786            });
12787
12788            let panel = workspace.update_in(cx, |workspace, window, cx| {
12789                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12790                workspace.add_panel(panel.clone(), window, cx);
12791                workspace.toggle_dock(DockPosition::Left, window, cx);
12792                panel
12793            });
12794
12795            workspace.update_in(cx, |workspace, window, cx| {
12796                workspace.resize_left_dock(px(350.), window, cx);
12797            });
12798
12799            cx.run_until_parked();
12800
12801            let persisted = workspace.read_with(cx, |workspace, cx| {
12802                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12803            });
12804            assert_eq!(
12805                persisted.and_then(|s| s.size),
12806                Some(px(350.)),
12807                "fixed-width panel size should be persisted to KVP"
12808            );
12809
12810            // Remove the panel and re-add a fresh instance with the same key.
12811            // The new instance should have its size state restored from KVP.
12812            workspace.update_in(cx, |workspace, window, cx| {
12813                workspace.remove_panel(&panel, window, cx);
12814            });
12815
12816            workspace.update_in(cx, |workspace, window, cx| {
12817                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12818                workspace.add_panel(new_panel, window, cx);
12819
12820                let left_dock = workspace.left_dock().read(cx);
12821                let size_state = left_dock
12822                    .panel::<TestPanel>()
12823                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12824                assert_eq!(
12825                    size_state.and_then(|s| s.size),
12826                    Some(px(350.)),
12827                    "re-added fixed-width panel should restore persisted size from KVP"
12828                );
12829            });
12830        }
12831
12832        // Flexible panel: both pixel size and ratio are persisted and restored.
12833        {
12834            let project = Project::test(fs.clone(), [], cx).await;
12835            let (multi_workspace, cx) =
12836                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12837            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12838
12839            workspace.update(cx, |workspace, _cx| {
12840                workspace.set_random_database_id();
12841                workspace.bounds.size.width = px(800.);
12842            });
12843
12844            let panel = workspace.update_in(cx, |workspace, window, cx| {
12845                let item = cx.new(|cx| {
12846                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12847                });
12848                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12849
12850                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12851                workspace.add_panel(panel.clone(), window, cx);
12852                workspace.toggle_dock(DockPosition::Right, window, cx);
12853                panel
12854            });
12855
12856            workspace.update_in(cx, |workspace, window, cx| {
12857                workspace.resize_right_dock(px(300.), window, cx);
12858            });
12859
12860            cx.run_until_parked();
12861
12862            let persisted = workspace
12863                .read_with(cx, |workspace, cx| {
12864                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12865                })
12866                .expect("flexible panel state should be persisted to KVP");
12867            assert_eq!(
12868                persisted.size, None,
12869                "flexible panel should not persist a redundant pixel size"
12870            );
12871            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12872
12873            // Remove the panel and re-add: both size and ratio should be restored.
12874            workspace.update_in(cx, |workspace, window, cx| {
12875                workspace.remove_panel(&panel, window, cx);
12876            });
12877
12878            workspace.update_in(cx, |workspace, window, cx| {
12879                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12880                workspace.add_panel(new_panel, window, cx);
12881
12882                let right_dock = workspace.right_dock().read(cx);
12883                let size_state = right_dock
12884                    .panel::<TestPanel>()
12885                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12886                    .expect("re-added flexible panel should have restored size state from KVP");
12887                assert_eq!(
12888                    size_state.size, None,
12889                    "re-added flexible panel should not have a persisted pixel size"
12890                );
12891                assert_eq!(
12892                    size_state.flex,
12893                    Some(original_ratio),
12894                    "re-added flexible panel should restore persisted flex"
12895                );
12896            });
12897        }
12898    }
12899
12900    #[gpui::test]
12901    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12902        init_test(cx);
12903        let fs = FakeFs::new(cx.executor());
12904
12905        let project = Project::test(fs, [], cx).await;
12906        let (multi_workspace, cx) =
12907            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12908        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12909
12910        workspace.update(cx, |workspace, _cx| {
12911            workspace.bounds.size.width = px(900.);
12912        });
12913
12914        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12915        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12916        // and the center pane each take half the workspace width.
12917        workspace.update_in(cx, |workspace, window, cx| {
12918            let item = cx.new(|cx| {
12919                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12920            });
12921            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12922
12923            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12924            workspace.add_panel(panel, window, cx);
12925            workspace.toggle_dock(DockPosition::Left, window, cx);
12926
12927            let left_dock = workspace.left_dock().read(cx);
12928            let left_width = workspace
12929                .dock_size(&left_dock, window, cx)
12930                .expect("left dock should have an active panel");
12931
12932            assert_eq!(
12933                left_width,
12934                workspace.bounds.size.width / 2.,
12935                "flexible left panel should split evenly with the center pane"
12936            );
12937        });
12938
12939        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12940        // change horizontal width fractions, so the flexible panel stays at the same
12941        // width as each half of the split.
12942        workspace.update_in(cx, |workspace, window, cx| {
12943            workspace.split_pane(
12944                workspace.active_pane().clone(),
12945                SplitDirection::Down,
12946                window,
12947                cx,
12948            );
12949
12950            let left_dock = workspace.left_dock().read(cx);
12951            let left_width = workspace
12952                .dock_size(&left_dock, window, cx)
12953                .expect("left dock should still have an active panel after vertical split");
12954
12955            assert_eq!(
12956                left_width,
12957                workspace.bounds.size.width / 2.,
12958                "flexible left panel width should match each vertically-split pane"
12959            );
12960        });
12961
12962        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12963        // size reduces the available width, so the flexible left panel and the center
12964        // panes all shrink proportionally to accommodate it.
12965        workspace.update_in(cx, |workspace, window, cx| {
12966            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12967            workspace.add_panel(panel, window, cx);
12968            workspace.toggle_dock(DockPosition::Right, window, cx);
12969
12970            let right_dock = workspace.right_dock().read(cx);
12971            let right_width = workspace
12972                .dock_size(&right_dock, window, cx)
12973                .expect("right dock should have an active panel");
12974
12975            let left_dock = workspace.left_dock().read(cx);
12976            let left_width = workspace
12977                .dock_size(&left_dock, window, cx)
12978                .expect("left dock should still have an active panel");
12979
12980            let available_width = workspace.bounds.size.width - right_width;
12981            assert_eq!(
12982                left_width,
12983                available_width / 2.,
12984                "flexible left panel should shrink proportionally as the right dock takes space"
12985            );
12986        });
12987
12988        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12989        // flex sizing and the workspace width is divided among left-flex, center
12990        // (implicit flex 1.0), and right-flex.
12991        workspace.update_in(cx, |workspace, window, cx| {
12992            let right_dock = workspace.right_dock().clone();
12993            let right_panel = right_dock
12994                .read(cx)
12995                .visible_panel()
12996                .expect("right dock should have a visible panel")
12997                .clone();
12998            workspace.toggle_dock_panel_flexible_size(
12999                &right_dock,
13000                right_panel.as_ref(),
13001                window,
13002                cx,
13003            );
13004
13005            let right_dock = right_dock.read(cx);
13006            let right_panel = right_dock
13007                .visible_panel()
13008                .expect("right dock should still have a visible panel");
13009            assert!(
13010                right_panel.has_flexible_size(window, cx),
13011                "right panel should now be flexible"
13012            );
13013
13014            let right_size_state = right_dock
13015                .stored_panel_size_state(right_panel.as_ref())
13016                .expect("right panel should have a stored size state after toggling");
13017            let right_flex = right_size_state
13018                .flex
13019                .expect("right panel should have a flex value after toggling");
13020
13021            let left_dock = workspace.left_dock().read(cx);
13022            let left_width = workspace
13023                .dock_size(&left_dock, window, cx)
13024                .expect("left dock should still have an active panel");
13025            let right_width = workspace
13026                .dock_size(&right_dock, window, cx)
13027                .expect("right dock should still have an active panel");
13028
13029            let left_flex = workspace
13030                .default_dock_flex(DockPosition::Left)
13031                .expect("left dock should have a default flex");
13032
13033            let total_flex = left_flex + 1.0 + right_flex;
13034            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13035            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13036            assert_eq!(
13037                left_width, expected_left,
13038                "flexible left panel should share workspace width via flex ratios"
13039            );
13040            assert_eq!(
13041                right_width, expected_right,
13042                "flexible right panel should share workspace width via flex ratios"
13043            );
13044        });
13045    }
13046
13047    struct TestModal(FocusHandle);
13048
13049    impl TestModal {
13050        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13051            Self(cx.focus_handle())
13052        }
13053    }
13054
13055    impl EventEmitter<DismissEvent> for TestModal {}
13056
13057    impl Focusable for TestModal {
13058        fn focus_handle(&self, _cx: &App) -> FocusHandle {
13059            self.0.clone()
13060        }
13061    }
13062
13063    impl ModalView for TestModal {}
13064
13065    impl Render for TestModal {
13066        fn render(
13067            &mut self,
13068            _window: &mut Window,
13069            _cx: &mut Context<TestModal>,
13070        ) -> impl IntoElement {
13071            div().track_focus(&self.0)
13072        }
13073    }
13074
13075    #[gpui::test]
13076    async fn test_panels(cx: &mut gpui::TestAppContext) {
13077        init_test(cx);
13078        let fs = FakeFs::new(cx.executor());
13079
13080        let project = Project::test(fs, [], cx).await;
13081        let (multi_workspace, cx) =
13082            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13083        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13084
13085        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13086            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13087            workspace.add_panel(panel_1.clone(), window, cx);
13088            workspace.toggle_dock(DockPosition::Left, window, cx);
13089            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13090            workspace.add_panel(panel_2.clone(), window, cx);
13091            workspace.toggle_dock(DockPosition::Right, window, cx);
13092
13093            let left_dock = workspace.left_dock();
13094            assert_eq!(
13095                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13096                panel_1.panel_id()
13097            );
13098            assert_eq!(
13099                workspace.dock_size(&left_dock.read(cx), window, cx),
13100                Some(px(300.))
13101            );
13102
13103            workspace.resize_left_dock(px(1337.), window, cx);
13104            assert_eq!(
13105                workspace
13106                    .right_dock()
13107                    .read(cx)
13108                    .visible_panel()
13109                    .unwrap()
13110                    .panel_id(),
13111                panel_2.panel_id(),
13112            );
13113
13114            (panel_1, panel_2)
13115        });
13116
13117        // Move panel_1 to the right
13118        panel_1.update_in(cx, |panel_1, window, cx| {
13119            panel_1.set_position(DockPosition::Right, window, cx)
13120        });
13121
13122        workspace.update_in(cx, |workspace, window, cx| {
13123            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13124            // Since it was the only panel on the left, the left dock should now be closed.
13125            assert!(!workspace.left_dock().read(cx).is_open());
13126            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13127            let right_dock = workspace.right_dock();
13128            assert_eq!(
13129                right_dock.read(cx).visible_panel().unwrap().panel_id(),
13130                panel_1.panel_id()
13131            );
13132            assert_eq!(
13133                right_dock
13134                    .read(cx)
13135                    .active_panel_size()
13136                    .unwrap()
13137                    .size
13138                    .unwrap(),
13139                px(1337.)
13140            );
13141
13142            // Now we move panel_2 to the left
13143            panel_2.set_position(DockPosition::Left, window, cx);
13144        });
13145
13146        workspace.update(cx, |workspace, cx| {
13147            // Since panel_2 was not visible on the right, we don't open the left dock.
13148            assert!(!workspace.left_dock().read(cx).is_open());
13149            // And the right dock is unaffected in its displaying of panel_1
13150            assert!(workspace.right_dock().read(cx).is_open());
13151            assert_eq!(
13152                workspace
13153                    .right_dock()
13154                    .read(cx)
13155                    .visible_panel()
13156                    .unwrap()
13157                    .panel_id(),
13158                panel_1.panel_id(),
13159            );
13160        });
13161
13162        // Move panel_1 back to the left
13163        panel_1.update_in(cx, |panel_1, window, cx| {
13164            panel_1.set_position(DockPosition::Left, window, cx)
13165        });
13166
13167        workspace.update_in(cx, |workspace, window, cx| {
13168            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13169            let left_dock = workspace.left_dock();
13170            assert!(left_dock.read(cx).is_open());
13171            assert_eq!(
13172                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13173                panel_1.panel_id()
13174            );
13175            assert_eq!(
13176                workspace.dock_size(&left_dock.read(cx), window, cx),
13177                Some(px(1337.))
13178            );
13179            // And the right dock should be closed as it no longer has any panels.
13180            assert!(!workspace.right_dock().read(cx).is_open());
13181
13182            // Now we move panel_1 to the bottom
13183            panel_1.set_position(DockPosition::Bottom, window, cx);
13184        });
13185
13186        workspace.update_in(cx, |workspace, window, cx| {
13187            // Since panel_1 was visible on the left, we close the left dock.
13188            assert!(!workspace.left_dock().read(cx).is_open());
13189            // The bottom dock is sized based on the panel's default size,
13190            // since the panel orientation changed from vertical to horizontal.
13191            let bottom_dock = workspace.bottom_dock();
13192            assert_eq!(
13193                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13194                Some(px(300.))
13195            );
13196            // Close bottom dock and move panel_1 back to the left.
13197            bottom_dock.update(cx, |bottom_dock, cx| {
13198                bottom_dock.set_open(false, window, cx)
13199            });
13200            panel_1.set_position(DockPosition::Left, window, cx);
13201        });
13202
13203        // Emit activated event on panel 1
13204        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13205
13206        // Now the left dock is open and panel_1 is active and focused.
13207        workspace.update_in(cx, |workspace, window, cx| {
13208            let left_dock = workspace.left_dock();
13209            assert!(left_dock.read(cx).is_open());
13210            assert_eq!(
13211                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13212                panel_1.panel_id(),
13213            );
13214            assert!(panel_1.focus_handle(cx).is_focused(window));
13215        });
13216
13217        // Emit closed event on panel 2, which is not active
13218        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13219
13220        // Wo don't close the left dock, because panel_2 wasn't the active panel
13221        workspace.update(cx, |workspace, cx| {
13222            let left_dock = workspace.left_dock();
13223            assert!(left_dock.read(cx).is_open());
13224            assert_eq!(
13225                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13226                panel_1.panel_id(),
13227            );
13228        });
13229
13230        // Emitting a ZoomIn event shows the panel as zoomed.
13231        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13232        workspace.read_with(cx, |workspace, _| {
13233            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13234            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13235        });
13236
13237        // Move panel to another dock while it is zoomed
13238        panel_1.update_in(cx, |panel, window, cx| {
13239            panel.set_position(DockPosition::Right, window, cx)
13240        });
13241        workspace.read_with(cx, |workspace, _| {
13242            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13243
13244            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13245        });
13246
13247        // This is a helper for getting a:
13248        // - valid focus on an element,
13249        // - that isn't a part of the panes and panels system of the Workspace,
13250        // - and doesn't trigger the 'on_focus_lost' API.
13251        let focus_other_view = {
13252            let workspace = workspace.clone();
13253            move |cx: &mut VisualTestContext| {
13254                workspace.update_in(cx, |workspace, window, cx| {
13255                    if workspace.active_modal::<TestModal>(cx).is_some() {
13256                        workspace.toggle_modal(window, cx, TestModal::new);
13257                        workspace.toggle_modal(window, cx, TestModal::new);
13258                    } else {
13259                        workspace.toggle_modal(window, cx, TestModal::new);
13260                    }
13261                })
13262            }
13263        };
13264
13265        // If focus is transferred to another view that's not a panel or another pane, we still show
13266        // the panel as zoomed.
13267        focus_other_view(cx);
13268        workspace.read_with(cx, |workspace, _| {
13269            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13270            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13271        });
13272
13273        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13274        workspace.update_in(cx, |_workspace, window, cx| {
13275            cx.focus_self(window);
13276        });
13277        workspace.read_with(cx, |workspace, _| {
13278            assert_eq!(workspace.zoomed, None);
13279            assert_eq!(workspace.zoomed_position, None);
13280        });
13281
13282        // If focus is transferred again to another view that's not a panel or a pane, we won't
13283        // show the panel as zoomed because it wasn't zoomed before.
13284        focus_other_view(cx);
13285        workspace.read_with(cx, |workspace, _| {
13286            assert_eq!(workspace.zoomed, None);
13287            assert_eq!(workspace.zoomed_position, None);
13288        });
13289
13290        // When the panel is activated, it is zoomed again.
13291        cx.dispatch_action(ToggleRightDock);
13292        workspace.read_with(cx, |workspace, _| {
13293            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13294            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13295        });
13296
13297        // Emitting a ZoomOut event unzooms the panel.
13298        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13299        workspace.read_with(cx, |workspace, _| {
13300            assert_eq!(workspace.zoomed, None);
13301            assert_eq!(workspace.zoomed_position, None);
13302        });
13303
13304        // Emit closed event on panel 1, which is active
13305        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13306
13307        // Now the left dock is closed, because panel_1 was the active panel
13308        workspace.update(cx, |workspace, cx| {
13309            let right_dock = workspace.right_dock();
13310            assert!(!right_dock.read(cx).is_open());
13311        });
13312    }
13313
13314    #[gpui::test]
13315    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13316        init_test(cx);
13317
13318        let fs = FakeFs::new(cx.background_executor.clone());
13319        let project = Project::test(fs, [], cx).await;
13320        let (workspace, cx) =
13321            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13322        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13323
13324        let dirty_regular_buffer = cx.new(|cx| {
13325            TestItem::new(cx)
13326                .with_dirty(true)
13327                .with_label("1.txt")
13328                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13329        });
13330        let dirty_regular_buffer_2 = cx.new(|cx| {
13331            TestItem::new(cx)
13332                .with_dirty(true)
13333                .with_label("2.txt")
13334                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13335        });
13336        let dirty_multi_buffer_with_both = cx.new(|cx| {
13337            TestItem::new(cx)
13338                .with_dirty(true)
13339                .with_buffer_kind(ItemBufferKind::Multibuffer)
13340                .with_label("Fake Project Search")
13341                .with_project_items(&[
13342                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13343                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13344                ])
13345        });
13346        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13347        workspace.update_in(cx, |workspace, window, cx| {
13348            workspace.add_item(
13349                pane.clone(),
13350                Box::new(dirty_regular_buffer.clone()),
13351                None,
13352                false,
13353                false,
13354                window,
13355                cx,
13356            );
13357            workspace.add_item(
13358                pane.clone(),
13359                Box::new(dirty_regular_buffer_2.clone()),
13360                None,
13361                false,
13362                false,
13363                window,
13364                cx,
13365            );
13366            workspace.add_item(
13367                pane.clone(),
13368                Box::new(dirty_multi_buffer_with_both.clone()),
13369                None,
13370                false,
13371                false,
13372                window,
13373                cx,
13374            );
13375        });
13376
13377        pane.update_in(cx, |pane, window, cx| {
13378            pane.activate_item(2, true, true, window, cx);
13379            assert_eq!(
13380                pane.active_item().unwrap().item_id(),
13381                multi_buffer_with_both_files_id,
13382                "Should select the multi buffer in the pane"
13383            );
13384        });
13385        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13386            pane.close_other_items(
13387                &CloseOtherItems {
13388                    save_intent: Some(SaveIntent::Save),
13389                    close_pinned: true,
13390                },
13391                None,
13392                window,
13393                cx,
13394            )
13395        });
13396        cx.background_executor.run_until_parked();
13397        assert!(!cx.has_pending_prompt());
13398        close_all_but_multi_buffer_task
13399            .await
13400            .expect("Closing all buffers but the multi buffer failed");
13401        pane.update(cx, |pane, cx| {
13402            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13403            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13404            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13405            assert_eq!(pane.items_len(), 1);
13406            assert_eq!(
13407                pane.active_item().unwrap().item_id(),
13408                multi_buffer_with_both_files_id,
13409                "Should have only the multi buffer left in the pane"
13410            );
13411            assert!(
13412                dirty_multi_buffer_with_both.read(cx).is_dirty,
13413                "The multi buffer containing the unsaved buffer should still be dirty"
13414            );
13415        });
13416
13417        dirty_regular_buffer.update(cx, |buffer, cx| {
13418            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13419        });
13420
13421        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13422            pane.close_active_item(
13423                &CloseActiveItem {
13424                    save_intent: Some(SaveIntent::Close),
13425                    close_pinned: false,
13426                },
13427                window,
13428                cx,
13429            )
13430        });
13431        cx.background_executor.run_until_parked();
13432        assert!(
13433            cx.has_pending_prompt(),
13434            "Dirty multi buffer should prompt a save dialog"
13435        );
13436        cx.simulate_prompt_answer("Save");
13437        cx.background_executor.run_until_parked();
13438        close_multi_buffer_task
13439            .await
13440            .expect("Closing the multi buffer failed");
13441        pane.update(cx, |pane, cx| {
13442            assert_eq!(
13443                dirty_multi_buffer_with_both.read(cx).save_count,
13444                1,
13445                "Multi buffer item should get be saved"
13446            );
13447            // Test impl does not save inner items, so we do not assert them
13448            assert_eq!(
13449                pane.items_len(),
13450                0,
13451                "No more items should be left in the pane"
13452            );
13453            assert!(pane.active_item().is_none());
13454        });
13455    }
13456
13457    #[gpui::test]
13458    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13459        cx: &mut TestAppContext,
13460    ) {
13461        init_test(cx);
13462
13463        let fs = FakeFs::new(cx.background_executor.clone());
13464        let project = Project::test(fs, [], cx).await;
13465        let (workspace, cx) =
13466            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13467        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13468
13469        let dirty_regular_buffer = cx.new(|cx| {
13470            TestItem::new(cx)
13471                .with_dirty(true)
13472                .with_label("1.txt")
13473                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13474        });
13475        let dirty_regular_buffer_2 = cx.new(|cx| {
13476            TestItem::new(cx)
13477                .with_dirty(true)
13478                .with_label("2.txt")
13479                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13480        });
13481        let clear_regular_buffer = cx.new(|cx| {
13482            TestItem::new(cx)
13483                .with_label("3.txt")
13484                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13485        });
13486
13487        let dirty_multi_buffer_with_both = cx.new(|cx| {
13488            TestItem::new(cx)
13489                .with_dirty(true)
13490                .with_buffer_kind(ItemBufferKind::Multibuffer)
13491                .with_label("Fake Project Search")
13492                .with_project_items(&[
13493                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13494                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13495                    clear_regular_buffer.read(cx).project_items[0].clone(),
13496                ])
13497        });
13498        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13499        workspace.update_in(cx, |workspace, window, cx| {
13500            workspace.add_item(
13501                pane.clone(),
13502                Box::new(dirty_regular_buffer.clone()),
13503                None,
13504                false,
13505                false,
13506                window,
13507                cx,
13508            );
13509            workspace.add_item(
13510                pane.clone(),
13511                Box::new(dirty_multi_buffer_with_both.clone()),
13512                None,
13513                false,
13514                false,
13515                window,
13516                cx,
13517            );
13518        });
13519
13520        pane.update_in(cx, |pane, window, cx| {
13521            pane.activate_item(1, true, true, window, cx);
13522            assert_eq!(
13523                pane.active_item().unwrap().item_id(),
13524                multi_buffer_with_both_files_id,
13525                "Should select the multi buffer in the pane"
13526            );
13527        });
13528        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13529            pane.close_active_item(
13530                &CloseActiveItem {
13531                    save_intent: None,
13532                    close_pinned: false,
13533                },
13534                window,
13535                cx,
13536            )
13537        });
13538        cx.background_executor.run_until_parked();
13539        assert!(
13540            cx.has_pending_prompt(),
13541            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13542        );
13543    }
13544
13545    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13546    /// closed when they are deleted from disk.
13547    #[gpui::test]
13548    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13549        init_test(cx);
13550
13551        // Enable the close_on_disk_deletion setting
13552        cx.update_global(|store: &mut SettingsStore, cx| {
13553            store.update_user_settings(cx, |settings| {
13554                settings.workspace.close_on_file_delete = Some(true);
13555            });
13556        });
13557
13558        let fs = FakeFs::new(cx.background_executor.clone());
13559        let project = Project::test(fs, [], cx).await;
13560        let (workspace, cx) =
13561            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13562        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13563
13564        // Create a test item that simulates a file
13565        let item = cx.new(|cx| {
13566            TestItem::new(cx)
13567                .with_label("test.txt")
13568                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13569        });
13570
13571        // Add item to workspace
13572        workspace.update_in(cx, |workspace, window, cx| {
13573            workspace.add_item(
13574                pane.clone(),
13575                Box::new(item.clone()),
13576                None,
13577                false,
13578                false,
13579                window,
13580                cx,
13581            );
13582        });
13583
13584        // Verify the item is in the pane
13585        pane.read_with(cx, |pane, _| {
13586            assert_eq!(pane.items().count(), 1);
13587        });
13588
13589        // Simulate file deletion by setting the item's deleted state
13590        item.update(cx, |item, _| {
13591            item.set_has_deleted_file(true);
13592        });
13593
13594        // Emit UpdateTab event to trigger the close behavior
13595        cx.run_until_parked();
13596        item.update(cx, |_, cx| {
13597            cx.emit(ItemEvent::UpdateTab);
13598        });
13599
13600        // Allow the close operation to complete
13601        cx.run_until_parked();
13602
13603        // Verify the item was automatically closed
13604        pane.read_with(cx, |pane, _| {
13605            assert_eq!(
13606                pane.items().count(),
13607                0,
13608                "Item should be automatically closed when file is deleted"
13609            );
13610        });
13611    }
13612
13613    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13614    /// open with a strikethrough when they are deleted from disk.
13615    #[gpui::test]
13616    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13617        init_test(cx);
13618
13619        // Ensure close_on_disk_deletion is disabled (default)
13620        cx.update_global(|store: &mut SettingsStore, cx| {
13621            store.update_user_settings(cx, |settings| {
13622                settings.workspace.close_on_file_delete = Some(false);
13623            });
13624        });
13625
13626        let fs = FakeFs::new(cx.background_executor.clone());
13627        let project = Project::test(fs, [], cx).await;
13628        let (workspace, cx) =
13629            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13630        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13631
13632        // Create a test item that simulates a file
13633        let item = cx.new(|cx| {
13634            TestItem::new(cx)
13635                .with_label("test.txt")
13636                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13637        });
13638
13639        // Add item to workspace
13640        workspace.update_in(cx, |workspace, window, cx| {
13641            workspace.add_item(
13642                pane.clone(),
13643                Box::new(item.clone()),
13644                None,
13645                false,
13646                false,
13647                window,
13648                cx,
13649            );
13650        });
13651
13652        // Verify the item is in the pane
13653        pane.read_with(cx, |pane, _| {
13654            assert_eq!(pane.items().count(), 1);
13655        });
13656
13657        // Simulate file deletion
13658        item.update(cx, |item, _| {
13659            item.set_has_deleted_file(true);
13660        });
13661
13662        // Emit UpdateTab event
13663        cx.run_until_parked();
13664        item.update(cx, |_, cx| {
13665            cx.emit(ItemEvent::UpdateTab);
13666        });
13667
13668        // Allow any potential close operation to complete
13669        cx.run_until_parked();
13670
13671        // Verify the item remains open (with strikethrough)
13672        pane.read_with(cx, |pane, _| {
13673            assert_eq!(
13674                pane.items().count(),
13675                1,
13676                "Item should remain open when close_on_disk_deletion is disabled"
13677            );
13678        });
13679
13680        // Verify the item shows as deleted
13681        item.read_with(cx, |item, _| {
13682            assert!(
13683                item.has_deleted_file,
13684                "Item should be marked as having deleted file"
13685            );
13686        });
13687    }
13688
13689    /// Tests that dirty files are not automatically closed when deleted from disk,
13690    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13691    /// unsaved changes without being prompted.
13692    #[gpui::test]
13693    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13694        init_test(cx);
13695
13696        // Enable the close_on_file_delete setting
13697        cx.update_global(|store: &mut SettingsStore, cx| {
13698            store.update_user_settings(cx, |settings| {
13699                settings.workspace.close_on_file_delete = Some(true);
13700            });
13701        });
13702
13703        let fs = FakeFs::new(cx.background_executor.clone());
13704        let project = Project::test(fs, [], cx).await;
13705        let (workspace, cx) =
13706            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13707        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13708
13709        // Create a dirty test item
13710        let item = cx.new(|cx| {
13711            TestItem::new(cx)
13712                .with_dirty(true)
13713                .with_label("test.txt")
13714                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13715        });
13716
13717        // Add item to workspace
13718        workspace.update_in(cx, |workspace, window, cx| {
13719            workspace.add_item(
13720                pane.clone(),
13721                Box::new(item.clone()),
13722                None,
13723                false,
13724                false,
13725                window,
13726                cx,
13727            );
13728        });
13729
13730        // Simulate file deletion
13731        item.update(cx, |item, _| {
13732            item.set_has_deleted_file(true);
13733        });
13734
13735        // Emit UpdateTab event to trigger the close behavior
13736        cx.run_until_parked();
13737        item.update(cx, |_, cx| {
13738            cx.emit(ItemEvent::UpdateTab);
13739        });
13740
13741        // Allow any potential close operation to complete
13742        cx.run_until_parked();
13743
13744        // Verify the item remains open (dirty files are not auto-closed)
13745        pane.read_with(cx, |pane, _| {
13746            assert_eq!(
13747                pane.items().count(),
13748                1,
13749                "Dirty items should not be automatically closed even when file is deleted"
13750            );
13751        });
13752
13753        // Verify the item is marked as deleted and still dirty
13754        item.read_with(cx, |item, _| {
13755            assert!(
13756                item.has_deleted_file,
13757                "Item should be marked as having deleted file"
13758            );
13759            assert!(item.is_dirty, "Item should still be dirty");
13760        });
13761    }
13762
13763    /// Tests that navigation history is cleaned up when files are auto-closed
13764    /// due to deletion from disk.
13765    #[gpui::test]
13766    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13767        init_test(cx);
13768
13769        // Enable the close_on_file_delete setting
13770        cx.update_global(|store: &mut SettingsStore, cx| {
13771            store.update_user_settings(cx, |settings| {
13772                settings.workspace.close_on_file_delete = Some(true);
13773            });
13774        });
13775
13776        let fs = FakeFs::new(cx.background_executor.clone());
13777        let project = Project::test(fs, [], cx).await;
13778        let (workspace, cx) =
13779            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13780        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13781
13782        // Create test items
13783        let item1 = cx.new(|cx| {
13784            TestItem::new(cx)
13785                .with_label("test1.txt")
13786                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13787        });
13788        let item1_id = item1.item_id();
13789
13790        let item2 = cx.new(|cx| {
13791            TestItem::new(cx)
13792                .with_label("test2.txt")
13793                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13794        });
13795
13796        // Add items to workspace
13797        workspace.update_in(cx, |workspace, window, cx| {
13798            workspace.add_item(
13799                pane.clone(),
13800                Box::new(item1.clone()),
13801                None,
13802                false,
13803                false,
13804                window,
13805                cx,
13806            );
13807            workspace.add_item(
13808                pane.clone(),
13809                Box::new(item2.clone()),
13810                None,
13811                false,
13812                false,
13813                window,
13814                cx,
13815            );
13816        });
13817
13818        // Activate item1 to ensure it gets navigation entries
13819        pane.update_in(cx, |pane, window, cx| {
13820            pane.activate_item(0, true, true, window, cx);
13821        });
13822
13823        // Switch to item2 and back to create navigation history
13824        pane.update_in(cx, |pane, window, cx| {
13825            pane.activate_item(1, true, true, window, cx);
13826        });
13827        cx.run_until_parked();
13828
13829        pane.update_in(cx, |pane, window, cx| {
13830            pane.activate_item(0, true, true, window, cx);
13831        });
13832        cx.run_until_parked();
13833
13834        // Simulate file deletion for item1
13835        item1.update(cx, |item, _| {
13836            item.set_has_deleted_file(true);
13837        });
13838
13839        // Emit UpdateTab event to trigger the close behavior
13840        item1.update(cx, |_, cx| {
13841            cx.emit(ItemEvent::UpdateTab);
13842        });
13843        cx.run_until_parked();
13844
13845        // Verify item1 was closed
13846        pane.read_with(cx, |pane, _| {
13847            assert_eq!(
13848                pane.items().count(),
13849                1,
13850                "Should have 1 item remaining after auto-close"
13851            );
13852        });
13853
13854        // Check navigation history after close
13855        let has_item = pane.read_with(cx, |pane, cx| {
13856            let mut has_item = false;
13857            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13858                if entry.item.id() == item1_id {
13859                    has_item = true;
13860                }
13861            });
13862            has_item
13863        });
13864
13865        assert!(
13866            !has_item,
13867            "Navigation history should not contain closed item entries"
13868        );
13869    }
13870
13871    #[gpui::test]
13872    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13873        cx: &mut TestAppContext,
13874    ) {
13875        init_test(cx);
13876
13877        let fs = FakeFs::new(cx.background_executor.clone());
13878        let project = Project::test(fs, [], cx).await;
13879        let (workspace, cx) =
13880            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13881        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13882
13883        let dirty_regular_buffer = cx.new(|cx| {
13884            TestItem::new(cx)
13885                .with_dirty(true)
13886                .with_label("1.txt")
13887                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13888        });
13889        let dirty_regular_buffer_2 = cx.new(|cx| {
13890            TestItem::new(cx)
13891                .with_dirty(true)
13892                .with_label("2.txt")
13893                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13894        });
13895        let clear_regular_buffer = cx.new(|cx| {
13896            TestItem::new(cx)
13897                .with_label("3.txt")
13898                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13899        });
13900
13901        let dirty_multi_buffer = cx.new(|cx| {
13902            TestItem::new(cx)
13903                .with_dirty(true)
13904                .with_buffer_kind(ItemBufferKind::Multibuffer)
13905                .with_label("Fake Project Search")
13906                .with_project_items(&[
13907                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13908                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13909                    clear_regular_buffer.read(cx).project_items[0].clone(),
13910                ])
13911        });
13912        workspace.update_in(cx, |workspace, window, cx| {
13913            workspace.add_item(
13914                pane.clone(),
13915                Box::new(dirty_regular_buffer.clone()),
13916                None,
13917                false,
13918                false,
13919                window,
13920                cx,
13921            );
13922            workspace.add_item(
13923                pane.clone(),
13924                Box::new(dirty_regular_buffer_2.clone()),
13925                None,
13926                false,
13927                false,
13928                window,
13929                cx,
13930            );
13931            workspace.add_item(
13932                pane.clone(),
13933                Box::new(dirty_multi_buffer.clone()),
13934                None,
13935                false,
13936                false,
13937                window,
13938                cx,
13939            );
13940        });
13941
13942        pane.update_in(cx, |pane, window, cx| {
13943            pane.activate_item(2, true, true, window, cx);
13944            assert_eq!(
13945                pane.active_item().unwrap().item_id(),
13946                dirty_multi_buffer.item_id(),
13947                "Should select the multi buffer in the pane"
13948            );
13949        });
13950        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13951            pane.close_active_item(
13952                &CloseActiveItem {
13953                    save_intent: None,
13954                    close_pinned: false,
13955                },
13956                window,
13957                cx,
13958            )
13959        });
13960        cx.background_executor.run_until_parked();
13961        assert!(
13962            !cx.has_pending_prompt(),
13963            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13964        );
13965        close_multi_buffer_task
13966            .await
13967            .expect("Closing multi buffer failed");
13968        pane.update(cx, |pane, cx| {
13969            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13970            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13971            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13972            assert_eq!(
13973                pane.items()
13974                    .map(|item| item.item_id())
13975                    .sorted()
13976                    .collect::<Vec<_>>(),
13977                vec![
13978                    dirty_regular_buffer.item_id(),
13979                    dirty_regular_buffer_2.item_id(),
13980                ],
13981                "Should have no multi buffer left in the pane"
13982            );
13983            assert!(dirty_regular_buffer.read(cx).is_dirty);
13984            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13985        });
13986    }
13987
13988    #[gpui::test]
13989    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13990        init_test(cx);
13991        let fs = FakeFs::new(cx.executor());
13992        let project = Project::test(fs, [], cx).await;
13993        let (multi_workspace, cx) =
13994            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13995        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13996
13997        // Add a new panel to the right dock, opening the dock and setting the
13998        // focus to the new panel.
13999        let panel = workspace.update_in(cx, |workspace, window, cx| {
14000            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14001            workspace.add_panel(panel.clone(), window, cx);
14002
14003            workspace
14004                .right_dock()
14005                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14006
14007            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14008
14009            panel
14010        });
14011
14012        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14013        // panel to the next valid position which, in this case, is the left
14014        // dock.
14015        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14016        workspace.update(cx, |workspace, cx| {
14017            assert!(workspace.left_dock().read(cx).is_open());
14018            assert_eq!(panel.read(cx).position, DockPosition::Left);
14019        });
14020
14021        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14022        // panel to the next valid position which, in this case, is the bottom
14023        // dock.
14024        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14025        workspace.update(cx, |workspace, cx| {
14026            assert!(workspace.bottom_dock().read(cx).is_open());
14027            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14028        });
14029
14030        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14031        // around moving the panel to its initial position, the right dock.
14032        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14033        workspace.update(cx, |workspace, cx| {
14034            assert!(workspace.right_dock().read(cx).is_open());
14035            assert_eq!(panel.read(cx).position, DockPosition::Right);
14036        });
14037
14038        // Remove focus from the panel, ensuring that, if the panel is not
14039        // focused, the `MoveFocusedPanelToNextPosition` action does not update
14040        // the panel's position, so the panel is still in the right dock.
14041        workspace.update_in(cx, |workspace, window, cx| {
14042            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14043        });
14044
14045        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14046        workspace.update(cx, |workspace, cx| {
14047            assert!(workspace.right_dock().read(cx).is_open());
14048            assert_eq!(panel.read(cx).position, DockPosition::Right);
14049        });
14050    }
14051
14052    #[gpui::test]
14053    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14054        init_test(cx);
14055
14056        let fs = FakeFs::new(cx.executor());
14057        let project = Project::test(fs, [], cx).await;
14058        let (workspace, cx) =
14059            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14060
14061        let item_1 = cx.new(|cx| {
14062            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14063        });
14064        workspace.update_in(cx, |workspace, window, cx| {
14065            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14066            workspace.move_item_to_pane_in_direction(
14067                &MoveItemToPaneInDirection {
14068                    direction: SplitDirection::Right,
14069                    focus: true,
14070                    clone: false,
14071                },
14072                window,
14073                cx,
14074            );
14075            workspace.move_item_to_pane_at_index(
14076                &MoveItemToPane {
14077                    destination: 3,
14078                    focus: true,
14079                    clone: false,
14080                },
14081                window,
14082                cx,
14083            );
14084
14085            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14086            assert_eq!(
14087                pane_items_paths(&workspace.active_pane, cx),
14088                vec!["first.txt".to_string()],
14089                "Single item was not moved anywhere"
14090            );
14091        });
14092
14093        let item_2 = cx.new(|cx| {
14094            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14095        });
14096        workspace.update_in(cx, |workspace, window, cx| {
14097            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14098            assert_eq!(
14099                pane_items_paths(&workspace.panes[0], cx),
14100                vec!["first.txt".to_string(), "second.txt".to_string()],
14101            );
14102            workspace.move_item_to_pane_in_direction(
14103                &MoveItemToPaneInDirection {
14104                    direction: SplitDirection::Right,
14105                    focus: true,
14106                    clone: false,
14107                },
14108                window,
14109                cx,
14110            );
14111
14112            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14113            assert_eq!(
14114                pane_items_paths(&workspace.panes[0], cx),
14115                vec!["first.txt".to_string()],
14116                "After moving, one item should be left in the original pane"
14117            );
14118            assert_eq!(
14119                pane_items_paths(&workspace.panes[1], cx),
14120                vec!["second.txt".to_string()],
14121                "New item should have been moved to the new pane"
14122            );
14123        });
14124
14125        let item_3 = cx.new(|cx| {
14126            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14127        });
14128        workspace.update_in(cx, |workspace, window, cx| {
14129            let original_pane = workspace.panes[0].clone();
14130            workspace.set_active_pane(&original_pane, window, cx);
14131            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14132            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14133            assert_eq!(
14134                pane_items_paths(&workspace.active_pane, cx),
14135                vec!["first.txt".to_string(), "third.txt".to_string()],
14136                "New pane should be ready to move one item out"
14137            );
14138
14139            workspace.move_item_to_pane_at_index(
14140                &MoveItemToPane {
14141                    destination: 3,
14142                    focus: true,
14143                    clone: false,
14144                },
14145                window,
14146                cx,
14147            );
14148            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14149            assert_eq!(
14150                pane_items_paths(&workspace.active_pane, cx),
14151                vec!["first.txt".to_string()],
14152                "After moving, one item should be left in the original pane"
14153            );
14154            assert_eq!(
14155                pane_items_paths(&workspace.panes[1], cx),
14156                vec!["second.txt".to_string()],
14157                "Previously created pane should be unchanged"
14158            );
14159            assert_eq!(
14160                pane_items_paths(&workspace.panes[2], cx),
14161                vec!["third.txt".to_string()],
14162                "New item should have been moved to the new pane"
14163            );
14164        });
14165    }
14166
14167    #[gpui::test]
14168    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14169        init_test(cx);
14170
14171        let fs = FakeFs::new(cx.executor());
14172        let project = Project::test(fs, [], cx).await;
14173        let (workspace, cx) =
14174            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14175
14176        let item_1 = cx.new(|cx| {
14177            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14178        });
14179        workspace.update_in(cx, |workspace, window, cx| {
14180            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14181            workspace.move_item_to_pane_in_direction(
14182                &MoveItemToPaneInDirection {
14183                    direction: SplitDirection::Right,
14184                    focus: true,
14185                    clone: true,
14186                },
14187                window,
14188                cx,
14189            );
14190        });
14191        cx.run_until_parked();
14192        workspace.update_in(cx, |workspace, window, cx| {
14193            workspace.move_item_to_pane_at_index(
14194                &MoveItemToPane {
14195                    destination: 3,
14196                    focus: true,
14197                    clone: true,
14198                },
14199                window,
14200                cx,
14201            );
14202        });
14203        cx.run_until_parked();
14204
14205        workspace.update(cx, |workspace, cx| {
14206            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14207            for pane in workspace.panes() {
14208                assert_eq!(
14209                    pane_items_paths(pane, cx),
14210                    vec!["first.txt".to_string()],
14211                    "Single item exists in all panes"
14212                );
14213            }
14214        });
14215
14216        // verify that the active pane has been updated after waiting for the
14217        // pane focus event to fire and resolve
14218        workspace.read_with(cx, |workspace, _app| {
14219            assert_eq!(
14220                workspace.active_pane(),
14221                &workspace.panes[2],
14222                "The third pane should be the active one: {:?}",
14223                workspace.panes
14224            );
14225        })
14226    }
14227
14228    #[gpui::test]
14229    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14230        init_test(cx);
14231
14232        let fs = FakeFs::new(cx.executor());
14233        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14234
14235        let project = Project::test(fs, ["root".as_ref()], cx).await;
14236        let (workspace, cx) =
14237            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14238
14239        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14240        // Add item to pane A with project path
14241        let item_a = cx.new(|cx| {
14242            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14243        });
14244        workspace.update_in(cx, |workspace, window, cx| {
14245            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14246        });
14247
14248        // Split to create pane B
14249        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14250            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14251        });
14252
14253        // Add item with SAME project path to pane B, and pin it
14254        let item_b = cx.new(|cx| {
14255            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14256        });
14257        pane_b.update_in(cx, |pane, window, cx| {
14258            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14259            pane.set_pinned_count(1);
14260        });
14261
14262        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14263        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14264
14265        // close_pinned: false should only close the unpinned copy
14266        workspace.update_in(cx, |workspace, window, cx| {
14267            workspace.close_item_in_all_panes(
14268                &CloseItemInAllPanes {
14269                    save_intent: Some(SaveIntent::Close),
14270                    close_pinned: false,
14271                },
14272                window,
14273                cx,
14274            )
14275        });
14276        cx.executor().run_until_parked();
14277
14278        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14279        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14280        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14281        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14282
14283        // Split again, seeing as closing the previous item also closed its
14284        // pane, so only pane remains, which does not allow us to properly test
14285        // that both items close when `close_pinned: true`.
14286        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14287            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14288        });
14289
14290        // Add an item with the same project path to pane C so that
14291        // close_item_in_all_panes can determine what to close across all panes
14292        // (it reads the active item from the active pane, and split_pane
14293        // creates an empty pane).
14294        let item_c = cx.new(|cx| {
14295            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14296        });
14297        pane_c.update_in(cx, |pane, window, cx| {
14298            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14299        });
14300
14301        // close_pinned: true should close the pinned copy too
14302        workspace.update_in(cx, |workspace, window, cx| {
14303            let panes_count = workspace.panes().len();
14304            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14305
14306            workspace.close_item_in_all_panes(
14307                &CloseItemInAllPanes {
14308                    save_intent: Some(SaveIntent::Close),
14309                    close_pinned: true,
14310                },
14311                window,
14312                cx,
14313            )
14314        });
14315        cx.executor().run_until_parked();
14316
14317        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14318        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14319        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14320        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14321    }
14322
14323    mod register_project_item_tests {
14324
14325        use super::*;
14326
14327        // View
14328        struct TestPngItemView {
14329            focus_handle: FocusHandle,
14330        }
14331        // Model
14332        struct TestPngItem {}
14333
14334        impl project::ProjectItem for TestPngItem {
14335            fn try_open(
14336                _project: &Entity<Project>,
14337                path: &ProjectPath,
14338                cx: &mut App,
14339            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14340                if path.path.extension().unwrap() == "png" {
14341                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14342                } else {
14343                    None
14344                }
14345            }
14346
14347            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14348                None
14349            }
14350
14351            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14352                None
14353            }
14354
14355            fn is_dirty(&self) -> bool {
14356                false
14357            }
14358        }
14359
14360        impl Item for TestPngItemView {
14361            type Event = ();
14362            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14363                "".into()
14364            }
14365        }
14366        impl EventEmitter<()> for TestPngItemView {}
14367        impl Focusable for TestPngItemView {
14368            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14369                self.focus_handle.clone()
14370            }
14371        }
14372
14373        impl Render for TestPngItemView {
14374            fn render(
14375                &mut self,
14376                _window: &mut Window,
14377                _cx: &mut Context<Self>,
14378            ) -> impl IntoElement {
14379                Empty
14380            }
14381        }
14382
14383        impl ProjectItem for TestPngItemView {
14384            type Item = TestPngItem;
14385
14386            fn for_project_item(
14387                _project: Entity<Project>,
14388                _pane: Option<&Pane>,
14389                _item: Entity<Self::Item>,
14390                _: &mut Window,
14391                cx: &mut Context<Self>,
14392            ) -> Self
14393            where
14394                Self: Sized,
14395            {
14396                Self {
14397                    focus_handle: cx.focus_handle(),
14398                }
14399            }
14400        }
14401
14402        // View
14403        struct TestIpynbItemView {
14404            focus_handle: FocusHandle,
14405        }
14406        // Model
14407        struct TestIpynbItem {}
14408
14409        impl project::ProjectItem for TestIpynbItem {
14410            fn try_open(
14411                _project: &Entity<Project>,
14412                path: &ProjectPath,
14413                cx: &mut App,
14414            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14415                if path.path.extension().unwrap() == "ipynb" {
14416                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14417                } else {
14418                    None
14419                }
14420            }
14421
14422            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14423                None
14424            }
14425
14426            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14427                None
14428            }
14429
14430            fn is_dirty(&self) -> bool {
14431                false
14432            }
14433        }
14434
14435        impl Item for TestIpynbItemView {
14436            type Event = ();
14437            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14438                "".into()
14439            }
14440        }
14441        impl EventEmitter<()> for TestIpynbItemView {}
14442        impl Focusable for TestIpynbItemView {
14443            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14444                self.focus_handle.clone()
14445            }
14446        }
14447
14448        impl Render for TestIpynbItemView {
14449            fn render(
14450                &mut self,
14451                _window: &mut Window,
14452                _cx: &mut Context<Self>,
14453            ) -> impl IntoElement {
14454                Empty
14455            }
14456        }
14457
14458        impl ProjectItem for TestIpynbItemView {
14459            type Item = TestIpynbItem;
14460
14461            fn for_project_item(
14462                _project: Entity<Project>,
14463                _pane: Option<&Pane>,
14464                _item: Entity<Self::Item>,
14465                _: &mut Window,
14466                cx: &mut Context<Self>,
14467            ) -> Self
14468            where
14469                Self: Sized,
14470            {
14471                Self {
14472                    focus_handle: cx.focus_handle(),
14473                }
14474            }
14475        }
14476
14477        struct TestAlternatePngItemView {
14478            focus_handle: FocusHandle,
14479        }
14480
14481        impl Item for TestAlternatePngItemView {
14482            type Event = ();
14483            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14484                "".into()
14485            }
14486        }
14487
14488        impl EventEmitter<()> for TestAlternatePngItemView {}
14489        impl Focusable for TestAlternatePngItemView {
14490            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14491                self.focus_handle.clone()
14492            }
14493        }
14494
14495        impl Render for TestAlternatePngItemView {
14496            fn render(
14497                &mut self,
14498                _window: &mut Window,
14499                _cx: &mut Context<Self>,
14500            ) -> impl IntoElement {
14501                Empty
14502            }
14503        }
14504
14505        impl ProjectItem for TestAlternatePngItemView {
14506            type Item = TestPngItem;
14507
14508            fn for_project_item(
14509                _project: Entity<Project>,
14510                _pane: Option<&Pane>,
14511                _item: Entity<Self::Item>,
14512                _: &mut Window,
14513                cx: &mut Context<Self>,
14514            ) -> Self
14515            where
14516                Self: Sized,
14517            {
14518                Self {
14519                    focus_handle: cx.focus_handle(),
14520                }
14521            }
14522        }
14523
14524        #[gpui::test]
14525        async fn test_register_project_item(cx: &mut TestAppContext) {
14526            init_test(cx);
14527
14528            cx.update(|cx| {
14529                register_project_item::<TestPngItemView>(cx);
14530                register_project_item::<TestIpynbItemView>(cx);
14531            });
14532
14533            let fs = FakeFs::new(cx.executor());
14534            fs.insert_tree(
14535                "/root1",
14536                json!({
14537                    "one.png": "BINARYDATAHERE",
14538                    "two.ipynb": "{ totally a notebook }",
14539                    "three.txt": "editing text, sure why not?"
14540                }),
14541            )
14542            .await;
14543
14544            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14545            let (workspace, cx) =
14546                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14547
14548            let worktree_id = project.update(cx, |project, cx| {
14549                project.worktrees(cx).next().unwrap().read(cx).id()
14550            });
14551
14552            let handle = workspace
14553                .update_in(cx, |workspace, window, cx| {
14554                    let project_path = (worktree_id, rel_path("one.png"));
14555                    workspace.open_path(project_path, None, true, window, cx)
14556                })
14557                .await
14558                .unwrap();
14559
14560            // Now we can check if the handle we got back errored or not
14561            assert_eq!(
14562                handle.to_any_view().entity_type(),
14563                TypeId::of::<TestPngItemView>()
14564            );
14565
14566            let handle = workspace
14567                .update_in(cx, |workspace, window, cx| {
14568                    let project_path = (worktree_id, rel_path("two.ipynb"));
14569                    workspace.open_path(project_path, None, true, window, cx)
14570                })
14571                .await
14572                .unwrap();
14573
14574            assert_eq!(
14575                handle.to_any_view().entity_type(),
14576                TypeId::of::<TestIpynbItemView>()
14577            );
14578
14579            let handle = workspace
14580                .update_in(cx, |workspace, window, cx| {
14581                    let project_path = (worktree_id, rel_path("three.txt"));
14582                    workspace.open_path(project_path, None, true, window, cx)
14583                })
14584                .await;
14585            assert!(handle.is_err());
14586        }
14587
14588        #[gpui::test]
14589        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14590            init_test(cx);
14591
14592            cx.update(|cx| {
14593                register_project_item::<TestPngItemView>(cx);
14594                register_project_item::<TestAlternatePngItemView>(cx);
14595            });
14596
14597            let fs = FakeFs::new(cx.executor());
14598            fs.insert_tree(
14599                "/root1",
14600                json!({
14601                    "one.png": "BINARYDATAHERE",
14602                    "two.ipynb": "{ totally a notebook }",
14603                    "three.txt": "editing text, sure why not?"
14604                }),
14605            )
14606            .await;
14607            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14608            let (workspace, cx) =
14609                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14610            let worktree_id = project.update(cx, |project, cx| {
14611                project.worktrees(cx).next().unwrap().read(cx).id()
14612            });
14613
14614            let handle = workspace
14615                .update_in(cx, |workspace, window, cx| {
14616                    let project_path = (worktree_id, rel_path("one.png"));
14617                    workspace.open_path(project_path, None, true, window, cx)
14618                })
14619                .await
14620                .unwrap();
14621
14622            // This _must_ be the second item registered
14623            assert_eq!(
14624                handle.to_any_view().entity_type(),
14625                TypeId::of::<TestAlternatePngItemView>()
14626            );
14627
14628            let handle = workspace
14629                .update_in(cx, |workspace, window, cx| {
14630                    let project_path = (worktree_id, rel_path("three.txt"));
14631                    workspace.open_path(project_path, None, true, window, cx)
14632                })
14633                .await;
14634            assert!(handle.is_err());
14635        }
14636    }
14637
14638    #[gpui::test]
14639    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14640        init_test(cx);
14641
14642        let fs = FakeFs::new(cx.executor());
14643        let project = Project::test(fs, [], cx).await;
14644        let (workspace, _cx) =
14645            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14646
14647        // Test with status bar shown (default)
14648        workspace.read_with(cx, |workspace, cx| {
14649            let visible = workspace.status_bar_visible(cx);
14650            assert!(visible, "Status bar should be visible by default");
14651        });
14652
14653        // Test with status bar hidden
14654        cx.update_global(|store: &mut SettingsStore, cx| {
14655            store.update_user_settings(cx, |settings| {
14656                settings.status_bar.get_or_insert_default().show = Some(false);
14657            });
14658        });
14659
14660        workspace.read_with(cx, |workspace, cx| {
14661            let visible = workspace.status_bar_visible(cx);
14662            assert!(!visible, "Status bar should be hidden when show is false");
14663        });
14664
14665        // Test with status bar shown explicitly
14666        cx.update_global(|store: &mut SettingsStore, cx| {
14667            store.update_user_settings(cx, |settings| {
14668                settings.status_bar.get_or_insert_default().show = Some(true);
14669            });
14670        });
14671
14672        workspace.read_with(cx, |workspace, cx| {
14673            let visible = workspace.status_bar_visible(cx);
14674            assert!(visible, "Status bar should be visible when show is true");
14675        });
14676    }
14677
14678    #[gpui::test]
14679    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14680        init_test(cx);
14681
14682        let fs = FakeFs::new(cx.executor());
14683        let project = Project::test(fs, [], cx).await;
14684        let (multi_workspace, cx) =
14685            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14686        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14687        let panel = workspace.update_in(cx, |workspace, window, cx| {
14688            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14689            workspace.add_panel(panel.clone(), window, cx);
14690
14691            workspace
14692                .right_dock()
14693                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14694
14695            panel
14696        });
14697
14698        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14699        let item_a = cx.new(TestItem::new);
14700        let item_b = cx.new(TestItem::new);
14701        let item_a_id = item_a.entity_id();
14702        let item_b_id = item_b.entity_id();
14703
14704        pane.update_in(cx, |pane, window, cx| {
14705            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14706            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14707        });
14708
14709        pane.read_with(cx, |pane, _| {
14710            assert_eq!(pane.items_len(), 2);
14711            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14712        });
14713
14714        workspace.update_in(cx, |workspace, window, cx| {
14715            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14716        });
14717
14718        workspace.update_in(cx, |_, window, cx| {
14719            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14720        });
14721
14722        // Assert that the `pane::CloseActiveItem` action is handled at the
14723        // workspace level when one of the dock panels is focused and, in that
14724        // case, the center pane's active item is closed but the focus is not
14725        // moved.
14726        cx.dispatch_action(pane::CloseActiveItem::default());
14727        cx.run_until_parked();
14728
14729        pane.read_with(cx, |pane, _| {
14730            assert_eq!(pane.items_len(), 1);
14731            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14732        });
14733
14734        workspace.update_in(cx, |workspace, window, cx| {
14735            assert!(workspace.right_dock().read(cx).is_open());
14736            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14737        });
14738    }
14739
14740    #[gpui::test]
14741    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14742        init_test(cx);
14743        let fs = FakeFs::new(cx.executor());
14744
14745        let project_a = Project::test(fs.clone(), [], cx).await;
14746        let project_b = Project::test(fs, [], cx).await;
14747
14748        let multi_workspace_handle =
14749            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14750        cx.run_until_parked();
14751
14752        multi_workspace_handle
14753            .update(cx, |mw, _window, cx| {
14754                mw.open_sidebar(cx);
14755            })
14756            .unwrap();
14757
14758        let workspace_a = multi_workspace_handle
14759            .read_with(cx, |mw, _| mw.workspace().clone())
14760            .unwrap();
14761
14762        let _workspace_b = multi_workspace_handle
14763            .update(cx, |mw, window, cx| {
14764                mw.test_add_workspace(project_b, window, cx)
14765            })
14766            .unwrap();
14767
14768        // Switch to workspace A
14769        multi_workspace_handle
14770            .update(cx, |mw, window, cx| {
14771                let workspace = mw.workspaces().next().unwrap().clone();
14772                mw.activate(workspace, window, cx);
14773            })
14774            .unwrap();
14775
14776        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14777
14778        // Add a panel to workspace A's right dock and open the dock
14779        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14780            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14781            workspace.add_panel(panel.clone(), window, cx);
14782            workspace
14783                .right_dock()
14784                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14785            panel
14786        });
14787
14788        // Focus the panel through the workspace (matching existing test pattern)
14789        workspace_a.update_in(cx, |workspace, window, cx| {
14790            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14791        });
14792
14793        // Zoom the panel
14794        panel.update_in(cx, |panel, window, cx| {
14795            panel.set_zoomed(true, window, cx);
14796        });
14797
14798        // Verify the panel is zoomed and the dock is open
14799        workspace_a.update_in(cx, |workspace, window, cx| {
14800            assert!(
14801                workspace.right_dock().read(cx).is_open(),
14802                "dock should be open before switch"
14803            );
14804            assert!(
14805                panel.is_zoomed(window, cx),
14806                "panel should be zoomed before switch"
14807            );
14808            assert!(
14809                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14810                "panel should be focused before switch"
14811            );
14812        });
14813
14814        // Switch to workspace B
14815        multi_workspace_handle
14816            .update(cx, |mw, window, cx| {
14817                let workspace = mw.workspaces().nth(1).unwrap().clone();
14818                mw.activate(workspace, window, cx);
14819            })
14820            .unwrap();
14821        cx.run_until_parked();
14822
14823        // Switch back to workspace A
14824        multi_workspace_handle
14825            .update(cx, |mw, window, cx| {
14826                let workspace = mw.workspaces().next().unwrap().clone();
14827                mw.activate(workspace, window, cx);
14828            })
14829            .unwrap();
14830        cx.run_until_parked();
14831
14832        // Verify the panel is still zoomed and the dock is still open
14833        workspace_a.update_in(cx, |workspace, window, cx| {
14834            assert!(
14835                workspace.right_dock().read(cx).is_open(),
14836                "dock should still be open after switching back"
14837            );
14838            assert!(
14839                panel.is_zoomed(window, cx),
14840                "panel should still be zoomed after switching back"
14841            );
14842        });
14843    }
14844
14845    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14846        pane.read(cx)
14847            .items()
14848            .flat_map(|item| {
14849                item.project_paths(cx)
14850                    .into_iter()
14851                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14852            })
14853            .collect()
14854    }
14855
14856    pub fn init_test(cx: &mut TestAppContext) {
14857        cx.update(|cx| {
14858            let settings_store = SettingsStore::test(cx);
14859            cx.set_global(settings_store);
14860            cx.set_global(db::AppDatabase::test_new());
14861            theme_settings::init(theme::LoadThemes::JustBase, cx);
14862        });
14863    }
14864
14865    #[gpui::test]
14866    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14867        use settings::{ThemeName, ThemeSelection};
14868        use theme::SystemAppearance;
14869        use zed_actions::theme::ToggleMode;
14870
14871        init_test(cx);
14872
14873        let fs = FakeFs::new(cx.executor());
14874        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14875
14876        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14877            .await;
14878
14879        // Build a test project and workspace view so the test can invoke
14880        // the workspace action handler the same way the UI would.
14881        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14882        let (workspace, cx) =
14883            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14884
14885        // Seed the settings file with a plain static light theme so the
14886        // first toggle always starts from a known persisted state.
14887        workspace.update_in(cx, |_workspace, _window, cx| {
14888            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14889            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14890                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14891            });
14892        });
14893        cx.executor().advance_clock(Duration::from_millis(200));
14894        cx.run_until_parked();
14895
14896        // Confirm the initial persisted settings contain the static theme
14897        // we just wrote before any toggling happens.
14898        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14899        assert!(settings_text.contains(r#""theme": "One Light""#));
14900
14901        // Toggle once. This should migrate the persisted theme settings
14902        // into light/dark slots and enable system mode.
14903        workspace.update_in(cx, |workspace, window, cx| {
14904            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14905        });
14906        cx.executor().advance_clock(Duration::from_millis(200));
14907        cx.run_until_parked();
14908
14909        // 1. Static -> Dynamic
14910        // this assertion checks theme changed from static to dynamic.
14911        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14912        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14913        assert_eq!(
14914            parsed["theme"],
14915            serde_json::json!({
14916                "mode": "system",
14917                "light": "One Light",
14918                "dark": "One Dark"
14919            })
14920        );
14921
14922        // 2. Toggle again, suppose it will change the mode to light
14923        workspace.update_in(cx, |workspace, window, cx| {
14924            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14925        });
14926        cx.executor().advance_clock(Duration::from_millis(200));
14927        cx.run_until_parked();
14928
14929        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14930        assert!(settings_text.contains(r#""mode": "light""#));
14931    }
14932
14933    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14934        let item = TestProjectItem::new(id, path, cx);
14935        item.update(cx, |item, _| {
14936            item.is_dirty = true;
14937        });
14938        item
14939    }
14940
14941    #[gpui::test]
14942    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14943        cx: &mut gpui::TestAppContext,
14944    ) {
14945        init_test(cx);
14946        let fs = FakeFs::new(cx.executor());
14947
14948        let project = Project::test(fs, [], cx).await;
14949        let (workspace, cx) =
14950            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14951
14952        let panel = workspace.update_in(cx, |workspace, window, cx| {
14953            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14954            workspace.add_panel(panel.clone(), window, cx);
14955            workspace
14956                .right_dock()
14957                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14958            panel
14959        });
14960
14961        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14962        pane.update_in(cx, |pane, window, cx| {
14963            let item = cx.new(TestItem::new);
14964            pane.add_item(Box::new(item), true, true, None, window, cx);
14965        });
14966
14967        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14968        // mirrors the real-world flow and avoids side effects from directly
14969        // focusing the panel while the center pane is active.
14970        workspace.update_in(cx, |workspace, window, cx| {
14971            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14972        });
14973
14974        panel.update_in(cx, |panel, window, cx| {
14975            panel.set_zoomed(true, window, cx);
14976        });
14977
14978        workspace.update_in(cx, |workspace, window, cx| {
14979            assert!(workspace.right_dock().read(cx).is_open());
14980            assert!(panel.is_zoomed(window, cx));
14981            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14982        });
14983
14984        // Simulate a spurious pane::Event::Focus on the center pane while the
14985        // panel still has focus. This mirrors what happens during macOS window
14986        // activation: the center pane fires a focus event even though actual
14987        // focus remains on the dock panel.
14988        pane.update_in(cx, |_, _, cx| {
14989            cx.emit(pane::Event::Focus);
14990        });
14991
14992        // The dock must remain open because the panel had focus at the time the
14993        // event was processed. Before the fix, dock_to_preserve was None for
14994        // panels that don't implement pane(), causing the dock to close.
14995        workspace.update_in(cx, |workspace, window, cx| {
14996            assert!(
14997                workspace.right_dock().read(cx).is_open(),
14998                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14999            );
15000            assert!(panel.is_zoomed(window, cx));
15001        });
15002    }
15003
15004    #[gpui::test]
15005    async fn test_panels_stay_open_after_position_change_and_settings_update(
15006        cx: &mut gpui::TestAppContext,
15007    ) {
15008        init_test(cx);
15009        let fs = FakeFs::new(cx.executor());
15010        let project = Project::test(fs, [], cx).await;
15011        let (workspace, cx) =
15012            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15013
15014        // Add two panels to the left dock and open it.
15015        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15016            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15017            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15018            workspace.add_panel(panel_a.clone(), window, cx);
15019            workspace.add_panel(panel_b.clone(), window, cx);
15020            workspace.left_dock().update(cx, |dock, cx| {
15021                dock.set_open(true, window, cx);
15022                dock.activate_panel(0, window, cx);
15023            });
15024            (panel_a, panel_b)
15025        });
15026
15027        workspace.update_in(cx, |workspace, _, cx| {
15028            assert!(workspace.left_dock().read(cx).is_open());
15029        });
15030
15031        // Simulate a feature flag changing default dock positions: both panels
15032        // move from Left to Right.
15033        workspace.update_in(cx, |_workspace, _window, cx| {
15034            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15035            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15036            cx.update_global::<SettingsStore, _>(|_, _| {});
15037        });
15038
15039        // Both panels should now be in the right dock.
15040        workspace.update_in(cx, |workspace, _, cx| {
15041            let right_dock = workspace.right_dock().read(cx);
15042            assert_eq!(right_dock.panels_len(), 2);
15043        });
15044
15045        // Open the right dock and activate panel_b (simulating the user
15046        // opening the panel after it moved).
15047        workspace.update_in(cx, |workspace, window, cx| {
15048            workspace.right_dock().update(cx, |dock, cx| {
15049                dock.set_open(true, window, cx);
15050                dock.activate_panel(1, window, cx);
15051            });
15052        });
15053
15054        // Now trigger another SettingsStore change
15055        workspace.update_in(cx, |_workspace, _window, cx| {
15056            cx.update_global::<SettingsStore, _>(|_, _| {});
15057        });
15058
15059        workspace.update_in(cx, |workspace, _, cx| {
15060            assert!(
15061                workspace.right_dock().read(cx).is_open(),
15062                "Right dock should still be open after a settings change"
15063            );
15064            assert_eq!(
15065                workspace.right_dock().read(cx).panels_len(),
15066                2,
15067                "Both panels should still be in the right dock"
15068            );
15069        });
15070    }
15071}